logger.conf.sample: add missing comment mark
[asterisk/asterisk.git] / channels / chan_pjsip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Joshua Colp <jcolp@digium.com>
22  *
23  * \brief PSJIP SIP Channel Driver
24  *
25  * \ingroup channel_drivers
26  */
27
28 /*** MODULEINFO
29         <depend>pjproject</depend>
30         <depend>res_pjsip</depend>
31         <depend>res_pjsip_pubsub</depend>
32         <depend>res_pjsip_session</depend>
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 #include <pjsip.h>
39 #include <pjsip_ua.h>
40 #include <pjlib.h>
41
42 #include "asterisk/lock.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/module.h"
45 #include "asterisk/pbx.h"
46 #include "asterisk/rtp_engine.h"
47 #include "asterisk/acl.h"
48 #include "asterisk/callerid.h"
49 #include "asterisk/file.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/app.h"
52 #include "asterisk/musiconhold.h"
53 #include "asterisk/causes.h"
54 #include "asterisk/taskprocessor.h"
55 #include "asterisk/dsp.h"
56 #include "asterisk/stasis_endpoints.h"
57 #include "asterisk/stasis_channels.h"
58 #include "asterisk/indications.h"
59 #include "asterisk/format_cache.h"
60 #include "asterisk/translate.h"
61 #include "asterisk/threadstorage.h"
62 #include "asterisk/features_config.h"
63 #include "asterisk/pickup.h"
64 #include "asterisk/test.h"
65 #include "asterisk/message.h"
66
67 #include "asterisk/res_pjsip.h"
68 #include "asterisk/res_pjsip_session.h"
69 #include "asterisk/stream.h"
70
71 #include "pjsip/include/chan_pjsip.h"
72 #include "pjsip/include/dialplan_functions.h"
73 #include "pjsip/include/cli_functions.h"
74
75 AST_THREADSTORAGE(uniqueid_threadbuf);
76 #define UNIQUEID_BUFSIZE 256
77
78 static const char channel_type[] = "PJSIP";
79
80 static unsigned int chan_idx;
81
82 static void chan_pjsip_pvt_dtor(void *obj)
83 {
84 }
85
86 /* \brief Asterisk core interaction functions */
87 static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
88 static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type,
89         struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids,
90         const struct ast_channel *requestor, const char *data, int *cause);
91 static int chan_pjsip_sendtext_data(struct ast_channel *ast, struct ast_msg_data *msg);
92 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
93 static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
94 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
95 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
96 static int chan_pjsip_hangup(struct ast_channel *ast);
97 static int chan_pjsip_answer(struct ast_channel *ast);
98 static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast);
99 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
100 static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *f);
101 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
102 static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
103 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
104 static int chan_pjsip_devicestate(const char *data);
105 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
106 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast);
107
108 /*! \brief PBX interface structure for channel registration */
109 struct ast_channel_tech chan_pjsip_tech = {
110         .type = channel_type,
111         .description = "PJSIP Channel Driver",
112         .requester = chan_pjsip_request,
113         .requester_with_stream_topology = chan_pjsip_request_with_stream_topology,
114         .send_text = chan_pjsip_sendtext,
115         .send_text_data = chan_pjsip_sendtext_data,
116         .send_digit_begin = chan_pjsip_digit_begin,
117         .send_digit_end = chan_pjsip_digit_end,
118         .call = chan_pjsip_call,
119         .hangup = chan_pjsip_hangup,
120         .answer = chan_pjsip_answer,
121         .read_stream = chan_pjsip_read_stream,
122         .write = chan_pjsip_write,
123         .write_stream = chan_pjsip_write_stream,
124         .exception = chan_pjsip_read_stream,
125         .indicate = chan_pjsip_indicate,
126         .transfer = chan_pjsip_transfer,
127         .fixup = chan_pjsip_fixup,
128         .devicestate = chan_pjsip_devicestate,
129         .queryoption = chan_pjsip_queryoption,
130         .func_channel_read = pjsip_acf_channel_read,
131         .get_pvt_uniqueid = chan_pjsip_get_uniqueid,
132         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER | AST_CHAN_TP_SEND_TEXT_DATA
133 };
134
135 /*! \brief SIP session interaction functions */
136 static void chan_pjsip_session_begin(struct ast_sip_session *session);
137 static void chan_pjsip_session_end(struct ast_sip_session *session);
138 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
139 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
140
141 /*! \brief SIP session supplement structure */
142 static struct ast_sip_session_supplement chan_pjsip_supplement = {
143         .method = "INVITE",
144         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
145         .session_begin = chan_pjsip_session_begin,
146         .session_end = chan_pjsip_session_end,
147         .incoming_request = chan_pjsip_incoming_request,
148         /* It is important that this supplement runs after media has been negotiated */
149         .response_priority = AST_SIP_SESSION_AFTER_MEDIA,
150 };
151
152 /*! \brief SIP session supplement structure just for responses */
153 static struct ast_sip_session_supplement chan_pjsip_supplement_response = {
154         .method = "INVITE",
155         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
156         .incoming_response = chan_pjsip_incoming_response,
157         .response_priority = AST_SIP_SESSION_BEFORE_MEDIA | AST_SIP_SESSION_AFTER_MEDIA,
158 };
159
160 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
161
162 static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
163         .method = "ACK",
164         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
165         .incoming_request = chan_pjsip_incoming_ack,
166 };
167
168 /*! \brief Function called by RTP engine to get local audio RTP peer */
169 static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
170 {
171         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
172         struct ast_sip_endpoint *endpoint;
173         struct ast_datastore *datastore;
174         struct ast_sip_session_media *media;
175
176         if (!channel || !channel->session) {
177                 return AST_RTP_GLUE_RESULT_FORBID;
178         }
179
180         /* XXX Getting the first RTP instance for direct media related stuff seems just
181          * absolutely wrong. But the native RTP bridge knows no other method than single-stream
182          * for direct media. So this is the best we can do.
183          */
184         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
185         if (!media || !media->rtp) {
186                 return AST_RTP_GLUE_RESULT_FORBID;
187         }
188
189         datastore = ast_sip_session_get_datastore(channel->session, "t38");
190         if (datastore) {
191                 ao2_ref(datastore, -1);
192                 return AST_RTP_GLUE_RESULT_FORBID;
193         }
194
195         endpoint = channel->session->endpoint;
196
197         *instance = media->rtp;
198         ao2_ref(*instance, +1);
199
200         ast_assert(endpoint != NULL);
201         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
202                 return AST_RTP_GLUE_RESULT_FORBID;
203         }
204
205         if (endpoint->media.direct_media.enabled) {
206                 return AST_RTP_GLUE_RESULT_REMOTE;
207         }
208
209         return AST_RTP_GLUE_RESULT_LOCAL;
210 }
211
212 /*! \brief Function called by RTP engine to get local video RTP peer */
213 static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
214 {
215         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
216         struct ast_sip_endpoint *endpoint;
217         struct ast_sip_session_media *media;
218
219         if (!channel || !channel->session) {
220                 return AST_RTP_GLUE_RESULT_FORBID;
221         }
222
223         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
224         if (!media || !media->rtp) {
225                 return AST_RTP_GLUE_RESULT_FORBID;
226         }
227
228         endpoint = channel->session->endpoint;
229
230         *instance = media->rtp;
231         ao2_ref(*instance, +1);
232
233         ast_assert(endpoint != NULL);
234         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
235                 return AST_RTP_GLUE_RESULT_FORBID;
236         }
237
238         return AST_RTP_GLUE_RESULT_LOCAL;
239 }
240
241 /*! \brief Function called by RTP engine to get peer capabilities */
242 static void chan_pjsip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
243 {
244         SCOPE_ENTER(1, "%s Native formats %s\n", ast_channel_name(chan),
245                 ast_str_tmp(AST_FORMAT_CAP_NAMES_LEN, ast_format_cap_get_names(ast_channel_nativeformats(chan), &STR_TMP)));
246         ast_format_cap_append_from_cap(result, ast_channel_nativeformats(chan), AST_MEDIA_TYPE_UNKNOWN);
247         SCOPE_EXIT_RTN();
248 }
249
250 /*! \brief Destructor function for \ref transport_info_data */
251 static void transport_info_destroy(void *obj)
252 {
253         struct transport_info_data *data = obj;
254         ast_free(data);
255 }
256
257 /*! \brief Datastore used to store local/remote addresses for the
258  * INVITE request that created the PJSIP channel */
259 static struct ast_datastore_info transport_info = {
260         .type = "chan_pjsip_transport_info",
261         .destroy = transport_info_destroy,
262 };
263
264 static struct ast_datastore_info direct_media_mitigation_info = { };
265
266 static int direct_media_mitigate_glare(struct ast_sip_session *session)
267 {
268         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
269
270         if (session->endpoint->media.direct_media.glare_mitigation ==
271                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
272                 return 0;
273         }
274
275         datastore = ast_sip_session_get_datastore(session, "direct_media_glare_mitigation");
276         if (!datastore) {
277                 return 0;
278         }
279
280         /* Removing the datastore ensures we won't try to mitigate glare on subsequent reinvites */
281         ast_sip_session_remove_datastore(session, "direct_media_glare_mitigation");
282
283         if ((session->endpoint->media.direct_media.glare_mitigation ==
284                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING &&
285                         session->inv_session->role == PJSIP_ROLE_UAC) ||
286                         (session->endpoint->media.direct_media.glare_mitigation ==
287                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING &&
288                         session->inv_session->role == PJSIP_ROLE_UAS)) {
289                 return 1;
290         }
291
292         return 0;
293 }
294
295 /*! \brief Helper function to find the position for RTCP */
296 static int rtp_find_rtcp_fd_position(struct ast_sip_session *session, struct ast_rtp_instance *rtp)
297 {
298         int index;
299
300         for (index = 0; index < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++index) {
301                 struct ast_sip_session_media_read_callback_state *callback_state =
302                         AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, index);
303
304                 if (callback_state->fd != ast_rtp_instance_fd(rtp, 1)) {
305                         continue;
306                 }
307
308                 return index;
309         }
310
311         return -1;
312 }
313
314 /*!
315  * \pre chan is locked
316  */
317 static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
318                 struct ast_sip_session_media *media, struct ast_sip_session *session)
319 {
320         int changed = 0, position = -1;
321
322         if (media->rtp) {
323                 position = rtp_find_rtcp_fd_position(session, media->rtp);
324         }
325
326         if (rtp) {
327                 changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
328                 if (media->rtp) {
329                         if (position != -1) {
330                                 ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, -1);
331                         }
332                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
333                 }
334         } else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
335                 ast_sockaddr_setnull(&media->direct_media_addr);
336                 changed = 1;
337                 if (media->rtp) {
338                         /* Direct media has ended - reset time of last received RTP packet
339                          * to avoid premature RTP timeout. Synchronisation between the
340                          * modification of direct_mdedia_addr+last_rx here and reading the
341                          * values in res_pjsip_sdp_rtp.c:rtp_check_timeout() is provided
342                          * by the channel's lock (which is held while this function is
343                          * executed).
344                          */
345                         ast_rtp_instance_set_last_rx(media->rtp, time(NULL));
346                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
347                         if (position != -1) {
348                                 ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, ast_rtp_instance_fd(media->rtp, 1));
349                         }
350                 }
351         }
352
353         return changed;
354 }
355
356 struct rtp_direct_media_data {
357         struct ast_channel *chan;
358         struct ast_rtp_instance *rtp;
359         struct ast_rtp_instance *vrtp;
360         struct ast_format_cap *cap;
361         struct ast_sip_session *session;
362 };
363
364 static void rtp_direct_media_data_destroy(void *data)
365 {
366         struct rtp_direct_media_data *cdata = data;
367
368         ao2_cleanup(cdata->session);
369         ao2_cleanup(cdata->cap);
370         ao2_cleanup(cdata->vrtp);
371         ao2_cleanup(cdata->rtp);
372         ao2_cleanup(cdata->chan);
373 }
374
375 static struct rtp_direct_media_data *rtp_direct_media_data_create(
376         struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp,
377         const struct ast_format_cap *cap, struct ast_sip_session *session)
378 {
379         struct rtp_direct_media_data *cdata = ao2_alloc(sizeof(*cdata), rtp_direct_media_data_destroy);
380
381         if (!cdata) {
382                 return NULL;
383         }
384
385         cdata->chan = ao2_bump(chan);
386         cdata->rtp = ao2_bump(rtp);
387         cdata->vrtp = ao2_bump(vrtp);
388         cdata->cap = ao2_bump((struct ast_format_cap *)cap);
389         cdata->session = ao2_bump(session);
390
391         return cdata;
392 }
393
394 static int send_direct_media_request(void *data)
395 {
396         struct rtp_direct_media_data *cdata = data;
397         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(cdata->chan);
398         struct ast_sip_session *session;
399         int changed = 0;
400         int res = 0;
401
402         /* XXX In an ideal world each media stream would be direct, but for now preserve behavior
403          * and connect only the default media sessions for audio and video.
404          */
405
406         /* The channel needs to be locked when checking for RTP changes.
407          * Otherwise, we could end up destroying an underlying RTCP structure
408          * at the same time that the channel thread is attempting to read RTCP
409          */
410         ast_channel_lock(cdata->chan);
411         session = channel->session;
412         if (session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO]) {
413                 changed |= check_for_rtp_changes(
414                         cdata->chan, cdata->rtp, session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO], session);
415         }
416         if (session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO]) {
417                 changed |= check_for_rtp_changes(
418                         cdata->chan, cdata->vrtp, session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO], session);
419         }
420         ast_channel_unlock(cdata->chan);
421
422         if (direct_media_mitigate_glare(cdata->session)) {
423                 ast_debug(4, "Disregarding setting RTP on %s: mitigating re-INVITE glare\n", ast_channel_name(cdata->chan));
424                 ao2_ref(cdata, -1);
425                 return 0;
426         }
427
428         if (cdata->cap && ast_format_cap_count(cdata->cap) &&
429             !ast_format_cap_identical(cdata->session->direct_media_cap, cdata->cap)) {
430                 ast_format_cap_remove_by_type(cdata->session->direct_media_cap, AST_MEDIA_TYPE_UNKNOWN);
431                 ast_format_cap_append_from_cap(cdata->session->direct_media_cap, cdata->cap, AST_MEDIA_TYPE_UNKNOWN);
432                 changed = 1;
433         }
434
435         if (changed) {
436                 ast_debug(4, "RTP changed on %s; initiating direct media update\n", ast_channel_name(cdata->chan));
437                 res = ast_sip_session_refresh(cdata->session, NULL, NULL, NULL,
438                         cdata->session->endpoint->media.direct_media.method, 1, NULL);
439         }
440
441         ao2_ref(cdata, -1);
442         return res;
443 }
444
445 /*! \brief Function called by RTP engine to change where the remote party should send media */
446 static int chan_pjsip_set_rtp_peer(struct ast_channel *chan,
447                 struct ast_rtp_instance *rtp,
448                 struct ast_rtp_instance *vrtp,
449                 struct ast_rtp_instance *tpeer,
450                 const struct ast_format_cap *cap,
451                 int nat_active)
452 {
453         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
454         struct ast_sip_session *session = channel->session;
455         struct rtp_direct_media_data *cdata;
456         SCOPE_ENTER(1, "%s %s\n", ast_channel_name(chan),
457                 ast_str_tmp(AST_FORMAT_CAP_NAMES_LEN, ast_format_cap_get_names(cap, &STR_TMP)));
458
459         /* Don't try to do any direct media shenanigans on early bridges */
460         if ((rtp || vrtp || tpeer) && !ast_channel_is_bridged(chan)) {
461                 ast_debug(4, "Disregarding setting RTP on %s: channel is not bridged\n", ast_channel_name(chan));
462                 SCOPE_EXIT_RTN_VALUE(0, "Channel not bridged\n");
463         }
464
465         if (nat_active && session->endpoint->media.direct_media.disable_on_nat) {
466                 ast_debug(4, "Disregarding setting RTP on %s: NAT is active\n", ast_channel_name(chan));
467                 SCOPE_EXIT_RTN_VALUE(0, "NAT is active\n");
468         }
469
470         cdata = rtp_direct_media_data_create(chan, rtp, vrtp, cap, session);
471         if (!cdata) {
472                 SCOPE_EXIT_RTN_VALUE(0);
473         }
474
475         if (ast_sip_push_task(session->serializer, send_direct_media_request, cdata)) {
476                 ast_log(LOG_ERROR, "Unable to send direct media request for channel %s\n", ast_channel_name(chan));
477                 ao2_ref(cdata, -1);
478         }
479
480         SCOPE_EXIT_RTN_VALUE(0);
481 }
482
483 /*! \brief Local glue for interacting with the RTP engine core */
484 static struct ast_rtp_glue chan_pjsip_rtp_glue = {
485         .type = "PJSIP",
486         .get_rtp_info = chan_pjsip_get_rtp_peer,
487         .get_vrtp_info = chan_pjsip_get_vrtp_peer,
488         .get_codec = chan_pjsip_get_codec,
489         .update_peer = chan_pjsip_set_rtp_peer,
490 };
491
492 static void set_channel_on_rtp_instance(const struct ast_sip_session *session,
493         const char *channel_id)
494 {
495         int i;
496
497         for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->sessions); ++i) {
498                 struct ast_sip_session_media *session_media;
499
500                 session_media = AST_VECTOR_GET(&session->active_media_state->sessions, i);
501                 if (!session_media || !session_media->rtp) {
502                         continue;
503                 }
504
505                 ast_rtp_instance_set_channel_id(session_media->rtp, channel_id);
506         }
507 }
508
509 /*!
510  * \brief Determine if a topology is compatible with format capabilities
511  *
512  * This will return true if ANY formats in the topology are compatible with the format
513  * capabilities.
514  *
515  * XXX When supporting true multistream, we will need to be sure to mark which streams from
516  * top1 are compatible with which streams from top2. Then the ones that are not compatible
517  * will need to be marked as "removed" so that they are negotiated as expected.
518  *
519  * \param top Topology
520  * \param cap Format capabilities
521  * \retval 1 The topology has at least one compatible format
522  * \retval 0 The topology has no compatible formats or an error occurred.
523  */
524 static int compatible_formats_exist(struct ast_stream_topology *top, struct ast_format_cap *cap)
525 {
526         struct ast_format_cap *cap_from_top;
527         int res;
528         SCOPE_ENTER(1, "Topology: %s Formats: %s\n",
529                 ast_str_tmp(AST_FORMAT_CAP_NAMES_LEN, ast_stream_topology_to_str(top, &STR_TMP)),
530                 ast_str_tmp(AST_FORMAT_CAP_NAMES_LEN, ast_format_cap_get_names(cap, &STR_TMP)));
531
532         cap_from_top = ast_stream_topology_get_formats(top);
533
534         if (!cap_from_top) {
535                 SCOPE_EXIT_RTN_VALUE(0, "Topology had no formats\n");
536         }
537
538         res = ast_format_cap_iscompatible(cap_from_top, cap);
539         ao2_ref(cap_from_top, -1);
540
541         SCOPE_EXIT_RTN_VALUE(res, "Compatible? %s\n", res ? "yes" : "no");
542 }
543
544 /*! \brief Function called to create a new PJSIP Asterisk channel */
545 static struct ast_channel *chan_pjsip_new(struct ast_sip_session *session, int state, const char *exten, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *cid_name)
546 {
547         struct ast_channel *chan;
548         struct ast_format_cap *caps;
549         RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
550         struct ast_sip_channel_pvt *channel;
551         struct ast_variable *var;
552         struct ast_stream_topology *topology;
553         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(session));
554
555         if (!(pvt = ao2_alloc_options(sizeof(*pvt), chan_pjsip_pvt_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK))) {
556                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create pvt\n");
557         }
558
559         chan = ast_channel_alloc_with_endpoint(1, state,
560                 S_COR(session->id.number.valid, session->id.number.str, ""),
561                 S_COR(session->id.name.valid, session->id.name.str, ""),
562                 session->endpoint->accountcode,
563                 exten, session->endpoint->context,
564                 assignedids, requestor, 0,
565                 session->endpoint->persistent, "PJSIP/%s-%08x",
566                 ast_sorcery_object_get_id(session->endpoint),
567                 (unsigned) ast_atomic_fetchadd_int((int *) &chan_idx, +1));
568         if (!chan) {
569                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create channel\n");
570         }
571
572         ast_channel_tech_set(chan, &chan_pjsip_tech);
573
574         if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
575                 ast_channel_unlock(chan);
576                 ast_hangup(chan);
577                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create pvt channel\n");
578         }
579
580         ast_channel_tech_pvt_set(chan, channel);
581
582         if (!ast_stream_topology_get_count(session->pending_media_state->topology) ||
583                 !compatible_formats_exist(session->pending_media_state->topology, session->endpoint->media.codecs)) {
584                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
585                 if (!caps) {
586                         ast_channel_unlock(chan);
587                         ast_hangup(chan);
588                         SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create caps\n");
589                 }
590                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
591                 topology = ast_stream_topology_clone(session->endpoint->media.topology);
592         } else {
593                 caps = ast_stream_topology_get_formats(session->pending_media_state->topology);
594                 topology = ast_stream_topology_clone(session->pending_media_state->topology);
595         }
596
597         if (!topology || !caps) {
598                 ao2_cleanup(caps);
599                 ast_stream_topology_free(topology);
600                 ast_channel_unlock(chan);
601                 ast_hangup(chan);
602                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't get caps or clone topology\n");
603         }
604
605         ast_channel_stage_snapshot(chan);
606
607         ast_channel_nativeformats_set(chan, caps);
608         ast_channel_set_stream_topology(chan, topology);
609
610         if (!ast_format_cap_empty(caps)) {
611                 struct ast_format *fmt;
612
613                 fmt = ast_format_cap_get_best_by_type(caps, AST_MEDIA_TYPE_AUDIO);
614                 if (!fmt) {
615                         /* Since our capabilities aren't empty, this will succeed */
616                         fmt = ast_format_cap_get_format(caps, 0);
617                 }
618                 ast_channel_set_writeformat(chan, fmt);
619                 ast_channel_set_rawwriteformat(chan, fmt);
620                 ast_channel_set_readformat(chan, fmt);
621                 ast_channel_set_rawreadformat(chan, fmt);
622                 ao2_ref(fmt, -1);
623         }
624
625         ao2_ref(caps, -1);
626
627         if (state == AST_STATE_RING) {
628                 ast_channel_rings_set(chan, 1);
629         }
630
631         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
632
633         ast_party_id_copy(&ast_channel_caller(chan)->id, &session->id);
634         ast_party_id_copy(&ast_channel_caller(chan)->ani, &session->id);
635
636         if (!ast_strlen_zero(exten)) {
637                 /* Set provided DNID on the new channel. */
638                 ast_channel_dialed(chan)->number.str = ast_strdup(exten);
639         }
640
641         ast_channel_priority_set(chan, 1);
642
643         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
644         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
645
646         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
647         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
648
649         if (!ast_strlen_zero(session->endpoint->language)) {
650                 ast_channel_language_set(chan, session->endpoint->language);
651         }
652
653         if (!ast_strlen_zero(session->endpoint->zone)) {
654                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
655                 if (!zone) {
656                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
657                 }
658                 ast_channel_zone_set(chan, zone);
659         }
660
661         for (var = session->endpoint->channel_vars; var; var = var->next) {
662                 char buf[512];
663                 pbx_builtin_setvar_helper(chan, var->name, ast_get_encoded_str(
664                                                   var->value, buf, sizeof(buf)));
665         }
666
667         ast_channel_stage_snapshot_done(chan);
668         ast_channel_unlock(chan);
669
670         set_channel_on_rtp_instance(session, ast_channel_uniqueid(chan));
671
672         SCOPE_EXIT_RTN_VALUE(chan);
673 }
674
675 struct answer_data {
676         struct ast_sip_session *session;
677         unsigned long indent;
678 };
679
680 static int answer(void *data)
681 {
682         struct answer_data *ans_data = data;
683         pj_status_t status = PJ_SUCCESS;
684         pjsip_tx_data *packet = NULL;
685         struct ast_sip_session *session = ans_data->session;
686         SCOPE_ENTER_TASK(1, ans_data->indent, "%s\n", ast_sip_session_get_name(session));
687
688         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
689                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
690                         session->inv_session->cause,
691                         pjsip_get_status_text(session->inv_session->cause)->ptr);
692 #ifdef HAVE_PJSIP_INV_SESSION_REF
693                 pjsip_inv_dec_ref(session->inv_session);
694 #endif
695                 SCOPE_EXIT_RTN_VALUE(0, "Disconnected\n");
696         }
697
698         pjsip_dlg_inc_lock(session->inv_session->dlg);
699         if (session->inv_session->invite_tsx) {
700                 status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
701         } else {
702                 ast_log(LOG_ERROR,"Cannot answer '%s' because there is no associated SIP transaction\n",
703                         ast_channel_name(session->channel));
704         }
705         pjsip_dlg_dec_lock(session->inv_session->dlg);
706
707         if (status == PJ_SUCCESS && packet) {
708                 ast_sip_session_send_response(session, packet);
709         }
710
711 #ifdef HAVE_PJSIP_INV_SESSION_REF
712         pjsip_inv_dec_ref(session->inv_session);
713 #endif
714
715         if (status != PJ_SUCCESS) {
716                 char err[PJ_ERR_MSG_SIZE];
717
718                 pj_strerror(status, err, sizeof(err));
719                 ast_log(LOG_WARNING,"Cannot answer '%s': %s\n",
720                         ast_channel_name(session->channel), err);
721                 /*
722                  * Return this value so we can distinguish between this
723                  * failure and the threadpool synchronous push failing.
724                  */
725                 SCOPE_EXIT_RTN_VALUE(-2, "pjproject failure\n");
726         }
727         SCOPE_EXIT_RTN_VALUE(0);
728 }
729
730 /*! \brief Function called by core when we should answer a PJSIP session */
731 static int chan_pjsip_answer(struct ast_channel *ast)
732 {
733         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
734         struct ast_sip_session *session;
735         struct answer_data ans_data = { 0, };
736         int res;
737         SCOPE_ENTER(1, "%s\n", ast_channel_name(ast));
738
739         if (ast_channel_state(ast) == AST_STATE_UP) {
740                 SCOPE_EXIT_RTN_VALUE(0, "Already up\n");
741                 return 0;
742         }
743
744         ast_setstate(ast, AST_STATE_UP);
745         session = ao2_bump(channel->session);
746
747 #ifdef HAVE_PJSIP_INV_SESSION_REF
748         if (pjsip_inv_add_ref(session->inv_session) != PJ_SUCCESS) {
749                 ast_log(LOG_ERROR, "Couldn't increase the session reference counter\n");
750                 ao2_ref(session, -1);
751                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't increase the session reference counter\n");
752         }
753 #endif
754
755         /* the answer task needs to be pushed synchronously otherwise a race condition
756            can occur between this thread and bridging (specifically when native bridging
757            attempts to do direct media) */
758         ast_channel_unlock(ast);
759         ans_data.session = session;
760         ans_data.indent = ast_trace_get_indent();
761         res = ast_sip_push_task_wait_serializer(session->serializer, answer, &ans_data);
762         if (res) {
763                 if (res == -1) {
764                         ast_log(LOG_ERROR,"Cannot answer '%s': Unable to push answer task to the threadpool.\n",
765                                 ast_channel_name(session->channel));
766 #ifdef HAVE_PJSIP_INV_SESSION_REF
767                         pjsip_inv_dec_ref(session->inv_session);
768 #endif
769                 }
770                 ao2_ref(session, -1);
771                 ast_channel_lock(ast);
772                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't push task\n");
773         }
774         ao2_ref(session, -1);
775         ast_channel_lock(ast);
776
777         SCOPE_EXIT_RTN_VALUE(0);
778 }
779
780 /*! \brief Internal helper function called when CNG tone is detected */
781 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_channel *ast, struct ast_sip_session *session,
782         struct ast_frame *f)
783 {
784         const char *target_context;
785         int exists;
786         int dsp_features;
787
788         dsp_features = ast_dsp_get_features(session->dsp);
789         dsp_features &= ~DSP_FEATURE_FAX_DETECT;
790         if (dsp_features) {
791                 ast_dsp_set_features(session->dsp, dsp_features);
792         } else {
793                 ast_dsp_free(session->dsp);
794                 session->dsp = NULL;
795         }
796
797         /* If already executing in the fax extension don't do anything */
798         if (!strcmp(ast_channel_exten(ast), "fax")) {
799                 return f;
800         }
801
802         target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
803
804         /*
805          * We need to unlock the channel here because ast_exists_extension has the
806          * potential to start and stop an autoservice on the channel. Such action
807          * is prone to deadlock if the channel is locked.
808          *
809          * ast_async_goto() has its own restriction on not holding the channel lock.
810          */
811         ast_channel_unlock(ast);
812         ast_frfree(f);
813         f = &ast_null_frame;
814         exists = ast_exists_extension(ast, target_context, "fax", 1,
815                 S_COR(ast_channel_caller(ast)->id.number.valid,
816                         ast_channel_caller(ast)->id.number.str, NULL));
817         if (exists) {
818                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
819                         ast_channel_name(ast));
820                 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
821                 if (ast_async_goto(ast, target_context, "fax", 1)) {
822                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
823                                 ast_channel_name(ast), target_context);
824                 }
825         } else {
826                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
827                         ast_channel_name(ast), target_context);
828         }
829
830         /* It's possible for a masquerade to have occurred when doing the ast_async_goto resulting in
831          * the channel on the session having changed. Since we need to return with the original channel
832          * locked we lock the channel that was passed in and not session->channel.
833          */
834         ast_channel_lock(ast);
835
836         return f;
837 }
838
839 /*! \brief Determine if the given frame is in a format we've negotiated */
840 static int is_compatible_format(struct ast_sip_session *session, struct ast_frame *f)
841 {
842         struct ast_stream_topology *topology = session->active_media_state->topology;
843         struct ast_stream *stream = ast_stream_topology_get_stream(topology, f->stream_num);
844         const struct ast_format_cap *cap = ast_stream_get_formats(stream);
845
846         return ast_format_cap_iscompatible_format(cap, f->subclass.format) != AST_FORMAT_CMP_NOT_EQUAL;
847 }
848
849 /*!
850  * \brief Function called by core to read any waiting frames
851  *
852  * \note The channel is already locked.
853  */
854 static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast)
855 {
856         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
857         struct ast_sip_session *session = channel->session;
858         struct ast_sip_session_media_read_callback_state *callback_state;
859         struct ast_frame *f;
860         int fdno = ast_channel_fdno(ast) - AST_EXTENDED_FDS;
861         struct ast_frame *cur;
862
863         if (fdno >= AST_VECTOR_SIZE(&session->active_media_state->read_callbacks)) {
864                 return &ast_null_frame;
865         }
866
867         callback_state = AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, fdno);
868         f = callback_state->read_callback(session, callback_state->session);
869
870         if (!f) {
871                 return f;
872         }
873
874         for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
875                 if (cur->frametype == AST_FRAME_VOICE) {
876                         break;
877                 }
878         }
879
880         if (!cur || callback_state->session != session->active_media_state->default_session[callback_state->session->type]) {
881                 return f;
882         }
883
884         session = channel->session;
885
886         /*
887          * Asymmetric RTP only has one native format set at a time.
888          * Therefore we need to update the native format to the current
889          * raw read format BEFORE the native format check
890          */
891         if (!session->endpoint->asymmetric_rtp_codec &&
892                 ast_format_cmp(ast_channel_rawwriteformat(ast), cur->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL &&
893                 is_compatible_format(session, cur)) {
894                 struct ast_format_cap *caps;
895
896                 /* For maximum compatibility we ensure that the formats match that of the received media */
897                 ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when we're sending '%s', switching to match\n",
898                         ast_format_get_name(cur->subclass.format), ast_channel_name(ast),
899                         ast_format_get_name(ast_channel_rawwriteformat(ast)));
900
901                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
902                 if (caps) {
903                         ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(ast), AST_MEDIA_TYPE_UNKNOWN);
904                         ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO);
905                         ast_format_cap_append(caps, cur->subclass.format, 0);
906                         ast_channel_nativeformats_set(ast, caps);
907                         ao2_ref(caps, -1);
908                 }
909
910                 ast_set_write_format_path(ast, ast_channel_writeformat(ast), cur->subclass.format);
911                 ast_set_read_format_path(ast, ast_channel_readformat(ast), cur->subclass.format);
912
913                 if (ast_channel_is_bridged(ast)) {
914                         ast_channel_set_unbridged_nolock(ast, 1);
915                 }
916         }
917
918         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), cur->subclass.format)
919                         == AST_FORMAT_CMP_NOT_EQUAL) {
920                 ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when it has not been negotiated\n",
921                                 ast_format_get_name(cur->subclass.format), ast_channel_name(ast));
922                 ast_frfree(f);
923                 return &ast_null_frame;
924         }
925
926         if (session->dsp) {
927                 int dsp_features;
928
929                 dsp_features = ast_dsp_get_features(session->dsp);
930                 if ((dsp_features & DSP_FEATURE_FAX_DETECT)
931                         && session->endpoint->faxdetect_timeout
932                         && session->endpoint->faxdetect_timeout <= ast_channel_get_up_time(ast)) {
933                         dsp_features &= ~DSP_FEATURE_FAX_DETECT;
934                         if (dsp_features) {
935                                 ast_dsp_set_features(session->dsp, dsp_features);
936                         } else {
937                                 ast_dsp_free(session->dsp);
938                                 session->dsp = NULL;
939                         }
940                         ast_debug(3, "Channel driver fax CNG detection timeout on %s\n",
941                                 ast_channel_name(ast));
942                 }
943         }
944         if (session->dsp) {
945                 f = ast_dsp_process(ast, session->dsp, f);
946                 if (f && (f->frametype == AST_FRAME_DTMF)) {
947                         if (f->subclass.integer == 'f') {
948                                 ast_debug(3, "Channel driver fax CNG detected on %s\n",
949                                         ast_channel_name(ast));
950                                 f = chan_pjsip_cng_tone_detected(ast, session, f);
951                                 /* When chan_pjsip_cng_tone_detected returns it is possible for the
952                                  * channel pointed to by ast and by session->channel to differ due to a
953                                  * masquerade. It's best not to touch things after this.
954                                  */
955                         } else {
956                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
957                                         ast_channel_name(ast));
958                         }
959                 }
960         }
961
962         return f;
963 }
964
965 static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *frame)
966 {
967         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
968         struct ast_sip_session *session = channel->session;
969         struct ast_sip_session_media *media = NULL;
970         int res = 0;
971
972         /* The core provides a guarantee that the stream will exist when we are called if stream_num is provided */
973         if (stream_num >= 0) {
974                 /* What is not guaranteed is that a media session will exist */
975                 if (stream_num < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions)) {
976                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, stream_num);
977                 }
978         }
979
980         switch (frame->frametype) {
981         case AST_FRAME_VOICE:
982                 if (!media) {
983                         return 0;
984                 } else if (media->type != AST_MEDIA_TYPE_AUDIO) {
985                         ast_debug(3, "Channel %s stream %d is of type '%s', not audio!\n",
986                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
987                         return 0;
988                 } else if (media == channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO] &&
989                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
990                         struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
991                         struct ast_str *write_transpath = ast_str_alloca(256);
992                         struct ast_str *read_transpath = ast_str_alloca(256);
993
994                         ast_log(LOG_WARNING,
995                                 "Channel %s asked to send %s frame when native formats are %s (rd:%s->%s;%s wr:%s->%s;%s)\n",
996                                 ast_channel_name(ast),
997                                 ast_format_get_name(frame->subclass.format),
998                                 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
999                                 ast_format_get_name(ast_channel_rawreadformat(ast)),
1000                                 ast_format_get_name(ast_channel_readformat(ast)),
1001                                 ast_translate_path_to_str(ast_channel_readtrans(ast), &read_transpath),
1002                                 ast_format_get_name(ast_channel_writeformat(ast)),
1003                                 ast_format_get_name(ast_channel_rawwriteformat(ast)),
1004                                 ast_translate_path_to_str(ast_channel_writetrans(ast), &write_transpath));
1005                         return 0;
1006                 } else if (media->write_callback) {
1007                         res = media->write_callback(session, media, frame);
1008
1009                 }
1010                 break;
1011         case AST_FRAME_VIDEO:
1012                 if (!media) {
1013                         return 0;
1014                 } else if (media->type != AST_MEDIA_TYPE_VIDEO) {
1015                         ast_debug(3, "Channel %s stream %d is of type '%s', not video!\n",
1016                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
1017                         return 0;
1018                 } else if (media->write_callback) {
1019                         res = media->write_callback(session, media, frame);
1020                 }
1021                 break;
1022         case AST_FRAME_MODEM:
1023                 if (!media) {
1024                         return 0;
1025                 } else if (media->type != AST_MEDIA_TYPE_IMAGE) {
1026                         ast_debug(3, "Channel %s stream %d is of type '%s', not image!\n",
1027                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
1028                         return 0;
1029                 } else if (media->write_callback) {
1030                         res = media->write_callback(session, media, frame);
1031                 }
1032                 break;
1033         case AST_FRAME_CNG:
1034                 break;
1035         case AST_FRAME_RTCP:
1036                 /* We only support writing out feedback */
1037                 if (frame->subclass.integer != AST_RTP_RTCP_PSFB || !media) {
1038                         return 0;
1039                 } else if (media->type != AST_MEDIA_TYPE_VIDEO) {
1040                         ast_debug(3, "Channel %s stream %d is of type '%s', not video! Unable to write RTCP feedback.\n",
1041                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
1042                         return 0;
1043                 } else if (media->write_callback) {
1044                         res = media->write_callback(session, media, frame);
1045                 }
1046                 break;
1047         default:
1048                 ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
1049                 break;
1050         }
1051
1052         return res;
1053 }
1054
1055 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
1056 {
1057         return chan_pjsip_write_stream(ast, -1, frame);
1058 }
1059
1060 /*! \brief Function called by core to change the underlying owner channel */
1061 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1062 {
1063         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
1064
1065         if (channel->session->channel != oldchan) {
1066                 return -1;
1067         }
1068
1069         /*
1070          * The masquerade has suspended the channel's session
1071          * serializer so we can safely change it outside of
1072          * the serializer thread.
1073          */
1074         channel->session->channel = newchan;
1075
1076         set_channel_on_rtp_instance(channel->session, ast_channel_uniqueid(newchan));
1077
1078         return 0;
1079 }
1080
1081 /*! AO2 hash function for on hold UIDs */
1082 static int uid_hold_hash_fn(const void *obj, const int flags)
1083 {
1084         const char *key = obj;
1085
1086         switch (flags & OBJ_SEARCH_MASK) {
1087         case OBJ_SEARCH_KEY:
1088                 break;
1089         case OBJ_SEARCH_OBJECT:
1090                 break;
1091         default:
1092                 /* Hash can only work on something with a full key. */
1093                 ast_assert(0);
1094                 return 0;
1095         }
1096         return ast_str_hash(key);
1097 }
1098
1099 /*! AO2 sort function for on hold UIDs */
1100 static int uid_hold_sort_fn(const void *obj_left, const void *obj_right, const int flags)
1101 {
1102         const char *left = obj_left;
1103         const char *right = obj_right;
1104         int cmp;
1105
1106         switch (flags & OBJ_SEARCH_MASK) {
1107         case OBJ_SEARCH_OBJECT:
1108         case OBJ_SEARCH_KEY:
1109                 cmp = strcmp(left, right);
1110                 break;
1111         case OBJ_SEARCH_PARTIAL_KEY:
1112                 cmp = strncmp(left, right, strlen(right));
1113                 break;
1114         default:
1115                 /* Sort can only work on something with a full or partial key. */
1116                 ast_assert(0);
1117                 cmp = 0;
1118                 break;
1119         }
1120         return cmp;
1121 }
1122
1123 static struct ao2_container *pjsip_uids_onhold;
1124
1125 /*!
1126  * \brief Add a channel ID to the list of PJSIP channels on hold
1127  *
1128  * \param chan_uid - Unique ID of the channel being put into the hold list
1129  *
1130  * \retval 0 Channel has been added to or was already in the hold list
1131  * \retval -1 Failed to add channel to the hold list
1132  */
1133 static int chan_pjsip_add_hold(const char *chan_uid)
1134 {
1135         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1136
1137         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1138         if (hold_uid) {
1139                 /* Device is already on hold. Nothing to do. */
1140                 return 0;
1141         }
1142
1143         /* Device wasn't in hold list already. Create a new one. */
1144         hold_uid = ao2_alloc_options(strlen(chan_uid) + 1, NULL,
1145                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1146         if (!hold_uid) {
1147                 return -1;
1148         }
1149
1150         ast_copy_string(hold_uid, chan_uid, strlen(chan_uid) + 1);
1151
1152         if (ao2_link(pjsip_uids_onhold, hold_uid) == 0) {
1153                 return -1;
1154         }
1155
1156         return 0;
1157 }
1158
1159 /*!
1160  * \brief Remove a channel ID from the list of PJSIP channels on hold
1161  *
1162  * \param chan_uid - Unique ID of the channel being taken out of the hold list
1163  */
1164 static void chan_pjsip_remove_hold(const char *chan_uid)
1165 {
1166         ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
1167 }
1168
1169 /*!
1170  * \brief Determine whether a channel ID is in the list of PJSIP channels on hold
1171  *
1172  * \param chan_uid - Channel being checked
1173  *
1174  * \retval 0 The channel is not in the hold list
1175  * \retval 1 The channel is in the hold list
1176  */
1177 static int chan_pjsip_get_hold(const char *chan_uid)
1178 {
1179         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1180
1181         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1182         if (!hold_uid) {
1183                 return 0;
1184         }
1185
1186         return 1;
1187 }
1188
1189 /*! \brief Function called to get the device state of an endpoint */
1190 static int chan_pjsip_devicestate(const char *data)
1191 {
1192         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
1193         enum ast_device_state state = AST_DEVICE_UNKNOWN;
1194         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
1195         struct ast_devstate_aggregate aggregate;
1196         int num, inuse = 0;
1197
1198         if (!endpoint) {
1199                 return AST_DEVICE_INVALID;
1200         }
1201
1202         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
1203                 ast_endpoint_get_resource(endpoint->persistent));
1204
1205         if (!endpoint_snapshot) {
1206                 return AST_DEVICE_INVALID;
1207         }
1208
1209         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
1210                 state = AST_DEVICE_UNAVAILABLE;
1211         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
1212                 state = AST_DEVICE_NOT_INUSE;
1213         }
1214
1215         if (!endpoint_snapshot->num_channels) {
1216                 return state;
1217         }
1218
1219         ast_devstate_aggregate_init(&aggregate);
1220
1221         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
1222                 struct ast_channel_snapshot *snapshot;
1223
1224                 snapshot = ast_channel_snapshot_get_latest(endpoint_snapshot->channel_ids[num]);
1225                 if (!snapshot) {
1226                         continue;
1227                 }
1228
1229                 if (chan_pjsip_get_hold(snapshot->base->uniqueid)) {
1230                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
1231                 } else {
1232                         ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
1233                 }
1234
1235                 if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
1236                         (snapshot->state == AST_STATE_BUSY)) {
1237                         inuse++;
1238                 }
1239
1240                 ao2_ref(snapshot, -1);
1241         }
1242
1243         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
1244                 state = AST_DEVICE_BUSY;
1245         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
1246                 state = ast_devstate_aggregate_result(&aggregate);
1247         }
1248
1249         return state;
1250 }
1251
1252 /*! \brief Function called to query options on a channel */
1253 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
1254 {
1255         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1256         int res = -1;
1257         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1258
1259         if (!channel) {
1260                 return -1;
1261         }
1262
1263         switch (option) {
1264         case AST_OPTION_T38_STATE:
1265                 if (channel->session->endpoint->media.t38.enabled) {
1266                         switch (channel->session->t38state) {
1267                         case T38_LOCAL_REINVITE:
1268                         case T38_PEER_REINVITE:
1269                                 state = T38_STATE_NEGOTIATING;
1270                                 break;
1271                         case T38_ENABLED:
1272                                 state = T38_STATE_NEGOTIATED;
1273                                 break;
1274                         case T38_REJECTED:
1275                                 state = T38_STATE_REJECTED;
1276                                 break;
1277                         default:
1278                                 state = T38_STATE_UNKNOWN;
1279                                 break;
1280                         }
1281                 }
1282
1283                 *((enum ast_t38_state *) data) = state;
1284                 res = 0;
1285
1286                 break;
1287         default:
1288                 break;
1289         }
1290
1291         return res;
1292 }
1293
1294 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
1295 {
1296         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1297         char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);
1298
1299         if (!uniqueid) {
1300                 return "";
1301         }
1302
1303         ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);
1304
1305         return uniqueid;
1306 }
1307
1308 struct indicate_data {
1309         struct ast_sip_session *session;
1310         int condition;
1311         int response_code;
1312         void *frame_data;
1313         size_t datalen;
1314 };
1315
1316 static void indicate_data_destroy(void *obj)
1317 {
1318         struct indicate_data *ind_data = obj;
1319
1320         ast_free(ind_data->frame_data);
1321         ao2_ref(ind_data->session, -1);
1322 }
1323
1324 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
1325                 int condition, int response_code, const void *frame_data, size_t datalen)
1326 {
1327         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
1328
1329         if (!ind_data) {
1330                 return NULL;
1331         }
1332
1333         ind_data->frame_data = ast_malloc(datalen);
1334         if (!ind_data->frame_data) {
1335                 ao2_ref(ind_data, -1);
1336                 return NULL;
1337         }
1338
1339         memcpy(ind_data->frame_data, frame_data, datalen);
1340         ind_data->datalen = datalen;
1341         ind_data->condition = condition;
1342         ind_data->response_code = response_code;
1343         ao2_ref(session, +1);
1344         ind_data->session = session;
1345
1346         return ind_data;
1347 }
1348
1349 static int indicate(void *data)
1350 {
1351         pjsip_tx_data *packet = NULL;
1352         struct indicate_data *ind_data = data;
1353         struct ast_sip_session *session = ind_data->session;
1354         int response_code = ind_data->response_code;
1355
1356         if ((session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED) &&
1357                 (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS)) {
1358                 ast_sip_session_send_response(session, packet);
1359         }
1360
1361 #ifdef HAVE_PJSIP_INV_SESSION_REF
1362         pjsip_inv_dec_ref(session->inv_session);
1363 #endif
1364         ao2_ref(ind_data, -1);
1365
1366         return 0;
1367 }
1368
1369 /*! \brief Send SIP INFO with video update request */
1370 static int transmit_info_with_vidupdate(void *data)
1371 {
1372         const char * xml =
1373                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1374                 " <media_control>\r\n"
1375                 "  <vc_primitive>\r\n"
1376                 "   <to_encoder>\r\n"
1377                 "    <picture_fast_update/>\r\n"
1378                 "   </to_encoder>\r\n"
1379                 "  </vc_primitive>\r\n"
1380                 " </media_control>\r\n";
1381
1382         const struct ast_sip_body body = {
1383                 .type = "application",
1384                 .subtype = "media_control+xml",
1385                 .body_text = xml
1386         };
1387
1388         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1389         struct pjsip_tx_data *tdata;
1390
1391         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1392                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1393                         session->inv_session->cause,
1394                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1395                 goto failure;
1396         }
1397
1398         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1399                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1400                 goto failure;
1401         }
1402         if (ast_sip_add_body(tdata, &body)) {
1403                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1404                 goto failure;
1405         }
1406         ast_sip_session_send_request(session, tdata);
1407
1408 #ifdef HAVE_PJSIP_INV_SESSION_REF
1409         pjsip_inv_dec_ref(session->inv_session);
1410 #endif
1411
1412         return 0;
1413
1414 failure:
1415 #ifdef HAVE_PJSIP_INV_SESSION_REF
1416         pjsip_inv_dec_ref(session->inv_session);
1417 #endif
1418         return -1;
1419
1420 }
1421
1422 /*!
1423  * \internal
1424  * \brief TRUE if a COLP update can be sent to the peer.
1425  * \since 13.3.0
1426  *
1427  * \param session The session to see if the COLP update is allowed.
1428  *
1429  * \retval 0 Update is not allowed.
1430  * \retval 1 Update is allowed.
1431  */
1432 static int is_colp_update_allowed(struct ast_sip_session *session)
1433 {
1434         struct ast_party_id connected_id;
1435         int update_allowed = 0;
1436
1437         if (!session->endpoint->id.send_connected_line
1438                 || (!session->endpoint->id.send_pai && !session->endpoint->id.send_rpid)) {
1439                 return 0;
1440         }
1441
1442         /*
1443          * Check if privacy allows the update.  Check while the channel
1444          * is locked so we can work with the shallow connected_id copy.
1445          */
1446         ast_channel_lock(session->channel);
1447         connected_id = ast_channel_connected_effective_id(session->channel);
1448         if (connected_id.number.valid
1449                 && (session->endpoint->id.trust_outbound
1450                         || (ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED)) {
1451                 update_allowed = 1;
1452         }
1453         ast_channel_unlock(session->channel);
1454
1455         return update_allowed;
1456 }
1457
1458 /*! \brief Update connected line information */
1459 static int update_connected_line_information(void *data)
1460 {
1461         struct ast_sip_session *session = data;
1462
1463         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1464                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1465                         session->inv_session->cause,
1466                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1467 #ifdef HAVE_PJSIP_INV_SESSION_REF
1468                 pjsip_inv_dec_ref(session->inv_session);
1469 #endif
1470                 ao2_ref(session, -1);
1471                 return -1;
1472         }
1473
1474         if (ast_channel_state(session->channel) == AST_STATE_UP
1475                 || session->inv_session->role == PJSIP_ROLE_UAC) {
1476                 if (is_colp_update_allowed(session)) {
1477                         enum ast_sip_session_refresh_method method;
1478                         int generate_new_sdp;
1479
1480                         method = session->endpoint->id.refresh_method;
1481                         if (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE) {
1482                                 method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1483                         }
1484
1485                         /* Only the INVITE method actually needs SDP, UPDATE can do without */
1486                         generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
1487
1488                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
1489                 }
1490         } else if (session->endpoint->id.rpid_immediate
1491                 && session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
1492                 && is_colp_update_allowed(session)) {
1493                 int response_code = 0;
1494
1495                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1496                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1497                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1498                         response_code = 183;
1499                 }
1500
1501                 if (response_code) {
1502                         struct pjsip_tx_data *packet = NULL;
1503
1504                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1505                                 ast_sip_session_send_response(session, packet);
1506                         }
1507                 }
1508         }
1509
1510 #ifdef HAVE_PJSIP_INV_SESSION_REF
1511         pjsip_inv_dec_ref(session->inv_session);
1512 #endif
1513
1514         ao2_ref(session, -1);
1515         return 0;
1516 }
1517
1518 /*! \brief Callback which changes the value of locally held on the media stream */
1519 static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
1520 {
1521         if (session_media) {
1522                 session_media->locally_held = held;
1523         }
1524 }
1525
1526 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
1527 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
1528 {
1529         AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
1530         ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
1531         ao2_ref(session, -1);
1532
1533         return 0;
1534 }
1535
1536 /*! \brief Update local hold state to be held */
1537 static int remote_send_hold(void *data)
1538 {
1539         return remote_send_hold_refresh(data, 1);
1540 }
1541
1542 /*! \brief Update local hold state to be unheld */
1543 static int remote_send_unhold(void *data)
1544 {
1545         return remote_send_hold_refresh(data, 0);
1546 }
1547
1548 struct topology_change_refresh_data {
1549         struct ast_sip_session *session;
1550         struct ast_sip_session_media_state *media_state;
1551 };
1552
1553 static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
1554 {
1555         ao2_cleanup(refresh_data->session);
1556
1557         ast_sip_session_media_state_free(refresh_data->media_state);
1558         ast_free(refresh_data);
1559 }
1560
1561 static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
1562         struct ast_sip_session *session, const struct ast_stream_topology *topology)
1563 {
1564         struct topology_change_refresh_data *refresh_data;
1565
1566         refresh_data = ast_calloc(1, sizeof(*refresh_data));
1567         if (!refresh_data) {
1568                 return NULL;
1569         }
1570
1571         refresh_data->session = ao2_bump(session);
1572         refresh_data->media_state = ast_sip_session_media_state_alloc();
1573         if (!refresh_data->media_state) {
1574                 topology_change_refresh_data_free(refresh_data);
1575                 return NULL;
1576         }
1577         refresh_data->media_state->topology = ast_stream_topology_clone(topology);
1578         if (!refresh_data->media_state->topology) {
1579                 topology_change_refresh_data_free(refresh_data);
1580                 return NULL;
1581         }
1582
1583         return refresh_data;
1584 }
1585
1586 static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
1587 {
1588         SCOPE_ENTER(1, "%s Status code: %d\n", ast_sip_session_get_name(session),
1589                 rdata->msg_info.msg->line.status.code);
1590
1591         if (PJSIP_IS_STATUS_IN_CLASS(rdata->msg_info.msg->line.status.code, 200)) {
1592                 /* The topology was changed to something new so give notice to what requested
1593                  * it so it queries the channel and updates accordingly.
1594                  */
1595                 if (session->channel) {
1596                         ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
1597                 }
1598         } else if (300 <= rdata->msg_info.msg->line.status.code) {
1599                 /* The topology change failed, so drop the current pending media state */
1600                 ast_sip_session_media_state_reset(session->pending_media_state);
1601         }
1602
1603         SCOPE_EXIT_RTN_VALUE(0);
1604 }
1605
1606 static int send_topology_change_refresh(void *data)
1607 {
1608         struct topology_change_refresh_data *refresh_data = data;
1609         int ret;
1610         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(refresh_data->session));
1611
1612         ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
1613                 AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
1614         refresh_data->media_state = NULL;
1615         topology_change_refresh_data_free(refresh_data);
1616
1617         SCOPE_EXIT_RTN_VALUE(ret, "RC: %d\n", ret);
1618 }
1619
1620 static int handle_topology_request_change(struct ast_sip_session *session,
1621         const struct ast_stream_topology *proposed)
1622 {
1623         struct topology_change_refresh_data *refresh_data;
1624         int res;
1625         SCOPE_ENTER(1);
1626
1627         refresh_data = topology_change_refresh_data_alloc(session, proposed);
1628         if (!refresh_data) {
1629                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create refresh_data\n");
1630         }
1631
1632         res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
1633         if (res) {
1634                 topology_change_refresh_data_free(refresh_data);
1635         }
1636         SCOPE_EXIT_RTN_VALUE(res, "RC: %d\n", res);
1637 }
1638
1639 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1640 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1641 {
1642         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1643         struct ast_sip_session_media *media;
1644         int response_code = 0;
1645         int res = 0;
1646         char *device_buf;
1647         size_t device_buf_size;
1648         int i;
1649         const struct ast_stream_topology *topology;
1650         struct ast_frame f = { .frametype = AST_FRAME_CONTROL, .subclass = { .integer = condition } };
1651         char subclass[40] = "";
1652         SCOPE_ENTER(1, "%s Handling %s\n", ast_channel_name(ast),
1653                 ast_frame_subclass2str(&f, subclass, sizeof(subclass), NULL, 0));
1654
1655         switch (condition) {
1656         case AST_CONTROL_RINGING:
1657                 if (ast_channel_state(ast) == AST_STATE_RING) {
1658                         if (channel->session->endpoint->inband_progress ||
1659                                 (channel->session->inv_session && channel->session->inv_session->neg &&
1660                                 pjmedia_sdp_neg_get_state(channel->session->inv_session->neg) == PJMEDIA_SDP_NEG_STATE_DONE)) {
1661                                 response_code = 183;
1662                                 res = -1;
1663                         } else {
1664                                 response_code = 180;
1665                         }
1666                 } else {
1667                         res = -1;
1668                 }
1669                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1670                 break;
1671         case AST_CONTROL_BUSY:
1672                 if (ast_channel_state(ast) != AST_STATE_UP) {
1673                         response_code = 486;
1674                 } else {
1675                         res = -1;
1676                 }
1677                 break;
1678         case AST_CONTROL_CONGESTION:
1679                 if (ast_channel_state(ast) != AST_STATE_UP) {
1680                         response_code = 503;
1681                 } else {
1682                         res = -1;
1683                 }
1684                 break;
1685         case AST_CONTROL_INCOMPLETE:
1686                 if (ast_channel_state(ast) != AST_STATE_UP) {
1687                         response_code = 484;
1688                 } else {
1689                         res = -1;
1690                 }
1691                 break;
1692         case AST_CONTROL_PROCEEDING:
1693                 if (ast_channel_state(ast) != AST_STATE_UP) {
1694                         response_code = 100;
1695                 } else {
1696                         res = -1;
1697                 }
1698                 break;
1699         case AST_CONTROL_PROGRESS:
1700                 if (ast_channel_state(ast) != AST_STATE_UP) {
1701                         response_code = 183;
1702                 } else {
1703                         res = -1;
1704                 }
1705                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1706                 break;
1707         case AST_CONTROL_VIDUPDATE:
1708                 for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
1709                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
1710                         if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
1711                                 continue;
1712                         }
1713                         if (media->rtp) {
1714                                 /* FIXME: Only use this for VP8. Additional work would have to be done to
1715                                  * fully support other video codecs */
1716
1717                                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL ||
1718                                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp9) != AST_FORMAT_CMP_NOT_EQUAL ||
1719                                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h265) != AST_FORMAT_CMP_NOT_EQUAL ||
1720                                         (channel->session->endpoint->media.webrtc &&
1721                                          ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h264) != AST_FORMAT_CMP_NOT_EQUAL)) {
1722                                         /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1723                                          * RTP engine would provide a way to externally write/schedule RTCP
1724                                          * packets */
1725                                         struct ast_frame fr;
1726                                         fr.frametype = AST_FRAME_CONTROL;
1727                                         fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1728                                         res = ast_rtp_instance_write(media->rtp, &fr);
1729                                 } else {
1730                                         ao2_ref(channel->session, +1);
1731 #ifdef HAVE_PJSIP_INV_SESSION_REF
1732                                         if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1733                                                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1734                                                 ao2_cleanup(channel->session);
1735                                         } else {
1736 #endif
1737                                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1738                                                         ao2_cleanup(channel->session);
1739                                                 }
1740 #ifdef HAVE_PJSIP_INV_SESSION_REF
1741                                         }
1742 #endif
1743                                 }
1744                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1745                         } else {
1746                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1747                                 res = -1;
1748                         }
1749                 }
1750                 /* XXX If there were no video streams, then this should set
1751                  * res to -1
1752                  */
1753                 break;
1754         case AST_CONTROL_CONNECTED_LINE:
1755                 ao2_ref(channel->session, +1);
1756 #ifdef HAVE_PJSIP_INV_SESSION_REF
1757                 if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1758                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1759                         ao2_cleanup(channel->session);
1760                         SCOPE_EXIT_RTN_VALUE(-1, "Couldn't increase the session reference counter\n");
1761                 }
1762 #endif
1763                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1764 #ifdef HAVE_PJSIP_INV_SESSION_REF
1765                         pjsip_inv_dec_ref(channel->session->inv_session);
1766 #endif
1767                         ao2_cleanup(channel->session);
1768                 }
1769                 break;
1770         case AST_CONTROL_UPDATE_RTP_PEER:
1771                 break;
1772         case AST_CONTROL_PVT_CAUSE_CODE:
1773                 res = -1;
1774                 break;
1775         case AST_CONTROL_MASQUERADE_NOTIFY:
1776                 ast_assert(datalen == sizeof(int));
1777                 if (*(int *) data) {
1778                         /*
1779                          * Masquerade is beginning:
1780                          * Wait for session serializer to get suspended.
1781                          */
1782                         ast_channel_unlock(ast);
1783                         ast_sip_session_suspend(channel->session);
1784                         ast_channel_lock(ast);
1785                 } else {
1786                         /*
1787                          * Masquerade is complete:
1788                          * Unsuspend the session serializer.
1789                          */
1790                         ast_sip_session_unsuspend(channel->session);
1791                 }
1792                 break;
1793         case AST_CONTROL_HOLD:
1794                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1795                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1796                 device_buf = alloca(device_buf_size);
1797                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1798                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1799                 if (!channel->session->moh_passthrough) {
1800                         ast_moh_start(ast, data, NULL);
1801                 } else {
1802                         if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
1803                                 ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
1804                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1805                                 ao2_ref(channel->session, -1);
1806                         }
1807                 }
1808                 break;
1809         case AST_CONTROL_UNHOLD:
1810                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1811                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1812                 device_buf = alloca(device_buf_size);
1813                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1814                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1815                 if (!channel->session->moh_passthrough) {
1816                         ast_moh_stop(ast);
1817                 } else {
1818                         if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
1819                                 ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
1820                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1821                                 ao2_ref(channel->session, -1);
1822                         }
1823                 }
1824                 break;
1825         case AST_CONTROL_SRCUPDATE:
1826                 break;
1827         case AST_CONTROL_SRCCHANGE:
1828                 break;
1829         case AST_CONTROL_REDIRECTING:
1830                 if (ast_channel_state(ast) != AST_STATE_UP) {
1831                         response_code = 181;
1832                 } else {
1833                         res = -1;
1834                 }
1835                 break;
1836         case AST_CONTROL_T38_PARAMETERS:
1837                 res = 0;
1838
1839                 if (channel->session->t38state == T38_PEER_REINVITE) {
1840                         const struct ast_control_t38_parameters *parameters = data;
1841
1842                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1843                                 res = AST_T38_REQUEST_PARMS;
1844                         }
1845                 }
1846
1847                 break;
1848         case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1849                 topology = data;
1850                 res = handle_topology_request_change(channel->session, topology);
1851                 break;
1852         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
1853                 break;
1854         case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
1855                 break;
1856         case -1:
1857                 res = -1;
1858                 break;
1859         default:
1860                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1861                 res = -1;
1862                 break;
1863         }
1864
1865         if (response_code) {
1866                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1867
1868                 if (!ind_data) {
1869                         SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create indicate data\n");
1870                 }
1871 #ifdef HAVE_PJSIP_INV_SESSION_REF
1872                 if (pjsip_inv_add_ref(ind_data->session->inv_session) != PJ_SUCCESS) {
1873                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1874                         ao2_cleanup(ind_data);
1875                         SCOPE_EXIT_RTN_VALUE(-1, "Couldn't increase the session reference counter\n");
1876                 }
1877 #endif
1878                 if (ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1879                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1880                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1881 #ifdef HAVE_PJSIP_INV_SESSION_REF
1882                         pjsip_inv_dec_ref(ind_data->session->inv_session);
1883 #endif
1884                         ao2_cleanup(ind_data);
1885                         res = -1;
1886                 }
1887         }
1888
1889         SCOPE_EXIT_RTN_VALUE(res, "RC: %d\n", res);
1890 }
1891
1892 struct transfer_data {
1893         struct ast_sip_session *session;
1894         char *target;
1895 };
1896
1897 static void transfer_data_destroy(void *obj)
1898 {
1899         struct transfer_data *trnf_data = obj;
1900
1901         ast_free(trnf_data->target);
1902         ao2_cleanup(trnf_data->session);
1903 }
1904
1905 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1906 {
1907         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1908
1909         if (!trnf_data) {
1910                 return NULL;
1911         }
1912
1913         if (!(trnf_data->target = ast_strdup(target))) {
1914                 ao2_ref(trnf_data, -1);
1915                 return NULL;
1916         }
1917
1918         ao2_ref(session, +1);
1919         trnf_data->session = session;
1920
1921         return trnf_data;
1922 }
1923
1924 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1925 {
1926         pjsip_tx_data *packet;
1927         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1928         pjsip_contact_hdr *contact;
1929         pj_str_t tmp;
1930
1931         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS
1932                 || !packet) {
1933                 ast_log(LOG_WARNING, "Failed to redirect PJSIP session for channel %s\n",
1934                         ast_channel_name(session->channel));
1935                 message = AST_TRANSFER_FAILED;
1936                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1937
1938                 return;
1939         }
1940
1941         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1942                 contact = pjsip_contact_hdr_create(packet->pool);
1943         }
1944
1945         pj_strdup2_with_null(packet->pool, &tmp, target);
1946         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1947                 ast_log(LOG_WARNING, "Failed to parse destination URI '%s' for channel %s\n",
1948                         target, ast_channel_name(session->channel));
1949                 message = AST_TRANSFER_FAILED;
1950                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1951                 pjsip_tx_data_dec_ref(packet);
1952
1953                 return;
1954         }
1955         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1956
1957         ast_sip_session_send_response(session, packet);
1958         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1959 }
1960
1961 /*! \brief REFER Callback module, used to attach session data structure to subscription */
1962 static pjsip_module refer_callback_module = {
1963         .name = { "REFER Callback", 14 },
1964         .id = -1,
1965 };
1966
1967 /*!
1968  * \brief Callback function to report status of implicit REFER-NOTIFY subscription.
1969  *
1970  * This function will be called on any state change in the REFER-NOTIFY subscription.
1971  * Its primary purpose is to report SUCCESS/FAILURE of a transfer initiated via
1972  * \ref transfer_refer as well as to terminate the subscription, if necessary.
1973  */
1974 static void xfer_client_on_evsub_state(pjsip_evsub *sub, pjsip_event *event)
1975 {
1976         struct ast_sip_session *session;
1977         struct ast_channel *chan = NULL;
1978         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1979         int res = 0;
1980
1981         if (!event) {
1982                 return;
1983         }
1984
1985         session = pjsip_evsub_get_mod_data(sub, refer_callback_module.id);
1986         if (!session) {
1987                 return;
1988         }
1989
1990         chan = session->channel;
1991         if (!chan) {
1992                 return;
1993         }
1994
1995         if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACCEPTED) {
1996                 /* Check if subscription is suppressed and terminate and send completion code, if so. */
1997                 pjsip_rx_data *rdata;
1998                 pjsip_generic_string_hdr *refer_sub;
1999                 const pj_str_t REFER_SUB = { "Refer-Sub", 9 };
2000
2001                 ast_debug(3, "Transfer accepted on channel %s\n", ast_channel_name(chan));
2002
2003                 /* Check if response message */
2004                 if (event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
2005                         rdata = event->body.tsx_state.src.rdata;
2006
2007                         /* Find Refer-Sub header */
2008                         refer_sub = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &REFER_SUB, NULL);
2009
2010                         /* Check if subscription is suppressed. If it is, the far end will not terminate it,
2011                          * and the subscription will remain active until it times out.  Terminating it here
2012                          * eliminates the unnecessary timeout.
2013                          */
2014                         if (refer_sub && !pj_stricmp2(&refer_sub->hvalue, "false")) {
2015                                 /* Since no subscription is desired, assume that call has been transferred successfully. */
2016                                 /* Terminate subscription. */
2017                                 pjsip_evsub_terminate(sub, PJ_TRUE);
2018                                 res = -1;
2019                         }
2020                 }
2021         } else if (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_ACTIVE ||
2022                         pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED) {
2023                 /* Check for NOTIFY complete or error. */
2024                 pjsip_msg *msg;
2025                 pjsip_msg_body *body;
2026                 pjsip_status_line status_line = { .code = 0 };
2027                 pj_bool_t is_last;
2028                 pj_status_t status;
2029
2030                 if (event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
2031                         pjsip_rx_data *rdata;
2032
2033                         rdata = event->body.tsx_state.src.rdata;
2034                         msg = rdata->msg_info.msg;
2035
2036                         if (!pjsip_method_cmp(&msg->line.req.method, pjsip_get_notify_method())) {
2037                                 body = msg->body;
2038                                 if (body && !pj_stricmp2(&body->content_type.type, "message")
2039                                         && !pj_stricmp2(&body->content_type.subtype, "sipfrag")) {
2040                                         pjsip_parse_status_line((char *)body->data, body->len, &status_line);
2041                                 }
2042                         }
2043                 } else {
2044                         status_line.code = 500;
2045                         status_line.reason = *pjsip_get_status_text(500);
2046                 }
2047
2048                 is_last = (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED);
2049                 /* If the status code is >= 200, the subscription is finished. */
2050                 if (status_line.code >= 200 || is_last) {
2051                         res = -1;
2052
2053                         /* If the subscription has terminated, return AST_TRANSFER_SUCCESS for 2XX.
2054                          * Any other status code returns AST_TRANSFER_FAILED.
2055                          * The subscription should not terminate for any code < 200,
2056                          * but if it does, that constitutes a failure. */
2057                         if (status_line.code < 200 || status_line.code >= 300) {
2058                                 message = AST_TRANSFER_FAILED;
2059                         }
2060                         /* If subscription not terminated and subscription is finished (status code >= 200)
2061                          * terminate it */
2062                         if (!is_last) {
2063                                 pjsip_tx_data *tdata;
2064
2065                                 status = pjsip_evsub_initiate(sub, pjsip_get_subscribe_method(), 0, &tdata);
2066                                 if (status == PJ_SUCCESS) {
2067                                         pjsip_evsub_send_request(sub, tdata);
2068                                 }
2069                         }
2070                         /* Finished. Remove session from subscription */
2071                         pjsip_evsub_set_mod_data(sub, refer_callback_module.id, NULL);
2072                         ast_debug(3, "Transfer channel %s completed: %d %.*s (%s)\n",
2073                                         ast_channel_name(chan),
2074                                         status_line.code,
2075                                         (int)status_line.reason.slen, status_line.reason.ptr,
2076                                         (message == AST_TRANSFER_SUCCESS) ? "Success" : "Failure");
2077                 }
2078         }
2079
2080         if (res) {
2081                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
2082         }
2083 }
2084
2085 static void transfer_refer(struct ast_sip_session *session, const char *target)
2086 {
2087         pjsip_evsub *sub;
2088         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
2089         pj_str_t tmp;
2090         pjsip_tx_data *packet;
2091         const char *ref_by_val;
2092         char local_info[pj_strlen(&session->inv_session->dlg->local.info_str) + 1];
2093         struct pjsip_evsub_user xfer_cb;
2094
2095         pj_bzero(&xfer_cb, sizeof(xfer_cb));
2096         xfer_cb.on_evsub_state = &xfer_client_on_evsub_state;
2097
2098         if (pjsip_xfer_create_uac(session->inv_session->dlg, &xfer_cb, &sub) != PJ_SUCCESS) {
2099                 message = AST_TRANSFER_FAILED;
2100                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
2101
2102                 return;
2103         }
2104
2105         pjsip_evsub_set_mod_data(sub, refer_callback_module.id, session);
2106
2107         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
2108                 message = AST_TRANSFER_FAILED;
2109                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
2110                 pjsip_evsub_terminate(sub, PJ_FALSE);
2111
2112                 return;
2113         }
2114
2115         ref_by_val = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
2116         if (!ast_strlen_zero(ref_by_val)) {
2117                 ast_sip_add_header(packet, "Referred-By", ref_by_val);
2118         } else {
2119                 ast_copy_pj_str(local_info, &session->inv_session->dlg->local.info_str, sizeof(local_info));
2120                 ast_sip_add_header(packet, "Referred-By", local_info);
2121         }
2122
2123         pjsip_xfer_send_request(sub, packet);
2124 }
2125
2126 static int transfer(void *data)
2127 {
2128         struct transfer_data *trnf_data = data;
2129         struct ast_sip_endpoint *endpoint = NULL;
2130         struct ast_sip_contact *contact = NULL;
2131         const char *target = trnf_data->target;
2132
2133         if (trnf_data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2134                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2135                         trnf_data->session->inv_session->cause,
2136                         pjsip_get_status_text(trnf_data->session->inv_session->cause)->ptr);
2137         } else {
2138                 /* See if we have an endpoint; if so, use its contact */
2139                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", target);
2140                 if (endpoint) {
2141                         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
2142                         if (contact && !ast_strlen_zero(contact->uri)) {
2143                                 target = contact->uri;
2144                         }
2145                 }
2146
2147                 if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
2148                         transfer_redirect(trnf_data->session, target);
2149                 } else {
2150                         transfer_refer(trnf_data->session, target);
2151                 }
2152         }
2153
2154 #ifdef HAVE_PJSIP_INV_SESSION_REF
2155         pjsip_inv_dec_ref(trnf_data->session->inv_session);
2156 #endif
2157
2158         ao2_ref(trnf_data, -1);
2159         ao2_cleanup(endpoint);
2160         ao2_cleanup(contact);
2161         return 0;
2162 }
2163
2164 /*! \brief Function called by core for Asterisk initiated transfer */
2165 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
2166 {
2167         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
2168         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
2169
2170         if (!trnf_data) {
2171                 return -1;
2172         }
2173
2174 #ifdef HAVE_PJSIP_INV_SESSION_REF
2175         if (pjsip_inv_add_ref(trnf_data->session->inv_session) != PJ_SUCCESS) {
2176                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2177                 ao2_cleanup(trnf_data);
2178                 return -1;
2179         }
2180 #endif
2181
2182         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
2183                 ast_log(LOG_WARNING, "Error requesting transfer\n");
2184 #ifdef HAVE_PJSIP_INV_SESSION_REF
2185                 pjsip_inv_dec_ref(trnf_data->session->inv_session);
2186 #endif
2187                 ao2_cleanup(trnf_data);
2188                 return -1;
2189         }
2190
2191         return 0;
2192 }
2193
2194 /*! \brief Function called by core to start a DTMF digit */
2195 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
2196 {
2197         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
2198         struct ast_sip_session_media *media;
2199
2200         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
2201
2202         switch (channel->session->dtmf) {
2203         case AST_SIP_DTMF_RFC_4733:
2204                 if (!media || !media->rtp) {
2205                         return 0;
2206                 }
2207
2208                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2209                 break;
2210         case AST_SIP_DTMF_AUTO:
2211                 if (!media || !media->rtp) {
2212                         return 0;
2213                 }
2214
2215                 if (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND) {
2216                         return -1;
2217                 }
2218
2219                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2220                 break;
2221         case AST_SIP_DTMF_AUTO_INFO:
2222                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_NONE)) {
2223                         return 0;
2224                 }
2225                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2226                 break;
2227         case AST_SIP_DTMF_NONE:
2228                 break;
2229         case AST_SIP_DTMF_INBAND:
2230                 return -1;
2231         default:
2232                 break;
2233         }
2234
2235         return 0;
2236 }
2237
2238 struct info_dtmf_data {
2239         struct ast_sip_session *session;
2240         char digit;
2241         unsigned int duration;
2242 };
2243
2244 static void info_dtmf_data_destroy(void *obj)
2245 {
2246         struct info_dtmf_data *dtmf_data = obj;
2247         ao2_ref(dtmf_data->session, -1);
2248 }
2249
2250 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
2251 {
2252         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
2253         if (!dtmf_data) {
2254                 return NULL;
2255         }
2256         ao2_ref(session, +1);
2257         dtmf_data->session = session;
2258         dtmf_data->digit = digit;
2259         dtmf_data->duration = duration;
2260         return dtmf_data;
2261 }
2262
2263 static int transmit_info_dtmf(void *data)
2264 {
2265         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
2266
2267         struct ast_sip_session *session = dtmf_data->session;
2268         struct pjsip_tx_data *tdata;
2269
2270         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
2271
2272         struct ast_sip_body body = {
2273                 .type = "application",
2274                 .subtype = "dtmf-relay",
2275         };
2276
2277         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2278                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2279                         session->inv_session->cause,
2280                         pjsip_get_status_text(session->inv_session->cause)->ptr);
2281                 goto failure;
2282         }
2283
2284         if (!(body_text = ast_str_create(32))) {
2285                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
2286                 goto failure;
2287         }
2288         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
2289
2290         body.body_text = ast_str_buffer(body_text);
2291
2292         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
2293                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
2294                 goto failure;
2295         }
2296         if (ast_sip_add_body(tdata, &body)) {
2297                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
2298                 pjsip_tx_data_dec_ref(tdata);
2299                 goto failure;
2300         }
2301         ast_sip_session_send_request(session, tdata);
2302
2303 #ifdef HAVE_PJSIP_INV_SESSION_REF
2304         pjsip_inv_dec_ref(session->inv_session);
2305 #endif
2306
2307         return 0;
2308
2309 failure:
2310 #ifdef HAVE_PJSIP_INV_SESSION_REF
2311         pjsip_inv_dec_ref(session->inv_session);
2312 #endif
2313         return -1;
2314
2315 }
2316
2317 /*! \brief Function called by core to stop a DTMF digit */
2318 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2319 {
2320         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2321         struct ast_sip_session_media *media;
2322
2323         if (!channel || !channel->session) {
2324                 /* This happens when the channel is hungup while a DTMF digit is playing. See ASTERISK-28086 */
2325                 ast_debug(3, "Channel %s disappeared while calling digit_end\n", ast_channel_name(ast));
2326                 return -1;
2327         }
2328
2329         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
2330
2331         switch (channel->session->dtmf) {
2332         case AST_SIP_DTMF_AUTO_INFO:
2333         {
2334                 if (!media || !media->rtp) {
2335                         return 0;
2336                 }
2337
2338                 if (ast_rtp_instance_dtmf_mode_get(media->rtp) != AST_RTP_DTMF_MODE_NONE) {
2339                         ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 negotiated so using it.\n", ast_channel_name(ast));
2340                         ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2341                         break;
2342                 }
2343                 /* If RFC_4733 was not negotiated, fail through to the DTMF_INFO processing */
2344                 ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 NOT negotiated using INFO instead.\n", ast_channel_name(ast));
2345         }
2346
2347         case AST_SIP_DTMF_INFO:
2348         {
2349                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
2350
2351                 if (!dtmf_data) {
2352                         return -1;
2353                 }
2354
2355 #ifdef HAVE_PJSIP_INV_SESSION_REF
2356                 if (pjsip_inv_add_ref(dtmf_data->session->inv_session) != PJ_SUCCESS) {
2357                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2358                         ao2_cleanup(dtmf_data);
2359                         return -1;
2360                 }
2361 #endif
2362
2363                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
2364                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
2365 #ifdef HAVE_PJSIP_INV_SESSION_REF
2366                         pjsip_inv_dec_ref(dtmf_data->session->inv_session);
2367 #endif
2368                         ao2_cleanup(dtmf_data);
2369                         return -1;
2370                 }
2371                 break;
2372         }
2373         case AST_SIP_DTMF_RFC_4733:
2374                 if (!media || !media->rtp) {
2375                         return 0;
2376                 }
2377
2378                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2379                 break;
2380         case AST_SIP_DTMF_AUTO:
2381                 if (!media || !media->rtp) {
2382                         return 0;
2383                 }
2384
2385                 if (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND) {
2386                          return -1;
2387                 }
2388
2389                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2390                 break;
2391         case AST_SIP_DTMF_NONE:
2392                 break;
2393         case AST_SIP_DTMF_INBAND:
2394                 return -1;
2395         }
2396
2397         return 0;
2398 }
2399
2400 static void update_initial_connected_line(struct ast_sip_session *session)
2401 {
2402         struct ast_party_connected_line connected;
2403
2404         /*
2405          * Use the channel CALLERID() as the initial connected line data.
2406          * The core or a predial handler may have supplied missing values
2407          * from the session->endpoint->id.self about who we are calling.
2408          */
2409         ast_channel_lock(session->channel);
2410         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
2411         ast_channel_unlock(session->channel);
2412
2413         /* Supply initial connected line information if available. */
2414         if (!session->id.number.valid && !session->id.name.valid) {
2415                 return;
2416         }
2417
2418         ast_party_connected_line_init(&connected);
2419         connected.id = session->id;
2420         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2421
2422         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
2423 }
2424
2425 static int call(void *data)
2426 {
2427         struct ast_sip_channel_pvt *channel = data;
2428         struct ast_sip_session *session = channel->session;
2429         pjsip_tx_data *tdata;
2430         int res = 0;
2431         SCOPE_ENTER(1, "%s Topology: %s\n",
2432                 ast_sip_session_get_name(session),
2433                 ast_str_tmp(256, ast_stream_topology_to_str(channel->session->pending_media_state->topology, &STR_TMP))
2434                 );
2435
2436
2437         res = ast_sip_session_create_invite(session, &tdata);
2438
2439         if (res) {
2440                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2441                 ast_queue_hangup(session->channel);
2442         } else {
2443                 set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
2444                 update_initial_connected_line(session);
2445                 ast_sip_session_send_request(session, tdata);
2446         }
2447         ao2_ref(channel, -1);
2448         SCOPE_EXIT_RTN_VALUE(res, "RC: %d\n", res);
2449 }
2450
2451 /*! \brief Function called by core to actually start calling a remote party */
2452 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
2453 {
2454         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2455         SCOPE_ENTER(1, "%s Topology: %s\n", ast_sip_session_get_name(channel->session),
2456                 ast_str_tmp(256, ast_stream_topology_to_str(channel->session->pending_media_state->topology, &STR_TMP)));
2457
2458         ao2_ref(channel, +1);
2459         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
2460                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
2461                 ao2_cleanup(channel);
2462                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't push task\n");
2463         }
2464
2465         SCOPE_EXIT_RTN_VALUE(0, "'call' task pushed\n");
2466 }
2467
2468 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
2469 static int hangup_cause2sip(int cause)
2470 {
2471         switch (cause) {
2472         case AST_CAUSE_UNALLOCATED:             /* 1 */
2473         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2474         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2475                 return 404;
2476         case AST_CAUSE_CONGESTION:              /* 34 */
2477         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2478                 return 503;
2479         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2480                 return 408;
2481         case AST_CAUSE_NO_ANSWER:               /* 19 */
2482         case AST_CAUSE_UNREGISTERED:        /* 20 */
2483                 return 480;
2484         case AST_CAUSE_CALL_REJECTED:           /* 21 */
2485                 return 403;
2486         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2487                 return 410;
2488         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2489                 return 480;
2490         case AST_CAUSE_INVALID_NUMBER_FORMAT:
2491                 return 484;
2492         case AST_CAUSE_USER_BUSY:
2493                 return 486;
2494         case AST_CAUSE_FAILURE:
2495                 return 500;
2496         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2497                 return 501;
2498         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2499                 return 503;
2500         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2501                 return 502;
2502         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2503                 return 488;
2504         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
2505                 return 500;
2506         case AST_CAUSE_NOTDEFINED:
2507         default:
2508                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
2509                 return 0;
2510         }
2511
2512         /* Never reached */
2513         return 0;
2514 }
2515
2516 struct hangup_data {
2517         int cause;
2518         struct ast_channel *chan;
2519 };
2520
2521 static void hangup_data_destroy(void *obj)
2522 {
2523         struct hangup_data *h_data = obj;
2524
2525         h_data->chan = ast_channel_unref(h_data->chan);
2526 }
2527
2528 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
2529 {
2530         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
2531
2532         if (!h_data) {
2533                 return NULL;
2534         }
2535
2536         h_data->cause = cause;
2537         h_data->chan = ast_channel_ref(chan);
2538
2539         return h_data;
2540 }
2541
2542 /*! \brief Clear a channel from a session along with its PVT */
2543 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
2544 {
2545         session->channel = NULL;
2546         set_channel_on_rtp_instance(session, "");
2547         ast_channel_tech_pvt_set(ast, NULL);
2548 }
2549
2550 static int hangup(void *data)
2551 {
2552         struct hangup_data *h_data = data;
2553         struct ast_channel *ast = h_data->chan;
2554         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2555         SCOPE_ENTER(1, "%s\n", ast_channel_name(ast));
2556
2557         /*
2558          * Before cleaning we have to ensure that channel or its session is not NULL
2559          * we have seen rare case when taskprocessor calls hangup but channel is NULL
2560          * due to SIP session timeout and answer happening at the same time
2561          */
2562         if (channel) {
2563                 struct ast_sip_session *session = channel->session;
2564                 if (session) {
2565                         int cause = h_data->cause;
2566
2567                         /*
2568                         * It's possible that session_terminate might cause the session to be destroyed
2569                         * immediately so we need to keep a reference to it so we can NULL session->channel
2570                         * afterwards.
2571                         */
2572                         ast_sip_session_terminate(ao2_bump(session), cause);
2573                         clear_session_and_channel(session, ast);
2574                         ao2_cleanup(session);
2575                 }
2576                 ao2_cleanup(channel);
2577         }
2578         ao2_cleanup(h_data);
2579         SCOPE_EXIT_RTN_VALUE(0);
2580 }
2581
2582 /*! \brief Function called by core to hang up a PJSIP session */
2583 static int chan_pjsip_hangup(struct ast_channel *ast)
2584 {
2585         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2586         int cause;
2587         struct hangup_data *h_data;
2588         SCOPE_ENTER(1, "%s\n", ast_channel_name(ast));
2589
2590         if (!channel || !channel->session) {
2591                 SCOPE_EXIT_RTN_VALUE(-1, "No channel or session\n");
2592         }
2593
2594         cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
2595         h_data = hangup_data_alloc(cause, ast);
2596
2597         if (!h_data) {
2598                 goto failure;
2599         }
2600
2601         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
2602                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
2603                 goto failure;
2604         }
2605
2606         SCOPE_EXIT_RTN_VALUE(0, "Cause: %d\n", cause);
2607
2608 failure:
2609         /* Go ahead and do our cleanup of the session and channel even if we're not going
2610          * to be able to send our SIP request/response
2611          */
2612         clear_session_and_channel(channel->session, ast);
2613         ao2_cleanup(channel);
2614         ao2_cleanup(h_data);
2615
2616         SCOPE_EXIT_RTN_VALUE(-1, "Cause: %d\n", cause);
2617 }
2618
2619 struct request_data {
2620         struct ast_sip_session *session;
2621         struct ast_stream_topology *topology;
2622         const char *dest;
2623         int cause;
2624 };
2625
2626 static int request(void *obj)
2627 {
2628         struct request_data *req_data = obj;
2629         struct ast_sip_session *session = NULL;
2630         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
2631         struct ast_sip_endpoint *endpoint;
2632
2633         AST_DECLARE_APP_ARGS(args,
2634                 AST_APP_ARG(endpoint);
2635                 AST_APP_ARG(aor);
2636         );
2637         SCOPE_ENTER(1, "%s\n",tmp);
2638
2639         if (ast_strlen_zero(tmp)) {
2640                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
2641                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2642                 SCOPE_EXIT_RTN_VALUE(-1, "Empty destination\n");
2643         }
2644
2645         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
2646
2647         if (ast_sip_get_disable_multi_domain()) {
2648                 /* If a request user has been specified extract it from the endpoint name portion */
2649                 if ((endpoint_name = strchr(args.endpoint, '@'))) {
2650                         request_user = args.endpoint;
2651                         *endpoint_name++ = '\0';
2652                 } else {
2653                         endpoint_name = args.endpoint;
2654                 }
2655
2656                 if (ast_strlen_zero(endpoint_name)) {
2657                         if (request_user) {
2658                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2659                                         request_user);
2660                         } else {
2661                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2662                         }
2663                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2664                         SCOPE_EXIT_RTN_VALUE(-1, "Empty endpoint name\n");
2665                 }
2666                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2667                         endpoint_name);
2668                 if (!endpoint) {
2669                         ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2670                         req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2671                         SCOPE_EXIT_RTN_VALUE(-1, "Endpoint not found\n");
2672                 }
2673         } else {
2674                 /* First try to find an exact endpoint match, for single (user) or multi-domain (user@domain) */
2675                 endpoint_name = args.endpoint;
2676                 if (ast_strlen_zero(endpoint_name)) {
2677                         ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2678                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2679                         SCOPE_EXIT_RTN_VALUE(-1, "Empty endpoint name\n");
2680                 }
2681                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2682                         endpoint_name);
2683                 if (!endpoint) {
2684                         /* It seems it's not a multi-domain endpoint or single endpoint exact match,
2685                          * it's possible that it's a SIP trunk with a specified user (user@trunkname),
2686                          * so extract the user before @ sign.
2687                          */
2688                         endpoint_name = strchr(args.endpoint, '@');
2689                         if (!endpoint_name) {
2690                                 /*
2691                                  * Couldn't find an '@' so it had to be an endpoint
2692                                  * name that doesn't exist.
2693                                  */
2694                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n",
2695                                         args.endpoint);
2696                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2697                                 SCOPE_EXIT_RTN_VALUE(-1, "Endpoint not found\n");
2698                         }
2699                         request_user = args.endpoint;
2700                         *endpoint_name++ = '\0';
2701
2702                         if (ast_strlen_zero(endpoint_name)) {
2703                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2704                                         request_user);
2705                                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2706                                 SCOPE_EXIT_RTN_VALUE(-1, "Empty endpoint name\n");
2707                         }
2708
2709                         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2710                                 endpoint_name);
2711                         if (!endpoint) {
2712                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2713                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2714                                 SCOPE_EXIT_RTN_VALUE(-1, "Endpoint not found\n");
2715                         }
2716                 }
2717         }
2718
2719         session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user,
2720                 req_data->topology);
2721         ao2_ref(endpoint, -1);
2722         if (!session) {
2723                 ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
2724                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2725                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create session\n");
2726         }
2727
2728         req_data->session = session;
2729
2730         SCOPE_EXIT_RTN_VALUE(0);
2731 }
2732
2733 /*! \brief Function called by core to create a new outgoing PJSIP session */
2734 static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
2735 {
2736         struct request_data req_data;
2737         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2738         SCOPE_ENTER(1, "%s Topology: %s\n", data,
2739                 ast_str_tmp(256, ast_stream_topology_to_str(topology, &STR_TMP)));
2740
2741         req_data.topology = topology;
2742         req_data.dest = data;
2743         /* Default failure value in case ast_sip_push_task_wait_servant() itself fails. */
2744         req_data.cause = AST_CAUSE_FAILURE;
2745
2746         if (ast_sip_push_task_wait_servant(NULL, request, &req_data)) {
2747                 *cause = req_data.cause;
2748                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't push task\n");
2749         }
2750
2751         session = req_data.session;
2752
2753         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
2754                 /* Session needs to be terminated prematurely */
2755                 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create channel\n");
2756         }
2757
2758         SCOPE_EXIT_RTN_VALUE(session->channel, "Channel: %s\n", ast_channel_name(session->channel));
2759 }
2760
2761 static struct ast_channel *chan_pjsip_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
2762 {
2763         struct ast_stream_topology *topology;
2764         struct ast_channel *chan;
2765
2766         topology = ast_stream_topology_create_from_format_cap(cap);
2767         if (!topology) {
2768                 return NULL;
2769         }
2770
2771         chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
2772
2773         ast_stream_topology_free(topology);
2774
2775         return chan;
2776 }
2777
2778 struct sendtext_data {
2779         struct ast_sip_session *session;
2780         struct ast_msg_data *msg;
2781 };
2782
2783 static void sendtext_data_destroy(void *obj)
2784 {
2785         struct sendtext_data *data = obj;
2786         ao2_cleanup(data->session);
2787         ast_free(data->msg);
2788 }
2789
2790 static struct sendtext_data* sendtext_data_create(struct ast_channel *chan,
2791         struct ast_msg_data *msg)
2792 {
2793         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
2794         struct sendtext_data *data = ao2_alloc(sizeof(*data), sendtext_data_destroy);
2795
2796         if (!data) {
2797                 return NULL;
2798         }
2799
2800         data->msg = ast_msg_data_dup(msg);
2801         if (!data->msg) {
2802                 ao2_cleanup(data);
2803                 return NULL;
2804         }
2805         data->session = channel->session;
2806         ao2_ref(data->session, +1);
2807
2808         return data;
2809 }
2810
2811 static int sendtext(void *obj)
2812 {
2813         struct sendtext_data *data = obj;
2814         pjsip_tx_data *tdata;
2815         const char *body_text = ast_msg_data_get_attribute(data->msg, AST_MSG_DATA_ATTR_BODY);
2816         const char *content_type = ast_msg_data_get_attribute(data->msg, AST_MSG_DATA_ATTR_CONTENT_TYPE);
2817         char *sep;
2818         struct ast_sip_body body = {
2819                 .type = "text",
2820                 .subtype = "plain",
2821                 .body_text = body_text,
2822         };
2823
2824         if (!ast_strlen_zero(content_type)) {
2825                 sep = strchr(content_type, '/');
2826                 if (sep) {
2827                         *sep = '\0';
2828                         body.type = content_type;
2829                         body.subtype = ++sep;
2830                 }
2831         }
2832
2833         if (data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2834                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2835                         data->session->inv_session->cause,
2836                         pjsip_get_status_text(data->session->inv_session->cause)->ptr);
2837         } else {
2838                 pjsip_from_hdr *hdr;
2839                 pjsip_name_addr *name_addr;
2840                 const char *from = ast_msg_data_get_attribute(data->msg, AST_MSG_DATA_ATTR_FROM);
2841                 const char *to = ast_msg_data_get_attribute(data->msg, AST_MSG_DATA_ATTR_TO);
2842                 int invalidate_tdata = 0;
2843
2844                 ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
2845                 ast_sip_add_body(tdata, &body);
2846
2847                 /*
2848                  * If we have a 'from' in the msg, set the display name in the From
2849                  * header to it.
2850                  */
2851                 if (!ast_strlen_zero(from)) {
2852                         hdr = PJSIP_MSG_FROM_HDR(tdata->msg);
2853                         name_addr = (pjsip_name_addr *) hdr->uri;
2854                         pj_strdup2(tdata->pool, &name_addr->display, from);
2855                         invalidate_tdata = 1;
2856                 }
2857
2858                 /*
2859                  * If we have a 'to' in the msg, set the display name in the To
2860                  * header to it.
2861                  */
2862                 if (!ast_strlen_zero(to)) {
2863                         hdr = PJSIP_MSG_TO_HDR(tdata->msg);
2864                         name_addr = (pjsip_name_addr *) hdr->uri;
2865                         pj_strdup2(tdata->pool, &name_addr->display, to);
2866                         invalidate_tdata = 1;
2867                 }
2868
2869                 if (invalidate_tdata) {
2870                         pjsip_tx_data_invalidate_msg(tdata);
2871                 }
2872
2873                 ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
2874         }
2875
2876 #ifdef HAVE_PJSIP_INV_SESSION_REF
2877         pjsip_inv_dec_ref(data->session->inv_session);
2878 #endif
2879
2880         ao2_cleanup(data);
2881
2882         return 0;
2883 }
2884
2885 /*! \brief Function called by core to send text on PJSIP session */
2886 static int chan_pjsip_sendtext_data(struct ast_channel *ast, struct ast_msg_data *msg)
2887 {
2888         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2889         struct sendtext_data *data = sendtext_data_create(ast, msg);
2890
2891         ast_debug(1, "Sending MESSAGE from '%s' to '%s:%s': %s\n",
2892                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_FROM),
2893                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_TO),
2894                 ast_channel_name(ast),
2895                 ast_msg_data_get_attribute(msg, AST_MSG_DATA_ATTR_BODY));
2896
2897         if (!data) {
2898                 return -1;
2899         }
2900
2901 #ifdef HAVE_PJSIP_INV_SESSION_REF
2902         if (pjsip_inv_add_ref(data->session->inv_session) != PJ_SUCCESS) {
2903                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2904                 ao2_ref(data, -1);
2905                 return -1;
2906         }
2907 #endif
2908
2909         if (ast_sip_push_task(channel->session->serializer, sendtext, data)) {
2910 #ifdef HAVE_PJSIP_INV_SESSION_REF
2911                 pjsip_inv_dec_ref(data->session->inv_session);
2912 #endif
2913                 ao2_ref(data, -1);
2914                 return -1;
2915         }
2916         return 0;
2917 }
2918
2919 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
2920 {
2921         struct ast_msg_data *msg;
2922         int rc;
2923         struct ast_msg_data_attribute attrs[] =
2924         {
2925                 {
2926                         .type = AST_MSG_DATA_ATTR_BODY,
2927                         .value = (char *)text,
2928                 }
2929         };
2930
2931         msg = ast_msg_data_alloc(AST_MSG_DATA_SOURCE_TYPE_UNKNOWN, attrs, ARRAY_LEN(attrs));
2932         if (!msg) {
2933                 return -1;
2934         }
2935         rc = chan_pjsip_sendtext_data(ast, msg);
2936         ast_free(msg);
2937
2938         return rc;
2939 }
2940
2941 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2942 static int hangup_sip2cause(int cause)
2943 {
2944         /* Possible values taken from causes.h */
2945
2946         switch(cause) {
2947         case 401:       /* Unauthorized */
2948                 return AST_CAUSE_CALL_REJECTED;
2949         case 403:       /* Not found */
2950                 return AST_CAUSE_CALL_REJECTED;
2951         case 404:       /* Not found */
2952                 return AST_CAUSE_UNALLOCATED;
2953         case 405:       /* Method not allowed */
2954                 return AST_CAUSE_INTERWORKING;
2955         case 407:       /* Proxy authentication required */
2956                 return AST_CAUSE_CALL_REJECTED;
2957         case 408:       /* No reaction */
2958                 return AST_CAUSE_NO_USER_RESPONSE;
2959         case 409:       /* Conflict */
2960                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2961         case 410:       /* Gone */
2962                 return AST_CAUSE_NUMBER_CHANGED;
2963         case 411:       /* Length required */
2964                 return AST_CAUSE_INTERWORKING;
2965         case 413:       /* Request entity too large */
2966                 return AST_CAUSE_INTERWORKING;
2967         case 414:       /* Request URI too large */
2968                 return AST_CAUSE_INTERWORKING;
2969         case 415:       /* Unsupported media type */
2970                 return AST_CAUSE_INTERWORKING;
2971         case 420:       /* Bad extension */
2972                 return AST_CAUSE_NO_ROUTE_DESTINATION;
2973         case 480:       /* No answer */
2974                 return AST_CAUSE_NO_ANSWER;
2975         case 481:       /* No answer */
2976                 return AST_CAUSE_INTERWORKING;
2977         case 482:       /* Loop detected */
2978                 return AST_CAUSE_INTERWORKING;
2979         case 483:       /* Too many hops */
2980                 return AST_CAUSE_NO_ANSWER;
2981         case 484:       /* Address incomplete */
2982                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2983         case 485:       /* Ambiguous */
2984                 return AST_CAUSE_UNALLOCATED;
2985         case 486:       /* Busy everywhere */
2986                 return AST_CAUSE_BUSY;
2987         case 487:       /* Request terminated */
2988                 return AST_CAUSE_INTERWORKING;
2989         case 488:       /* No codecs approved */
2990                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2991         case 491:       /* Request pending */
2992                 return AST_CAUSE_INTERWORKING;
2993         case 493:       /* Undecipherable */
2994                 return AST_CAUSE_INTERWORKING;
2995         case 500:       /* Server internal failure */
2996                 return AST_CAUSE_FAILURE;
2997         case 501:       /* Call rejected */
2998                 return AST_CAUSE_FACILITY_REJECTED;
2999         case 502:
3000                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
3001         case 503:       /* Service unavailable */
3002                 return AST_CAUSE_CONGESTION;
3003         case 504:       /* Gateway timeout */
3004                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
3005         case 505:       /* SIP version not supported */
3006                 return AST_CAUSE_INTERWORKING;
3007         case 600:       /* Busy everywhere */
3008                 return AST_CAUSE_USER_BUSY;
3009         case 603:       /* Decline */
3010                 return AST_CAUSE_CALL_REJECTED;
3011         case 604:       /* Does not exist anywhere */
3012                 return AST_CAUSE_UNALLOCATED;
3013         case 606:       /* Not acceptable */
3014                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
3015         default:
3016                 if (cause < 500 && cause >= 400) {
3017                         /* 4xx class error that is unknown - someting wrong with our request */
3018                         return AST_CAUSE_INTERWORKING;
3019                 } else if (cause < 600 && cause >= 500) {
3020                         /* 5xx class error - problem in the remote end */
3021                         return AST_CAUSE_CONGESTION;
3022                 } else if (cause < 700 && cause >= 600) {
3023                         /* 6xx - global errors in the 4xx class */
3024                         return AST_CAUSE_INTERWORKING;
3025                 }
3026                 return AST_CAUSE_NORMAL;
3027         }
3028         /* Never reached */
3029         return 0;
3030 }
3031
3032 static void chan_pjsip_session_begin(struct ast_sip_session *session)
3033 {
3034         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
3035         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(session));
3036
3037         if (session->endpoint->media.direct_media.glare_mitigation ==
3038                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
3039                 SCOPE_EXIT_RTN("Direct media no glare mitigation\n");
3040         }
3041
3042         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
3043                         "direct_media_glare_mitigation");
3044
3045         if (!datastore) {
3046                 SCOPE_EXIT_RTN("Couldn't create datastore\n");
3047         }
3048
3049         ast_sip_session_add_datastore(session, datastore);
3050         SCOPE_EXIT_RTN();
3051 }
3052
3053 /*! \brief Function called when the session ends */
3054 static void chan_pjsip_session_end(struct ast_sip_session *session)
3055 {
3056         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(session));
3057
3058         if (!session->channel) {
3059                 SCOPE_EXIT_RTN("No channel\n");
3060         }
3061
3062         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
3063
3064         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
3065         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
3066                 int cause = hangup_sip2cause(session->inv_session->cause);
3067
3068                 ast_queue_hangup_with_cause(session->channel, cause);
3069         } else {
3070                 ast_queue_hangup(session->channel);
3071         }
3072
3073         SCOPE_EXIT_RTN();
3074 }
3075
3076 /*! \brief Function called when a request is received on the session */
3077 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
3078 {
3079         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
3080         struct transport_info_data *transport_data;
3081         pjsip_tx_data *packet = NULL;
3082         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(session));
3083
3084         if (session->channel) {
3085                 SCOPE_EXIT_RTN_VALUE(0, "Already have channel\n");
3086         }
3087
3088         /* Check for a to-tag to determine if this is a reinvite */
3089         if (rdata->msg_info.to->tag.slen) {
3090                 /* Weird case. We've received a reinvite but we don't have a channel. The most
3091                  * typical case for this happening is that a blind transfer fails, and so the
3092                  * transferer attempts to reinvite himself back into the call. We already got
3093                  * rid of that channel, and the other side of the call is unrecoverable.
3094                  *
3095                  * We treat this as a failure, so our best bet is to just hang this call
3096                  * up and not create a new channel. Clearing defer_terminate here ensures that
3097                  * calling ast_sip_session_terminate() can result in a BYE being sent ASAP.
3098                  */
3099                 session->defer_terminate = 0;
3100                 ast_sip_session_terminate(session, 400);
3101                 SCOPE_EXIT_RTN_VALUE(-1, "Reinvite without channel\n");
3102         }
3103
3104         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
3105         if (!datastore) {
3106                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create datastore\n");
3107         }
3108
3109         transport_data = ast_calloc(1, sizeof(*transport_data));
3110         if (!transport_data) {
3111                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create transport_data\n");
3112         }
3113         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
3114         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
3115         datastore->data = transport_data;
3116         ast_sip_session_add_datastore(session, datastore);
3117
3118         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
3119                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS
3120                         && packet) {
3121                         ast_sip_session_send_response(session, packet);
3122                 }
3123
3124                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
3125                 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create channel\n");
3126         }
3127         /* channel gets created on incoming request, but we wait to call start
3128            so other supplements have a chance to run */
3129         SCOPE_EXIT_RTN_VALUE(0);
3130 }
3131
3132 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
3133 {
3134         struct ast_features_pickup_config *pickup_cfg;
3135         struct ast_channel *chan;
3136
3137         /* Check for a to-tag to determine if this is a reinvite */
3138         if (rdata->msg_info.to->tag.slen) {
3139                 /* We don't care about reinvites */
3140                 return 0;
3141         }
3142
3143         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
3144         if (!pickup_cfg) {
3145                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
3146                 return 0;
3147         }
3148
3149         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
3150                 ao2_ref(pickup_cfg, -1);
3151                 return 0;
3152         }
3153         ao2_ref(pickup_cfg, -1);
3154
3155         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
3156          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
3157          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
3158          */
3159         chan = ast_channel_ref(session->channel);
3160         if (ast_pickup_call(chan)) {
3161                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
3162         } else {
3163                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
3164         }
3165         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
3166          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
3167          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
3168          * to anything at all.
3169          */
3170         ast_hangup(chan);
3171         ast_channel_unref(chan);
3172
3173         return 1;
3174 }
3175
3176 static struct ast_sip_session_supplement call_pickup_supplement = {
3177         .method = "INVITE",
3178         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
3179         .incoming_request = call_pickup_incoming_request,
3180 };
3181
3182 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
3183 {
3184         int res;
3185         SCOPE_ENTER(1, "%s\n", ast_sip_session_get_name(session));
3186
3187         /* Check for a to-tag to determine if this is a reinvite */
3188         if (rdata->msg_info.to->tag.slen) {
3189                 /* We don't care about reinvites */
3190                 SCOPE_EXIT_RTN_VALUE(0, "Reinvite\n");
3191         }
3192
3193         res = ast_pbx_start(session->channel);
3194
3195         switch (res) {
3196         case AST_PBX_FAILED:
3197                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
3198                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
3199                 ast_hangup(session->channel);
3200                 break;
3201         case AST_PBX_CALL_LIMIT:
3202                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
3203                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
3204                 ast_hangup(session->channel);
3205                 break;
3206         case AST_PBX_SUCCESS:
3207         default:
3208                 break;
3209         }
3210
3211         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
3212
3213         SCOPE_EXIT_RTN_VALUE((res == AST_PBX_SUCCESS) ? 0 : -1, "RC: %d\n", res);
3214 }
3215
3216 static struct ast_sip_session_supplement pbx_start_supplement = {
3217         .method = "INVITE",
3218         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
3219         .incoming_request = pbx_start_incoming_request,
3220 };
3221
3222 /*! \brief Function called when a response is received on the session */
3223 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
3224 {
3225         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
3226         struct ast_control_pvt_cause_code *cause_code;
3227         int data_size = sizeof(*cause_code);
3228         SCOPE_ENTER(1, "%s Method: %.*s Status: %d\n", ast_sip_session_get_name(session),
3229                 (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3230
3231         if (!session->channel) {
3232                 SCOPE_EXIT_RTN("No channel\n");
3233         }
3234
3235         /* Build and send the tech-specific cause information */
3236         /* size of the string making up the cause code is "SIP " number + " " + reason length */
3237         data_size += 4 + 4 + pj_strlen(&status.reason);
3238         cause_code = ast_alloca(data_size);
3239         memset(cause_code, 0, data_size);
3240
3241         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
3242
3243         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
3244         (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
3245
3246         cause_code->ast_cause = hangup_sip2cause(status.code);
3247         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
3248         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
3249
3250         switch (status.code) {
3251         case 180:
3252                 ast_trace(1, "%s Method: %.*s Status: %d  Queueing RINGING\n", ast_sip_session_get_name(session),
3253                         (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3254                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
3255                 ast_channel_lock(session->channel);
3256                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
3257                         ast_setstate(session->channel, AST_STATE_RINGING);
3258                 }
3259                 ast_channel_unlock(session->channel);
3260                 break;
3261         case 183:
3262                 if (session->endpoint->ignore_183_without_sdp) {
3263                         pjsip_rdata_sdp_info *sdp = pjsip_rdata_get_sdp_info(rdata);
3264                         if (sdp && sdp->body.ptr) {
3265                                 ast_trace(1, "%s Method: %.*s Status: %d  Queueing PROGRESS with SDP\n", ast_sip_session_get_name(session),
3266                                         (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3267                                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
3268                         }
3269                 } else {
3270                         ast_trace(1, "%s Method: %.*s Status: %d  Queueing PROGRESS without SDP\n", ast_sip_session_get_name(session),
3271                                 (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3272                         ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
3273                 }
3274                 break;
3275         case 200:
3276                 ast_trace(1, "%s Method: %.*s Status: %d  Queueing ANSWER\n", ast_sip_session_get_name(session),
3277                         (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3278
3279                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
3280                 break;
3281         default:
3282                 ast_trace(1, "%s Method: %.*s Status: %d  Ignored\n", ast_sip_session_get_name(session),
3283                         (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
3284                 break;
3285         }
3286
3287         SCOPE_EXIT_RTN();
3288 }
3289
3290 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
3291 {
3292         SCOPE_ENTER(1, "%s Method: %.*s Status: %d  After Media\n", ast_sip_session_get_name(session),
3293                 (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr,
3294                 rdata->msg_info.msg->line.status.code);
3295
3296         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
3297                 if (session->endpoint->media.direct_media.enabled && session->channel) {
3298                         ast_trace(1, "%s Method: %.*s  Queueing SRCCHANGE\n", ast_sip_session_get_name(session),
3299                                 (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr);
3300                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
3301                 }
3302         }
3303         SCOPE_EXIT_RTN_VALUE(0);
3304 }
3305
3306 static int update_devstate(void *obj, void *arg, int flags)
3307 {
3308         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
3309                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
3310         return 0;
3311 }
3312
3313 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
3314         .name = "PJSIP_DIAL_CONTACTS",
3315         .read = pjsip_acf_dial_contacts_read,
3316 };
3317
3318 static struct ast_custom_function chan_pjsip_parse_uri_function = {
3319         .name = "PJSIP_PARSE_URI",
3320         .read = pjsip_acf_parse_uri_read,
3321 };
3322
3323 static struct ast_custom_function media_offer_function = {
3324         .name = "PJSIP_MEDIA_OFFER",
3325         .read = pjsip_acf_media_offer_read,
3326         .write = pjsip_acf_media_offer_write
3327 };
3328
3329 static struct ast_custom_function dtmf_mode_function = {
3330         .name = "PJSIP_DTMF_MODE",
3331         .read = pjsip_acf_dtmf_mode_read,
3332         .write = pjsip_acf_dtmf_mode_write
3333 };
3334
3335 static struct ast_custom_function moh_passthrough_function = {
3336         .name = "PJSIP_MOH_PASSTHROUGH",
3337         .read = pjsip_acf_moh_passthrough_read,
3338         .write = pjsip_acf_moh_passthrough_write
3339 };
3340
3341 static struct ast_custom_function session_refresh_function = {
3342         .name = "PJSIP_SEND_SESSION_REFRESH",
3343         .write = pjsip_acf_session_refresh_write,
3344 };
3345
3346 /*!
3347  * \brief Load the module
3348  *
3349  * Module loading including tests for configuration or dependencies.
3350  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
3351  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
3352  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
3353  * configuration file or other non-critical problem return
3354  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
3355  */
3356 static int load_module(void)
3357 {
3358         struct ao2_container *endpoints;
3359
3360         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
3361                 return AST_MODULE_LOAD_DECLINE;
3362         }
3363
3364         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
3365
3366         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
3367
3368         if (ast_channel_register(&chan_pjsip_tech)) {
3369                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
3370                 goto end;
3371         }
3372
3373         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
3374                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
3375                 goto end;
3376         }
3377
3378         if (ast_custom_function_register(&chan_pjsip_parse_uri_function)) {
3379                 ast_log(LOG_ERROR, "Unable to register PJSIP_PARSE_URI dialplan function\n");
3380                 goto end;
3381         }
3382
3383         if (ast_custom_function_register(&media_offer_function)) {
3384                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
3385                 goto end;
3386         }
3387
3388         if (ast_custom_function_register(&dtmf_mode_function)) {
3389                 ast_log(LOG_WARNING, "Unable to register PJSIP_DTMF_MODE dialplan function\n");
3390                 goto end;
3391         }
3392
3393         if (ast_custom_function_register(&moh_passthrough_function)) {
3394                 ast_log(LOG_WARNING, "Unable to register PJSIP_MOH_PASSTHROUGH dialplan function\n");
3395                 goto end;
3396         }
3397
3398         if (ast_custom_function_register(&session_refresh_function)) {
3399                 ast_log(LOG_WARNING, "Unable to register PJSIP_SEND_SESSION_REFRESH dialplan function\n");
3400                 goto end;
3401         }
3402
3403         ast_sip_register_service(&refer_callback_module);
3404
3405         ast_sip_session_register_supplement(&chan_pjsip_supplement);
3406         ast_sip_session_register_supplement(&chan_pjsip_supplement_response);
3407
3408         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
3409                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
3410                         uid_hold_sort_fn, NULL))) {
3411                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
3412                 goto end;
3413         }
3414
3415         ast_sip_session_register_supplement(&call_pickup_supplement);
3416         ast_sip_session_register_supplement(&pbx_start_supplement);
3417         ast_sip_session_register_supplement(&chan_pjsip_ack_supplement);
3418
3419         if (pjsip_channel_cli_register()) {
3420                 ast_log(LOG_ERROR, "Unable to register PJSIP Channel CLI\n");
3421                 goto end;
3422         }
3423
3424         /* since endpoints are loaded before the channel driver their device
3425            states get set to 'invalid', so they need to be updated */
3426         if ((endpoints = ast_sip_get_endpoints())) {
3427                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
3428                 ao2_ref(endpoints, -1);
3429         }
3430
3431         return 0;
3432
3433 end:
3434         ao2_cleanup(pjsip_uids_onhold);
3435         pjsip_uids_onhold = NULL;
3436         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3437         ast_sip_session_unregister_supplement(&pbx_start_supplement);
3438         ast_sip_session_unregister_supplement(&chan_pjsip_supplement_response);
3439         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3440         ast_sip_session_unregister_supplement(&call_pickup_supplement);
3441         ast_sip_unregister_service(&refer_callback_module);
3442         ast_custom_function_unregister(&dtmf_mode_function);
3443         ast_custom_function_unregister(&moh_passthrough_function);
3444         ast_custom_function_unregister(&media_offer_function);
3445         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3446         ast_custom_function_unregister(&chan_pjsip_parse_uri_function);
3447         ast_custom_function_unregister(&session_refresh_function);
3448         ast_channel_unregister(&chan_pjsip_tech);
3449         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3450
3451         return AST_MODULE_LOAD_DECLINE;
3452 }
3453
3454 /*! \brief Unload the PJSIP channel from Asterisk */
3455 static int unload_module(void)
3456 {
3457         ao2_cleanup(pjsip_uids_onhold);
3458         pjsip_uids_onhold = NULL;
3459
3460         pjsip_channel_cli_unregister();
3461
3462         ast_sip_session_unregister_supplement(&chan_pjsip_supplement_response);
3463         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3464         ast_sip_session_unregister_supplement(&pbx_start_supplement);
3465         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3466         ast_sip_session_unregister_supplement(&call_pickup_supplement);
3467
3468         ast_sip_unregister_service(&refer_callback_module);
3469
3470         ast_custom_function_unregister(&dtmf_mode_function);
3471         ast_custom_function_unregister(&moh_passthrough_function);
3472         ast_custom_function_unregister(&media_offer_function);
3473         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3474         ast_custom_function_unregister(&chan_pjsip_parse_uri_function);
3475         ast_custom_function_unregister(&session_refresh_function);
3476
3477         ast_channel_unregister(&chan_pjsip_tech);
3478         ao2_ref(chan_pjsip_tech.capabilities, -1);
3479         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3480
3481         return 0;
3482 }
3483
3484 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
3485         .support_level = AST_MODULE_SUPPORT_CORE,
3486         .load = load_module,
3487         .unload = unload_module,
3488         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
3489         .requires = "res_pjsip,res_pjsip_session,res_pjsip_pubsub",
3490 );