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