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