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