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