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