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