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