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