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