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