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