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