chan_pjsip: Add additional log message when an AOR is specified when dialing and...
[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_session</depend>
32         <support_level>core</support_level>
33  ***/
34
35 #include "asterisk.h"
36
37 #include <pjsip.h>
38 #include <pjsip_ua.h>
39 #include <pjlib.h>
40
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42
43 #include "asterisk/lock.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/module.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/rtp_engine.h"
48 #include "asterisk/acl.h"
49 #include "asterisk/callerid.h"
50 #include "asterisk/file.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/app.h"
53 #include "asterisk/musiconhold.h"
54 #include "asterisk/causes.h"
55 #include "asterisk/taskprocessor.h"
56 #include "asterisk/dsp.h"
57 #include "asterisk/stasis_endpoints.h"
58 #include "asterisk/stasis_channels.h"
59 #include "asterisk/indications.h"
60 #include "asterisk/format_cache.h"
61 #include "asterisk/translate.h"
62 #include "asterisk/threadstorage.h"
63 #include "asterisk/features_config.h"
64 #include "asterisk/pickup.h"
65 #include "asterisk/test.h"
66
67 #include "asterisk/res_pjsip.h"
68 #include "asterisk/res_pjsip_session.h"
69
70 #include "pjsip/include/chan_pjsip.h"
71 #include "pjsip/include/dialplan_functions.h"
72
73 AST_THREADSTORAGE(uniqueid_threadbuf);
74 #define UNIQUEID_BUFSIZE 256
75
76 static const char desc[] = "PJSIP Channel";
77 static const char channel_type[] = "PJSIP";
78
79 static unsigned int chan_idx;
80
81 static void chan_pjsip_pvt_dtor(void *obj)
82 {
83         struct chan_pjsip_pvt *pvt = obj;
84         int i;
85
86         for (i = 0; i < SIP_MEDIA_SIZE; ++i) {
87                 ao2_cleanup(pvt->media[i]);
88                 pvt->media[i] = NULL;
89         }
90 }
91
92 /* \brief Asterisk core interaction functions */
93 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);
94 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
95 static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
96 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
97 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
98 static int chan_pjsip_hangup(struct ast_channel *ast);
99 static int chan_pjsip_answer(struct ast_channel *ast);
100 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast);
101 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
102 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
103 static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
104 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
105 static int chan_pjsip_devicestate(const char *data);
106 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
107 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast);
108
109 /*! \brief PBX interface structure for channel registration */
110 struct ast_channel_tech chan_pjsip_tech = {
111         .type = channel_type,
112         .description = "PJSIP Channel Driver",
113         .requester = chan_pjsip_request,
114         .send_text = chan_pjsip_sendtext,
115         .send_digit_begin = chan_pjsip_digit_begin,
116         .send_digit_end = chan_pjsip_digit_end,
117         .call = chan_pjsip_call,
118         .hangup = chan_pjsip_hangup,
119         .answer = chan_pjsip_answer,
120         .read = chan_pjsip_read,
121         .write = chan_pjsip_write,
122         .write_video = chan_pjsip_write,
123         .exception = chan_pjsip_read,
124         .indicate = chan_pjsip_indicate,
125         .transfer = chan_pjsip_transfer,
126         .fixup = chan_pjsip_fixup,
127         .devicestate = chan_pjsip_devicestate,
128         .queryoption = chan_pjsip_queryoption,
129         .func_channel_read = pjsip_acf_channel_read,
130         .get_pvt_uniqueid = chan_pjsip_get_uniqueid,
131         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
132 };
133
134 /*! \brief SIP session interaction functions */
135 static void chan_pjsip_session_begin(struct ast_sip_session *session);
136 static void chan_pjsip_session_end(struct ast_sip_session *session);
137 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
138 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
139
140 /*! \brief SIP session supplement structure */
141 static struct ast_sip_session_supplement chan_pjsip_supplement = {
142         .method = "INVITE",
143         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
144         .session_begin = chan_pjsip_session_begin,
145         .session_end = chan_pjsip_session_end,
146         .incoming_request = chan_pjsip_incoming_request,
147         .incoming_response = chan_pjsip_incoming_response,
148         /* It is important that this supplement runs after media has been negotiated */
149         .response_priority = AST_SIP_SESSION_AFTER_MEDIA,
150 };
151
152 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
153
154 static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
155         .method = "ACK",
156         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
157         .incoming_request = chan_pjsip_incoming_ack,
158 };
159
160 /*! \brief Function called by RTP engine to get local audio RTP peer */
161 static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
162 {
163         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
164         struct chan_pjsip_pvt *pvt = channel->pvt;
165         struct ast_sip_endpoint *endpoint;
166
167         if (!pvt || !channel->session || !pvt->media[SIP_MEDIA_AUDIO]->rtp) {
168                 return AST_RTP_GLUE_RESULT_FORBID;
169         }
170
171         endpoint = channel->session->endpoint;
172
173         *instance = pvt->media[SIP_MEDIA_AUDIO]->rtp;
174         ao2_ref(*instance, +1);
175
176         ast_assert(endpoint != NULL);
177         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
178                 return AST_RTP_GLUE_RESULT_FORBID;
179         }
180
181         if (endpoint->media.direct_media.enabled) {
182                 return AST_RTP_GLUE_RESULT_REMOTE;
183         }
184
185         return AST_RTP_GLUE_RESULT_LOCAL;
186 }
187
188 /*! \brief Function called by RTP engine to get local video RTP peer */
189 static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
190 {
191         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
192         struct chan_pjsip_pvt *pvt = channel->pvt;
193         struct ast_sip_endpoint *endpoint;
194
195         if (!pvt || !channel->session || !pvt->media[SIP_MEDIA_VIDEO]->rtp) {
196                 return AST_RTP_GLUE_RESULT_FORBID;
197         }
198
199         endpoint = channel->session->endpoint;
200
201         *instance = pvt->media[SIP_MEDIA_VIDEO]->rtp;
202         ao2_ref(*instance, +1);
203
204         ast_assert(endpoint != NULL);
205         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
206                 return AST_RTP_GLUE_RESULT_FORBID;
207         }
208
209         return AST_RTP_GLUE_RESULT_LOCAL;
210 }
211
212 /*! \brief Function called by RTP engine to get peer capabilities */
213 static void chan_pjsip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
214 {
215         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
216
217         ast_format_cap_append_from_cap(result, channel->session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
218 }
219
220 static int send_direct_media_request(void *data)
221 {
222         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
223
224         return ast_sip_session_refresh(session, NULL, NULL, NULL,
225                         session->endpoint->media.direct_media.method, 1);
226 }
227
228 /*! \brief Destructor function for \ref transport_info_data */
229 static void transport_info_destroy(void *obj)
230 {
231         struct transport_info_data *data = obj;
232         ast_free(data);
233 }
234
235 /*! \brief Datastore used to store local/remote addresses for the
236  * INVITE request that created the PJSIP channel */
237 static struct ast_datastore_info transport_info = {
238         .type = "chan_pjsip_transport_info",
239         .destroy = transport_info_destroy,
240 };
241
242 static struct ast_datastore_info direct_media_mitigation_info = { };
243
244 static int direct_media_mitigate_glare(struct ast_sip_session *session)
245 {
246         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
247
248         if (session->endpoint->media.direct_media.glare_mitigation ==
249                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
250                 return 0;
251         }
252
253         datastore = ast_sip_session_get_datastore(session, "direct_media_glare_mitigation");
254         if (!datastore) {
255                 return 0;
256         }
257
258         /* Removing the datastore ensures we won't try to mitigate glare on subsequent reinvites */
259         ast_sip_session_remove_datastore(session, "direct_media_glare_mitigation");
260
261         if ((session->endpoint->media.direct_media.glare_mitigation ==
262                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING &&
263                         session->inv_session->role == PJSIP_ROLE_UAC) ||
264                         (session->endpoint->media.direct_media.glare_mitigation ==
265                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING &&
266                         session->inv_session->role == PJSIP_ROLE_UAS)) {
267                 return 1;
268         }
269
270         return 0;
271 }
272
273 static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
274                 struct ast_sip_session_media *media, int rtcp_fd)
275 {
276         int changed = 0;
277
278         if (rtp) {
279                 changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
280                 if (media->rtp) {
281                         ast_channel_set_fd(chan, rtcp_fd, -1);
282                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
283                 }
284         } else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
285                 ast_sockaddr_setnull(&media->direct_media_addr);
286                 changed = 1;
287                 if (media->rtp) {
288                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
289                         ast_channel_set_fd(chan, rtcp_fd, ast_rtp_instance_fd(media->rtp, 1));
290                 }
291         }
292
293         return changed;
294 }
295
296 /*! \brief Function called by RTP engine to change where the remote party should send media */
297 static int chan_pjsip_set_rtp_peer(struct ast_channel *chan,
298                 struct ast_rtp_instance *rtp,
299                 struct ast_rtp_instance *vrtp,
300                 struct ast_rtp_instance *tpeer,
301                 const struct ast_format_cap *cap,
302                 int nat_active)
303 {
304         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
305         struct chan_pjsip_pvt *pvt = channel->pvt;
306         struct ast_sip_session *session = channel->session;
307         int changed = 0;
308
309         /* Don't try to do any direct media shenanigans on early bridges */
310         if ((rtp || vrtp || tpeer) && !ast_channel_is_bridged(chan)) {
311                 ast_debug(4, "Disregarding setting RTP on %s: channel is not bridged\n", ast_channel_name(chan));
312                 return 0;
313         }
314
315         if (nat_active && session->endpoint->media.direct_media.disable_on_nat) {
316                 ast_debug(4, "Disregarding setting RTP on %s: NAT is active\n", ast_channel_name(chan));
317                 return 0;
318         }
319
320         if (pvt->media[SIP_MEDIA_AUDIO]) {
321                 changed |= check_for_rtp_changes(chan, rtp, pvt->media[SIP_MEDIA_AUDIO], 1);
322         }
323         if (pvt->media[SIP_MEDIA_VIDEO]) {
324                 changed |= check_for_rtp_changes(chan, vrtp, pvt->media[SIP_MEDIA_VIDEO], 3);
325         }
326
327         if (direct_media_mitigate_glare(session)) {
328                 ast_debug(4, "Disregarding setting RTP on %s: mitigating re-INVITE glare\n", ast_channel_name(chan));
329                 return 0;
330         }
331
332         if (cap && ast_format_cap_count(cap) && !ast_format_cap_identical(session->direct_media_cap, cap)) {
333                 ast_format_cap_remove_by_type(session->direct_media_cap, AST_MEDIA_TYPE_UNKNOWN);
334                 ast_format_cap_append_from_cap(session->direct_media_cap, cap, AST_MEDIA_TYPE_UNKNOWN);
335                 changed = 1;
336         }
337
338         if (changed) {
339                 ao2_ref(session, +1);
340
341                 ast_debug(4, "RTP changed on %s; initiating direct media update\n", ast_channel_name(chan));
342                 if (ast_sip_push_task(session->serializer, send_direct_media_request, session)) {
343                         ao2_cleanup(session);
344                 }
345         }
346
347         return 0;
348 }
349
350 /*! \brief Local glue for interacting with the RTP engine core */
351 static struct ast_rtp_glue chan_pjsip_rtp_glue = {
352         .type = "PJSIP",
353         .get_rtp_info = chan_pjsip_get_rtp_peer,
354         .get_vrtp_info = chan_pjsip_get_vrtp_peer,
355         .get_codec = chan_pjsip_get_codec,
356         .update_peer = chan_pjsip_set_rtp_peer,
357 };
358
359 static void set_channel_on_rtp_instance(struct chan_pjsip_pvt *pvt, const char *channel_id)
360 {
361         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
362                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, channel_id);
363         }
364         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
365                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, channel_id);
366         }
367 }
368
369 /*! \brief Function called to create a new PJSIP Asterisk channel */
370 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)
371 {
372         struct ast_channel *chan;
373         struct ast_format_cap *caps;
374         RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
375         struct ast_sip_channel_pvt *channel;
376         struct ast_variable *var;
377
378         if (!(pvt = ao2_alloc(sizeof(*pvt), chan_pjsip_pvt_dtor))) {
379                 return NULL;
380         }
381         caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
382         if (!caps) {
383                 return NULL;
384         }
385
386         chan = ast_channel_alloc_with_endpoint(1, state,
387                 S_COR(session->id.number.valid, session->id.number.str, ""),
388                 S_COR(session->id.name.valid, session->id.name.str, ""),
389                 session->endpoint->accountcode, "", "", assignedids, requestor, 0,
390                 session->endpoint->persistent, "PJSIP/%s-%08x",
391                 ast_sorcery_object_get_id(session->endpoint),
392                 (unsigned) ast_atomic_fetchadd_int((int *) &chan_idx, +1));
393         if (!chan) {
394                 ao2_ref(caps, -1);
395                 return NULL;
396         }
397
398         ast_channel_tech_set(chan, &chan_pjsip_tech);
399
400         if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
401                 ao2_ref(caps, -1);
402                 ast_channel_unlock(chan);
403                 ast_hangup(chan);
404                 return NULL;
405         }
406
407         ast_channel_stage_snapshot(chan);
408
409         ast_channel_tech_pvt_set(chan, channel);
410
411         if (!ast_format_cap_count(session->req_caps) ||
412                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
413                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
414         } else {
415                 ast_format_cap_append_from_cap(caps, session->req_caps, AST_MEDIA_TYPE_UNKNOWN);
416         }
417
418         ast_channel_nativeformats_set(chan, caps);
419
420         if (!ast_format_cap_empty(caps)) {
421                 /*
422                  * XXX Probably should pick the first audio codec instead
423                  * of simply the first codec.  The first codec may be video.
424                  */
425                 struct ast_format *fmt = ast_format_cap_get_format(caps, 0);
426
427                 ast_channel_set_writeformat(chan, fmt);
428                 ast_channel_set_rawwriteformat(chan, fmt);
429                 ast_channel_set_readformat(chan, fmt);
430                 ast_channel_set_rawreadformat(chan, fmt);
431                 ao2_ref(fmt, -1);
432         }
433
434         ao2_ref(caps, -1);
435
436         if (state == AST_STATE_RING) {
437                 ast_channel_rings_set(chan, 1);
438         }
439
440         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
441
442         ast_party_id_copy(&ast_channel_caller(chan)->id, &session->id);
443         ast_party_id_copy(&ast_channel_caller(chan)->ani, &session->id);
444
445         ast_channel_context_set(chan, session->endpoint->context);
446         ast_channel_exten_set(chan, S_OR(exten, "s"));
447         ast_channel_priority_set(chan, 1);
448
449         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
450         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
451
452         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
453         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
454
455         if (!ast_strlen_zero(session->endpoint->language)) {
456                 ast_channel_language_set(chan, session->endpoint->language);
457         }
458
459         if (!ast_strlen_zero(session->endpoint->zone)) {
460                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
461                 if (!zone) {
462                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
463                 }
464                 ast_channel_zone_set(chan, zone);
465         }
466
467         for (var = session->endpoint->channel_vars; var; var = var->next) {
468                 char buf[512];
469                 pbx_builtin_setvar_helper(chan, var->name, ast_get_encoded_str(
470                                                   var->value, buf, sizeof(buf)));
471         }
472
473         ast_channel_stage_snapshot_done(chan);
474         ast_channel_unlock(chan);
475
476         /* If res_pjsip_session is ever updated to create/destroy ast_sip_session_media
477          * during a call such as if multiple same-type stream support is introduced,
478          * these will need to be recaptured as well */
479         pvt->media[SIP_MEDIA_AUDIO] = ao2_find(session->media, "audio", OBJ_KEY);
480         pvt->media[SIP_MEDIA_VIDEO] = ao2_find(session->media, "video", OBJ_KEY);
481         set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(chan));
482
483         return chan;
484 }
485
486 static int answer(void *data)
487 {
488         pj_status_t status = PJ_SUCCESS;
489         pjsip_tx_data *packet = NULL;
490         struct ast_sip_session *session = data;
491
492         pjsip_dlg_inc_lock(session->inv_session->dlg);
493         if (session->inv_session->invite_tsx) {
494                 status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
495         } else {
496                 ast_log(LOG_ERROR,"Cannot answer '%s' because there is no associated SIP transaction\n",
497                         ast_channel_name(session->channel));
498         }
499         pjsip_dlg_dec_lock(session->inv_session->dlg);
500
501         if (status == PJ_SUCCESS && packet) {
502                 ast_sip_session_send_response(session, packet);
503         }
504
505         ao2_ref(session, -1);
506
507         return (status == PJ_SUCCESS) ? 0 : -1;
508 }
509
510 /*! \brief Function called by core when we should answer a PJSIP session */
511 static int chan_pjsip_answer(struct ast_channel *ast)
512 {
513         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
514
515         if (ast_channel_state(ast) == AST_STATE_UP) {
516                 return 0;
517         }
518
519         ast_setstate(ast, AST_STATE_UP);
520
521         ao2_ref(channel->session, +1);
522         if (ast_sip_push_task(channel->session->serializer, answer, channel->session)) {
523                 ast_log(LOG_WARNING, "Unable to push answer task to the threadpool. Cannot answer call\n");
524                 ao2_cleanup(channel->session);
525                 return -1;
526         }
527
528         return 0;
529 }
530
531 /*! \brief Internal helper function called when CNG tone is detected */
532 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
533 {
534         const char *target_context;
535         int exists;
536
537         /* If we only needed this DSP for fax detection purposes we can just drop it now */
538         if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
539                 ast_dsp_set_features(session->dsp, DSP_FEATURE_DIGIT_DETECT);
540         } else {
541                 ast_dsp_free(session->dsp);
542                 session->dsp = NULL;
543         }
544
545         /* If already executing in the fax extension don't do anything */
546         if (!strcmp(ast_channel_exten(session->channel), "fax")) {
547                 return f;
548         }
549
550         target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));
551
552         /* We need to unlock the channel here because ast_exists_extension has the
553          * potential to start and stop an autoservice on the channel. Such action
554          * is prone to deadlock if the channel is locked.
555          */
556         ast_channel_unlock(session->channel);
557         exists = ast_exists_extension(session->channel, target_context, "fax", 1,
558                 S_COR(ast_channel_caller(session->channel)->id.number.valid,
559                         ast_channel_caller(session->channel)->id.number.str, NULL));
560         ast_channel_lock(session->channel);
561
562         if (exists) {
563                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
564                         ast_channel_name(session->channel));
565                 pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
566                 if (ast_async_goto(session->channel, target_context, "fax", 1)) {
567                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
568                                 ast_channel_name(session->channel), target_context);
569                 }
570                 ast_frfree(f);
571                 f = &ast_null_frame;
572         } else {
573                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
574                         ast_channel_name(session->channel), target_context);
575         }
576
577         return f;
578 }
579
580 /*! \brief Function called by core to read any waiting frames */
581 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
582 {
583         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
584         struct chan_pjsip_pvt *pvt = channel->pvt;
585         struct ast_frame *f;
586         struct ast_sip_session_media *media = NULL;
587         int rtcp = 0;
588         int fdno = ast_channel_fdno(ast);
589
590         switch (fdno) {
591         case 0:
592                 media = pvt->media[SIP_MEDIA_AUDIO];
593                 break;
594         case 1:
595                 media = pvt->media[SIP_MEDIA_AUDIO];
596                 rtcp = 1;
597                 break;
598         case 2:
599                 media = pvt->media[SIP_MEDIA_VIDEO];
600                 break;
601         case 3:
602                 media = pvt->media[SIP_MEDIA_VIDEO];
603                 rtcp = 1;
604                 break;
605         }
606
607         if (!media || !media->rtp) {
608                 return &ast_null_frame;
609         }
610
611         if (!(f = ast_rtp_instance_read(media->rtp, rtcp))) {
612                 return f;
613         }
614
615         if (f->frametype != AST_FRAME_VOICE) {
616                 return f;
617         }
618
619         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
620                 struct ast_format_cap *caps;
621
622                 ast_debug(1, "Oooh, format changed to %s\n", ast_format_get_name(f->subclass.format));
623
624                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
625                 if (caps) {
626                         ast_format_cap_append(caps, f->subclass.format, 0);
627                         ast_channel_nativeformats_set(ast, caps);
628                         ao2_ref(caps, -1);
629                 }
630
631                 ast_set_read_format(ast, ast_channel_readformat(ast));
632                 ast_set_write_format(ast, ast_channel_writeformat(ast));
633         }
634
635         if (channel->session->dsp) {
636                 f = ast_dsp_process(ast, channel->session->dsp, f);
637
638                 if (f && (f->frametype == AST_FRAME_DTMF)) {
639                         if (f->subclass.integer == 'f') {
640                                 ast_debug(3, "Fax CNG detected on %s\n", ast_channel_name(ast));
641                                 f = chan_pjsip_cng_tone_detected(channel->session, f);
642                         } else {
643                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
644                                         ast_channel_name(ast));
645                         }
646                 }
647         }
648
649         return f;
650 }
651
652 /*! \brief Function called by core to write frames */
653 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
654 {
655         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
656         struct chan_pjsip_pvt *pvt = channel->pvt;
657         struct ast_sip_session_media *media;
658         int res = 0;
659
660         switch (frame->frametype) {
661         case AST_FRAME_VOICE:
662                 media = pvt->media[SIP_MEDIA_AUDIO];
663
664                 if (!media) {
665                         return 0;
666                 }
667                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
668                         struct ast_str *cap_buf = ast_str_alloca(128);
669                         struct ast_str *write_transpath = ast_str_alloca(256);
670                         struct ast_str *read_transpath = ast_str_alloca(256);
671
672                         ast_log(LOG_WARNING,
673                                 "Channel %s asked to send %s frame when native formats are %s (rd:%s->%s;%s wr:%s->%s;%s)\n",
674                                 ast_channel_name(ast),
675                                 ast_format_get_name(frame->subclass.format),
676                                 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
677                                 ast_format_get_name(ast_channel_rawreadformat(ast)),
678                                 ast_format_get_name(ast_channel_readformat(ast)),
679                                 ast_translate_path_to_str(ast_channel_readtrans(ast), &read_transpath),
680                                 ast_format_get_name(ast_channel_writeformat(ast)),
681                                 ast_format_get_name(ast_channel_rawwriteformat(ast)),
682                                 ast_translate_path_to_str(ast_channel_writetrans(ast), &write_transpath));
683                         return 0;
684                 }
685                 if (media->rtp) {
686                         res = ast_rtp_instance_write(media->rtp, frame);
687                 }
688                 break;
689         case AST_FRAME_VIDEO:
690                 if ((media = pvt->media[SIP_MEDIA_VIDEO]) && media->rtp) {
691                         res = ast_rtp_instance_write(media->rtp, frame);
692                 }
693                 break;
694         case AST_FRAME_MODEM:
695                 break;
696         default:
697                 ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
698                 break;
699         }
700
701         return res;
702 }
703
704 /*! \brief Function called by core to change the underlying owner channel */
705 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
706 {
707         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
708         struct chan_pjsip_pvt *pvt = channel->pvt;
709
710         if (channel->session->channel != oldchan) {
711                 return -1;
712         }
713
714         /*
715          * The masquerade has suspended the channel's session
716          * serializer so we can safely change it outside of
717          * the serializer thread.
718          */
719         channel->session->channel = newchan;
720
721         set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(newchan));
722
723         return 0;
724 }
725
726 /*! AO2 hash function for on hold UIDs */
727 static int uid_hold_hash_fn(const void *obj, const int flags)
728 {
729         const char *key = obj;
730
731         switch (flags & OBJ_SEARCH_MASK) {
732         case OBJ_SEARCH_KEY:
733                 break;
734         case OBJ_SEARCH_OBJECT:
735                 break;
736         default:
737                 /* Hash can only work on something with a full key. */
738                 ast_assert(0);
739                 return 0;
740         }
741         return ast_str_hash(key);
742 }
743
744 /*! AO2 sort function for on hold UIDs */
745 static int uid_hold_sort_fn(const void *obj_left, const void *obj_right, const int flags)
746 {
747         const char *left = obj_left;
748         const char *right = obj_right;
749         int cmp;
750
751         switch (flags & OBJ_SEARCH_MASK) {
752         case OBJ_SEARCH_OBJECT:
753         case OBJ_SEARCH_KEY:
754                 cmp = strcmp(left, right);
755                 break;
756         case OBJ_SEARCH_PARTIAL_KEY:
757                 cmp = strncmp(left, right, strlen(right));
758                 break;
759         default:
760                 /* Sort can only work on something with a full or partial key. */
761                 ast_assert(0);
762                 cmp = 0;
763                 break;
764         }
765         return cmp;
766 }
767
768 static struct ao2_container *pjsip_uids_onhold;
769
770 /*!
771  * \brief Add a channel ID to the list of PJSIP channels on hold
772  *
773  * \param chan_uid - Unique ID of the channel being put into the hold list
774  *
775  * \retval 0 Channel has been added to or was already in the hold list
776  * \retval -1 Failed to add channel to the hold list
777  */
778 static int chan_pjsip_add_hold(const char *chan_uid)
779 {
780         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
781
782         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
783         if (hold_uid) {
784                 /* Device is already on hold. Nothing to do. */
785                 return 0;
786         }
787
788         /* Device wasn't in hold list already. Create a new one. */
789         hold_uid = ao2_alloc_options(strlen(chan_uid) + 1, NULL,
790                 AO2_ALLOC_OPT_LOCK_NOLOCK);
791         if (!hold_uid) {
792                 return -1;
793         }
794
795         ast_copy_string(hold_uid, chan_uid, strlen(chan_uid) + 1);
796
797         if (ao2_link(pjsip_uids_onhold, hold_uid) == 0) {
798                 return -1;
799         }
800
801         return 0;
802 }
803
804 /*!
805  * \brief Remove a channel ID from the list of PJSIP channels on hold
806  *
807  * \param chan_uid - Unique ID of the channel being taken out of the hold list
808  */
809 static void chan_pjsip_remove_hold(const char *chan_uid)
810 {
811         ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
812 }
813
814 /*!
815  * \brief Determine whether a channel ID is in the list of PJSIP channels on hold
816  *
817  * \param chan_uid - Channel being checked
818  *
819  * \retval 0 The channel is not in the hold list
820  * \retval 1 The channel is in the hold list
821  */
822 static int chan_pjsip_get_hold(const char *chan_uid)
823 {
824         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
825
826         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
827         if (!hold_uid) {
828                 return 0;
829         }
830
831         return 1;
832 }
833
834 /*! \brief Function called to get the device state of an endpoint */
835 static int chan_pjsip_devicestate(const char *data)
836 {
837         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
838         enum ast_device_state state = AST_DEVICE_UNKNOWN;
839         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
840         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
841         struct ast_devstate_aggregate aggregate;
842         int num, inuse = 0;
843
844         if (!endpoint) {
845                 return AST_DEVICE_INVALID;
846         }
847
848         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
849                 ast_endpoint_get_resource(endpoint->persistent));
850
851         if (!endpoint_snapshot) {
852                 return AST_DEVICE_INVALID;
853         }
854
855         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
856                 state = AST_DEVICE_UNAVAILABLE;
857         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
858                 state = AST_DEVICE_NOT_INUSE;
859         }
860
861         if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
862                 return state;
863         }
864
865         ast_devstate_aggregate_init(&aggregate);
866
867         ao2_ref(cache, +1);
868
869         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
870                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
871                 struct ast_channel_snapshot *snapshot;
872
873                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
874                         endpoint_snapshot->channel_ids[num]);
875
876                 if (!msg) {
877                         continue;
878                 }
879
880                 snapshot = stasis_message_data(msg);
881
882                 if (chan_pjsip_get_hold(snapshot->uniqueid)) {
883                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
884                 } else {
885                         ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
886                 }
887
888                 if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
889                         (snapshot->state == AST_STATE_BUSY)) {
890                         inuse++;
891                 }
892         }
893
894         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
895                 state = AST_DEVICE_BUSY;
896         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
897                 state = ast_devstate_aggregate_result(&aggregate);
898         }
899
900         return state;
901 }
902
903 /*! \brief Function called to query options on a channel */
904 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
905 {
906         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
907         struct ast_sip_session *session = channel->session;
908         int res = -1;
909         enum ast_sip_session_t38state state = T38_STATE_UNAVAILABLE;
910
911         switch (option) {
912         case AST_OPTION_T38_STATE:
913                 if (session->endpoint->media.t38.enabled) {
914                         switch (session->t38state) {
915                         case T38_LOCAL_REINVITE:
916                         case T38_PEER_REINVITE:
917                                 state = T38_STATE_NEGOTIATING;
918                                 break;
919                         case T38_ENABLED:
920                                 state = T38_STATE_NEGOTIATED;
921                                 break;
922                         case T38_REJECTED:
923                                 state = T38_STATE_REJECTED;
924                                 break;
925                         default:
926                                 state = T38_STATE_UNKNOWN;
927                                 break;
928                         }
929                 }
930
931                 *((enum ast_t38_state *) data) = state;
932                 res = 0;
933
934                 break;
935         default:
936                 break;
937         }
938
939         return res;
940 }
941
942 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
943 {
944         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
945         char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);
946
947         if (!uniqueid) {
948                 return "";
949         }
950
951         ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);
952
953         return uniqueid;
954 }
955
956 struct indicate_data {
957         struct ast_sip_session *session;
958         int condition;
959         int response_code;
960         void *frame_data;
961         size_t datalen;
962 };
963
964 static void indicate_data_destroy(void *obj)
965 {
966         struct indicate_data *ind_data = obj;
967
968         ast_free(ind_data->frame_data);
969         ao2_ref(ind_data->session, -1);
970 }
971
972 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
973                 int condition, int response_code, const void *frame_data, size_t datalen)
974 {
975         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
976
977         if (!ind_data) {
978                 return NULL;
979         }
980
981         ind_data->frame_data = ast_malloc(datalen);
982         if (!ind_data->frame_data) {
983                 ao2_ref(ind_data, -1);
984                 return NULL;
985         }
986
987         memcpy(ind_data->frame_data, frame_data, datalen);
988         ind_data->datalen = datalen;
989         ind_data->condition = condition;
990         ind_data->response_code = response_code;
991         ao2_ref(session, +1);
992         ind_data->session = session;
993
994         return ind_data;
995 }
996
997 static int indicate(void *data)
998 {
999         pjsip_tx_data *packet = NULL;
1000         struct indicate_data *ind_data = data;
1001         struct ast_sip_session *session = ind_data->session;
1002         int response_code = ind_data->response_code;
1003
1004         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1005                 ast_sip_session_send_response(session, packet);
1006         }
1007
1008         ao2_ref(ind_data, -1);
1009
1010         return 0;
1011 }
1012
1013 /*! \brief Send SIP INFO with video update request */
1014 static int transmit_info_with_vidupdate(void *data)
1015 {
1016         const char * xml =
1017                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1018                 " <media_control>\r\n"
1019                 "  <vc_primitive>\r\n"
1020                 "   <to_encoder>\r\n"
1021                 "    <picture_fast_update/>\r\n"
1022                 "   </to_encoder>\r\n"
1023                 "  </vc_primitive>\r\n"
1024                 " </media_control>\r\n";
1025
1026         const struct ast_sip_body body = {
1027                 .type = "application",
1028                 .subtype = "media_control+xml",
1029                 .body_text = xml
1030         };
1031
1032         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1033         struct pjsip_tx_data *tdata;
1034
1035         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1036                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1037                 return -1;
1038         }
1039         if (ast_sip_add_body(tdata, &body)) {
1040                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1041                 return -1;
1042         }
1043         ast_sip_session_send_request(session, tdata);
1044
1045         return 0;
1046 }
1047
1048 /*! \brief Update connected line information */
1049 static int update_connected_line_information(void *data)
1050 {
1051         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1052
1053         if ((ast_channel_state(session->channel) != AST_STATE_UP) && (session->inv_session->role == PJSIP_UAS_ROLE)) {
1054                 int response_code = 0;
1055
1056                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1057                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1058                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1059                         response_code = 183;
1060                 }
1061
1062                 if (response_code) {
1063                         struct pjsip_tx_data *packet = NULL;
1064
1065                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1066                                 ast_sip_session_send_response(session, packet);
1067                         }
1068                 }
1069         } else {
1070                 enum ast_sip_session_refresh_method method = session->endpoint->id.refresh_method;
1071                 int generate_new_sdp;
1072                 struct ast_party_id connected_id;
1073
1074                 if (session->inv_session->invite_tsx && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1075                         method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1076                 }
1077
1078                 /* Only the INVITE method actually needs SDP, UPDATE can do without */
1079                 generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
1080
1081                 /*
1082                  * We can get away with a shallow copy here because we are
1083                  * not looking at strings.
1084                  */
1085                 ast_channel_lock(session->channel);
1086                 connected_id = ast_channel_connected_effective_id(session->channel);
1087                 ast_channel_unlock(session->channel);
1088
1089                 if ((session->endpoint->id.send_pai || session->endpoint->id.send_rpid) &&
1090                     (session->endpoint->id.trust_outbound ||
1091                      ((connected_id.name.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED &&
1092                       (connected_id.number.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED))) {
1093                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp);
1094                 }
1095         }
1096
1097         return 0;
1098 }
1099
1100 /*! \brief Callback which changes the value of locally held on the media stream */
1101 static int local_hold_set_state(void *obj, void *arg, int flags)
1102 {
1103         struct ast_sip_session_media *session_media = obj;
1104         unsigned int *held = arg;
1105
1106         session_media->locally_held = *held;
1107
1108         return 0;
1109 }
1110
1111 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
1112 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
1113 {
1114         ao2_callback(session->media, OBJ_NODATA, local_hold_set_state, &held);
1115         ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
1116         ao2_ref(session, -1);
1117
1118         return 0;
1119 }
1120
1121 /*! \brief Update local hold state to be held */
1122 static int remote_send_hold(void *data)
1123 {
1124         return remote_send_hold_refresh(data, 1);
1125 }
1126
1127 /*! \brief Update local hold state to be unheld */
1128 static int remote_send_unhold(void *data)
1129 {
1130         return remote_send_hold_refresh(data, 0);
1131 }
1132
1133 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1134 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1135 {
1136         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1137         struct chan_pjsip_pvt *pvt = channel->pvt;
1138         struct ast_sip_session_media *media;
1139         int response_code = 0;
1140         int res = 0;
1141         char *device_buf;
1142         size_t device_buf_size;
1143
1144         switch (condition) {
1145         case AST_CONTROL_RINGING:
1146                 if (ast_channel_state(ast) == AST_STATE_RING) {
1147                         if (channel->session->endpoint->inband_progress) {
1148                                 response_code = 183;
1149                                 res = -1;
1150                         } else {
1151                                 response_code = 180;
1152                         }
1153                 } else {
1154                         res = -1;
1155                 }
1156                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1157                 break;
1158         case AST_CONTROL_BUSY:
1159                 if (ast_channel_state(ast) != AST_STATE_UP) {
1160                         response_code = 486;
1161                 } else {
1162                         res = -1;
1163                 }
1164                 break;
1165         case AST_CONTROL_CONGESTION:
1166                 if (ast_channel_state(ast) != AST_STATE_UP) {
1167                         response_code = 503;
1168                 } else {
1169                         res = -1;
1170                 }
1171                 break;
1172         case AST_CONTROL_INCOMPLETE:
1173                 if (ast_channel_state(ast) != AST_STATE_UP) {
1174                         response_code = 484;
1175                 } else {
1176                         res = -1;
1177                 }
1178                 break;
1179         case AST_CONTROL_PROCEEDING:
1180                 if (ast_channel_state(ast) != AST_STATE_UP) {
1181                         response_code = 100;
1182                 } else {
1183                         res = -1;
1184                 }
1185                 break;
1186         case AST_CONTROL_PROGRESS:
1187                 if (ast_channel_state(ast) != AST_STATE_UP) {
1188                         response_code = 183;
1189                 } else {
1190                         res = -1;
1191                 }
1192                 break;
1193         case AST_CONTROL_VIDUPDATE:
1194                 media = pvt->media[SIP_MEDIA_VIDEO];
1195                 if (media && media->rtp) {
1196                         /* FIXME: Only use this for VP8. Additional work would have to be done to
1197                          * fully support other video codecs */
1198
1199                         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
1200                                 /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1201                                  * RTP engine would provide a way to externally write/schedule RTCP
1202                                  * packets */
1203                                 struct ast_frame fr;
1204                                 fr.frametype = AST_FRAME_CONTROL;
1205                                 fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1206                                 res = ast_rtp_instance_write(media->rtp, &fr);
1207                         } else {
1208                                 ao2_ref(channel->session, +1);
1209
1210                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1211                                         ao2_cleanup(channel->session);
1212                                 }
1213                         }
1214                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1215                 } else {
1216                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1217                         res = -1;
1218                 }
1219                 break;
1220         case AST_CONTROL_CONNECTED_LINE:
1221                 ao2_ref(channel->session, +1);
1222                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1223                         ao2_cleanup(channel->session);
1224                 }
1225                 break;
1226         case AST_CONTROL_UPDATE_RTP_PEER:
1227                 break;
1228         case AST_CONTROL_PVT_CAUSE_CODE:
1229                 res = -1;
1230                 break;
1231         case AST_CONTROL_MASQUERADE_NOTIFY:
1232                 ast_assert(datalen == sizeof(int));
1233                 if (*(int *) data) {
1234                         /*
1235                          * Masquerade is beginning:
1236                          * Wait for session serializer to get suspended.
1237                          */
1238                         ast_channel_unlock(ast);
1239                         ast_sip_session_suspend(channel->session);
1240                         ast_channel_lock(ast);
1241                 } else {
1242                         /*
1243                          * Masquerade is complete:
1244                          * Unsuspend the session serializer.
1245                          */
1246                         ast_sip_session_unsuspend(channel->session);
1247                 }
1248                 break;
1249         case AST_CONTROL_HOLD:
1250                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1251                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1252                 device_buf = alloca(device_buf_size);
1253                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1254                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1255                 if (!channel->session->endpoint->moh_passthrough) {
1256                         ast_moh_start(ast, data, NULL);
1257                 } else {
1258                         if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
1259                                 ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
1260                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1261                                 ao2_ref(channel->session, -1);
1262                         }
1263                 }
1264                 break;
1265         case AST_CONTROL_UNHOLD:
1266                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1267                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1268                 device_buf = alloca(device_buf_size);
1269                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1270                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1271                 if (!channel->session->endpoint->moh_passthrough) {
1272                         ast_moh_stop(ast);
1273                 } else {
1274                         if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
1275                                 ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
1276                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1277                                 ao2_ref(channel->session, -1);
1278                         }
1279                 }
1280                 break;
1281         case AST_CONTROL_SRCUPDATE:
1282                 break;
1283         case AST_CONTROL_SRCCHANGE:
1284                 break;
1285         case AST_CONTROL_REDIRECTING:
1286                 if (ast_channel_state(ast) != AST_STATE_UP) {
1287                         response_code = 181;
1288                 } else {
1289                         res = -1;
1290                 }
1291                 break;
1292         case AST_CONTROL_T38_PARAMETERS:
1293                 res = 0;
1294
1295                 if (channel->session->t38state == T38_PEER_REINVITE) {
1296                         const struct ast_control_t38_parameters *parameters = data;
1297
1298                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1299                                 res = AST_T38_REQUEST_PARMS;
1300                         }
1301                 }
1302
1303                 break;
1304         case -1:
1305                 res = -1;
1306                 break;
1307         default:
1308                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1309                 res = -1;
1310                 break;
1311         }
1312
1313         if (response_code) {
1314                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1315                 if (!ind_data || ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1316                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1317                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1318                         ao2_cleanup(ind_data);
1319                         res = -1;
1320                 }
1321         }
1322
1323         return res;
1324 }
1325
1326 struct transfer_data {
1327         struct ast_sip_session *session;
1328         char *target;
1329 };
1330
1331 static void transfer_data_destroy(void *obj)
1332 {
1333         struct transfer_data *trnf_data = obj;
1334
1335         ast_free(trnf_data->target);
1336         ao2_cleanup(trnf_data->session);
1337 }
1338
1339 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1340 {
1341         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1342
1343         if (!trnf_data) {
1344                 return NULL;
1345         }
1346
1347         if (!(trnf_data->target = ast_strdup(target))) {
1348                 ao2_ref(trnf_data, -1);
1349                 return NULL;
1350         }
1351
1352         ao2_ref(session, +1);
1353         trnf_data->session = session;
1354
1355         return trnf_data;
1356 }
1357
1358 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1359 {
1360         pjsip_tx_data *packet;
1361         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1362         pjsip_contact_hdr *contact;
1363         pj_str_t tmp;
1364
1365         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS) {
1366                 message = AST_TRANSFER_FAILED;
1367                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1368
1369                 return;
1370         }
1371
1372         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1373                 contact = pjsip_contact_hdr_create(packet->pool);
1374         }
1375
1376         pj_strdup2_with_null(packet->pool, &tmp, target);
1377         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1378                 message = AST_TRANSFER_FAILED;
1379                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1380                 pjsip_tx_data_dec_ref(packet);
1381
1382                 return;
1383         }
1384         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1385
1386         ast_sip_session_send_response(session, packet);
1387         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1388 }
1389
1390 static void transfer_refer(struct ast_sip_session *session, const char *target)
1391 {
1392         pjsip_evsub *sub;
1393         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1394         pj_str_t tmp;
1395         pjsip_tx_data *packet;
1396
1397         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1398                 message = AST_TRANSFER_FAILED;
1399                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1400
1401                 return;
1402         }
1403
1404         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1405                 message = AST_TRANSFER_FAILED;
1406                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1407                 pjsip_evsub_terminate(sub, PJ_FALSE);
1408
1409                 return;
1410         }
1411
1412         pjsip_xfer_send_request(sub, packet);
1413         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1414 }
1415
1416 static int transfer(void *data)
1417 {
1418         struct transfer_data *trnf_data = data;
1419
1420         if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1421                 transfer_redirect(trnf_data->session, trnf_data->target);
1422         } else {
1423                 transfer_refer(trnf_data->session, trnf_data->target);
1424         }
1425
1426         ao2_ref(trnf_data, -1);
1427         return 0;
1428 }
1429
1430 /*! \brief Function called by core for Asterisk initiated transfer */
1431 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1432 {
1433         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1434         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1435
1436         if (!trnf_data) {
1437                 return -1;
1438         }
1439
1440         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1441                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1442                 ao2_cleanup(trnf_data);
1443                 return -1;
1444         }
1445
1446         return 0;
1447 }
1448
1449 /*! \brief Function called by core to start a DTMF digit */
1450 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1451 {
1452         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1453         struct chan_pjsip_pvt *pvt = channel->pvt;
1454         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1455         int res = 0;
1456
1457         switch (channel->session->endpoint->dtmf) {
1458         case AST_SIP_DTMF_RFC_4733:
1459                 if (!media || !media->rtp) {
1460                         return -1;
1461                 }
1462
1463                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1464         case AST_SIP_DTMF_NONE:
1465                 break;
1466         case AST_SIP_DTMF_INBAND:
1467                 res = -1;
1468                 break;
1469         default:
1470                 break;
1471         }
1472
1473         return res;
1474 }
1475
1476 struct info_dtmf_data {
1477         struct ast_sip_session *session;
1478         char digit;
1479         unsigned int duration;
1480 };
1481
1482 static void info_dtmf_data_destroy(void *obj)
1483 {
1484         struct info_dtmf_data *dtmf_data = obj;
1485         ao2_ref(dtmf_data->session, -1);
1486 }
1487
1488 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1489 {
1490         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1491         if (!dtmf_data) {
1492                 return NULL;
1493         }
1494         ao2_ref(session, +1);
1495         dtmf_data->session = session;
1496         dtmf_data->digit = digit;
1497         dtmf_data->duration = duration;
1498         return dtmf_data;
1499 }
1500
1501 static int transmit_info_dtmf(void *data)
1502 {
1503         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
1504
1505         struct ast_sip_session *session = dtmf_data->session;
1506         struct pjsip_tx_data *tdata;
1507
1508         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
1509
1510         struct ast_sip_body body = {
1511                 .type = "application",
1512                 .subtype = "dtmf-relay",
1513         };
1514
1515         if (!(body_text = ast_str_create(32))) {
1516                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
1517                 return -1;
1518         }
1519         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
1520
1521         body.body_text = ast_str_buffer(body_text);
1522
1523         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1524                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
1525                 return -1;
1526         }
1527         if (ast_sip_add_body(tdata, &body)) {
1528                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
1529                 pjsip_tx_data_dec_ref(tdata);
1530                 return -1;
1531         }
1532         ast_sip_session_send_request(session, tdata);
1533
1534         return 0;
1535 }
1536
1537 /*! \brief Function called by core to stop a DTMF digit */
1538 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1539 {
1540         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1541         struct chan_pjsip_pvt *pvt = channel->pvt;
1542         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1543         int res = 0;
1544
1545         switch (channel->session->endpoint->dtmf) {
1546         case AST_SIP_DTMF_INFO:
1547         {
1548                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
1549
1550                 if (!dtmf_data) {
1551                         return -1;
1552                 }
1553
1554                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
1555                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
1556                         ao2_cleanup(dtmf_data);
1557                         return -1;
1558                 }
1559                 break;
1560         }
1561         case AST_SIP_DTMF_RFC_4733:
1562                 if (!media || !media->rtp) {
1563                         return -1;
1564                 }
1565
1566                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
1567         case AST_SIP_DTMF_NONE:
1568                 break;
1569         case AST_SIP_DTMF_INBAND:
1570                 res = -1;
1571                 break;
1572         }
1573
1574         return res;
1575 }
1576
1577 static void update_initial_connected_line(struct ast_sip_session *session)
1578 {
1579         struct ast_party_connected_line connected;
1580
1581         /*
1582          * Use the channel CALLERID() as the initial connected line data.
1583          * The core or a predial handler may have supplied missing values
1584          * from the session->endpoint->id.self about who we are calling.
1585          */
1586         ast_channel_lock(session->channel);
1587         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
1588         ast_channel_unlock(session->channel);
1589
1590         /* Supply initial connected line information if available. */
1591         if (!session->id.number.valid && !session->id.name.valid) {
1592                 return;
1593         }
1594
1595         ast_party_connected_line_init(&connected);
1596         connected.id = session->id;
1597         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1598
1599         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
1600 }
1601
1602 static int call(void *data)
1603 {
1604         struct ast_sip_channel_pvt *channel = data;
1605         struct ast_sip_session *session = channel->session;
1606         struct chan_pjsip_pvt *pvt = channel->pvt;
1607         pjsip_tx_data *tdata;
1608
1609         int res = ast_sip_session_create_invite(session, &tdata);
1610
1611         if (res) {
1612                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
1613                 ast_queue_hangup(session->channel);
1614         } else {
1615                 set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(session->channel));
1616                 update_initial_connected_line(session);
1617                 ast_sip_session_send_request(session, tdata);
1618         }
1619         ao2_ref(channel, -1);
1620         return res;
1621 }
1622
1623 /*! \brief Function called by core to actually start calling a remote party */
1624 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
1625 {
1626         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1627
1628         ao2_ref(channel, +1);
1629         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
1630                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
1631                 ao2_cleanup(channel);
1632                 return -1;
1633         }
1634
1635         return 0;
1636 }
1637
1638 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
1639 static int hangup_cause2sip(int cause)
1640 {
1641         switch (cause) {
1642         case AST_CAUSE_UNALLOCATED:             /* 1 */
1643         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
1644         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
1645                 return 404;
1646         case AST_CAUSE_CONGESTION:              /* 34 */
1647         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
1648                 return 503;
1649         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
1650                 return 408;
1651         case AST_CAUSE_NO_ANSWER:               /* 19 */
1652         case AST_CAUSE_UNREGISTERED:        /* 20 */
1653                 return 480;
1654         case AST_CAUSE_CALL_REJECTED:           /* 21 */
1655                 return 403;
1656         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
1657                 return 410;
1658         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
1659                 return 480;
1660         case AST_CAUSE_INVALID_NUMBER_FORMAT:
1661                 return 484;
1662         case AST_CAUSE_USER_BUSY:
1663                 return 486;
1664         case AST_CAUSE_FAILURE:
1665                 return 500;
1666         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
1667                 return 501;
1668         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
1669                 return 503;
1670         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
1671                 return 502;
1672         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
1673                 return 488;
1674         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
1675                 return 500;
1676         case AST_CAUSE_NOTDEFINED:
1677         default:
1678                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
1679                 return 0;
1680         }
1681
1682         /* Never reached */
1683         return 0;
1684 }
1685
1686 struct hangup_data {
1687         int cause;
1688         struct ast_channel *chan;
1689 };
1690
1691 static void hangup_data_destroy(void *obj)
1692 {
1693         struct hangup_data *h_data = obj;
1694
1695         h_data->chan = ast_channel_unref(h_data->chan);
1696 }
1697
1698 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
1699 {
1700         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
1701
1702         if (!h_data) {
1703                 return NULL;
1704         }
1705
1706         h_data->cause = cause;
1707         h_data->chan = ast_channel_ref(chan);
1708
1709         return h_data;
1710 }
1711
1712 /*! \brief Clear a channel from a session along with its PVT */
1713 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast, struct chan_pjsip_pvt *pvt)
1714 {
1715         session->channel = NULL;
1716         set_channel_on_rtp_instance(pvt, "");
1717         ast_channel_tech_pvt_set(ast, NULL);
1718 }
1719
1720 static int hangup(void *data)
1721 {
1722         struct hangup_data *h_data = data;
1723         struct ast_channel *ast = h_data->chan;
1724         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1725         struct chan_pjsip_pvt *pvt = channel->pvt;
1726         struct ast_sip_session *session = channel->session;
1727         int cause = h_data->cause;
1728
1729         if (!session->defer_terminate) {
1730                 pj_status_t status;
1731                 pjsip_tx_data *packet = NULL;
1732
1733                 if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1734                         pjsip_inv_terminate(session->inv_session, cause ? cause : 603, PJ_TRUE);
1735                 } else if (((status = pjsip_inv_end_session(session->inv_session, cause ? cause : 603, NULL, &packet)) == PJ_SUCCESS)
1736                         && packet) {
1737                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1738                                 ast_sip_session_send_response(session, packet);
1739                         } else {
1740                                 ast_sip_session_send_request(session, packet);
1741                         }
1742                 }
1743         }
1744
1745         clear_session_and_channel(session, ast, pvt);
1746         ao2_cleanup(channel);
1747         ao2_cleanup(h_data);
1748
1749         return 0;
1750 }
1751
1752 /*! \brief Function called by core to hang up a PJSIP session */
1753 static int chan_pjsip_hangup(struct ast_channel *ast)
1754 {
1755         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1756         struct chan_pjsip_pvt *pvt = channel->pvt;
1757         int cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
1758         struct hangup_data *h_data = hangup_data_alloc(cause, ast);
1759
1760         if (!h_data) {
1761                 goto failure;
1762         }
1763
1764         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
1765                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
1766                 goto failure;
1767         }
1768
1769         return 0;
1770
1771 failure:
1772         /* Go ahead and do our cleanup of the session and channel even if we're not going
1773          * to be able to send our SIP request/response
1774          */
1775         clear_session_and_channel(channel->session, ast, pvt);
1776         ao2_cleanup(channel);
1777         ao2_cleanup(h_data);
1778
1779         return -1;
1780 }
1781
1782 struct request_data {
1783         struct ast_sip_session *session;
1784         struct ast_format_cap *caps;
1785         const char *dest;
1786         int cause;
1787 };
1788
1789 static int request(void *obj)
1790 {
1791         struct request_data *req_data = obj;
1792         struct ast_sip_session *session = NULL;
1793         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
1794         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1795         struct ast_sip_aor *aor = NULL;
1796
1797         AST_DECLARE_APP_ARGS(args,
1798                 AST_APP_ARG(endpoint);
1799                 AST_APP_ARG(aor);
1800         );
1801
1802         if (ast_strlen_zero(tmp)) {
1803                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
1804                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1805                 return -1;
1806         }
1807
1808         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
1809
1810         /* If a request user has been specified extract it from the endpoint name portion */
1811         if ((endpoint_name = strchr(args.endpoint, '@'))) {
1812                 request_user = args.endpoint;
1813                 *endpoint_name++ = '\0';
1814         } else {
1815                 endpoint_name = args.endpoint;
1816         }
1817
1818         if (ast_strlen_zero(endpoint_name)) {
1819                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
1820                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1821         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1822                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
1823                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1824                 return -1;
1825         } else if (!ast_strlen_zero(args.aor) && (!(aor = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "aor", args.aor)))) {
1826                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - AOR '%s' was not found\n", args.aor);
1827                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1828                 return -1;
1829         }
1830
1831         ao2_cleanup(aor);
1832
1833         if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->caps))) {
1834                 ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
1835                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1836                 return -1;
1837         }
1838
1839         req_data->session = session;
1840
1841         return 0;
1842 }
1843
1844 /*! \brief Function called by core to create a new outgoing PJSIP session */
1845 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)
1846 {
1847         struct request_data req_data;
1848         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1849
1850         req_data.caps = cap;
1851         req_data.dest = data;
1852
1853         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
1854                 *cause = req_data.cause;
1855                 return NULL;
1856         }
1857
1858         session = req_data.session;
1859
1860         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
1861                 /* Session needs to be terminated prematurely */
1862                 return NULL;
1863         }
1864
1865         return session->channel;
1866 }
1867
1868 struct sendtext_data {
1869         struct ast_sip_session *session;
1870         char text[0];
1871 };
1872
1873 static void sendtext_data_destroy(void *obj)
1874 {
1875         struct sendtext_data *data = obj;
1876         ao2_ref(data->session, -1);
1877 }
1878
1879 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
1880 {
1881         int size = strlen(text) + 1;
1882         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
1883
1884         if (!data) {
1885                 return NULL;
1886         }
1887
1888         data->session = session;
1889         ao2_ref(data->session, +1);
1890         ast_copy_string(data->text, text, size);
1891         return data;
1892 }
1893
1894 static int sendtext(void *obj)
1895 {
1896         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
1897         pjsip_tx_data *tdata;
1898
1899         const struct ast_sip_body body = {
1900                 .type = "text",
1901                 .subtype = "plain",
1902                 .body_text = data->text
1903         };
1904
1905         /* NOT ast_strlen_zero, because a zero-length message is specifically
1906          * allowed by RFC 3428 (See section 10, Examples) */
1907         if (!data->text) {
1908                 return 0;
1909         }
1910
1911         ast_debug(3, "Sending in dialog SIP message\n");
1912
1913         ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
1914         ast_sip_add_body(tdata, &body);
1915         ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
1916
1917         return 0;
1918 }
1919
1920 /*! \brief Function called by core to send text on PJSIP session */
1921 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
1922 {
1923         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1924         struct sendtext_data *data = sendtext_data_create(channel->session, text);
1925
1926         if (!data || ast_sip_push_task(channel->session->serializer, sendtext, data)) {
1927                 ao2_ref(data, -1);
1928                 return -1;
1929         }
1930         return 0;
1931 }
1932
1933 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
1934 static int hangup_sip2cause(int cause)
1935 {
1936         /* Possible values taken from causes.h */
1937
1938         switch(cause) {
1939         case 401:       /* Unauthorized */
1940                 return AST_CAUSE_CALL_REJECTED;
1941         case 403:       /* Not found */
1942                 return AST_CAUSE_CALL_REJECTED;
1943         case 404:       /* Not found */
1944                 return AST_CAUSE_UNALLOCATED;
1945         case 405:       /* Method not allowed */
1946                 return AST_CAUSE_INTERWORKING;
1947         case 407:       /* Proxy authentication required */
1948                 return AST_CAUSE_CALL_REJECTED;
1949         case 408:       /* No reaction */
1950                 return AST_CAUSE_NO_USER_RESPONSE;
1951         case 409:       /* Conflict */
1952                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1953         case 410:       /* Gone */
1954                 return AST_CAUSE_NUMBER_CHANGED;
1955         case 411:       /* Length required */
1956                 return AST_CAUSE_INTERWORKING;
1957         case 413:       /* Request entity too large */
1958                 return AST_CAUSE_INTERWORKING;
1959         case 414:       /* Request URI too large */
1960                 return AST_CAUSE_INTERWORKING;
1961         case 415:       /* Unsupported media type */
1962                 return AST_CAUSE_INTERWORKING;
1963         case 420:       /* Bad extension */
1964                 return AST_CAUSE_NO_ROUTE_DESTINATION;
1965         case 480:       /* No answer */
1966                 return AST_CAUSE_NO_ANSWER;
1967         case 481:       /* No answer */
1968                 return AST_CAUSE_INTERWORKING;
1969         case 482:       /* Loop detected */
1970                 return AST_CAUSE_INTERWORKING;
1971         case 483:       /* Too many hops */
1972                 return AST_CAUSE_NO_ANSWER;
1973         case 484:       /* Address incomplete */
1974                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
1975         case 485:       /* Ambiguous */
1976                 return AST_CAUSE_UNALLOCATED;
1977         case 486:       /* Busy everywhere */
1978                 return AST_CAUSE_BUSY;
1979         case 487:       /* Request terminated */
1980                 return AST_CAUSE_INTERWORKING;
1981         case 488:       /* No codecs approved */
1982                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1983         case 491:       /* Request pending */
1984                 return AST_CAUSE_INTERWORKING;
1985         case 493:       /* Undecipherable */
1986                 return AST_CAUSE_INTERWORKING;
1987         case 500:       /* Server internal failure */
1988                 return AST_CAUSE_FAILURE;
1989         case 501:       /* Call rejected */
1990                 return AST_CAUSE_FACILITY_REJECTED;
1991         case 502:
1992                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1993         case 503:       /* Service unavailable */
1994                 return AST_CAUSE_CONGESTION;
1995         case 504:       /* Gateway timeout */
1996                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
1997         case 505:       /* SIP version not supported */
1998                 return AST_CAUSE_INTERWORKING;
1999         case 600:       /* Busy everywhere */
2000                 return AST_CAUSE_USER_BUSY;
2001         case 603:       /* Decline */
2002                 return AST_CAUSE_CALL_REJECTED;
2003         case 604:       /* Does not exist anywhere */
2004                 return AST_CAUSE_UNALLOCATED;
2005         case 606:       /* Not acceptable */
2006                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2007         default:
2008                 if (cause < 500 && cause >= 400) {
2009                         /* 4xx class error that is unknown - someting wrong with our request */
2010                         return AST_CAUSE_INTERWORKING;
2011                 } else if (cause < 600 && cause >= 500) {
2012                         /* 5xx class error - problem in the remote end */
2013                         return AST_CAUSE_CONGESTION;
2014                 } else if (cause < 700 && cause >= 600) {
2015                         /* 6xx - global errors in the 4xx class */
2016                         return AST_CAUSE_INTERWORKING;
2017                 }
2018                 return AST_CAUSE_NORMAL;
2019         }
2020         /* Never reached */
2021         return 0;
2022 }
2023
2024 static void chan_pjsip_session_begin(struct ast_sip_session *session)
2025 {
2026         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2027
2028         if (session->endpoint->media.direct_media.glare_mitigation ==
2029                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
2030                 return;
2031         }
2032
2033         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
2034                         "direct_media_glare_mitigation");
2035
2036         if (!datastore) {
2037                 return;
2038         }
2039
2040         ast_sip_session_add_datastore(session, datastore);
2041 }
2042
2043 /*! \brief Function called when the session ends */
2044 static void chan_pjsip_session_end(struct ast_sip_session *session)
2045 {
2046         if (!session->channel) {
2047                 return;
2048         }
2049
2050         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
2051
2052         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2053         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
2054                 int cause = hangup_sip2cause(session->inv_session->cause);
2055
2056                 ast_queue_hangup_with_cause(session->channel, cause);
2057         } else {
2058                 ast_queue_hangup(session->channel);
2059         }
2060 }
2061
2062 /*! \brief Function called when a request is received on the session */
2063 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2064 {
2065         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2066         struct transport_info_data *transport_data;
2067         pjsip_tx_data *packet = NULL;
2068
2069         if (session->channel) {
2070                 return 0;
2071         }
2072
2073         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
2074         if (!datastore) {
2075                 return -1;
2076         }
2077
2078         transport_data = ast_calloc(1, sizeof(*transport_data));
2079         if (!transport_data) {
2080                 return -1;
2081         }
2082         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
2083         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
2084         datastore->data = transport_data;
2085         ast_sip_session_add_datastore(session, datastore);
2086
2087         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2088                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS) {
2089                         ast_sip_session_send_response(session, packet);
2090                 }
2091
2092                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2093                 return -1;
2094         }
2095         /* channel gets created on incoming request, but we wait to call start
2096            so other supplements have a chance to run */
2097         return 0;
2098 }
2099
2100 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2101 {
2102         struct ast_features_pickup_config *pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2103         struct ast_channel *chan;
2104
2105         /* We don't care about reinvites */
2106         if (session->inv_session->state >= PJSIP_INV_STATE_CONFIRMED) {
2107                 return 0;
2108         }
2109
2110         if (!pickup_cfg) {
2111                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2112                 return 0;
2113         }
2114
2115         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2116                 ao2_ref(pickup_cfg, -1);
2117                 return 0;
2118         }
2119         ao2_ref(pickup_cfg, -1);
2120
2121         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2122          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2123          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2124          */
2125         chan = ast_channel_ref(session->channel);
2126         if (ast_pickup_call(chan)) {
2127                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2128         } else {
2129                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2130         }
2131         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2132          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2133          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2134          * to anything at all.
2135          */
2136         ast_hangup(chan);
2137         ast_channel_unref(chan);
2138
2139         return 1;
2140 }
2141
2142 static struct ast_sip_session_supplement call_pickup_supplement = {
2143         .method = "INVITE",
2144         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2145         .incoming_request = call_pickup_incoming_request,
2146 };
2147
2148 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2149 {
2150         int res;
2151
2152         /* We don't care about reinvites */
2153         if (session->inv_session->state >= PJSIP_INV_STATE_CONFIRMED) {
2154                 return 0;
2155         }
2156
2157         res = ast_pbx_start(session->channel);
2158
2159         switch (res) {
2160         case AST_PBX_FAILED:
2161                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2162                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2163                 ast_hangup(session->channel);
2164                 break;
2165         case AST_PBX_CALL_LIMIT:
2166                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2167                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2168                 ast_hangup(session->channel);
2169                 break;
2170         case AST_PBX_SUCCESS:
2171         default:
2172                 break;
2173         }
2174
2175         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2176
2177         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2178 }
2179
2180 static struct ast_sip_session_supplement pbx_start_supplement = {
2181         .method = "INVITE",
2182         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2183         .incoming_request = pbx_start_incoming_request,
2184 };
2185
2186 /*! \brief Function called when a response is received on the session */
2187 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2188 {
2189         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2190         struct ast_control_pvt_cause_code *cause_code;
2191         int data_size = sizeof(*cause_code);
2192
2193         if (!session->channel) {
2194                 return;
2195         }
2196
2197         switch (status.code) {
2198         case 180:
2199                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2200                 ast_channel_lock(session->channel);
2201                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2202                         ast_setstate(session->channel, AST_STATE_RINGING);
2203                 }
2204                 ast_channel_unlock(session->channel);
2205                 break;
2206         case 183:
2207                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2208                 break;
2209         case 200:
2210                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2211                 break;
2212         default:
2213                 break;
2214         }
2215
2216         /* Build and send the tech-specific cause information */
2217         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2218         data_size += 4 + 4 + pj_strlen(&status.reason);
2219         cause_code = ast_alloca(data_size);
2220         memset(cause_code, 0, data_size);
2221
2222         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2223
2224         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2225                 (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2226
2227         cause_code->ast_cause = hangup_sip2cause(status.code);
2228         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2229         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2230 }
2231
2232 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2233 {
2234         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2235                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2236                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2237                 }
2238         }
2239         return 0;
2240 }
2241
2242 static int update_devstate(void *obj, void *arg, int flags)
2243 {
2244         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2245                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2246         return 0;
2247 }
2248
2249 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2250         .name = "PJSIP_DIAL_CONTACTS",
2251         .read = pjsip_acf_dial_contacts_read,
2252 };
2253
2254 static struct ast_custom_function media_offer_function = {
2255         .name = "PJSIP_MEDIA_OFFER",
2256         .read = pjsip_acf_media_offer_read,
2257         .write = pjsip_acf_media_offer_write
2258 };
2259
2260 /*!
2261  * \brief Load the module
2262  *
2263  * Module loading including tests for configuration or dependencies.
2264  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2265  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2266  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2267  * configuration file or other non-critical problem return
2268  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2269  */
2270 static int load_module(void)
2271 {
2272         struct ao2_container *endpoints;
2273
2274         CHECK_PJSIP_SESSION_MODULE_LOADED();
2275
2276         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2277                 return AST_MODULE_LOAD_DECLINE;
2278         }
2279
2280         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
2281
2282         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2283
2284         if (ast_channel_register(&chan_pjsip_tech)) {
2285                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2286                 goto end;
2287         }
2288
2289         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2290                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2291                 goto end;
2292         }
2293
2294         if (ast_custom_function_register(&media_offer_function)) {
2295                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2296                 goto end;
2297         }
2298
2299         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2300                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2301                 goto end;
2302         }
2303
2304         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
2305                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
2306                         uid_hold_sort_fn, NULL))) {
2307                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
2308                 goto end;
2309         }
2310
2311         if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
2312                 ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
2313                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2314                 goto end;
2315         }
2316
2317         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2318                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2319                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2320                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2321                 goto end;
2322         }
2323
2324         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2325                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2326                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2327                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2328                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2329                 goto end;
2330         }
2331
2332         /* since endpoints are loaded before the channel driver their device
2333            states get set to 'invalid', so they need to be updated */
2334         if ((endpoints = ast_sip_get_endpoints())) {
2335                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
2336                 ao2_ref(endpoints, -1);
2337         }
2338
2339         return 0;
2340
2341 end:
2342         ao2_cleanup(pjsip_uids_onhold);
2343         pjsip_uids_onhold = NULL;
2344         ast_custom_function_unregister(&media_offer_function);
2345         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2346         ast_channel_unregister(&chan_pjsip_tech);
2347         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2348
2349         return AST_MODULE_LOAD_FAILURE;
2350 }
2351
2352 /*! \brief Unload the PJSIP channel from Asterisk */
2353 static int unload_module(void)
2354 {
2355         ao2_cleanup(pjsip_uids_onhold);
2356         pjsip_uids_onhold = NULL;
2357
2358         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2359         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2360         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2361         ast_sip_session_unregister_supplement(&call_pickup_supplement);
2362
2363         ast_custom_function_unregister(&media_offer_function);
2364         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2365
2366         ast_channel_unregister(&chan_pjsip_tech);
2367         ao2_ref(chan_pjsip_tech.capabilities, -1);
2368         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2369
2370         return 0;
2371 }
2372
2373 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
2374                 .support_level = AST_MODULE_SUPPORT_CORE,
2375                 .load = load_module,
2376                 .unload = unload_module,
2377                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2378                );