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