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