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