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