c958f8086441bbdbb215f408b89a9c845672ea41
[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 static void set_channel_on_rtp_instance(struct chan_pjsip_pvt *pvt, const char *channel_id)
357 {
358         if (pvt->media[SIP_MEDIA_AUDIO] && pvt->media[SIP_MEDIA_AUDIO]->rtp) {
359                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_AUDIO]->rtp, channel_id);
360         }
361         if (pvt->media[SIP_MEDIA_VIDEO] && pvt->media[SIP_MEDIA_VIDEO]->rtp) {
362                 ast_rtp_instance_set_channel_id(pvt->media[SIP_MEDIA_VIDEO]->rtp, channel_id);
363         }
364 }
365
366 /*! \brief Function called to create a new PJSIP Asterisk channel */
367 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)
368 {
369         struct ast_channel *chan;
370         struct ast_format_cap *caps;
371         struct ast_format *fmt;
372         RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
373         struct ast_sip_channel_pvt *channel;
374         struct ast_variable *var;
375
376         if (!(pvt = ao2_alloc(sizeof(*pvt), chan_pjsip_pvt_dtor))) {
377                 return NULL;
378         }
379         caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
380         if (!caps) {
381                 return NULL;
382         }
383
384         chan = ast_channel_alloc_with_endpoint(1, state, S_OR(session->id.number.str, ""),
385                                  S_OR(session->id.name.str, ""), session->endpoint->accountcode, "",
386                                  "", assignedids, requestor, 0, session->endpoint->persistent,
387                                  "PJSIP/%s-%08x", ast_sorcery_object_get_id(session->endpoint),
388                                  (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
389         if (!chan) {
390                 ao2_ref(caps, -1);
391                 return NULL;
392         }
393
394         ast_channel_tech_set(chan, &chan_pjsip_tech);
395
396         if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
397                 ao2_ref(caps, -1);
398                 ast_channel_unlock(chan);
399                 ast_hangup(chan);
400                 return NULL;
401         }
402
403         for (var = session->endpoint->channel_vars; var; var = var->next) {
404                 char buf[512];
405                 pbx_builtin_setvar_helper(chan, var->name, ast_get_encoded_str(
406                                                   var->value, buf, sizeof(buf)));
407         }
408
409         ast_channel_stage_snapshot(chan);
410
411         ast_channel_tech_pvt_set(chan, channel);
412
413         if (!ast_format_cap_count(session->req_caps) ||
414                 !ast_format_cap_iscompatible(session->req_caps, session->endpoint->media.codecs)) {
415                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
416         } else {
417                 ast_format_cap_append_from_cap(caps, session->req_caps, AST_MEDIA_TYPE_UNKNOWN);
418         }
419
420         ast_channel_nativeformats_set(chan, caps);
421         fmt = ast_format_cap_get_format(caps, 0);
422         ast_channel_set_writeformat(chan, fmt);
423         ast_channel_set_rawwriteformat(chan, fmt);
424         ast_channel_set_readformat(chan, fmt);
425         ast_channel_set_rawreadformat(chan, fmt);
426         ao2_ref(fmt, -1);
427         ao2_ref(caps, -1);
428
429         if (state == AST_STATE_RING) {
430                 ast_channel_rings_set(chan, 1);
431         }
432
433         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
434
435         ast_channel_context_set(chan, session->endpoint->context);
436         ast_channel_exten_set(chan, S_OR(exten, "s"));
437         ast_channel_priority_set(chan, 1);
438
439         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
440         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
441
442         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
443         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
444
445         if (!ast_strlen_zero(session->endpoint->language)) {
446                 ast_channel_language_set(chan, session->endpoint->language);
447         }
448
449         if (!ast_strlen_zero(session->endpoint->zone)) {
450                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
451                 if (!zone) {
452                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
453                 }
454                 ast_channel_zone_set(chan, zone);
455         }
456
457         ast_channel_stage_snapshot_done(chan);
458         ast_channel_unlock(chan);
459
460         /* If res_pjsip_session is ever updated to create/destroy ast_sip_session_media
461          * during a call such as if multiple same-type stream support is introduced,
462          * these will need to be recaptured as well */
463         pvt->media[SIP_MEDIA_AUDIO] = ao2_find(session->media, "audio", OBJ_KEY);
464         pvt->media[SIP_MEDIA_VIDEO] = ao2_find(session->media, "video", OBJ_KEY);
465         set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(chan));
466
467         return chan;
468 }
469
470 static int answer(void *data)
471 {
472         pj_status_t status = PJ_SUCCESS;
473         pjsip_tx_data *packet = NULL;
474         struct ast_sip_session *session = data;
475
476         pjsip_dlg_inc_lock(session->inv_session->dlg);
477         if (session->inv_session->invite_tsx) {
478                 status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
479         } else {
480                 ast_log(LOG_ERROR,"Cannot answer '%s' because there is no associated SIP transaction\n",
481                         ast_channel_name(session->channel));
482         }
483         pjsip_dlg_dec_lock(session->inv_session->dlg);
484
485         if (status == PJ_SUCCESS && packet) {
486                 ast_sip_session_send_response(session, packet);
487         }
488
489         ao2_ref(session, -1);
490
491         return (status == PJ_SUCCESS) ? 0 : -1;
492 }
493
494 /*! \brief Function called by core when we should answer a PJSIP session */
495 static int chan_pjsip_answer(struct ast_channel *ast)
496 {
497         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
498
499         if (ast_channel_state(ast) == AST_STATE_UP) {
500                 return 0;
501         }
502
503         ast_setstate(ast, AST_STATE_UP);
504
505         ao2_ref(channel->session, +1);
506         if (ast_sip_push_task(channel->session->serializer, answer, channel->session)) {
507                 ast_log(LOG_WARNING, "Unable to push answer task to the threadpool. Cannot answer call\n");
508                 ao2_cleanup(channel->session);
509                 return -1;
510         }
511
512         return 0;
513 }
514
515 /*! \brief Internal helper function called when CNG tone is detected */
516 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
517 {
518         const char *target_context;
519         int exists;
520
521         /* If we only needed this DSP for fax detection purposes we can just drop it now */
522         if (session->endpoint->dtmf == AST_SIP_DTMF_INBAND) {
523                 ast_dsp_set_features(session->dsp, DSP_FEATURE_DIGIT_DETECT);
524         } else {
525                 ast_dsp_free(session->dsp);
526                 session->dsp = NULL;
527         }
528
529         /* If already executing in the fax extension don't do anything */
530         if (!strcmp(ast_channel_exten(session->channel), "fax")) {
531                 return f;
532         }
533
534         target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));
535
536         /* We need to unlock the channel here because ast_exists_extension has the
537          * potential to start and stop an autoservice on the channel. Such action
538          * is prone to deadlock if the channel is locked.
539          */
540         ast_channel_unlock(session->channel);
541         exists = ast_exists_extension(session->channel, target_context, "fax", 1,
542                 S_COR(ast_channel_caller(session->channel)->id.number.valid,
543                         ast_channel_caller(session->channel)->id.number.str, NULL));
544         ast_channel_lock(session->channel);
545
546         if (exists) {
547                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
548                         ast_channel_name(session->channel));
549                 pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
550                 if (ast_async_goto(session->channel, target_context, "fax", 1)) {
551                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
552                                 ast_channel_name(session->channel), target_context);
553                 }
554                 ast_frfree(f);
555                 f = &ast_null_frame;
556         } else {
557                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
558                         ast_channel_name(session->channel), target_context);
559         }
560
561         return f;
562 }
563
564 /*! \brief Function called by core to read any waiting frames */
565 static struct ast_frame *chan_pjsip_read(struct ast_channel *ast)
566 {
567         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
568         struct chan_pjsip_pvt *pvt = channel->pvt;
569         struct ast_frame *f;
570         struct ast_sip_session_media *media = NULL;
571         int rtcp = 0;
572         int fdno = ast_channel_fdno(ast);
573
574         switch (fdno) {
575         case 0:
576                 media = pvt->media[SIP_MEDIA_AUDIO];
577                 break;
578         case 1:
579                 media = pvt->media[SIP_MEDIA_AUDIO];
580                 rtcp = 1;
581                 break;
582         case 2:
583                 media = pvt->media[SIP_MEDIA_VIDEO];
584                 break;
585         case 3:
586                 media = pvt->media[SIP_MEDIA_VIDEO];
587                 rtcp = 1;
588                 break;
589         }
590
591         if (!media || !media->rtp) {
592                 return &ast_null_frame;
593         }
594
595         if (!(f = ast_rtp_instance_read(media->rtp, rtcp))) {
596                 return f;
597         }
598
599         if (f->frametype != AST_FRAME_VOICE) {
600                 return f;
601         }
602
603         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
604                 struct ast_format_cap *caps;
605
606                 ast_debug(1, "Oooh, format changed to %s\n", ast_format_get_name(f->subclass.format));
607
608                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
609                 if (caps) {
610                         ast_format_cap_append(caps, f->subclass.format, 0);
611                         ast_channel_nativeformats_set(ast, caps);
612                         ao2_ref(caps, -1);
613                 }
614
615                 ast_set_read_format(ast, ast_channel_readformat(ast));
616                 ast_set_write_format(ast, ast_channel_writeformat(ast));
617         }
618
619         if (channel->session->dsp) {
620                 f = ast_dsp_process(ast, channel->session->dsp, f);
621
622                 if (f && (f->frametype == AST_FRAME_DTMF)) {
623                         if (f->subclass.integer == 'f') {
624                                 ast_debug(3, "Fax CNG detected on %s\n", ast_channel_name(ast));
625                                 f = chan_pjsip_cng_tone_detected(channel->session, f);
626                         } else {
627                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
628                                         ast_channel_name(ast));
629                         }
630                 }
631         }
632
633         return f;
634 }
635
636 /*! \brief Function called by core to write frames */
637 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
638 {
639         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
640         struct chan_pjsip_pvt *pvt = channel->pvt;
641         struct ast_sip_session_media *media;
642         int res = 0;
643
644         switch (frame->frametype) {
645         case AST_FRAME_VOICE:
646                 media = pvt->media[SIP_MEDIA_AUDIO];
647
648                 if (!media) {
649                         return 0;
650                 }
651                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
652                         struct ast_str *cap_buf = ast_str_alloca(64);
653
654                         ast_log(LOG_WARNING,
655                                 "Asked to transmit frame type %s, while native formats is %s (read/write = %s/%s)\n",
656                                 ast_format_get_name(frame->subclass.format),
657                                 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
658                                 ast_format_get_name(ast_channel_readformat(ast)),
659                                 ast_format_get_name(ast_channel_writeformat(ast)));
660                         return 0;
661                 }
662                 if (media->rtp) {
663                         res = ast_rtp_instance_write(media->rtp, frame);
664                 }
665                 break;
666         case AST_FRAME_VIDEO:
667                 if ((media = pvt->media[SIP_MEDIA_VIDEO]) && media->rtp) {
668                         res = ast_rtp_instance_write(media->rtp, frame);
669                 }
670                 break;
671         case AST_FRAME_MODEM:
672                 break;
673         default:
674                 ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
675                 break;
676         }
677
678         return res;
679 }
680
681 struct fixup_data {
682         struct ast_sip_session *session;
683         struct ast_channel *chan;
684 };
685
686 static int fixup(void *data)
687 {
688         struct fixup_data *fix_data = data;
689         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(fix_data->chan);
690         struct chan_pjsip_pvt *pvt = channel->pvt;
691
692         channel->session->channel = fix_data->chan;
693         set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(fix_data->chan));
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 (chan_pjsip_get_hold(snapshot->uniqueid)) {
876                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
877                 } else {
878                         ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
879                 }
880
881                 if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
882                         (snapshot->state == AST_STATE_BUSY)) {
883                         inuse++;
884                 }
885         }
886
887         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
888                 state = AST_DEVICE_BUSY;
889         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
890                 state = ast_devstate_aggregate_result(&aggregate);
891         }
892
893         return state;
894 }
895
896 /*! \brief Function called to query options on a channel */
897 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
898 {
899         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
900         struct ast_sip_session *session = channel->session;
901         int res = -1;
902         enum ast_sip_session_t38state state = T38_STATE_UNAVAILABLE;
903
904         switch (option) {
905         case AST_OPTION_T38_STATE:
906                 if (session->endpoint->media.t38.enabled) {
907                         switch (session->t38state) {
908                         case T38_LOCAL_REINVITE:
909                         case T38_PEER_REINVITE:
910                                 state = T38_STATE_NEGOTIATING;
911                                 break;
912                         case T38_ENABLED:
913                                 state = T38_STATE_NEGOTIATED;
914                                 break;
915                         case T38_REJECTED:
916                                 state = T38_STATE_REJECTED;
917                                 break;
918                         default:
919                                 state = T38_STATE_UNKNOWN;
920                                 break;
921                         }
922                 }
923
924                 *((enum ast_t38_state *) data) = state;
925                 res = 0;
926
927                 break;
928         default:
929                 break;
930         }
931
932         return res;
933 }
934
935 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
936 {
937         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
938         char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);
939
940         if (!uniqueid) {
941                 return "";
942         }
943
944         ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);
945
946         return uniqueid;
947 }
948
949 struct indicate_data {
950         struct ast_sip_session *session;
951         int condition;
952         int response_code;
953         void *frame_data;
954         size_t datalen;
955 };
956
957 static void indicate_data_destroy(void *obj)
958 {
959         struct indicate_data *ind_data = obj;
960
961         ast_free(ind_data->frame_data);
962         ao2_ref(ind_data->session, -1);
963 }
964
965 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
966                 int condition, int response_code, const void *frame_data, size_t datalen)
967 {
968         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
969
970         if (!ind_data) {
971                 return NULL;
972         }
973
974         ind_data->frame_data = ast_malloc(datalen);
975         if (!ind_data->frame_data) {
976                 ao2_ref(ind_data, -1);
977                 return NULL;
978         }
979
980         memcpy(ind_data->frame_data, frame_data, datalen);
981         ind_data->datalen = datalen;
982         ind_data->condition = condition;
983         ind_data->response_code = response_code;
984         ao2_ref(session, +1);
985         ind_data->session = session;
986
987         return ind_data;
988 }
989
990 static int indicate(void *data)
991 {
992         pjsip_tx_data *packet = NULL;
993         struct indicate_data *ind_data = data;
994         struct ast_sip_session *session = ind_data->session;
995         int response_code = ind_data->response_code;
996
997         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
998                 ast_sip_session_send_response(session, packet);
999         }
1000
1001         ao2_ref(ind_data, -1);
1002
1003         return 0;
1004 }
1005
1006 /*! \brief Send SIP INFO with video update request */
1007 static int transmit_info_with_vidupdate(void *data)
1008 {
1009         const char * xml =
1010                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1011                 " <media_control>\r\n"
1012                 "  <vc_primitive>\r\n"
1013                 "   <to_encoder>\r\n"
1014                 "    <picture_fast_update/>\r\n"
1015                 "   </to_encoder>\r\n"
1016                 "  </vc_primitive>\r\n"
1017                 " </media_control>\r\n";
1018
1019         const struct ast_sip_body body = {
1020                 .type = "application",
1021                 .subtype = "media_control+xml",
1022                 .body_text = xml
1023         };
1024
1025         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1026         struct pjsip_tx_data *tdata;
1027
1028         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1029                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1030                 return -1;
1031         }
1032         if (ast_sip_add_body(tdata, &body)) {
1033                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1034                 return -1;
1035         }
1036         ast_sip_session_send_request(session, tdata);
1037
1038         return 0;
1039 }
1040
1041 /*! \brief Update connected line information */
1042 static int update_connected_line_information(void *data)
1043 {
1044         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1045         struct ast_party_id connected_id;
1046
1047         if ((ast_channel_state(session->channel) != AST_STATE_UP) && (session->inv_session->role == PJSIP_UAS_ROLE)) {
1048                 int response_code = 0;
1049
1050                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1051                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1052                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1053                         response_code = 183;
1054                 }
1055
1056                 if (response_code) {
1057                         struct pjsip_tx_data *packet = NULL;
1058
1059                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1060                                 ast_sip_session_send_response(session, packet);
1061                         }
1062                 }
1063         } else {
1064                 enum ast_sip_session_refresh_method method = session->endpoint->id.refresh_method;
1065
1066                 if (session->inv_session->invite_tsx && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1067                         method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1068                 }
1069
1070                 connected_id = ast_channel_connected_effective_id(session->channel);
1071                 if ((session->endpoint->id.send_pai || session->endpoint->id.send_rpid) &&
1072                     (session->endpoint->id.trust_outbound ||
1073                      ((connected_id.name.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED &&
1074                       (connected_id.number.presentation & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED))) {
1075                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, 1);
1076                 }
1077         }
1078
1079         return 0;
1080 }
1081
1082 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1083 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1084 {
1085         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1086         struct chan_pjsip_pvt *pvt = channel->pvt;
1087         struct ast_sip_session_media *media;
1088         int response_code = 0;
1089         int res = 0;
1090         char *device_buf;
1091         size_t device_buf_size;
1092
1093         switch (condition) {
1094         case AST_CONTROL_RINGING:
1095                 if (ast_channel_state(ast) == AST_STATE_RING) {
1096                         if (channel->session->endpoint->inband_progress) {
1097                                 response_code = 183;
1098                                 res = -1;
1099                         } else {
1100                                 response_code = 180;
1101                         }
1102                 } else {
1103                         res = -1;
1104                 }
1105                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1106                 break;
1107         case AST_CONTROL_BUSY:
1108                 if (ast_channel_state(ast) != AST_STATE_UP) {
1109                         response_code = 486;
1110                 } else {
1111                         res = -1;
1112                 }
1113                 break;
1114         case AST_CONTROL_CONGESTION:
1115                 if (ast_channel_state(ast) != AST_STATE_UP) {
1116                         response_code = 503;
1117                 } else {
1118                         res = -1;
1119                 }
1120                 break;
1121         case AST_CONTROL_INCOMPLETE:
1122                 if (ast_channel_state(ast) != AST_STATE_UP) {
1123                         response_code = 484;
1124                 } else {
1125                         res = -1;
1126                 }
1127                 break;
1128         case AST_CONTROL_PROCEEDING:
1129                 if (ast_channel_state(ast) != AST_STATE_UP) {
1130                         response_code = 100;
1131                 } else {
1132                         res = -1;
1133                 }
1134                 break;
1135         case AST_CONTROL_PROGRESS:
1136                 if (ast_channel_state(ast) != AST_STATE_UP) {
1137                         response_code = 183;
1138                 } else {
1139                         res = -1;
1140                 }
1141                 break;
1142         case AST_CONTROL_VIDUPDATE:
1143                 media = pvt->media[SIP_MEDIA_VIDEO];
1144                 if (media && media->rtp) {
1145                         /* FIXME: Only use this for VP8. Additional work would have to be done to
1146                          * fully support other video codecs */
1147
1148                         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
1149                                 /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1150                                  * RTP engine would provide a way to externally write/schedule RTCP
1151                                  * packets */
1152                                 struct ast_frame fr;
1153                                 fr.frametype = AST_FRAME_CONTROL;
1154                                 fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1155                                 res = ast_rtp_instance_write(media->rtp, &fr);
1156                         } else {
1157                                 ao2_ref(channel->session, +1);
1158
1159                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1160                                         ao2_cleanup(channel->session);
1161                                 }
1162                         }
1163                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1164                 } else {
1165                         ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1166                         res = -1;
1167                 }
1168                 break;
1169         case AST_CONTROL_CONNECTED_LINE:
1170                 ao2_ref(channel->session, +1);
1171                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1172                         ao2_cleanup(channel->session);
1173                 }
1174                 break;
1175         case AST_CONTROL_UPDATE_RTP_PEER:
1176                 break;
1177         case AST_CONTROL_PVT_CAUSE_CODE:
1178                 res = -1;
1179                 break;
1180         case AST_CONTROL_HOLD:
1181                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1182                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1183                 device_buf = alloca(device_buf_size);
1184                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1185                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1186                 ast_moh_start(ast, data, NULL);
1187                 break;
1188         case AST_CONTROL_UNHOLD:
1189                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1190                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1191                 device_buf = alloca(device_buf_size);
1192                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1193                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1194                 ast_moh_stop(ast);
1195                 break;
1196         case AST_CONTROL_SRCUPDATE:
1197                 break;
1198         case AST_CONTROL_SRCCHANGE:
1199                 break;
1200         case AST_CONTROL_REDIRECTING:
1201                 if (ast_channel_state(ast) != AST_STATE_UP) {
1202                         response_code = 181;
1203                 } else {
1204                         res = -1;
1205                 }
1206                 break;
1207         case AST_CONTROL_T38_PARAMETERS:
1208                 res = 0;
1209
1210                 if (channel->session->t38state == T38_PEER_REINVITE) {
1211                         const struct ast_control_t38_parameters *parameters = data;
1212
1213                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1214                                 res = AST_T38_REQUEST_PARMS;
1215                         }
1216                 }
1217
1218                 break;
1219         case -1:
1220                 res = -1;
1221                 break;
1222         default:
1223                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1224                 res = -1;
1225                 break;
1226         }
1227
1228         if (response_code) {
1229                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1230                 if (!ind_data || ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1231                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1232                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1233                         ao2_cleanup(ind_data);
1234                         res = -1;
1235                 }
1236         }
1237
1238         return res;
1239 }
1240
1241 struct transfer_data {
1242         struct ast_sip_session *session;
1243         char *target;
1244 };
1245
1246 static void transfer_data_destroy(void *obj)
1247 {
1248         struct transfer_data *trnf_data = obj;
1249
1250         ast_free(trnf_data->target);
1251         ao2_cleanup(trnf_data->session);
1252 }
1253
1254 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1255 {
1256         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1257
1258         if (!trnf_data) {
1259                 return NULL;
1260         }
1261
1262         if (!(trnf_data->target = ast_strdup(target))) {
1263                 ao2_ref(trnf_data, -1);
1264                 return NULL;
1265         }
1266
1267         ao2_ref(session, +1);
1268         trnf_data->session = session;
1269
1270         return trnf_data;
1271 }
1272
1273 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1274 {
1275         pjsip_tx_data *packet;
1276         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1277         pjsip_contact_hdr *contact;
1278         pj_str_t tmp;
1279
1280         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS) {
1281                 message = AST_TRANSFER_FAILED;
1282                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1283
1284                 return;
1285         }
1286
1287         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1288                 contact = pjsip_contact_hdr_create(packet->pool);
1289         }
1290
1291         pj_strdup2_with_null(packet->pool, &tmp, target);
1292         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1293                 message = AST_TRANSFER_FAILED;
1294                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1295                 pjsip_tx_data_dec_ref(packet);
1296
1297                 return;
1298         }
1299         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1300
1301         ast_sip_session_send_response(session, packet);
1302         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1303 }
1304
1305 static void transfer_refer(struct ast_sip_session *session, const char *target)
1306 {
1307         pjsip_evsub *sub;
1308         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1309         pj_str_t tmp;
1310         pjsip_tx_data *packet;
1311
1312         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1313                 message = AST_TRANSFER_FAILED;
1314                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1315
1316                 return;
1317         }
1318
1319         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1320                 message = AST_TRANSFER_FAILED;
1321                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1322                 pjsip_evsub_terminate(sub, PJ_FALSE);
1323
1324                 return;
1325         }
1326
1327         pjsip_xfer_send_request(sub, packet);
1328         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1329 }
1330
1331 static int transfer(void *data)
1332 {
1333         struct transfer_data *trnf_data = data;
1334
1335         if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1336                 transfer_redirect(trnf_data->session, trnf_data->target);
1337         } else {
1338                 transfer_refer(trnf_data->session, trnf_data->target);
1339         }
1340
1341         ao2_ref(trnf_data, -1);
1342         return 0;
1343 }
1344
1345 /*! \brief Function called by core for Asterisk initiated transfer */
1346 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1347 {
1348         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1349         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1350
1351         if (!trnf_data) {
1352                 return -1;
1353         }
1354
1355         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1356                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1357                 ao2_cleanup(trnf_data);
1358                 return -1;
1359         }
1360
1361         return 0;
1362 }
1363
1364 /*! \brief Function called by core to start a DTMF digit */
1365 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1366 {
1367         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1368         struct chan_pjsip_pvt *pvt = channel->pvt;
1369         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1370         int res = 0;
1371
1372         switch (channel->session->endpoint->dtmf) {
1373         case AST_SIP_DTMF_RFC_4733:
1374                 if (!media || !media->rtp) {
1375                         return -1;
1376                 }
1377
1378                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1379         case AST_SIP_DTMF_NONE:
1380                 break;
1381         case AST_SIP_DTMF_INBAND:
1382                 res = -1;
1383                 break;
1384         default:
1385                 break;
1386         }
1387
1388         return res;
1389 }
1390
1391 struct info_dtmf_data {
1392         struct ast_sip_session *session;
1393         char digit;
1394         unsigned int duration;
1395 };
1396
1397 static void info_dtmf_data_destroy(void *obj)
1398 {
1399         struct info_dtmf_data *dtmf_data = obj;
1400         ao2_ref(dtmf_data->session, -1);
1401 }
1402
1403 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1404 {
1405         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1406         if (!dtmf_data) {
1407                 return NULL;
1408         }
1409         ao2_ref(session, +1);
1410         dtmf_data->session = session;
1411         dtmf_data->digit = digit;
1412         dtmf_data->duration = duration;
1413         return dtmf_data;
1414 }
1415
1416 static int transmit_info_dtmf(void *data)
1417 {
1418         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
1419
1420         struct ast_sip_session *session = dtmf_data->session;
1421         struct pjsip_tx_data *tdata;
1422
1423         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
1424
1425         struct ast_sip_body body = {
1426                 .type = "application",
1427                 .subtype = "dtmf-relay",
1428         };
1429
1430         if (!(body_text = ast_str_create(32))) {
1431                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
1432                 return -1;
1433         }
1434         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
1435
1436         body.body_text = ast_str_buffer(body_text);
1437
1438         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1439                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
1440                 return -1;
1441         }
1442         if (ast_sip_add_body(tdata, &body)) {
1443                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
1444                 pjsip_tx_data_dec_ref(tdata);
1445                 return -1;
1446         }
1447         ast_sip_session_send_request(session, tdata);
1448
1449         return 0;
1450 }
1451
1452 /*! \brief Function called by core to stop a DTMF digit */
1453 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1454 {
1455         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1456         struct chan_pjsip_pvt *pvt = channel->pvt;
1457         struct ast_sip_session_media *media = pvt->media[SIP_MEDIA_AUDIO];
1458         int res = 0;
1459
1460         switch (channel->session->endpoint->dtmf) {
1461         case AST_SIP_DTMF_INFO:
1462         {
1463                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
1464
1465                 if (!dtmf_data) {
1466                         return -1;
1467                 }
1468
1469                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
1470                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
1471                         ao2_cleanup(dtmf_data);
1472                         return -1;
1473                 }
1474                 break;
1475         }
1476         case AST_SIP_DTMF_RFC_4733:
1477                 if (!media || !media->rtp) {
1478                         return -1;
1479                 }
1480
1481                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
1482         case AST_SIP_DTMF_NONE:
1483                 break;
1484         case AST_SIP_DTMF_INBAND:
1485                 res = -1;
1486                 break;
1487         }
1488
1489         return res;
1490 }
1491
1492 static void update_initial_connected_line(struct ast_sip_session *session)
1493 {
1494         struct ast_party_connected_line connected;
1495         struct ast_set_party_connected_line update_connected;
1496         struct ast_sip_endpoint_id_configuration *id = &session->endpoint->id;
1497
1498         if (!id->self.number.valid && !id->self.name.valid) {
1499                 return;
1500         }
1501
1502         /* Supply initial connected line information if available. */
1503         memset(&update_connected, 0, sizeof(update_connected));
1504         ast_party_connected_line_init(&connected);
1505         connected.id.number = id->self.number;
1506         connected.id.name = id->self.name;
1507         connected.id.tag = id->self.tag;
1508         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
1509
1510         if (connected.id.number.valid) {
1511                 update_connected.id.number = 1;
1512         }
1513
1514         if (connected.id.name.valid) {
1515                 update_connected.id.name = 1;
1516         }
1517
1518         /* Invalidate any earlier private connected id representation */
1519         ast_set_party_id_all(&update_connected.priv);
1520
1521         ast_channel_queue_connected_line_update(session->channel, &connected, &update_connected);
1522 }
1523
1524 static int call(void *data)
1525 {
1526         struct ast_sip_channel_pvt *channel = data;
1527         struct ast_sip_session *session = channel->session;
1528         struct chan_pjsip_pvt *pvt = channel->pvt;
1529         pjsip_tx_data *tdata;
1530
1531         int res = ast_sip_session_create_invite(session, &tdata);
1532
1533         if (res) {
1534                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
1535                 ast_queue_hangup(session->channel);
1536         } else {
1537                 set_channel_on_rtp_instance(pvt, ast_channel_uniqueid(session->channel));
1538                 update_initial_connected_line(session);
1539                 ast_sip_session_send_request(session, tdata);
1540         }
1541         ao2_ref(channel, -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, +1);
1551         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
1552                 ast_log(LOG_WARNING, "Error attempting to place outbound call to call '%s'\n", dest);
1553                 ao2_cleanup(channel);
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         set_channel_on_rtp_instance(pvt, "");
1639         ast_channel_tech_pvt_set(ast, NULL);
1640 }
1641
1642 static int hangup(void *data)
1643 {
1644         struct hangup_data *h_data = data;
1645         struct ast_channel *ast = h_data->chan;
1646         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1647         struct chan_pjsip_pvt *pvt = channel->pvt;
1648         struct ast_sip_session *session = channel->session;
1649         int cause = h_data->cause;
1650
1651         if (!session->defer_terminate) {
1652                 pj_status_t status;
1653                 pjsip_tx_data *packet = NULL;
1654
1655                 if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1656                         pjsip_inv_terminate(session->inv_session, cause ? cause : 603, PJ_TRUE);
1657                 } else if (((status = pjsip_inv_end_session(session->inv_session, cause ? cause : 603, NULL, &packet)) == PJ_SUCCESS)
1658                         && packet) {
1659                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1660                                 ast_sip_session_send_response(session, packet);
1661                         } else {
1662                                 ast_sip_session_send_request(session, packet);
1663                         }
1664                 }
1665         }
1666
1667         clear_session_and_channel(session, ast, pvt);
1668         ao2_cleanup(channel);
1669         ao2_cleanup(h_data);
1670
1671         return 0;
1672 }
1673
1674 /*! \brief Function called by core to hang up a PJSIP session */
1675 static int chan_pjsip_hangup(struct ast_channel *ast)
1676 {
1677         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1678         struct chan_pjsip_pvt *pvt = channel->pvt;
1679         int cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
1680         struct hangup_data *h_data = hangup_data_alloc(cause, ast);
1681
1682         if (!h_data) {
1683                 goto failure;
1684         }
1685
1686         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
1687                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
1688                 goto failure;
1689         }
1690
1691         return 0;
1692
1693 failure:
1694         /* Go ahead and do our cleanup of the session and channel even if we're not going
1695          * to be able to send our SIP request/response
1696          */
1697         clear_session_and_channel(channel->session, ast, pvt);
1698         ao2_cleanup(channel);
1699         ao2_cleanup(h_data);
1700
1701         return -1;
1702 }
1703
1704 struct request_data {
1705         struct ast_sip_session *session;
1706         struct ast_format_cap *caps;
1707         const char *dest;
1708         int cause;
1709 };
1710
1711 static int request(void *obj)
1712 {
1713         struct request_data *req_data = obj;
1714         struct ast_sip_session *session = NULL;
1715         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
1716         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
1717
1718         AST_DECLARE_APP_ARGS(args,
1719                 AST_APP_ARG(endpoint);
1720                 AST_APP_ARG(aor);
1721         );
1722
1723         if (ast_strlen_zero(tmp)) {
1724                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
1725                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1726                 return -1;
1727         }
1728
1729         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
1730
1731         /* If a request user has been specified extract it from the endpoint name portion */
1732         if ((endpoint_name = strchr(args.endpoint, '@'))) {
1733                 request_user = args.endpoint;
1734                 *endpoint_name++ = '\0';
1735         } else {
1736                 endpoint_name = args.endpoint;
1737         }
1738
1739         if (ast_strlen_zero(endpoint_name)) {
1740                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
1741                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
1742         } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
1743                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
1744                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1745                 return -1;
1746         }
1747
1748         if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->caps))) {
1749                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
1750                 return -1;
1751         }
1752
1753         req_data->session = session;
1754
1755         return 0;
1756 }
1757
1758 /*! \brief Function called by core to create a new outgoing PJSIP session */
1759 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)
1760 {
1761         struct request_data req_data;
1762         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1763
1764         req_data.caps = cap;
1765         req_data.dest = data;
1766
1767         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
1768                 *cause = req_data.cause;
1769                 return NULL;
1770         }
1771
1772         session = req_data.session;
1773
1774         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
1775                 /* Session needs to be terminated prematurely */
1776                 return NULL;
1777         }
1778
1779         return session->channel;
1780 }
1781
1782 struct sendtext_data {
1783         struct ast_sip_session *session;
1784         char text[0];
1785 };
1786
1787 static void sendtext_data_destroy(void *obj)
1788 {
1789         struct sendtext_data *data = obj;
1790         ao2_ref(data->session, -1);
1791 }
1792
1793 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
1794 {
1795         int size = strlen(text) + 1;
1796         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
1797
1798         if (!data) {
1799                 return NULL;
1800         }
1801
1802         data->session = session;
1803         ao2_ref(data->session, +1);
1804         ast_copy_string(data->text, text, size);
1805         return data;
1806 }
1807
1808 static int sendtext(void *obj)
1809 {
1810         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
1811         pjsip_tx_data *tdata;
1812
1813         const struct ast_sip_body body = {
1814                 .type = "text",
1815                 .subtype = "plain",
1816                 .body_text = data->text
1817         };
1818
1819         /* NOT ast_strlen_zero, because a zero-length message is specifically
1820          * allowed by RFC 3428 (See section 10, Examples) */
1821         if (!data->text) {
1822                 return 0;
1823         }
1824
1825         ast_debug(3, "Sending in dialog SIP message\n");
1826
1827         ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
1828         ast_sip_add_body(tdata, &body);
1829         ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
1830
1831         return 0;
1832 }
1833
1834 /*! \brief Function called by core to send text on PJSIP session */
1835 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
1836 {
1837         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1838         struct sendtext_data *data = sendtext_data_create(channel->session, text);
1839
1840         if (!data || ast_sip_push_task(channel->session->serializer, sendtext, data)) {
1841                 ao2_ref(data, -1);
1842                 return -1;
1843         }
1844         return 0;
1845 }
1846
1847 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
1848 static int hangup_sip2cause(int cause)
1849 {
1850         /* Possible values taken from causes.h */
1851
1852         switch(cause) {
1853         case 401:       /* Unauthorized */
1854                 return AST_CAUSE_CALL_REJECTED;
1855         case 403:       /* Not found */
1856                 return AST_CAUSE_CALL_REJECTED;
1857         case 404:       /* Not found */
1858                 return AST_CAUSE_UNALLOCATED;
1859         case 405:       /* Method not allowed */
1860                 return AST_CAUSE_INTERWORKING;
1861         case 407:       /* Proxy authentication required */
1862                 return AST_CAUSE_CALL_REJECTED;
1863         case 408:       /* No reaction */
1864                 return AST_CAUSE_NO_USER_RESPONSE;
1865         case 409:       /* Conflict */
1866                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
1867         case 410:       /* Gone */
1868                 return AST_CAUSE_NUMBER_CHANGED;
1869         case 411:       /* Length required */
1870                 return AST_CAUSE_INTERWORKING;
1871         case 413:       /* Request entity too large */
1872                 return AST_CAUSE_INTERWORKING;
1873         case 414:       /* Request URI too large */
1874                 return AST_CAUSE_INTERWORKING;
1875         case 415:       /* Unsupported media type */
1876                 return AST_CAUSE_INTERWORKING;
1877         case 420:       /* Bad extension */
1878                 return AST_CAUSE_NO_ROUTE_DESTINATION;
1879         case 480:       /* No answer */
1880                 return AST_CAUSE_NO_ANSWER;
1881         case 481:       /* No answer */
1882                 return AST_CAUSE_INTERWORKING;
1883         case 482:       /* Loop detected */
1884                 return AST_CAUSE_INTERWORKING;
1885         case 483:       /* Too many hops */
1886                 return AST_CAUSE_NO_ANSWER;
1887         case 484:       /* Address incomplete */
1888                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
1889         case 485:       /* Ambiguous */
1890                 return AST_CAUSE_UNALLOCATED;
1891         case 486:       /* Busy everywhere */
1892                 return AST_CAUSE_BUSY;
1893         case 487:       /* Request terminated */
1894                 return AST_CAUSE_INTERWORKING;
1895         case 488:       /* No codecs approved */
1896                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1897         case 491:       /* Request pending */
1898                 return AST_CAUSE_INTERWORKING;
1899         case 493:       /* Undecipherable */
1900                 return AST_CAUSE_INTERWORKING;
1901         case 500:       /* Server internal failure */
1902                 return AST_CAUSE_FAILURE;
1903         case 501:       /* Call rejected */
1904                 return AST_CAUSE_FACILITY_REJECTED;
1905         case 502:
1906                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1907         case 503:       /* Service unavailable */
1908                 return AST_CAUSE_CONGESTION;
1909         case 504:       /* Gateway timeout */
1910                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
1911         case 505:       /* SIP version not supported */
1912                 return AST_CAUSE_INTERWORKING;
1913         case 600:       /* Busy everywhere */
1914                 return AST_CAUSE_USER_BUSY;
1915         case 603:       /* Decline */
1916                 return AST_CAUSE_CALL_REJECTED;
1917         case 604:       /* Does not exist anywhere */
1918                 return AST_CAUSE_UNALLOCATED;
1919         case 606:       /* Not acceptable */
1920                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
1921         default:
1922                 if (cause < 500 && cause >= 400) {
1923                         /* 4xx class error that is unknown - someting wrong with our request */
1924                         return AST_CAUSE_INTERWORKING;
1925                 } else if (cause < 600 && cause >= 500) {
1926                         /* 5xx class error - problem in the remote end */
1927                         return AST_CAUSE_CONGESTION;
1928                 } else if (cause < 700 && cause >= 600) {
1929                         /* 6xx - global errors in the 4xx class */
1930                         return AST_CAUSE_INTERWORKING;
1931                 }
1932                 return AST_CAUSE_NORMAL;
1933         }
1934         /* Never reached */
1935         return 0;
1936 }
1937
1938 static void chan_pjsip_session_begin(struct ast_sip_session *session)
1939 {
1940         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1941
1942         if (session->endpoint->media.direct_media.glare_mitigation ==
1943                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
1944                 return;
1945         }
1946
1947         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
1948                         "direct_media_glare_mitigation");
1949
1950         if (!datastore) {
1951                 return;
1952         }
1953
1954         ast_sip_session_add_datastore(session, datastore);
1955 }
1956
1957 /*! \brief Function called when the session ends */
1958 static void chan_pjsip_session_end(struct ast_sip_session *session)
1959 {
1960         if (!session->channel) {
1961                 return;
1962         }
1963
1964         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
1965
1966         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
1967         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
1968                 int cause = hangup_sip2cause(session->inv_session->cause);
1969
1970                 ast_queue_hangup_with_cause(session->channel, cause);
1971         } else {
1972                 ast_queue_hangup(session->channel);
1973         }
1974 }
1975
1976 /*! \brief Function called when a request is received on the session */
1977 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1978 {
1979         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1980         struct transport_info_data *transport_data;
1981         pjsip_tx_data *packet = NULL;
1982
1983         if (session->channel) {
1984                 return 0;
1985         }
1986
1987         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
1988         if (!datastore) {
1989                 return -1;
1990         }
1991
1992         transport_data = ast_calloc(1, sizeof(*transport_data));
1993         if (!transport_data) {
1994                 return -1;
1995         }
1996         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
1997         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
1998         datastore->data = transport_data;
1999         ast_sip_session_add_datastore(session, datastore);
2000
2001         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2002                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS) {
2003                         ast_sip_session_send_response(session, packet);
2004                 }
2005
2006                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2007                 return -1;
2008         }
2009         /* channel gets created on incoming request, but we wait to call start
2010            so other supplements have a chance to run */
2011         return 0;
2012 }
2013
2014 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2015 {
2016         struct ast_features_pickup_config *pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2017         struct ast_channel *chan;
2018
2019         if (!pickup_cfg) {
2020                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2021                 return 0;
2022         }
2023
2024         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2025                 ao2_ref(pickup_cfg, -1);
2026                 return 0;
2027         }
2028         ao2_ref(pickup_cfg, -1);
2029
2030         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2031          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2032          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2033          */
2034         chan = ast_channel_ref(session->channel);
2035         if (ast_pickup_call(chan)) {
2036                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2037         } else {
2038                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2039         }
2040         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2041          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2042          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2043          * to anything at all.
2044          */
2045         ast_hangup(chan);
2046         ast_channel_unref(chan);
2047
2048         return 1;
2049 }
2050
2051 static struct ast_sip_session_supplement call_pickup_supplement = {
2052         .method = "INVITE",
2053         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2054         .incoming_request = call_pickup_incoming_request,
2055 };
2056
2057 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2058 {
2059         int res;
2060
2061         res = ast_pbx_start(session->channel);
2062
2063         switch (res) {
2064         case AST_PBX_FAILED:
2065                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2066                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2067                 ast_hangup(session->channel);
2068                 break;
2069         case AST_PBX_CALL_LIMIT:
2070                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2071                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2072                 ast_hangup(session->channel);
2073                 break;
2074         case AST_PBX_SUCCESS:
2075         default:
2076                 break;
2077         }
2078
2079         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2080
2081         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2082 }
2083
2084 static struct ast_sip_session_supplement pbx_start_supplement = {
2085         .method = "INVITE",
2086         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2087         .incoming_request = pbx_start_incoming_request,
2088 };
2089
2090 /*! \brief Function called when a response is received on the session */
2091 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2092 {
2093         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2094         struct ast_control_pvt_cause_code *cause_code;
2095         int data_size = sizeof(*cause_code);
2096
2097         if (!session->channel) {
2098                 return;
2099         }
2100
2101         switch (status.code) {
2102         case 180:
2103                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2104                 ast_channel_lock(session->channel);
2105                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2106                         ast_setstate(session->channel, AST_STATE_RINGING);
2107                 }
2108                 ast_channel_unlock(session->channel);
2109                 break;
2110         case 183:
2111                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2112                 break;
2113         case 200:
2114                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2115                 break;
2116         default:
2117                 break;
2118         }
2119
2120         /* Build and send the tech-specific cause information */
2121         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2122         data_size += 4 + 4 + pj_strlen(&status.reason);
2123         cause_code = ast_alloca(data_size);
2124         memset(cause_code, 0, data_size);
2125
2126         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2127
2128         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2129                 (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2130
2131         cause_code->ast_cause = hangup_sip2cause(status.code);
2132         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2133         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2134 }
2135
2136 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2137 {
2138         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2139                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2140                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2141                 }
2142         }
2143         return 0;
2144 }
2145
2146 static int update_devstate(void *obj, void *arg, int flags)
2147 {
2148         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2149                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2150         return 0;
2151 }
2152
2153 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2154         .name = "PJSIP_DIAL_CONTACTS",
2155         .read = pjsip_acf_dial_contacts_read,
2156 };
2157
2158 static struct ast_custom_function media_offer_function = {
2159         .name = "PJSIP_MEDIA_OFFER",
2160         .read = pjsip_acf_media_offer_read,
2161         .write = pjsip_acf_media_offer_write
2162 };
2163
2164 /*!
2165  * \brief Load the module
2166  *
2167  * Module loading including tests for configuration or dependencies.
2168  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2169  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2170  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2171  * configuration file or other non-critical problem return
2172  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2173  */
2174 static int load_module(void)
2175 {
2176         struct ao2_container *endpoints;
2177
2178         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2179                 return AST_MODULE_LOAD_DECLINE;
2180         }
2181
2182         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
2183
2184         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2185
2186         if (ast_channel_register(&chan_pjsip_tech)) {
2187                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2188                 goto end;
2189         }
2190
2191         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2192                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2193                 goto end;
2194         }
2195
2196         if (ast_custom_function_register(&media_offer_function)) {
2197                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2198                 goto end;
2199         }
2200
2201         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2202                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2203                 goto end;
2204         }
2205
2206         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
2207                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
2208                         uid_hold_sort_fn, NULL))) {
2209                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
2210                 goto end;
2211         }
2212
2213         if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
2214                 ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
2215                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2216                 goto end;
2217         }
2218
2219         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2220                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2221                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2222                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2223                 goto end;
2224         }
2225
2226         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2227                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2228                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2229                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2230                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2231                 goto end;
2232         }
2233
2234         /* since endpoints are loaded before the channel driver their device
2235            states get set to 'invalid', so they need to be updated */
2236         if ((endpoints = ast_sip_get_endpoints())) {
2237                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
2238                 ao2_ref(endpoints, -1);
2239         }
2240
2241         return 0;
2242
2243 end:
2244         ao2_cleanup(pjsip_uids_onhold);
2245         pjsip_uids_onhold = NULL;
2246         ast_custom_function_unregister(&media_offer_function);
2247         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2248         ast_channel_unregister(&chan_pjsip_tech);
2249         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2250
2251         return AST_MODULE_LOAD_FAILURE;
2252 }
2253
2254 /*! \brief Reload module */
2255 static int reload(void)
2256 {
2257         return -1;
2258 }
2259
2260 /*! \brief Unload the PJSIP channel from Asterisk */
2261 static int unload_module(void)
2262 {
2263         ao2_cleanup(pjsip_uids_onhold);
2264         pjsip_uids_onhold = NULL;
2265
2266         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2267         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2268         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2269         ast_sip_session_unregister_supplement(&call_pickup_supplement);
2270
2271         ast_custom_function_unregister(&media_offer_function);
2272         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2273
2274         ast_channel_unregister(&chan_pjsip_tech);
2275         ao2_ref(chan_pjsip_tech.capabilities, -1);
2276         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2277
2278         return 0;
2279 }
2280
2281 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
2282                 .support_level = AST_MODULE_SUPPORT_CORE,
2283                 .load = load_module,
2284                 .unload = unload_module,
2285                 .reload = reload,
2286                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
2287                );