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