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