core: Don't allow free to mean ast_free (and malloc, etc..).
[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                 struct ast_party_id connected_id;
1085
1086                 if (session->inv_session->invite_tsx && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1087                         method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1088                 }
1089
1090                 /*
1091                  * We can get away with a shallow copy here because we are
1092                  * not looking at strings.
1093                  */
1094                 ast_channel_lock(session->channel);
1095                 connected_id = ast_channel_connected_effective_id(session->channel);
1096                 ast_channel_unlock(session->channel);
1097
1098                 if ((session->endpoint->id.send_pai || session->endpoint->id.send_rpid) &&
1099                     (session->endpoint->id.trust_outbound ||
1100                      ((connected_id.name.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED &&
1101                       (connected_id.number.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED))) {
1102                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, 1);
1103                 }
1104         }
1105
1106         return 0;
1107 }
1108
1109 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1110 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1111 {
1112         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1113         struct chan_pjsip_pvt *pvt = channel->pvt;
1114         struct ast_sip_session_media *media;
1115         int response_code = 0;
1116         int res = 0;
1117         char *device_buf;
1118         size_t device_buf_size;
1119
1120         switch (condition) {
1121         case AST_CONTROL_RINGING:
1122                 if (ast_channel_state(ast) == AST_STATE_RING) {
1123                         if (channel->session->endpoint->inband_progress) {
1124                                 response_code = 183;
1125                                 res = -1;
1126                         } else {
1127                                 response_code = 180;
1128                         }
1129                 } else {
1130                         res = -1;
1131                 }
1132                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1133                 break;
1134         case AST_CONTROL_BUSY:
1135                 if (ast_channel_state(ast) != AST_STATE_UP) {
1136                         response_code = 486;
1137                 } else {
1138                         res = -1;
1139                 }
1140                 break;
1141         case AST_CONTROL_CONGESTION:
1142                 if (ast_channel_state(ast) != AST_STATE_UP) {
1143                         response_code = 503;
1144                 } else {
1145                         res = -1;
1146                 }
1147                 break;
1148         case AST_CONTROL_INCOMPLETE:
1149                 if (ast_channel_state(ast) != AST_STATE_UP) {
1150                         response_code = 484;
1151                 } else {
1152                         res = -1;
1153                 }
1154                 break;
1155         case AST_CONTROL_PROCEEDING:
1156                 if (ast_channel_state(ast) != AST_STATE_UP) {
1157                         response_code = 100;
1158                 } else {
1159                         res = -1;
1160                 }
1161                 break;
1162         case AST_CONTROL_PROGRESS:
1163                 if (ast_channel_state(ast) != AST_STATE_UP) {
1164                         response_code = 183;
1165                 } else {
1166                         res = -1;
1167                 }
1168                 break;
1169         case AST_CONTROL_VIDUPDATE:
1170                 media = pvt->media[SIP_MEDIA_VIDEO];
1171                 if (media && media->rtp) {
1172                         /* FIXME: Only use this for VP8. Additional work would have to be done to
1173                          * fully support other video codecs */
1174
1175                         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
1176                                 /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1177                                  * RTP engine would provide a way to externally write/schedule RTCP
1178                                  * packets */
1179                                 struct ast_frame fr;
1180                                 fr.frametype = AST_FRAME_CONTROL;
1181                                 fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1182                                 res = ast_rtp_instance_write(media->rtp, &fr);
1183                         } else {
1184                                 ao2_ref(channel->session, +1);
1185
1186                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1187                                         ao2_cleanup(channel->session);
1188                                 }
1189                         }
1190                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1191                 } else {
1192                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1193                         res = -1;
1194                 }
1195                 break;
1196         case AST_CONTROL_CONNECTED_LINE:
1197                 ao2_ref(channel->session, +1);
1198                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1199                         ao2_cleanup(channel->session);
1200                 }
1201                 break;
1202         case AST_CONTROL_UPDATE_RTP_PEER:
1203                 break;
1204         case AST_CONTROL_PVT_CAUSE_CODE:
1205                 res = -1;
1206                 break;
1207         case AST_CONTROL_HOLD:
1208                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1209                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1210                 device_buf = alloca(device_buf_size);
1211                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1212                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1213                 ast_moh_start(ast, data, NULL);
1214                 break;
1215         case AST_CONTROL_UNHOLD:
1216                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1217                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1218                 device_buf = alloca(device_buf_size);
1219                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1220                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1221                 ast_moh_stop(ast);
1222                 break;
1223         case AST_CONTROL_SRCUPDATE:
1224                 break;
1225         case AST_CONTROL_SRCCHANGE:
1226                 break;
1227         case AST_CONTROL_REDIRECTING:
1228                 if (ast_channel_state(ast) != AST_STATE_UP) {
1229                         response_code = 181;
1230                 } else {
1231                         res = -1;
1232                 }
1233                 break;
1234         case AST_CONTROL_T38_PARAMETERS:
1235                 res = 0;
1236
1237                 if (channel->session->t38state == T38_PEER_REINVITE) {
1238                         const struct ast_control_t38_parameters *parameters = data;
1239
1240                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1241                                 res = AST_T38_REQUEST_PARMS;
1242                         }
1243                 }
1244
1245                 break;
1246         case -1:
1247                 res = -1;
1248                 break;
1249         default:
1250                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1251                 res = -1;
1252                 break;
1253         }
1254
1255         if (response_code) {
1256                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1257                 if (!ind_data || ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1258                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1259                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1260                         ao2_cleanup(ind_data);
1261                         res = -1;
1262                 }
1263         }
1264
1265         return res;
1266 }
1267
1268 struct transfer_data {
1269         struct ast_sip_session *session;
1270         char *target;
1271 };
1272
1273 static void transfer_data_destroy(void *obj)
1274 {
1275         struct transfer_data *trnf_data = obj;
1276
1277         ast_free(trnf_data->target);
1278         ao2_cleanup(trnf_data->session);
1279 }
1280
1281 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1282 {
1283         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1284
1285         if (!trnf_data) {
1286                 return NULL;
1287         }
1288
1289         if (!(trnf_data->target = ast_strdup(target))) {
1290                 ao2_ref(trnf_data, -1);
1291                 return NULL;
1292         }
1293
1294         ao2_ref(session, +1);
1295         trnf_data->session = session;
1296
1297         return trnf_data;
1298 }
1299
1300 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1301 {
1302         pjsip_tx_data *packet;
1303         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1304         pjsip_contact_hdr *contact;
1305         pj_str_t tmp;
1306
1307         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS) {
1308                 message = AST_TRANSFER_FAILED;
1309                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1310
1311                 return;
1312         }
1313
1314         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1315                 contact = pjsip_contact_hdr_create(packet->pool);
1316         }
1317
1318         pj_strdup2_with_null(packet->pool, &tmp, target);
1319         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1320                 message = AST_TRANSFER_FAILED;
1321                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1322                 pjsip_tx_data_dec_ref(packet);
1323
1324                 return;
1325         }
1326         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1327
1328         ast_sip_session_send_response(session, packet);
1329         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1330 }
1331
1332 static void transfer_refer(struct ast_sip_session *session, const char *target)
1333 {
1334         pjsip_evsub *sub;
1335         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1336         pj_str_t tmp;
1337         pjsip_tx_data *packet;
1338
1339         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1340                 message = AST_TRANSFER_FAILED;
1341                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1342
1343                 return;
1344         }
1345
1346         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1347                 message = AST_TRANSFER_FAILED;
1348                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1349                 pjsip_evsub_terminate(sub, PJ_FALSE);
1350
1351                 return;
1352         }
1353
1354         pjsip_xfer_send_request(sub, packet);
1355         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1356 }
1357
1358 static int transfer(void *data)
1359 {
1360         struct transfer_data *trnf_data = data;
1361
1362         if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1363                 transfer_redirect(trnf_data->session, trnf_data->target);
1364         } else {
1365                 transfer_refer(trnf_data->session, trnf_data->target);
1366         }
1367
1368         ao2_ref(trnf_data, -1);
1369         return 0;
1370 }
1371
1372 /*! \brief Function called by core for Asterisk initiated transfer */
1373 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1374 {
1375         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1376         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1377
1378         if (!trnf_data) {
1379                 return -1;
1380         }
1381
1382         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1383                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1384                 ao2_cleanup(trnf_data);
1385                 return -1;
1386         }
1387
1388         return 0;
1389 }
1390
1391 /*! \brief Function called by core to start a DTMF digit */
1392 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1393 {
1394         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1395         struct chan_pjsip_pvt *pvt = channel->pvt;
1396         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1397         int res = 0;
1398
1399         switch (channel->session->endpoint->dtmf) {
1400         case AST_SIP_DTMF_RFC_4733:
1401                 if (!media || !media->rtp) {
1402                         return -1;
1403                 }
1404
1405                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1406         case AST_SIP_DTMF_NONE:
1407                 break;
1408         case AST_SIP_DTMF_INBAND:
1409                 res = -1;
1410                 break;
1411         default:
1412                 break;
1413         }
1414
1415         return res;
1416 }
1417
1418 struct info_dtmf_data {
1419         struct ast_sip_session *session;
1420         char digit;
1421         unsigned int duration;
1422 };
1423
1424 static void info_dtmf_data_destroy(void *obj)
1425 {
1426         struct info_dtmf_data *dtmf_data = obj;
1427         ao2_ref(dtmf_data->session, -1);
1428 }
1429
1430 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1431 {
1432         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1433         if (!dtmf_data) {
1434                 return NULL;
1435         }
1436         ao2_ref(session, +1);
1437         dtmf_data->session = session;
1438         dtmf_data->digit = digit;
1439         dtmf_data->duration = duration;
1440         return dtmf_data;
1441 }
1442
1443 static int transmit_info_dtmf(void *data)
1444 {
1445         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
1446
1447         struct ast_sip_session *session = dtmf_data->session;
1448         struct pjsip_tx_data *tdata;
1449
1450         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
1451
1452         struct ast_sip_body body = {
1453                 .type = "application",
1454                 .subtype = "dtmf-relay",
1455         };
1456
1457         if (!(body_text = ast_str_create(32))) {
1458                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
1459                 return -1;
1460         }
1461         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
1462
1463         body.body_text = ast_str_buffer(body_text);
1464
1465         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1466                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
1467                 return -1;
1468         }
1469         if (ast_sip_add_body(tdata, &body)) {
1470                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
1471                 pjsip_tx_data_dec_ref(tdata);
1472                 return -1;
1473         }
1474         ast_sip_session_send_request(session, tdata);
1475
1476         return 0;
1477 }
1478
1479 /*! \brief Function called by core to stop a DTMF digit */
1480 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1481 {
1482         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1483         struct chan_pjsip_pvt *pvt = channel->pvt;
1484         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1485         int res = 0;
1486
1487         switch (channel->session->endpoint->dtmf) {
1488         case AST_SIP_DTMF_INFO:
1489         {
1490                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
1491
1492                 if (!dtmf_data) {
1493                         return -1;
1494                 }
1495
1496                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
1497                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
1498                         ao2_cleanup(dtmf_data);
1499                         return -1;
1500                 }
1501                 break;
1502         }
1503         case AST_SIP_DTMF_RFC_4733:
1504                 if (!media || !media->rtp) {
1505                         return -1;
1506                 }
1507
1508                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
1509         case AST_SIP_DTMF_NONE:
1510                 break;
1511         case AST_SIP_DTMF_INBAND:
1512                 res = -1;
1513                 break;
1514         }
1515
1516         return res;
1517 }
1518
1519 static void update_initial_connected_line(struct ast_sip_session *session)
1520 {
1521         struct ast_party_connected_line connected;
1522
1523         /*
1524          * Use the channel CALLERID() as the initial connected line data.
1525          * The core or a predial handler may have supplied missing values
1526          * from the session->endpoint->id.self about who we are calling.
1527          */
1528         ast_channel_lock(session->channel);
1529         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
1530         ast_channel_unlock(session->channel);
1531
1532         /* Supply initial connected line information if available. */
1533         if (!session->id.number.valid && !session->id.name.valid) {
1534                 return;
1535         }
1536
1537         ast_party_connected_line_init(&connected);
1538         connected.id = session->id;
1539         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1540
1541         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
1542 }
1543
1544 static int call(void *data)
1545 {
1546         struct ast_sip_channel_pvt *channel = data;
1547         struct ast_sip_session *session = channel->session;
1548         struct chan_pjsip_pvt *pvt = channel->pvt;
1549         pjsip_tx_data *tdata;
1550
1551         int res = ast_sip_session_create_invite(session, &tdata);
1552
1553         if (res) {
1554                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
1555                 ast_queue_hangup(session->channel);
1556         } else {
1557                 set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(session->channel));
1558                 update_initial_connected_line(session);
1559                 ast_sip_session_send_request(session, tdata);
1560         }
1561         ao2_ref(channel, -1);
1562         return res;
1563 }
1564
1565 /*! \brief Function called by core to actually start calling a remote party */
1566 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
1567 {
1568         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1569
1570         ao2_ref(channel, +1);
1571         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
1572                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
1573                 ao2_cleanup(channel);
1574                 return -1;
1575         }
1576
1577         return 0;
1578 }
1579
1580 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
1581 static int hangup_cause2sip(int cause)
1582 {
1583         switch (cause) {
1584         case AST_CAUSE_UNALLOCATED:             /* 1 */
1585         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
1586         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
1587                 return 404;
1588         case AST_CAUSE_CONGESTION:              /* 34 */
1589         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
1590                 return 503;
1591         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
1592                 return 408;
1593         case AST_CAUSE_NO_ANSWER:               /* 19 */
1594         case AST_CAUSE_UNREGISTERED:        /* 20 */
1595                 return 480;
1596         case AST_CAUSE_CALL_REJECTED:           /* 21 */
1597                 return 403;
1598         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
1599                 return 410;
1600         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
1601                 return 480;
1602         case AST_CAUSE_INVALID_NUMBER_FORMAT:
1603                 return 484;
1604         case AST_CAUSE_USER_BUSY:
1605                 return 486;
1606         case AST_CAUSE_FAILURE:
1607                 return 500;
1608         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
1609                 return 501;
1610         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
1611                 return 503;
1612         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
1613                 return 502;
1614         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
1615                 return 488;
1616         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
1617                 return 500;
1618         case AST_CAUSE_NOTDEFINED:
1619         default:
1620                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
1621                 return 0;
1622         }
1623
1624         /* Never reached */
1625         return 0;
1626 }
1627
1628 struct hangup_data {
1629         int cause;
1630         struct ast_channel *chan;
1631 };
1632
1633 static void hangup_data_destroy(void *obj)
1634 {
1635         struct hangup_data *h_data = obj;
1636
1637         h_data->chan = ast_channel_unref(h_data->chan);
1638 }
1639
1640 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
1641 {
1642         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
1643
1644         if (!h_data) {
1645                 return NULL;
1646         }
1647
1648         h_data->cause = cause;
1649         h_data->chan = ast_channel_ref(chan);
1650
1651         return h_data;
1652 }
1653
1654 /*! \brief Clear a channel from a session along with its PVT */
1655 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast, struct chan_pjsip_pvt *pvt)
1656 {
1657         session->channel = NULL;
1658         set_channel_on_rtp_instance(pvt, "");
1659         ast_channel_tech_pvt_set(ast, NULL);
1660 }
1661
1662 static int hangup(void *data)
1663 {
1664         struct hangup_data *h_data = data;
1665         struct ast_channel *ast = h_data->chan;
1666         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1667         struct chan_pjsip_pvt *pvt = channel->pvt;
1668         struct ast_sip_session *session = channel->session;
1669         int cause = h_data->cause;
1670
1671         if (!session->defer_terminate) {
1672                 pj_status_t status;
1673                 pjsip_tx_data *packet = NULL;
1674
1675                 if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1676                         pjsip_inv_terminate(session->inv_session, cause ? cause : 603, PJ_TRUE);
1677                 } else if (((status = pjsip_inv_end_session(session->inv_session, cause ? cause : 603, NULL, &packet)) == PJ_SUCCESS)
1678                         && packet) {
1679                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1680                                 ast_sip_session_send_response(session, packet);
1681                         } else {
1682                                 ast_sip_session_send_request(session, packet);
1683                         }
1684                 }
1685         }
1686
1687         clear_session_and_channel(session, ast, pvt);
1688         ao2_cleanup(channel);
1689         ao2_cleanup(h_data);
1690
1691         return 0;
1692 }
1693
1694 /*! \brief Function called by core to hang up a PJSIP session */
1695 static int chan_pjsip_hangup(struct ast_channel *ast)
1696 {
1697         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1698         struct chan_pjsip_pvt *pvt = channel->pvt;
1699         int cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
1700         struct hangup_data *h_data = hangup_data_alloc(cause, ast);
1701
1702         if (!h_data) {
1703                 goto failure;
1704         }
1705
1706         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
1707                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
1708                 goto failure;
1709         }
1710
1711         return 0;
1712
1713 failure:
1714         /* Go ahead and do our cleanup of the session and channel even if we're not going
1715          * to be able to send our SIP request/response
1716          */
1717         clear_session_and_channel(channel->session, ast, pvt);
1718         ao2_cleanup(channel);
1719         ao2_cleanup(h_data);
1720
1721         return -1;
1722 }
1723
1724 struct request_data {
1725         struct ast_sip_session *session;
1726         struct ast_format_cap *caps;
1727         const char *dest;
1728         int cause;
1729 };
1730
1731 static int request(void *obj)
1732 {
1733         struct request_data *req_data = obj;
1734         struct ast_sip_session *session = NULL;
1735         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
1736         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1737
1738         AST_DECLARE_APP_ARGS(args,
1739                 AST_APP_ARG(endpoint);
1740                 AST_APP_ARG(aor);
1741         );
1742
1743         if (ast_strlen_zero(tmp)) {
1744                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
1745                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1746                 return -1;
1747         }
1748
1749         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
1750
1751         /* If a request user has been specified extract it from the endpoint name portion */
1752         if ((endpoint_name = strchr(args.endpoint, '@'))) {
1753                 request_user = args.endpoint;
1754                 *endpoint_name++ = '\0';
1755         } else {
1756                 endpoint_name = args.endpoint;
1757         }
1758
1759         if (ast_strlen_zero(endpoint_name)) {
1760                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
1761                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1762         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1763                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
1764                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1765                 return -1;
1766         }
1767
1768         if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->caps))) {
1769                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1770                 return -1;
1771         }
1772
1773         req_data->session = session;
1774
1775         return 0;
1776 }
1777
1778 /*! \brief Function called by core to create a new outgoing PJSIP session */
1779 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)
1780 {
1781         struct request_data req_data;
1782         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1783
1784         req_data.caps = cap;
1785         req_data.dest = data;
1786
1787         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
1788                 *cause = req_data.cause;
1789                 return NULL;
1790         }
1791
1792         session = req_data.session;
1793
1794         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
1795                 /* Session needs to be terminated prematurely */
1796                 return NULL;
1797         }
1798
1799         return session->channel;
1800 }
1801
1802 struct sendtext_data {
1803         struct ast_sip_session *session;
1804         char text[0];
1805 };
1806
1807 static void sendtext_data_destroy(void *obj)
1808 {
1809         struct sendtext_data *data = obj;
1810         ao2_ref(data->session, -1);
1811 }
1812
1813 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
1814 {
1815         int size = strlen(text) + 1;
1816         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
1817
1818         if (!data) {
1819                 return NULL;
1820         }
1821
1822         data->session = session;
1823         ao2_ref(data->session, +1);
1824         ast_copy_string(data->text, text, size);
1825         return data;
1826 }
1827
1828 static int sendtext(void *obj)
1829 {
1830         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
1831         pjsip_tx_data *tdata;
1832
1833         const struct ast_sip_body body = {
1834                 .type = "text",
1835                 .subtype = "plain",
1836                 .body_text = data->text
1837         };
1838
1839         /* NOT ast_strlen_zero, because a zero-length message is specifically
1840          * allowed by RFC 3428 (See section 10, Examples) */
1841         if (!data->text) {
1842                 return 0;
1843         }
1844
1845         ast_debug(3, "Sending in dialog SIP message\n");
1846
1847         ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
1848         ast_sip_add_body(tdata, &body);
1849         ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
1850
1851         return 0;
1852 }
1853
1854 /*! \brief Function called by core to send text on PJSIP session */
1855 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
1856 {
1857         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1858         struct sendtext_data *data = sendtext_data_create(channel->session, text);
1859
1860         if (!data || ast_sip_push_task(channel->session->serializer, sendtext, data)) {
1861                 ao2_ref(data, -1);
1862                 return -1;
1863         }
1864         return 0;
1865 }
1866
1867 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
1868 static int hangup_sip2cause(int cause)
1869 {
1870         /* Possible values taken from causes.h */
1871
1872         switch(cause) {
1873         case 401:       /* Unauthorized */
1874                 return AST_CAUSE_CALL_REJECTED;
1875         case 403:       /* Not found */
1876                 return AST_CAUSE_CALL_REJECTED;
1877         case 404:       /* Not found */
1878                 return AST_CAUSE_UNALLOCATED;
1879         case 405:       /* Method not allowed */
1880                 return AST_CAUSE_INTERWORKING;
1881         case 407:       /* Proxy authentication required */
1882                 return AST_CAUSE_CALL_REJECTED;
1883         case 408:       /* No reaction */
1884                 return AST_CAUSE_NO_USER_RESPONSE;
1885         case 409:       /* Conflict */
1886                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1887         case 410:       /* Gone */
1888                 return AST_CAUSE_NUMBER_CHANGED;
1889         case 411:       /* Length required */
1890                 return AST_CAUSE_INTERWORKING;
1891         case 413:       /* Request entity too large */
1892                 return AST_CAUSE_INTERWORKING;
1893         case 414:       /* Request URI too large */
1894                 return AST_CAUSE_INTERWORKING;
1895         case 415:       /* Unsupported media type */
1896                 return AST_CAUSE_INTERWORKING;
1897         case 420:       /* Bad extension */
1898                 return AST_CAUSE_NO_ROUTE_DESTINATION;
1899         case 480:       /* No answer */
1900                 return AST_CAUSE_NO_ANSWER;
1901         case 481:       /* No answer */
1902                 return AST_CAUSE_INTERWORKING;
1903         case 482:       /* Loop detected */
1904                 return AST_CAUSE_INTERWORKING;
1905         case 483:       /* Too many hops */
1906                 return AST_CAUSE_NO_ANSWER;
1907         case 484:       /* Address incomplete */
1908                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
1909         case 485:       /* Ambiguous */
1910                 return AST_CAUSE_UNALLOCATED;
1911         case 486:       /* Busy everywhere */
1912                 return AST_CAUSE_BUSY;
1913         case 487:       /* Request terminated */
1914                 return AST_CAUSE_INTERWORKING;
1915         case 488:       /* No codecs approved */
1916                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1917         case 491:       /* Request pending */
1918                 return AST_CAUSE_INTERWORKING;
1919         case 493:       /* Undecipherable */
1920                 return AST_CAUSE_INTERWORKING;
1921         case 500:       /* Server internal failure */
1922                 return AST_CAUSE_FAILURE;
1923         case 501:       /* Call rejected */
1924                 return AST_CAUSE_FACILITY_REJECTED;
1925         case 502:
1926                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1927         case 503:       /* Service unavailable */
1928                 return AST_CAUSE_CONGESTION;
1929         case 504:       /* Gateway timeout */
1930                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
1931         case 505:       /* SIP version not supported */
1932                 return AST_CAUSE_INTERWORKING;
1933         case 600:       /* Busy everywhere */
1934                 return AST_CAUSE_USER_BUSY;
1935         case 603:       /* Decline */
1936                 return AST_CAUSE_CALL_REJECTED;
1937         case 604:       /* Does not exist anywhere */
1938                 return AST_CAUSE_UNALLOCATED;
1939         case 606:       /* Not acceptable */
1940                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1941         default:
1942                 if (cause < 500 && cause >= 400) {
1943                         /* 4xx class error that is unknown - someting wrong with our request */
1944                         return AST_CAUSE_INTERWORKING;
1945                 } else if (cause < 600 && cause >= 500) {
1946                         /* 5xx class error - problem in the remote end */
1947                         return AST_CAUSE_CONGESTION;
1948                 } else if (cause < 700 && cause >= 600) {
1949                         /* 6xx - global errors in the 4xx class */
1950                         return AST_CAUSE_INTERWORKING;
1951                 }
1952                 return AST_CAUSE_NORMAL;
1953         }
1954         /* Never reached */
1955         return 0;
1956 }
1957
1958 static void chan_pjsip_session_begin(struct ast_sip_session *session)
1959 {
1960         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1961
1962         if (session->endpoint->media.direct_media.glare_mitigation ==
1963                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
1964                 return;
1965         }
1966
1967         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
1968                         "direct_media_glare_mitigation");
1969
1970         if (!datastore) {
1971                 return;
1972         }
1973
1974         ast_sip_session_add_datastore(session, datastore);
1975 }
1976
1977 /*! \brief Function called when the session ends */
1978 static void chan_pjsip_session_end(struct ast_sip_session *session)
1979 {
1980         if (!session->channel) {
1981                 return;
1982         }
1983
1984         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
1985
1986         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
1987         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
1988                 int cause = hangup_sip2cause(session->inv_session->cause);
1989
1990                 ast_queue_hangup_with_cause(session->channel, cause);
1991         } else {
1992                 ast_queue_hangup(session->channel);
1993         }
1994 }
1995
1996 /*! \brief Function called when a request is received on the session */
1997 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1998 {
1999         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2000         struct transport_info_data *transport_data;
2001         pjsip_tx_data *packet = NULL;
2002
2003         if (session->channel) {
2004                 return 0;
2005         }
2006
2007         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
2008         if (!datastore) {
2009                 return -1;
2010         }
2011
2012         transport_data = ast_calloc(1, sizeof(*transport_data));
2013         if (!transport_data) {
2014                 return -1;
2015         }
2016         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
2017         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
2018         datastore->data = transport_data;
2019         ast_sip_session_add_datastore(session, datastore);
2020
2021         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2022                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS) {
2023                         ast_sip_session_send_response(session, packet);
2024                 }
2025
2026                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2027                 return -1;
2028         }
2029         /* channel gets created on incoming request, but we wait to call start
2030            so other supplements have a chance to run */
2031         return 0;
2032 }
2033
2034 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2035 {
2036         struct ast_features_pickup_config *pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2037         struct ast_channel *chan;
2038
2039         /* We don't care about reinvites */
2040         if (session->inv_session->state >= PJSIP_INV_STATE_CONFIRMED) {
2041                 return 0;
2042         }
2043
2044         if (!pickup_cfg) {
2045                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2046                 return 0;
2047         }
2048
2049         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2050                 ao2_ref(pickup_cfg, -1);
2051                 return 0;
2052         }
2053         ao2_ref(pickup_cfg, -1);
2054
2055         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2056          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2057          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2058          */
2059         chan = ast_channel_ref(session->channel);
2060         if (ast_pickup_call(chan)) {
2061                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2062         } else {
2063                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2064         }
2065         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2066          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2067          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2068          * to anything at all.
2069          */
2070         ast_hangup(chan);
2071         ast_channel_unref(chan);
2072
2073         return 1;
2074 }
2075
2076 static struct ast_sip_session_supplement call_pickup_supplement = {
2077         .method = "INVITE",
2078         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2079         .incoming_request = call_pickup_incoming_request,
2080 };
2081
2082 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2083 {
2084         int res;
2085
2086         /* We don't care about reinvites */
2087         if (session->inv_session->state >= PJSIP_INV_STATE_CONFIRMED) {
2088                 return 0;
2089         }
2090
2091         res = ast_pbx_start(session->channel);
2092
2093         switch (res) {
2094         case AST_PBX_FAILED:
2095                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2096                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2097                 ast_hangup(session->channel);
2098                 break;
2099         case AST_PBX_CALL_LIMIT:
2100                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2101                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2102                 ast_hangup(session->channel);
2103                 break;
2104         case AST_PBX_SUCCESS:
2105         default:
2106                 break;
2107         }
2108
2109         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2110
2111         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2112 }
2113
2114 static struct ast_sip_session_supplement pbx_start_supplement = {
2115         .method = "INVITE",
2116         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2117         .incoming_request = pbx_start_incoming_request,
2118 };
2119
2120 /*! \brief Function called when a response is received on the session */
2121 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2122 {
2123         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2124         struct ast_control_pvt_cause_code *cause_code;
2125         int data_size = sizeof(*cause_code);
2126
2127         if (!session->channel) {
2128                 return;
2129         }
2130
2131         switch (status.code) {
2132         case 180:
2133                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2134                 ast_channel_lock(session->channel);
2135                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2136                         ast_setstate(session->channel, AST_STATE_RINGING);
2137                 }
2138                 ast_channel_unlock(session->channel);
2139                 break;
2140         case 183:
2141                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2142                 break;
2143         case 200:
2144                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2145                 break;
2146         default:
2147                 break;
2148         }
2149
2150         /* Build and send the tech-specific cause information */
2151         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2152         data_size += 4 + 4 + pj_strlen(&status.reason);
2153         cause_code = ast_alloca(data_size);
2154         memset(cause_code, 0, data_size);
2155
2156         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2157
2158         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2159                 (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2160
2161         cause_code->ast_cause = hangup_sip2cause(status.code);
2162         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2163         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2164 }
2165
2166 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2167 {
2168         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2169                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2170                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2171                 }
2172         }
2173         return 0;
2174 }
2175
2176 static int update_devstate(void *obj, void *arg, int flags)
2177 {
2178         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2179                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2180         return 0;
2181 }
2182
2183 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2184         .name = "PJSIP_DIAL_CONTACTS",
2185         .read = pjsip_acf_dial_contacts_read,
2186 };
2187
2188 static struct ast_custom_function media_offer_function = {
2189         .name = "PJSIP_MEDIA_OFFER",
2190         .read = pjsip_acf_media_offer_read,
2191         .write = pjsip_acf_media_offer_write
2192 };
2193
2194 /*!
2195  * \brief Load the module
2196  *
2197  * Module loading including tests for configuration or dependencies.
2198  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2199  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2200  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2201  * configuration file or other non-critical problem return
2202  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2203  */
2204 static int load_module(void)
2205 {
2206         struct ao2_container *endpoints;
2207
2208         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2209                 return AST_MODULE_LOAD_DECLINE;
2210         }
2211
2212         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
2213
2214         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2215
2216         if (ast_channel_register(&chan_pjsip_tech)) {
2217                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2218                 goto end;
2219         }
2220
2221         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2222                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2223                 goto end;
2224         }
2225
2226         if (ast_custom_function_register(&media_offer_function)) {
2227                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2228                 goto end;
2229         }
2230
2231         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2232                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2233                 goto end;
2234         }
2235
2236         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
2237                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
2238                         uid_hold_sort_fn, NULL))) {
2239                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
2240                 goto end;
2241         }
2242
2243         if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
2244                 ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
2245                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2246                 goto end;
2247         }
2248
2249         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2250                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2251                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2252                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2253                 goto end;
2254         }
2255
2256         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2257                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2258                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2259                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2260                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2261                 goto end;
2262         }
2263
2264         /* since endpoints are loaded before the channel driver their device
2265            states get set to 'invalid', so they need to be updated */
2266         if ((endpoints = ast_sip_get_endpoints())) {
2267                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
2268                 ao2_ref(endpoints, -1);
2269         }
2270
2271         return 0;
2272
2273 end:
2274         ao2_cleanup(pjsip_uids_onhold);
2275         pjsip_uids_onhold = NULL;
2276         ast_custom_function_unregister(&media_offer_function);
2277         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2278         ast_channel_unregister(&chan_pjsip_tech);
2279         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2280
2281         return AST_MODULE_LOAD_FAILURE;
2282 }
2283
2284 /*! \brief Reload module */
2285 static int reload(void)
2286 {
2287         return -1;
2288 }
2289
2290 /*! \brief Unload the PJSIP channel from Asterisk */
2291 static int unload_module(void)
2292 {
2293         ao2_cleanup(pjsip_uids_onhold);
2294         pjsip_uids_onhold = NULL;
2295
2296         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2297         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2298         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2299         ast_sip_session_unregister_supplement(&call_pickup_supplement);
2300
2301         ast_custom_function_unregister(&media_offer_function);
2302         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2303
2304         ast_channel_unregister(&chan_pjsip_tech);
2305         ao2_ref(chan_pjsip_tech.capabilities, -1);
2306         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2307
2308         return 0;
2309 }
2310
2311 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
2312                 .support_level = AST_MODULE_SUPPORT_CORE,
2313                 .load = load_module,
2314                 .unload = unload_module,
2315                 .reload = reload,
2316                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2317                );