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