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