pjsip / res_rtp_asterisk: Add support for sending REMB
[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 #include "asterisk/lock.h"
42 #include "asterisk/channel.h"
43 #include "asterisk/module.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/rtp_engine.h"
46 #include "asterisk/acl.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/file.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/app.h"
51 #include "asterisk/musiconhold.h"
52 #include "asterisk/causes.h"
53 #include "asterisk/taskprocessor.h"
54 #include "asterisk/dsp.h"
55 #include "asterisk/stasis_endpoints.h"
56 #include "asterisk/stasis_channels.h"
57 #include "asterisk/indications.h"
58 #include "asterisk/format_cache.h"
59 #include "asterisk/translate.h"
60 #include "asterisk/threadstorage.h"
61 #include "asterisk/features_config.h"
62 #include "asterisk/pickup.h"
63 #include "asterisk/test.h"
64
65 #include "asterisk/res_pjsip.h"
66 #include "asterisk/res_pjsip_session.h"
67 #include "asterisk/stream.h"
68
69 #include "pjsip/include/chan_pjsip.h"
70 #include "pjsip/include/dialplan_functions.h"
71 #include "pjsip/include/cli_functions.h"
72
73 AST_THREADSTORAGE(uniqueid_threadbuf);
74 #define UNIQUEID_BUFSIZE 256
75
76 static const char channel_type[] = "PJSIP";
77
78 static unsigned int chan_idx;
79
80 static void chan_pjsip_pvt_dtor(void *obj)
81 {
82 }
83
84 /* \brief Asterisk core interaction functions */
85 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);
86 static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type,
87         struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids,
88         const struct ast_channel *requestor, const char *data, int *cause);
89 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text);
90 static int chan_pjsip_digit_begin(struct ast_channel *ast, char digit);
91 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
92 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout);
93 static int chan_pjsip_hangup(struct ast_channel *ast);
94 static int chan_pjsip_answer(struct ast_channel *ast);
95 static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast);
96 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *f);
97 static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *f);
98 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
99 static int chan_pjsip_transfer(struct ast_channel *ast, const char *target);
100 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
101 static int chan_pjsip_devicestate(const char *data);
102 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
103 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast);
104
105 /*! \brief PBX interface structure for channel registration */
106 struct ast_channel_tech chan_pjsip_tech = {
107         .type = channel_type,
108         .description = "PJSIP Channel Driver",
109         .requester = chan_pjsip_request,
110         .requester_with_stream_topology = chan_pjsip_request_with_stream_topology,
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_stream = chan_pjsip_read_stream,
118         .write = chan_pjsip_write,
119         .write_stream = chan_pjsip_write_stream,
120         .exception = chan_pjsip_read_stream,
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         /* It is important that this supplement runs after media has been negotiated */
146         .response_priority = AST_SIP_SESSION_AFTER_MEDIA,
147 };
148
149 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata);
150
151 static struct ast_sip_session_supplement chan_pjsip_ack_supplement = {
152         .method = "ACK",
153         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL,
154         .incoming_request = chan_pjsip_incoming_ack,
155 };
156
157 /*! \brief Function called by RTP engine to get local audio RTP peer */
158 static enum ast_rtp_glue_result chan_pjsip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
159 {
160         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
161         struct ast_sip_endpoint *endpoint;
162         struct ast_datastore *datastore;
163         struct ast_sip_session_media *media;
164
165         if (!channel || !channel->session) {
166                 return AST_RTP_GLUE_RESULT_FORBID;
167         }
168
169         /* XXX Getting the first RTP instance for direct media related stuff seems just
170          * absolutely wrong. But the native RTP bridge knows no other method than single-stream
171          * for direct media. So this is the best we can do.
172          */
173         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
174         if (!media || !media->rtp) {
175                 return AST_RTP_GLUE_RESULT_FORBID;
176         }
177
178         datastore = ast_sip_session_get_datastore(channel->session, "t38");
179         if (datastore) {
180                 ao2_ref(datastore, -1);
181                 return AST_RTP_GLUE_RESULT_FORBID;
182         }
183
184         endpoint = channel->session->endpoint;
185
186         *instance = media->rtp;
187         ao2_ref(*instance, +1);
188
189         ast_assert(endpoint != NULL);
190         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
191                 return AST_RTP_GLUE_RESULT_FORBID;
192         }
193
194         if (endpoint->media.direct_media.enabled) {
195                 return AST_RTP_GLUE_RESULT_REMOTE;
196         }
197
198         return AST_RTP_GLUE_RESULT_LOCAL;
199 }
200
201 /*! \brief Function called by RTP engine to get local video RTP peer */
202 static enum ast_rtp_glue_result chan_pjsip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
203 {
204         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
205         struct ast_sip_endpoint *endpoint;
206         struct ast_sip_session_media *media;
207
208         if (!channel || !channel->session) {
209                 return AST_RTP_GLUE_RESULT_FORBID;
210         }
211
212         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO];
213         if (!media || !media->rtp) {
214                 return AST_RTP_GLUE_RESULT_FORBID;
215         }
216
217         endpoint = channel->session->endpoint;
218
219         *instance = media->rtp;
220         ao2_ref(*instance, +1);
221
222         ast_assert(endpoint != NULL);
223         if (endpoint->media.rtp.encryption != AST_SIP_MEDIA_ENCRYPT_NONE) {
224                 return AST_RTP_GLUE_RESULT_FORBID;
225         }
226
227         return AST_RTP_GLUE_RESULT_LOCAL;
228 }
229
230 /*! \brief Function called by RTP engine to get peer capabilities */
231 static void chan_pjsip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
232 {
233         ast_format_cap_append_from_cap(result, ast_channel_nativeformats(chan), AST_MEDIA_TYPE_UNKNOWN);
234 }
235
236 /*! \brief Destructor function for \ref transport_info_data */
237 static void transport_info_destroy(void *obj)
238 {
239         struct transport_info_data *data = obj;
240         ast_free(data);
241 }
242
243 /*! \brief Datastore used to store local/remote addresses for the
244  * INVITE request that created the PJSIP channel */
245 static struct ast_datastore_info transport_info = {
246         .type = "chan_pjsip_transport_info",
247         .destroy = transport_info_destroy,
248 };
249
250 static struct ast_datastore_info direct_media_mitigation_info = { };
251
252 static int direct_media_mitigate_glare(struct ast_sip_session *session)
253 {
254         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
255
256         if (session->endpoint->media.direct_media.glare_mitigation ==
257                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
258                 return 0;
259         }
260
261         datastore = ast_sip_session_get_datastore(session, "direct_media_glare_mitigation");
262         if (!datastore) {
263                 return 0;
264         }
265
266         /* Removing the datastore ensures we won't try to mitigate glare on subsequent reinvites */
267         ast_sip_session_remove_datastore(session, "direct_media_glare_mitigation");
268
269         if ((session->endpoint->media.direct_media.glare_mitigation ==
270                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_OUTGOING &&
271                         session->inv_session->role == PJSIP_ROLE_UAC) ||
272                         (session->endpoint->media.direct_media.glare_mitigation ==
273                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_INCOMING &&
274                         session->inv_session->role == PJSIP_ROLE_UAS)) {
275                 return 1;
276         }
277
278         return 0;
279 }
280
281 /*! \brief Helper function to find the position for RTCP */
282 static int rtp_find_rtcp_fd_position(struct ast_sip_session *session, struct ast_rtp_instance *rtp)
283 {
284         int index;
285
286         for (index = 0; index < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++index) {
287                 struct ast_sip_session_media_read_callback_state *callback_state =
288                         AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, index);
289
290                 if (callback_state->fd != ast_rtp_instance_fd(rtp, 1)) {
291                         continue;
292                 }
293
294                 return index;
295         }
296
297         return -1;
298 }
299
300 /*!
301  * \pre chan is locked
302  */
303 static int check_for_rtp_changes(struct ast_channel *chan, struct ast_rtp_instance *rtp,
304                 struct ast_sip_session_media *media, struct ast_sip_session *session)
305 {
306         int changed = 0, position = -1;
307
308         if (media->rtp) {
309                 position = rtp_find_rtcp_fd_position(session, media->rtp);
310         }
311
312         if (rtp) {
313                 changed = ast_rtp_instance_get_and_cmp_remote_address(rtp, &media->direct_media_addr);
314                 if (media->rtp) {
315                         if (position != -1) {
316                                 ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, -1);
317                         }
318                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 0);
319                 }
320         } else if (!ast_sockaddr_isnull(&media->direct_media_addr)){
321                 ast_sockaddr_setnull(&media->direct_media_addr);
322                 changed = 1;
323                 if (media->rtp) {
324                         ast_rtp_instance_set_prop(media->rtp, AST_RTP_PROPERTY_RTCP, 1);
325                         if (position != -1) {
326                                 ast_channel_set_fd(chan, position + AST_EXTENDED_FDS, ast_rtp_instance_fd(media->rtp, 1));
327                         }
328                 }
329         }
330
331         return changed;
332 }
333
334 struct rtp_direct_media_data {
335         struct ast_channel *chan;
336         struct ast_rtp_instance *rtp;
337         struct ast_rtp_instance *vrtp;
338         struct ast_format_cap *cap;
339         struct ast_sip_session *session;
340 };
341
342 static void rtp_direct_media_data_destroy(void *data)
343 {
344         struct rtp_direct_media_data *cdata = data;
345
346         ao2_cleanup(cdata->session);
347         ao2_cleanup(cdata->cap);
348         ao2_cleanup(cdata->vrtp);
349         ao2_cleanup(cdata->rtp);
350         ao2_cleanup(cdata->chan);
351 }
352
353 static struct rtp_direct_media_data *rtp_direct_media_data_create(
354         struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp,
355         const struct ast_format_cap *cap, struct ast_sip_session *session)
356 {
357         struct rtp_direct_media_data *cdata = ao2_alloc(sizeof(*cdata), rtp_direct_media_data_destroy);
358
359         if (!cdata) {
360                 return NULL;
361         }
362
363         cdata->chan = ao2_bump(chan);
364         cdata->rtp = ao2_bump(rtp);
365         cdata->vrtp = ao2_bump(vrtp);
366         cdata->cap = ao2_bump((struct ast_format_cap *)cap);
367         cdata->session = ao2_bump(session);
368
369         return cdata;
370 }
371
372 static int send_direct_media_request(void *data)
373 {
374         struct rtp_direct_media_data *cdata = data;
375         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(cdata->chan);
376         struct ast_sip_session *session;
377         int changed = 0;
378         int res = 0;
379
380         /* XXX In an ideal world each media stream would be direct, but for now preserve behavior
381          * and connect only the default media sessions for audio and video.
382          */
383
384         /* The channel needs to be locked when checking for RTP changes.
385          * Otherwise, we could end up destroying an underlying RTCP structure
386          * at the same time that the channel thread is attempting to read RTCP
387          */
388         ast_channel_lock(cdata->chan);
389         session = channel->session;
390         if (session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO]) {
391                 changed |= check_for_rtp_changes(
392                         cdata->chan, cdata->rtp, session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO], session);
393         }
394         if (session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO]) {
395                 changed |= check_for_rtp_changes(
396                         cdata->chan, cdata->vrtp, session->active_media_state->default_session[AST_MEDIA_TYPE_VIDEO], session);
397         }
398         ast_channel_unlock(cdata->chan);
399
400         if (direct_media_mitigate_glare(cdata->session)) {
401                 ast_debug(4, "Disregarding setting RTP on %s: mitigating re-INVITE glare\n", ast_channel_name(cdata->chan));
402                 ao2_ref(cdata, -1);
403                 return 0;
404         }
405
406         if (cdata->cap && ast_format_cap_count(cdata->cap) &&
407             !ast_format_cap_identical(cdata->session->direct_media_cap, cdata->cap)) {
408                 ast_format_cap_remove_by_type(cdata->session->direct_media_cap, AST_MEDIA_TYPE_UNKNOWN);
409                 ast_format_cap_append_from_cap(cdata->session->direct_media_cap, cdata->cap, AST_MEDIA_TYPE_UNKNOWN);
410                 changed = 1;
411         }
412
413         if (changed) {
414                 ast_debug(4, "RTP changed on %s; initiating direct media update\n", ast_channel_name(cdata->chan));
415                 res = ast_sip_session_refresh(cdata->session, NULL, NULL, NULL,
416                         cdata->session->endpoint->media.direct_media.method, 1, NULL);
417         }
418
419         ao2_ref(cdata, -1);
420         return res;
421 }
422
423 /*! \brief Function called by RTP engine to change where the remote party should send media */
424 static int chan_pjsip_set_rtp_peer(struct ast_channel *chan,
425                 struct ast_rtp_instance *rtp,
426                 struct ast_rtp_instance *vrtp,
427                 struct ast_rtp_instance *tpeer,
428                 const struct ast_format_cap *cap,
429                 int nat_active)
430 {
431         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
432         struct ast_sip_session *session = channel->session;
433         struct rtp_direct_media_data *cdata;
434
435         /* Don't try to do any direct media shenanigans on early bridges */
436         if ((rtp || vrtp || tpeer) && !ast_channel_is_bridged(chan)) {
437                 ast_debug(4, "Disregarding setting RTP on %s: channel is not bridged\n", ast_channel_name(chan));
438                 return 0;
439         }
440
441         if (nat_active && session->endpoint->media.direct_media.disable_on_nat) {
442                 ast_debug(4, "Disregarding setting RTP on %s: NAT is active\n", ast_channel_name(chan));
443                 return 0;
444         }
445
446         cdata = rtp_direct_media_data_create(chan, rtp, vrtp, cap, session);
447         if (!cdata) {
448                 return 0;
449         }
450
451         if (ast_sip_push_task(session->serializer, send_direct_media_request, cdata)) {
452                 ast_log(LOG_ERROR, "Unable to send direct media request for channel %s\n", ast_channel_name(chan));
453                 ao2_ref(cdata, -1);
454         }
455
456         return 0;
457 }
458
459 /*! \brief Local glue for interacting with the RTP engine core */
460 static struct ast_rtp_glue chan_pjsip_rtp_glue = {
461         .type = "PJSIP",
462         .get_rtp_info = chan_pjsip_get_rtp_peer,
463         .get_vrtp_info = chan_pjsip_get_vrtp_peer,
464         .get_codec = chan_pjsip_get_codec,
465         .update_peer = chan_pjsip_set_rtp_peer,
466 };
467
468 static void set_channel_on_rtp_instance(const struct ast_sip_session *session,
469         const char *channel_id)
470 {
471         int i;
472
473         for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->sessions); ++i) {
474                 struct ast_sip_session_media *session_media;
475
476                 session_media = AST_VECTOR_GET(&session->active_media_state->sessions, i);
477                 if (!session_media || !session_media->rtp) {
478                         continue;
479                 }
480
481                 ast_rtp_instance_set_channel_id(session_media->rtp, channel_id);
482         }
483 }
484
485 /*!
486  * \brief Determine if a topology is compatible with format capabilities
487  *
488  * This will return true if ANY formats in the topology are compatible with the format
489  * capabilities.
490  *
491  * XXX When supporting true multistream, we will need to be sure to mark which streams from
492  * top1 are compatible with which streams from top2. Then the ones that are not compatible
493  * will need to be marked as "removed" so that they are negotiated as expected.
494  *
495  * \param top Topology
496  * \param cap Format capabilities
497  * \retval 1 The topology has at least one compatible format
498  * \retval 0 The topology has no compatible formats or an error occurred.
499  */
500 static int compatible_formats_exist(struct ast_stream_topology *top, struct ast_format_cap *cap)
501 {
502         struct ast_format_cap *cap_from_top;
503         int res;
504
505         cap_from_top = ast_format_cap_from_stream_topology(top);
506
507         if (!cap_from_top) {
508                 return 0;
509         }
510
511         res = ast_format_cap_iscompatible(cap_from_top, cap);
512         ao2_ref(cap_from_top, -1);
513
514         return res;
515 }
516
517 /*! \brief Function called to create a new PJSIP Asterisk channel */
518 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)
519 {
520         struct ast_channel *chan;
521         struct ast_format_cap *caps;
522         RAII_VAR(struct chan_pjsip_pvt *, pvt, NULL, ao2_cleanup);
523         struct ast_sip_channel_pvt *channel;
524         struct ast_variable *var;
525         struct ast_stream_topology *topology;
526
527         if (!(pvt = ao2_alloc_options(sizeof(*pvt), chan_pjsip_pvt_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK))) {
528                 return NULL;
529         }
530
531         chan = ast_channel_alloc_with_endpoint(1, state,
532                 S_COR(session->id.number.valid, session->id.number.str, ""),
533                 S_COR(session->id.name.valid, session->id.name.str, ""),
534                 session->endpoint->accountcode,
535                 exten, session->endpoint->context,
536                 assignedids, requestor, 0,
537                 session->endpoint->persistent, "PJSIP/%s-%08x",
538                 ast_sorcery_object_get_id(session->endpoint),
539                 (unsigned) ast_atomic_fetchadd_int((int *) &chan_idx, +1));
540         if (!chan) {
541                 return NULL;
542         }
543
544         ast_channel_tech_set(chan, &chan_pjsip_tech);
545
546         if (!(channel = ast_sip_channel_pvt_alloc(pvt, session))) {
547                 ast_channel_unlock(chan);
548                 ast_hangup(chan);
549                 return NULL;
550         }
551
552         ast_channel_tech_pvt_set(chan, channel);
553
554         if (!ast_stream_topology_get_count(session->pending_media_state->topology) ||
555                 !compatible_formats_exist(session->pending_media_state->topology, session->endpoint->media.codecs)) {
556                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
557                 if (!caps) {
558                         ast_channel_unlock(chan);
559                         ast_hangup(chan);
560                         return NULL;
561                 }
562                 ast_format_cap_append_from_cap(caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
563                 topology = ast_stream_topology_clone(session->endpoint->media.topology);
564         } else {
565                 caps = ast_format_cap_from_stream_topology(session->pending_media_state->topology);
566                 topology = ast_stream_topology_clone(session->pending_media_state->topology);
567         }
568
569         if (!topology || !caps) {
570                 ao2_cleanup(caps);
571                 ast_stream_topology_free(topology);
572                 ast_channel_unlock(chan);
573                 ast_hangup(chan);
574                 return NULL;
575         }
576
577         ast_channel_stage_snapshot(chan);
578
579         ast_channel_nativeformats_set(chan, caps);
580         ast_channel_set_stream_topology(chan, topology);
581
582         if (!ast_format_cap_empty(caps)) {
583                 struct ast_format *fmt;
584
585                 fmt = ast_format_cap_get_best_by_type(caps, AST_MEDIA_TYPE_AUDIO);
586                 if (!fmt) {
587                         /* Since our capabilities aren't empty, this will succeed */
588                         fmt = ast_format_cap_get_format(caps, 0);
589                 }
590                 ast_channel_set_writeformat(chan, fmt);
591                 ast_channel_set_rawwriteformat(chan, fmt);
592                 ast_channel_set_readformat(chan, fmt);
593                 ast_channel_set_rawreadformat(chan, fmt);
594                 ao2_ref(fmt, -1);
595         }
596
597         ao2_ref(caps, -1);
598
599         if (state == AST_STATE_RING) {
600                 ast_channel_rings_set(chan, 1);
601         }
602
603         ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
604
605         ast_party_id_copy(&ast_channel_caller(chan)->id, &session->id);
606         ast_party_id_copy(&ast_channel_caller(chan)->ani, &session->id);
607
608         if (!ast_strlen_zero(exten)) {
609                 /* Set provided DNID on the new channel. */
610                 ast_channel_dialed(chan)->number.str = ast_strdup(exten);
611         }
612
613         ast_channel_priority_set(chan, 1);
614
615         ast_channel_callgroup_set(chan, session->endpoint->pickup.callgroup);
616         ast_channel_pickupgroup_set(chan, session->endpoint->pickup.pickupgroup);
617
618         ast_channel_named_callgroups_set(chan, session->endpoint->pickup.named_callgroups);
619         ast_channel_named_pickupgroups_set(chan, session->endpoint->pickup.named_pickupgroups);
620
621         if (!ast_strlen_zero(session->endpoint->language)) {
622                 ast_channel_language_set(chan, session->endpoint->language);
623         }
624
625         if (!ast_strlen_zero(session->endpoint->zone)) {
626                 struct ast_tone_zone *zone = ast_get_indication_zone(session->endpoint->zone);
627                 if (!zone) {
628                         ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", session->endpoint->zone);
629                 }
630                 ast_channel_zone_set(chan, zone);
631         }
632
633         for (var = session->endpoint->channel_vars; var; var = var->next) {
634                 char buf[512];
635                 pbx_builtin_setvar_helper(chan, var->name, ast_get_encoded_str(
636                                                   var->value, buf, sizeof(buf)));
637         }
638
639         ast_channel_stage_snapshot_done(chan);
640         ast_channel_unlock(chan);
641
642         set_channel_on_rtp_instance(session, ast_channel_uniqueid(chan));
643
644         return chan;
645 }
646
647 static int answer(void *data)
648 {
649         pj_status_t status = PJ_SUCCESS;
650         pjsip_tx_data *packet = NULL;
651         struct ast_sip_session *session = data;
652
653         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
654                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
655                         session->inv_session->cause,
656                         pjsip_get_status_text(session->inv_session->cause)->ptr);
657 #ifdef HAVE_PJSIP_INV_SESSION_REF
658                 pjsip_inv_dec_ref(session->inv_session);
659 #endif
660                 return 0;
661         }
662
663         pjsip_dlg_inc_lock(session->inv_session->dlg);
664         if (session->inv_session->invite_tsx) {
665                 status = pjsip_inv_answer(session->inv_session, 200, NULL, NULL, &packet);
666         } else {
667                 ast_log(LOG_ERROR,"Cannot answer '%s' because there is no associated SIP transaction\n",
668                         ast_channel_name(session->channel));
669         }
670         pjsip_dlg_dec_lock(session->inv_session->dlg);
671
672         if (status == PJ_SUCCESS && packet) {
673                 ast_sip_session_send_response(session, packet);
674         }
675
676 #ifdef HAVE_PJSIP_INV_SESSION_REF
677         pjsip_inv_dec_ref(session->inv_session);
678 #endif
679
680         if (status != PJ_SUCCESS) {
681                 char err[PJ_ERR_MSG_SIZE];
682
683                 pj_strerror(status, err, sizeof(err));
684                 ast_log(LOG_WARNING,"Cannot answer '%s': %s\n",
685                         ast_channel_name(session->channel), err);
686                 /*
687                  * Return this value so we can distinguish between this
688                  * failure and the threadpool synchronous push failing.
689                  */
690                 return -2;
691         }
692         return 0;
693 }
694
695 /*! \brief Function called by core when we should answer a PJSIP session */
696 static int chan_pjsip_answer(struct ast_channel *ast)
697 {
698         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
699         struct ast_sip_session *session;
700         int res;
701
702         if (ast_channel_state(ast) == AST_STATE_UP) {
703                 return 0;
704         }
705
706         ast_setstate(ast, AST_STATE_UP);
707         session = ao2_bump(channel->session);
708
709 #ifdef HAVE_PJSIP_INV_SESSION_REF
710         if (pjsip_inv_add_ref(session->inv_session) != PJ_SUCCESS) {
711                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
712                 ao2_ref(session, -1);
713                 return -1;
714         }
715 #endif
716
717         /* the answer task needs to be pushed synchronously otherwise a race condition
718            can occur between this thread and bridging (specifically when native bridging
719            attempts to do direct media) */
720         ast_channel_unlock(ast);
721         res = ast_sip_push_task_synchronous(session->serializer, answer, session);
722         if (res) {
723                 if (res == -1) {
724                         ast_log(LOG_ERROR,"Cannot answer '%s': Unable to push answer task to the threadpool.\n",
725                                 ast_channel_name(session->channel));
726 #ifdef HAVE_PJSIP_INV_SESSION_REF
727                         pjsip_inv_dec_ref(session->inv_session);
728 #endif
729                 }
730                 ao2_ref(session, -1);
731                 ast_channel_lock(ast);
732                 return -1;
733         }
734         ao2_ref(session, -1);
735         ast_channel_lock(ast);
736
737         return 0;
738 }
739
740 /*! \brief Internal helper function called when CNG tone is detected */
741 static struct ast_frame *chan_pjsip_cng_tone_detected(struct ast_sip_session *session, struct ast_frame *f)
742 {
743         const char *target_context;
744         int exists;
745         int dsp_features;
746
747         dsp_features = ast_dsp_get_features(session->dsp);
748         dsp_features &= ~DSP_FEATURE_FAX_DETECT;
749         if (dsp_features) {
750                 ast_dsp_set_features(session->dsp, dsp_features);
751         } else {
752                 ast_dsp_free(session->dsp);
753                 session->dsp = NULL;
754         }
755
756         /* If already executing in the fax extension don't do anything */
757         if (!strcmp(ast_channel_exten(session->channel), "fax")) {
758                 return f;
759         }
760
761         target_context = S_OR(ast_channel_macrocontext(session->channel), ast_channel_context(session->channel));
762
763         /*
764          * We need to unlock the channel here because ast_exists_extension has the
765          * potential to start and stop an autoservice on the channel. Such action
766          * is prone to deadlock if the channel is locked.
767          *
768          * ast_async_goto() has its own restriction on not holding the channel lock.
769          */
770         ast_channel_unlock(session->channel);
771         ast_frfree(f);
772         f = &ast_null_frame;
773         exists = ast_exists_extension(session->channel, target_context, "fax", 1,
774                 S_COR(ast_channel_caller(session->channel)->id.number.valid,
775                         ast_channel_caller(session->channel)->id.number.str, NULL));
776         if (exists) {
777                 ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n",
778                         ast_channel_name(session->channel));
779                 pbx_builtin_setvar_helper(session->channel, "FAXEXTEN", ast_channel_exten(session->channel));
780                 if (ast_async_goto(session->channel, target_context, "fax", 1)) {
781                         ast_log(LOG_ERROR, "Failed to async goto '%s' into fax extension in '%s'\n",
782                                 ast_channel_name(session->channel), target_context);
783                 }
784         } else {
785                 ast_log(LOG_NOTICE, "FAX CNG detected on '%s' but no fax extension in '%s'\n",
786                         ast_channel_name(session->channel), target_context);
787         }
788         ast_channel_lock(session->channel);
789
790         return f;
791 }
792
793 /*!
794  * \brief Function called by core to read any waiting frames
795  *
796  * \note The channel is already locked.
797  */
798 static struct ast_frame *chan_pjsip_read_stream(struct ast_channel *ast)
799 {
800         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
801         struct ast_sip_session *session = channel->session;
802         struct ast_sip_session_media_read_callback_state *callback_state;
803         struct ast_frame *f;
804         int fdno = ast_channel_fdno(ast) - AST_EXTENDED_FDS;
805
806         if (fdno >= AST_VECTOR_SIZE(&session->active_media_state->read_callbacks)) {
807                 return &ast_null_frame;
808         }
809
810         callback_state = AST_VECTOR_GET_ADDR(&session->active_media_state->read_callbacks, fdno);
811         f = callback_state->read_callback(session, callback_state->session);
812
813         if (!f) {
814                 return f;
815         }
816
817         if (f->frametype != AST_FRAME_VOICE ||
818                 callback_state->session != session->active_media_state->default_session[callback_state->session->type]) {
819                 return f;
820         }
821
822         session = channel->session;
823
824         /*
825          * Asymmetric RTP only has one native format set at a time.
826          * Therefore we need to update the native format to the current
827          * raw read format BEFORE the native format check
828          */
829         if (!session->endpoint->asymmetric_rtp_codec &&
830                 ast_format_cmp(ast_channel_rawwriteformat(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
831                 struct ast_format_cap *caps;
832
833                 /* For maximum compatibility we ensure that the formats match that of the received media */
834                 ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when we're sending '%s', switching to match\n",
835                         ast_format_get_name(f->subclass.format), ast_channel_name(ast),
836                         ast_format_get_name(ast_channel_rawwriteformat(ast)));
837
838                 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
839                 if (caps) {
840                         ast_format_cap_append_from_cap(caps, ast_channel_nativeformats(ast), AST_MEDIA_TYPE_UNKNOWN);
841                         ast_format_cap_remove_by_type(caps, AST_MEDIA_TYPE_AUDIO);
842                         ast_format_cap_append(caps, f->subclass.format, 0);
843                         ast_channel_nativeformats_set(ast, caps);
844                         ao2_ref(caps, -1);
845                 }
846
847                 ast_set_write_format_path(ast, ast_channel_writeformat(ast), f->subclass.format);
848                 ast_set_read_format_path(ast, ast_channel_readformat(ast), f->subclass.format);
849
850                 if (ast_channel_is_bridged(ast)) {
851                         ast_channel_set_unbridged_nolock(ast, 1);
852                 }
853         }
854
855         if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), f->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
856                 ast_debug(1, "Oooh, got a frame with format of %s on channel '%s' when it has not been negotiated\n",
857                         ast_format_get_name(f->subclass.format), ast_channel_name(ast));
858
859                 ast_frfree(f);
860                 return &ast_null_frame;
861         }
862
863         if (session->dsp) {
864                 int dsp_features;
865
866                 dsp_features = ast_dsp_get_features(session->dsp);
867                 if ((dsp_features & DSP_FEATURE_FAX_DETECT)
868                         && session->endpoint->faxdetect_timeout
869                         && session->endpoint->faxdetect_timeout <= ast_channel_get_up_time(ast)) {
870                         dsp_features &= ~DSP_FEATURE_FAX_DETECT;
871                         if (dsp_features) {
872                                 ast_dsp_set_features(session->dsp, dsp_features);
873                         } else {
874                                 ast_dsp_free(session->dsp);
875                                 session->dsp = NULL;
876                         }
877                         ast_debug(3, "Channel driver fax CNG detection timeout on %s\n",
878                                 ast_channel_name(ast));
879                 }
880         }
881         if (session->dsp) {
882                 f = ast_dsp_process(ast, session->dsp, f);
883                 if (f && (f->frametype == AST_FRAME_DTMF)) {
884                         if (f->subclass.integer == 'f') {
885                                 ast_debug(3, "Channel driver fax CNG detected on %s\n",
886                                         ast_channel_name(ast));
887                                 f = chan_pjsip_cng_tone_detected(session, f);
888                         } else {
889                                 ast_debug(3, "* Detected inband DTMF '%c' on '%s'\n", f->subclass.integer,
890                                         ast_channel_name(ast));
891                         }
892                 }
893         }
894
895         return f;
896 }
897
898 static int chan_pjsip_write_stream(struct ast_channel *ast, int stream_num, struct ast_frame *frame)
899 {
900         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
901         struct ast_sip_session *session = channel->session;
902         struct ast_sip_session_media *media = NULL;
903         int res = 0;
904
905         /* The core provides a guarantee that the stream will exist when we are called if stream_num is provided */
906         if (stream_num >= 0) {
907                 /* What is not guaranteed is that a media session will exist */
908                 if (stream_num < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions)) {
909                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, stream_num);
910                 }
911         }
912
913         switch (frame->frametype) {
914         case AST_FRAME_VOICE:
915                 if (!media) {
916                         return 0;
917                 } else if (media->type != AST_MEDIA_TYPE_AUDIO) {
918                         ast_debug(3, "Channel %s stream %d is of type '%s', not audio!\n",
919                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
920                         return 0;
921                 } else if (media == channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO] &&
922                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), frame->subclass.format) == AST_FORMAT_CMP_NOT_EQUAL) {
923                         struct ast_str *cap_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
924                         struct ast_str *write_transpath = ast_str_alloca(256);
925                         struct ast_str *read_transpath = ast_str_alloca(256);
926
927                         ast_log(LOG_WARNING,
928                                 "Channel %s asked to send %s frame when native formats are %s (rd:%s->%s;%s wr:%s->%s;%s)\n",
929                                 ast_channel_name(ast),
930                                 ast_format_get_name(frame->subclass.format),
931                                 ast_format_cap_get_names(ast_channel_nativeformats(ast), &cap_buf),
932                                 ast_format_get_name(ast_channel_rawreadformat(ast)),
933                                 ast_format_get_name(ast_channel_readformat(ast)),
934                                 ast_translate_path_to_str(ast_channel_readtrans(ast), &read_transpath),
935                                 ast_format_get_name(ast_channel_writeformat(ast)),
936                                 ast_format_get_name(ast_channel_rawwriteformat(ast)),
937                                 ast_translate_path_to_str(ast_channel_writetrans(ast), &write_transpath));
938                         return 0;
939                 } else if (media->write_callback) {
940                         res = media->write_callback(session, media, frame);
941
942                 }
943                 break;
944         case AST_FRAME_VIDEO:
945                 if (!media) {
946                         return 0;
947                 } else if (media->type != AST_MEDIA_TYPE_VIDEO) {
948                         ast_debug(3, "Channel %s stream %d is of type '%s', not video!\n",
949                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
950                         return 0;
951                 } else if (media->write_callback) {
952                         res = media->write_callback(session, media, frame);
953                 }
954                 break;
955         case AST_FRAME_MODEM:
956                 if (!media) {
957                         return 0;
958                 } else if (media->type != AST_MEDIA_TYPE_IMAGE) {
959                         ast_debug(3, "Channel %s stream %d is of type '%s', not image!\n",
960                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
961                         return 0;
962                 } else if (media->write_callback) {
963                         res = media->write_callback(session, media, frame);
964                 }
965                 break;
966         case AST_FRAME_CNG:
967                 break;
968         case AST_FRAME_RTCP:
969                 /* We only support writing out feedback */
970                 if (frame->subclass.integer != AST_RTP_RTCP_PSFB || !media) {
971                         return 0;
972                 } else if (media->type != AST_MEDIA_TYPE_VIDEO) {
973                         ast_debug(3, "Channel %s stream %d is of type '%s', not video! Unable to write RTCP feedback.\n",
974                                 ast_channel_name(ast), stream_num, ast_codec_media_type2str(media->type));
975                         return 0;
976                 } else if (media->write_callback) {
977                         res = media->write_callback(session, media, frame);
978                 }
979                 break;
980         default:
981                 ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
982                 break;
983         }
984
985         return res;
986 }
987
988 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
989 {
990         return chan_pjsip_write_stream(ast, -1, frame);
991 }
992
993 /*! \brief Function called by core to change the underlying owner channel */
994 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
995 {
996         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
997
998         if (channel->session->channel != oldchan) {
999                 return -1;
1000         }
1001
1002         /*
1003          * The masquerade has suspended the channel's session
1004          * serializer so we can safely change it outside of
1005          * the serializer thread.
1006          */
1007         channel->session->channel = newchan;
1008
1009         set_channel_on_rtp_instance(channel->session, ast_channel_uniqueid(newchan));
1010
1011         return 0;
1012 }
1013
1014 /*! AO2 hash function for on hold UIDs */
1015 static int uid_hold_hash_fn(const void *obj, const int flags)
1016 {
1017         const char *key = obj;
1018
1019         switch (flags & OBJ_SEARCH_MASK) {
1020         case OBJ_SEARCH_KEY:
1021                 break;
1022         case OBJ_SEARCH_OBJECT:
1023                 break;
1024         default:
1025                 /* Hash can only work on something with a full key. */
1026                 ast_assert(0);
1027                 return 0;
1028         }
1029         return ast_str_hash(key);
1030 }
1031
1032 /*! AO2 sort function for on hold UIDs */
1033 static int uid_hold_sort_fn(const void *obj_left, const void *obj_right, const int flags)
1034 {
1035         const char *left = obj_left;
1036         const char *right = obj_right;
1037         int cmp;
1038
1039         switch (flags & OBJ_SEARCH_MASK) {
1040         case OBJ_SEARCH_OBJECT:
1041         case OBJ_SEARCH_KEY:
1042                 cmp = strcmp(left, right);
1043                 break;
1044         case OBJ_SEARCH_PARTIAL_KEY:
1045                 cmp = strncmp(left, right, strlen(right));
1046                 break;
1047         default:
1048                 /* Sort can only work on something with a full or partial key. */
1049                 ast_assert(0);
1050                 cmp = 0;
1051                 break;
1052         }
1053         return cmp;
1054 }
1055
1056 static struct ao2_container *pjsip_uids_onhold;
1057
1058 /*!
1059  * \brief Add a channel ID to the list of PJSIP channels on hold
1060  *
1061  * \param chan_uid - Unique ID of the channel being put into the hold list
1062  *
1063  * \retval 0 Channel has been added to or was already in the hold list
1064  * \retval -1 Failed to add channel to the hold list
1065  */
1066 static int chan_pjsip_add_hold(const char *chan_uid)
1067 {
1068         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1069
1070         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1071         if (hold_uid) {
1072                 /* Device is already on hold. Nothing to do. */
1073                 return 0;
1074         }
1075
1076         /* Device wasn't in hold list already. Create a new one. */
1077         hold_uid = ao2_alloc_options(strlen(chan_uid) + 1, NULL,
1078                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1079         if (!hold_uid) {
1080                 return -1;
1081         }
1082
1083         ast_copy_string(hold_uid, chan_uid, strlen(chan_uid) + 1);
1084
1085         if (ao2_link(pjsip_uids_onhold, hold_uid) == 0) {
1086                 return -1;
1087         }
1088
1089         return 0;
1090 }
1091
1092 /*!
1093  * \brief Remove a channel ID from the list of PJSIP channels on hold
1094  *
1095  * \param chan_uid - Unique ID of the channel being taken out of the hold list
1096  */
1097 static void chan_pjsip_remove_hold(const char *chan_uid)
1098 {
1099         ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
1100 }
1101
1102 /*!
1103  * \brief Determine whether a channel ID is in the list of PJSIP channels on hold
1104  *
1105  * \param chan_uid - Channel being checked
1106  *
1107  * \retval 0 The channel is not in the hold list
1108  * \retval 1 The channel is in the hold list
1109  */
1110 static int chan_pjsip_get_hold(const char *chan_uid)
1111 {
1112         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1113
1114         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1115         if (!hold_uid) {
1116                 return 0;
1117         }
1118
1119         return 1;
1120 }
1121
1122 /*! \brief Function called to get the device state of an endpoint */
1123 static int chan_pjsip_devicestate(const char *data)
1124 {
1125         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
1126         enum ast_device_state state = AST_DEVICE_UNKNOWN;
1127         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
1128         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
1129         struct ast_devstate_aggregate aggregate;
1130         int num, inuse = 0;
1131
1132         if (!endpoint) {
1133                 return AST_DEVICE_INVALID;
1134         }
1135
1136         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
1137                 ast_endpoint_get_resource(endpoint->persistent));
1138
1139         if (!endpoint_snapshot) {
1140                 return AST_DEVICE_INVALID;
1141         }
1142
1143         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
1144                 state = AST_DEVICE_UNAVAILABLE;
1145         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
1146                 state = AST_DEVICE_NOT_INUSE;
1147         }
1148
1149         if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
1150                 return state;
1151         }
1152
1153         ast_devstate_aggregate_init(&aggregate);
1154
1155         ao2_ref(cache, +1);
1156
1157         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
1158                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
1159                 struct ast_channel_snapshot *snapshot;
1160
1161                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
1162                         endpoint_snapshot->channel_ids[num]);
1163
1164                 if (!msg) {
1165                         continue;
1166                 }
1167
1168                 snapshot = stasis_message_data(msg);
1169
1170                 if (chan_pjsip_get_hold(snapshot->uniqueid)) {
1171                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
1172                 } else {
1173                         ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
1174                 }
1175
1176                 if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
1177                         (snapshot->state == AST_STATE_BUSY)) {
1178                         inuse++;
1179                 }
1180         }
1181
1182         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
1183                 state = AST_DEVICE_BUSY;
1184         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
1185                 state = ast_devstate_aggregate_result(&aggregate);
1186         }
1187
1188         return state;
1189 }
1190
1191 /*! \brief Function called to query options on a channel */
1192 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
1193 {
1194         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1195         struct ast_sip_session *session = channel->session;
1196         int res = -1;
1197         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1198
1199         switch (option) {
1200         case AST_OPTION_T38_STATE:
1201                 if (session->endpoint->media.t38.enabled) {
1202                         switch (session->t38state) {
1203                         case T38_LOCAL_REINVITE:
1204                         case T38_PEER_REINVITE:
1205                                 state = T38_STATE_NEGOTIATING;
1206                                 break;
1207                         case T38_ENABLED:
1208                                 state = T38_STATE_NEGOTIATED;
1209                                 break;
1210                         case T38_REJECTED:
1211                                 state = T38_STATE_REJECTED;
1212                                 break;
1213                         default:
1214                                 state = T38_STATE_UNKNOWN;
1215                                 break;
1216                         }
1217                 }
1218
1219                 *((enum ast_t38_state *) data) = state;
1220                 res = 0;
1221
1222                 break;
1223         default:
1224                 break;
1225         }
1226
1227         return res;
1228 }
1229
1230 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
1231 {
1232         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1233         char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);
1234
1235         if (!uniqueid) {
1236                 return "";
1237         }
1238
1239         ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);
1240
1241         return uniqueid;
1242 }
1243
1244 struct indicate_data {
1245         struct ast_sip_session *session;
1246         int condition;
1247         int response_code;
1248         void *frame_data;
1249         size_t datalen;
1250 };
1251
1252 static void indicate_data_destroy(void *obj)
1253 {
1254         struct indicate_data *ind_data = obj;
1255
1256         ast_free(ind_data->frame_data);
1257         ao2_ref(ind_data->session, -1);
1258 }
1259
1260 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
1261                 int condition, int response_code, const void *frame_data, size_t datalen)
1262 {
1263         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
1264
1265         if (!ind_data) {
1266                 return NULL;
1267         }
1268
1269         ind_data->frame_data = ast_malloc(datalen);
1270         if (!ind_data->frame_data) {
1271                 ao2_ref(ind_data, -1);
1272                 return NULL;
1273         }
1274
1275         memcpy(ind_data->frame_data, frame_data, datalen);
1276         ind_data->datalen = datalen;
1277         ind_data->condition = condition;
1278         ind_data->response_code = response_code;
1279         ao2_ref(session, +1);
1280         ind_data->session = session;
1281
1282         return ind_data;
1283 }
1284
1285 static int indicate(void *data)
1286 {
1287         pjsip_tx_data *packet = NULL;
1288         struct indicate_data *ind_data = data;
1289         struct ast_sip_session *session = ind_data->session;
1290         int response_code = ind_data->response_code;
1291
1292         if ((session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED) &&
1293                 (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS)) {
1294                 ast_sip_session_send_response(session, packet);
1295         }
1296
1297 #ifdef HAVE_PJSIP_INV_SESSION_REF
1298         pjsip_inv_dec_ref(session->inv_session);
1299 #endif
1300         ao2_ref(ind_data, -1);
1301
1302         return 0;
1303 }
1304
1305 /*! \brief Send SIP INFO with video update request */
1306 static int transmit_info_with_vidupdate(void *data)
1307 {
1308         const char * xml =
1309                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1310                 " <media_control>\r\n"
1311                 "  <vc_primitive>\r\n"
1312                 "   <to_encoder>\r\n"
1313                 "    <picture_fast_update/>\r\n"
1314                 "   </to_encoder>\r\n"
1315                 "  </vc_primitive>\r\n"
1316                 " </media_control>\r\n";
1317
1318         const struct ast_sip_body body = {
1319                 .type = "application",
1320                 .subtype = "media_control+xml",
1321                 .body_text = xml
1322         };
1323
1324         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1325         struct pjsip_tx_data *tdata;
1326
1327         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1328                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1329                         session->inv_session->cause,
1330                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1331                 goto failure;
1332         }
1333
1334         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1335                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1336                 goto failure;
1337         }
1338         if (ast_sip_add_body(tdata, &body)) {
1339                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1340                 goto failure;
1341         }
1342         ast_sip_session_send_request(session, tdata);
1343
1344 #ifdef HAVE_PJSIP_INV_SESSION_REF
1345         pjsip_inv_dec_ref(session->inv_session);
1346 #endif
1347
1348         return 0;
1349
1350 failure:
1351 #ifdef HAVE_PJSIP_INV_SESSION_REF
1352         pjsip_inv_dec_ref(session->inv_session);
1353 #endif
1354         return -1;
1355
1356 }
1357
1358 /*!
1359  * \internal
1360  * \brief TRUE if a COLP update can be sent to the peer.
1361  * \since 13.3.0
1362  *
1363  * \param session The session to see if the COLP update is allowed.
1364  *
1365  * \retval 0 Update is not allowed.
1366  * \retval 1 Update is allowed.
1367  */
1368 static int is_colp_update_allowed(struct ast_sip_session *session)
1369 {
1370         struct ast_party_id connected_id;
1371         int update_allowed = 0;
1372
1373         if (!session->endpoint->id.send_pai && !session->endpoint->id.send_rpid) {
1374                 return 0;
1375         }
1376
1377         /*
1378          * Check if privacy allows the update.  Check while the channel
1379          * is locked so we can work with the shallow connected_id copy.
1380          */
1381         ast_channel_lock(session->channel);
1382         connected_id = ast_channel_connected_effective_id(session->channel);
1383         if (connected_id.number.valid
1384                 && (session->endpoint->id.trust_outbound
1385                         || (ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED)) {
1386                 update_allowed = 1;
1387         }
1388         ast_channel_unlock(session->channel);
1389
1390         return update_allowed;
1391 }
1392
1393 /*! \brief Update connected line information */
1394 static int update_connected_line_information(void *data)
1395 {
1396         struct ast_sip_session *session = data;
1397
1398         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1399                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1400                         session->inv_session->cause,
1401                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1402 #ifdef HAVE_PJSIP_INV_SESSION_REF
1403                 pjsip_inv_dec_ref(session->inv_session);
1404 #endif
1405                 ao2_ref(session, -1);
1406                 return -1;
1407         }
1408
1409         if (ast_channel_state(session->channel) == AST_STATE_UP
1410                 || session->inv_session->role == PJSIP_ROLE_UAC) {
1411                 if (is_colp_update_allowed(session)) {
1412                         enum ast_sip_session_refresh_method method;
1413                         int generate_new_sdp;
1414
1415                         method = session->endpoint->id.refresh_method;
1416                         if (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE) {
1417                                 method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1418                         }
1419
1420                         /* Only the INVITE method actually needs SDP, UPDATE can do without */
1421                         generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
1422
1423                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
1424                 }
1425         } else if (session->endpoint->id.rpid_immediate
1426                 && session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
1427                 && is_colp_update_allowed(session)) {
1428                 int response_code = 0;
1429
1430                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1431                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1432                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1433                         response_code = 183;
1434                 }
1435
1436                 if (response_code) {
1437                         struct pjsip_tx_data *packet = NULL;
1438
1439                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1440                                 ast_sip_session_send_response(session, packet);
1441                         }
1442                 }
1443         }
1444
1445 #ifdef HAVE_PJSIP_INV_SESSION_REF
1446         pjsip_inv_dec_ref(session->inv_session);
1447 #endif
1448
1449         ao2_ref(session, -1);
1450         return 0;
1451 }
1452
1453 /*! \brief Callback which changes the value of locally held on the media stream */
1454 static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
1455 {
1456         if (session_media) {
1457                 session_media->locally_held = held;
1458         }
1459 }
1460
1461 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
1462 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
1463 {
1464         AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
1465         ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
1466         ao2_ref(session, -1);
1467
1468         return 0;
1469 }
1470
1471 /*! \brief Update local hold state to be held */
1472 static int remote_send_hold(void *data)
1473 {
1474         return remote_send_hold_refresh(data, 1);
1475 }
1476
1477 /*! \brief Update local hold state to be unheld */
1478 static int remote_send_unhold(void *data)
1479 {
1480         return remote_send_hold_refresh(data, 0);
1481 }
1482
1483 struct topology_change_refresh_data {
1484         struct ast_sip_session *session;
1485         struct ast_sip_session_media_state *media_state;
1486 };
1487
1488 static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
1489 {
1490         ao2_cleanup(refresh_data->session);
1491
1492         ast_sip_session_media_state_free(refresh_data->media_state);
1493         ast_free(refresh_data);
1494 }
1495
1496 static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
1497         struct ast_sip_session *session, const struct ast_stream_topology *topology)
1498 {
1499         struct topology_change_refresh_data *refresh_data;
1500
1501         refresh_data = ast_calloc(1, sizeof(*refresh_data));
1502         if (!refresh_data) {
1503                 return NULL;
1504         }
1505
1506         refresh_data->session = ao2_bump(session);
1507         refresh_data->media_state = ast_sip_session_media_state_alloc();
1508         if (!refresh_data->media_state) {
1509                 topology_change_refresh_data_free(refresh_data);
1510                 return NULL;
1511         }
1512         refresh_data->media_state->topology = ast_stream_topology_clone(topology);
1513         if (!refresh_data->media_state->topology) {
1514                 topology_change_refresh_data_free(refresh_data);
1515                 return NULL;
1516         }
1517
1518         return refresh_data;
1519 }
1520
1521 static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
1522 {
1523         if (PJSIP_IS_STATUS_IN_CLASS(rdata->msg_info.msg->line.status.code, 200)) {
1524                 /* The topology was changed to something new so give notice to what requested
1525                  * it so it queries the channel and updates accordingly.
1526                  */
1527                 if (session->channel) {
1528                         ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
1529                 }
1530         } else if (300 <= rdata->msg_info.msg->line.status.code) {
1531                 /* The topology change failed, so drop the current pending media state */
1532                 ast_sip_session_media_state_reset(session->pending_media_state);
1533         }
1534
1535         return 0;
1536 }
1537
1538 static int send_topology_change_refresh(void *data)
1539 {
1540         struct topology_change_refresh_data *refresh_data = data;
1541         int ret;
1542
1543         ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
1544                 AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
1545         refresh_data->media_state = NULL;
1546         topology_change_refresh_data_free(refresh_data);
1547
1548         return ret;
1549 }
1550
1551 static int handle_topology_request_change(struct ast_sip_session *session,
1552         const struct ast_stream_topology *proposed)
1553 {
1554         struct topology_change_refresh_data *refresh_data;
1555         int res;
1556
1557         refresh_data = topology_change_refresh_data_alloc(session, proposed);
1558         if (!refresh_data) {
1559                 return -1;
1560         }
1561
1562         res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
1563         if (res) {
1564                 topology_change_refresh_data_free(refresh_data);
1565         }
1566         return res;
1567 }
1568
1569 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1570 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1571 {
1572         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1573         struct ast_sip_session_media *media;
1574         int response_code = 0;
1575         int res = 0;
1576         char *device_buf;
1577         size_t device_buf_size;
1578         int i;
1579         const struct ast_stream_topology *topology;
1580
1581         switch (condition) {
1582         case AST_CONTROL_RINGING:
1583                 if (ast_channel_state(ast) == AST_STATE_RING) {
1584                         if (channel->session->endpoint->inband_progress) {
1585                                 response_code = 183;
1586                                 res = -1;
1587                         } else {
1588                                 response_code = 180;
1589                         }
1590                 } else {
1591                         res = -1;
1592                 }
1593                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1594                 break;
1595         case AST_CONTROL_BUSY:
1596                 if (ast_channel_state(ast) != AST_STATE_UP) {
1597                         response_code = 486;
1598                 } else {
1599                         res = -1;
1600                 }
1601                 break;
1602         case AST_CONTROL_CONGESTION:
1603                 if (ast_channel_state(ast) != AST_STATE_UP) {
1604                         response_code = 503;
1605                 } else {
1606                         res = -1;
1607                 }
1608                 break;
1609         case AST_CONTROL_INCOMPLETE:
1610                 if (ast_channel_state(ast) != AST_STATE_UP) {
1611                         response_code = 484;
1612                 } else {
1613                         res = -1;
1614                 }
1615                 break;
1616         case AST_CONTROL_PROCEEDING:
1617                 if (ast_channel_state(ast) != AST_STATE_UP) {
1618                         response_code = 100;
1619                 } else {
1620                         res = -1;
1621                 }
1622                 break;
1623         case AST_CONTROL_PROGRESS:
1624                 if (ast_channel_state(ast) != AST_STATE_UP) {
1625                         response_code = 183;
1626                 } else {
1627                         res = -1;
1628                 }
1629                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1630                 break;
1631         case AST_CONTROL_VIDUPDATE:
1632                 for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
1633                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
1634                         if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
1635                                 continue;
1636                         }
1637                         if (media->rtp) {
1638                                 /* FIXME: Only use this for VP8. Additional work would have to be done to
1639                                  * fully support other video codecs */
1640
1641                                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL ||
1642                                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp9) != AST_FORMAT_CMP_NOT_EQUAL ||
1643                                         (channel->session->endpoint->media.webrtc &&
1644                                          ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h264) != AST_FORMAT_CMP_NOT_EQUAL)) {
1645                                         /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1646                                          * RTP engine would provide a way to externally write/schedule RTCP
1647                                          * packets */
1648                                         struct ast_frame fr;
1649                                         fr.frametype = AST_FRAME_CONTROL;
1650                                         fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1651                                         res = ast_rtp_instance_write(media->rtp, &fr);
1652                                 } else {
1653                                         ao2_ref(channel->session, +1);
1654 #ifdef HAVE_PJSIP_INV_SESSION_REF
1655                                         if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1656                                                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1657                                                 ao2_cleanup(channel->session);
1658                                         } else {
1659 #endif
1660                                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1661                                                         ao2_cleanup(channel->session);
1662                                                 }
1663 #ifdef HAVE_PJSIP_INV_SESSION_REF
1664                                         }
1665 #endif
1666                                 }
1667                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1668                         } else {
1669                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1670                                 res = -1;
1671                         }
1672                 }
1673                 /* XXX If there were no video streams, then this should set
1674                  * res to -1
1675                  */
1676                 break;
1677         case AST_CONTROL_CONNECTED_LINE:
1678                 ao2_ref(channel->session, +1);
1679 #ifdef HAVE_PJSIP_INV_SESSION_REF
1680                 if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1681                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1682                         ao2_cleanup(channel->session);
1683                         return -1;
1684                 }
1685 #endif
1686                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1687 #ifdef HAVE_PJSIP_INV_SESSION_REF
1688                         pjsip_inv_dec_ref(channel->session->inv_session);
1689 #endif
1690                         ao2_cleanup(channel->session);
1691                 }
1692                 break;
1693         case AST_CONTROL_UPDATE_RTP_PEER:
1694                 break;
1695         case AST_CONTROL_PVT_CAUSE_CODE:
1696                 res = -1;
1697                 break;
1698         case AST_CONTROL_MASQUERADE_NOTIFY:
1699                 ast_assert(datalen == sizeof(int));
1700                 if (*(int *) data) {
1701                         /*
1702                          * Masquerade is beginning:
1703                          * Wait for session serializer to get suspended.
1704                          */
1705                         ast_channel_unlock(ast);
1706                         ast_sip_session_suspend(channel->session);
1707                         ast_channel_lock(ast);
1708                 } else {
1709                         /*
1710                          * Masquerade is complete:
1711                          * Unsuspend the session serializer.
1712                          */
1713                         ast_sip_session_unsuspend(channel->session);
1714                 }
1715                 break;
1716         case AST_CONTROL_HOLD:
1717                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1718                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1719                 device_buf = alloca(device_buf_size);
1720                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1721                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1722                 if (!channel->session->endpoint->moh_passthrough) {
1723                         ast_moh_start(ast, data, NULL);
1724                 } else {
1725                         if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
1726                                 ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
1727                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1728                                 ao2_ref(channel->session, -1);
1729                         }
1730                 }
1731                 break;
1732         case AST_CONTROL_UNHOLD:
1733                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1734                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1735                 device_buf = alloca(device_buf_size);
1736                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1737                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1738                 if (!channel->session->endpoint->moh_passthrough) {
1739                         ast_moh_stop(ast);
1740                 } else {
1741                         if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
1742                                 ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
1743                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1744                                 ao2_ref(channel->session, -1);
1745                         }
1746                 }
1747                 break;
1748         case AST_CONTROL_SRCUPDATE:
1749                 break;
1750         case AST_CONTROL_SRCCHANGE:
1751                 break;
1752         case AST_CONTROL_REDIRECTING:
1753                 if (ast_channel_state(ast) != AST_STATE_UP) {
1754                         response_code = 181;
1755                 } else {
1756                         res = -1;
1757                 }
1758                 break;
1759         case AST_CONTROL_T38_PARAMETERS:
1760                 res = 0;
1761
1762                 if (channel->session->t38state == T38_PEER_REINVITE) {
1763                         const struct ast_control_t38_parameters *parameters = data;
1764
1765                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1766                                 res = AST_T38_REQUEST_PARMS;
1767                         }
1768                 }
1769
1770                 break;
1771         case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1772                 topology = data;
1773                 res = handle_topology_request_change(channel->session, topology);
1774                 break;
1775         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
1776                 break;
1777         case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
1778                 break;
1779         case -1:
1780                 res = -1;
1781                 break;
1782         default:
1783                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1784                 res = -1;
1785                 break;
1786         }
1787
1788         if (response_code) {
1789                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1790
1791                 if (!ind_data) {
1792                         return -1;
1793                 }
1794 #ifdef HAVE_PJSIP_INV_SESSION_REF
1795                 if (pjsip_inv_add_ref(ind_data->session->inv_session) != PJ_SUCCESS) {
1796                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1797                         ao2_cleanup(ind_data);
1798                         return -1;
1799                 }
1800 #endif
1801                 if (ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1802                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1803                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1804 #ifdef HAVE_PJSIP_INV_SESSION_REF
1805                         pjsip_inv_dec_ref(ind_data->session->inv_session);
1806 #endif
1807                         ao2_cleanup(ind_data);
1808                         res = -1;
1809                 }
1810         }
1811
1812         return res;
1813 }
1814
1815 struct transfer_data {
1816         struct ast_sip_session *session;
1817         char *target;
1818 };
1819
1820 static void transfer_data_destroy(void *obj)
1821 {
1822         struct transfer_data *trnf_data = obj;
1823
1824         ast_free(trnf_data->target);
1825         ao2_cleanup(trnf_data->session);
1826 }
1827
1828 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1829 {
1830         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1831
1832         if (!trnf_data) {
1833                 return NULL;
1834         }
1835
1836         if (!(trnf_data->target = ast_strdup(target))) {
1837                 ao2_ref(trnf_data, -1);
1838                 return NULL;
1839         }
1840
1841         ao2_ref(session, +1);
1842         trnf_data->session = session;
1843
1844         return trnf_data;
1845 }
1846
1847 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1848 {
1849         pjsip_tx_data *packet;
1850         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1851         pjsip_contact_hdr *contact;
1852         pj_str_t tmp;
1853
1854         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS
1855                 || !packet) {
1856                 ast_log(LOG_WARNING, "Failed to redirect PJSIP session for channel %s\n",
1857                         ast_channel_name(session->channel));
1858                 message = AST_TRANSFER_FAILED;
1859                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1860
1861                 return;
1862         }
1863
1864         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1865                 contact = pjsip_contact_hdr_create(packet->pool);
1866         }
1867
1868         pj_strdup2_with_null(packet->pool, &tmp, target);
1869         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1870                 ast_log(LOG_WARNING, "Failed to parse destination URI '%s' for channel %s\n",
1871                         target, ast_channel_name(session->channel));
1872                 message = AST_TRANSFER_FAILED;
1873                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1874                 pjsip_tx_data_dec_ref(packet);
1875
1876                 return;
1877         }
1878         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1879
1880         ast_sip_session_send_response(session, packet);
1881         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1882 }
1883
1884 static void transfer_refer(struct ast_sip_session *session, const char *target)
1885 {
1886         pjsip_evsub *sub;
1887         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1888         pj_str_t tmp;
1889         pjsip_tx_data *packet;
1890         const char *ref_by_val;
1891         char local_info[pj_strlen(&session->inv_session->dlg->local.info_str) + 1];
1892
1893         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1894                 message = AST_TRANSFER_FAILED;
1895                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1896
1897                 return;
1898         }
1899
1900         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1901                 message = AST_TRANSFER_FAILED;
1902                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1903                 pjsip_evsub_terminate(sub, PJ_FALSE);
1904
1905                 return;
1906         }
1907
1908         ref_by_val = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
1909         if (!ast_strlen_zero(ref_by_val)) {
1910                 ast_sip_add_header(packet, "Referred-By", ref_by_val);
1911         } else {
1912                 ast_copy_pj_str(local_info, &session->inv_session->dlg->local.info_str, sizeof(local_info));
1913                 ast_sip_add_header(packet, "Referred-By", local_info);
1914         }
1915
1916         pjsip_xfer_send_request(sub, packet);
1917         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1918 }
1919
1920 static int transfer(void *data)
1921 {
1922         struct transfer_data *trnf_data = data;
1923         struct ast_sip_endpoint *endpoint = NULL;
1924         struct ast_sip_contact *contact = NULL;
1925         const char *target = trnf_data->target;
1926
1927         if (trnf_data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1928                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1929                         trnf_data->session->inv_session->cause,
1930                         pjsip_get_status_text(trnf_data->session->inv_session->cause)->ptr);
1931         } else {
1932                 /* See if we have an endpoint; if so, use its contact */
1933                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", target);
1934                 if (endpoint) {
1935                         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
1936                         if (contact && !ast_strlen_zero(contact->uri)) {
1937                                 target = contact->uri;
1938                         }
1939                 }
1940
1941                 if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1942                         transfer_redirect(trnf_data->session, target);
1943                 } else {
1944                         transfer_refer(trnf_data->session, target);
1945                 }
1946         }
1947
1948 #ifdef HAVE_PJSIP_INV_SESSION_REF
1949         pjsip_inv_dec_ref(trnf_data->session->inv_session);
1950 #endif
1951
1952         ao2_ref(trnf_data, -1);
1953         ao2_cleanup(endpoint);
1954         ao2_cleanup(contact);
1955         return 0;
1956 }
1957
1958 /*! \brief Function called by core for Asterisk initiated transfer */
1959 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1960 {
1961         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1962         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1963
1964         if (!trnf_data) {
1965                 return -1;
1966         }
1967
1968 #ifdef HAVE_PJSIP_INV_SESSION_REF
1969         if (pjsip_inv_add_ref(trnf_data->session->inv_session) != PJ_SUCCESS) {
1970                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1971                 ao2_cleanup(trnf_data);
1972                 return -1;
1973         }
1974 #endif
1975
1976         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1977                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1978 #ifdef HAVE_PJSIP_INV_SESSION_REF
1979                 pjsip_inv_dec_ref(trnf_data->session->inv_session);
1980 #endif
1981                 ao2_cleanup(trnf_data);
1982                 return -1;
1983         }
1984
1985         return 0;
1986 }
1987
1988 /*! \brief Function called by core to start a DTMF digit */
1989 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1990 {
1991         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1992         struct ast_sip_session_media *media;
1993         int res = 0;
1994
1995         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
1996
1997         switch (channel->session->dtmf) {
1998         case AST_SIP_DTMF_RFC_4733:
1999                 if (!media || !media->rtp) {
2000                         return -1;
2001                 }
2002
2003                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2004                 break;
2005         case AST_SIP_DTMF_AUTO:
2006                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
2007                         return -1;
2008                 }
2009
2010                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2011                 break;
2012         case AST_SIP_DTMF_AUTO_INFO:
2013                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_NONE)) {
2014                         return -1;
2015                 }
2016                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2017                 break;
2018         case AST_SIP_DTMF_NONE:
2019                 break;
2020         case AST_SIP_DTMF_INBAND:
2021                 res = -1;
2022                 break;
2023         default:
2024                 break;
2025         }
2026
2027         return res;
2028 }
2029
2030 struct info_dtmf_data {
2031         struct ast_sip_session *session;
2032         char digit;
2033         unsigned int duration;
2034 };
2035
2036 static void info_dtmf_data_destroy(void *obj)
2037 {
2038         struct info_dtmf_data *dtmf_data = obj;
2039         ao2_ref(dtmf_data->session, -1);
2040 }
2041
2042 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
2043 {
2044         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
2045         if (!dtmf_data) {
2046                 return NULL;
2047         }
2048         ao2_ref(session, +1);
2049         dtmf_data->session = session;
2050         dtmf_data->digit = digit;
2051         dtmf_data->duration = duration;
2052         return dtmf_data;
2053 }
2054
2055 static int transmit_info_dtmf(void *data)
2056 {
2057         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
2058
2059         struct ast_sip_session *session = dtmf_data->session;
2060         struct pjsip_tx_data *tdata;
2061
2062         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
2063
2064         struct ast_sip_body body = {
2065                 .type = "application",
2066                 .subtype = "dtmf-relay",
2067         };
2068
2069         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2070                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2071                         session->inv_session->cause,
2072                         pjsip_get_status_text(session->inv_session->cause)->ptr);
2073                 goto failure;
2074         }
2075
2076         if (!(body_text = ast_str_create(32))) {
2077                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
2078                 goto failure;
2079         }
2080         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
2081
2082         body.body_text = ast_str_buffer(body_text);
2083
2084         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
2085                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
2086                 goto failure;
2087         }
2088         if (ast_sip_add_body(tdata, &body)) {
2089                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
2090                 pjsip_tx_data_dec_ref(tdata);
2091                 goto failure;
2092         }
2093         ast_sip_session_send_request(session, tdata);
2094
2095 #ifdef HAVE_PJSIP_INV_SESSION_REF
2096         pjsip_inv_dec_ref(session->inv_session);
2097 #endif
2098
2099         return 0;
2100
2101 failure:
2102 #ifdef HAVE_PJSIP_INV_SESSION_REF
2103         pjsip_inv_dec_ref(session->inv_session);
2104 #endif
2105         return -1;
2106
2107 }
2108
2109 /*! \brief Function called by core to stop a DTMF digit */
2110 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2111 {
2112         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2113         struct ast_sip_session_media *media;
2114         int res = 0;
2115
2116         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
2117
2118         switch (channel->session->dtmf) {
2119         case AST_SIP_DTMF_AUTO_INFO:
2120         {
2121                 if (!media || !media->rtp) {
2122                         return -1;
2123                 }
2124                 if (ast_rtp_instance_dtmf_mode_get(media->rtp) != AST_RTP_DTMF_MODE_NONE) {
2125                         ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 negotiated so using it.\n", ast_channel_name(ast));
2126                         ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2127                         break;
2128                 }
2129                 /* If RFC_4733 was not negotiated, fail through to the DTMF_INFO processing */
2130                 ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 NOT negotiated using INFO instead.\n", ast_channel_name(ast));
2131         }
2132
2133         case AST_SIP_DTMF_INFO:
2134         {
2135                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
2136
2137                 if (!dtmf_data) {
2138                         return -1;
2139                 }
2140
2141 #ifdef HAVE_PJSIP_INV_SESSION_REF
2142                 if (pjsip_inv_add_ref(dtmf_data->session->inv_session) != PJ_SUCCESS) {
2143                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2144                         ao2_cleanup(dtmf_data);
2145                         return -1;
2146                 }
2147 #endif
2148
2149                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
2150                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
2151 #ifdef HAVE_PJSIP_INV_SESSION_REF
2152                         pjsip_inv_dec_ref(dtmf_data->session->inv_session);
2153 #endif
2154                         ao2_cleanup(dtmf_data);
2155                         return -1;
2156                 }
2157                 break;
2158         }
2159         case AST_SIP_DTMF_RFC_4733:
2160                 if (!media || !media->rtp) {
2161                         return -1;
2162                 }
2163
2164                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2165                 break;
2166         case AST_SIP_DTMF_AUTO:
2167                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
2168                          return -1;
2169                 }
2170
2171                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2172                 break;
2173
2174
2175         case AST_SIP_DTMF_NONE:
2176                 break;
2177         case AST_SIP_DTMF_INBAND:
2178                 res = -1;
2179                 break;
2180         }
2181
2182         return res;
2183 }
2184
2185 static void update_initial_connected_line(struct ast_sip_session *session)
2186 {
2187         struct ast_party_connected_line connected;
2188
2189         /*
2190          * Use the channel CALLERID() as the initial connected line data.
2191          * The core or a predial handler may have supplied missing values
2192          * from the session->endpoint->id.self about who we are calling.
2193          */
2194         ast_channel_lock(session->channel);
2195         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
2196         ast_channel_unlock(session->channel);
2197
2198         /* Supply initial connected line information if available. */
2199         if (!session->id.number.valid && !session->id.name.valid) {
2200                 return;
2201         }
2202
2203         ast_party_connected_line_init(&connected);
2204         connected.id = session->id;
2205         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2206
2207         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
2208 }
2209
2210 static int call(void *data)
2211 {
2212         struct ast_sip_channel_pvt *channel = data;
2213         struct ast_sip_session *session = channel->session;
2214         pjsip_tx_data *tdata;
2215
2216         int res = ast_sip_session_create_invite(session, &tdata);
2217
2218         if (res) {
2219                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2220                 ast_queue_hangup(session->channel);
2221         } else {
2222                 set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
2223                 update_initial_connected_line(session);
2224                 ast_sip_session_send_request(session, tdata);
2225         }
2226         ao2_ref(channel, -1);
2227         return res;
2228 }
2229
2230 /*! \brief Function called by core to actually start calling a remote party */
2231 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
2232 {
2233         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2234
2235         ao2_ref(channel, +1);
2236         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
2237                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
2238                 ao2_cleanup(channel);
2239                 return -1;
2240         }
2241
2242         return 0;
2243 }
2244
2245 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
2246 static int hangup_cause2sip(int cause)
2247 {
2248         switch (cause) {
2249         case AST_CAUSE_UNALLOCATED:             /* 1 */
2250         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2251         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2252                 return 404;
2253         case AST_CAUSE_CONGESTION:              /* 34 */
2254         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2255                 return 503;
2256         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2257                 return 408;
2258         case AST_CAUSE_NO_ANSWER:               /* 19 */
2259         case AST_CAUSE_UNREGISTERED:        /* 20 */
2260                 return 480;
2261         case AST_CAUSE_CALL_REJECTED:           /* 21 */
2262                 return 403;
2263         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2264                 return 410;
2265         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2266                 return 480;
2267         case AST_CAUSE_INVALID_NUMBER_FORMAT:
2268                 return 484;
2269         case AST_CAUSE_USER_BUSY:
2270                 return 486;
2271         case AST_CAUSE_FAILURE:
2272                 return 500;
2273         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2274                 return 501;
2275         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2276                 return 503;
2277         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2278                 return 502;
2279         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2280                 return 488;
2281         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
2282                 return 500;
2283         case AST_CAUSE_NOTDEFINED:
2284         default:
2285                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
2286                 return 0;
2287         }
2288
2289         /* Never reached */
2290         return 0;
2291 }
2292
2293 struct hangup_data {
2294         int cause;
2295         struct ast_channel *chan;
2296 };
2297
2298 static void hangup_data_destroy(void *obj)
2299 {
2300         struct hangup_data *h_data = obj;
2301
2302         h_data->chan = ast_channel_unref(h_data->chan);
2303 }
2304
2305 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
2306 {
2307         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
2308
2309         if (!h_data) {
2310                 return NULL;
2311         }
2312
2313         h_data->cause = cause;
2314         h_data->chan = ast_channel_ref(chan);
2315
2316         return h_data;
2317 }
2318
2319 /*! \brief Clear a channel from a session along with its PVT */
2320 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
2321 {
2322         session->channel = NULL;
2323         set_channel_on_rtp_instance(session, "");
2324         ast_channel_tech_pvt_set(ast, NULL);
2325 }
2326
2327 static int hangup(void *data)
2328 {
2329         struct hangup_data *h_data = data;
2330         struct ast_channel *ast = h_data->chan;
2331         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2332         struct ast_sip_session *session = channel->session;
2333         int cause = h_data->cause;
2334
2335         /*
2336          * It's possible that session_terminate might cause the session to be destroyed
2337          * immediately so we need to keep a reference to it so we can NULL session->channel
2338          * afterwards.
2339          */
2340         ast_sip_session_terminate(ao2_bump(session), cause);
2341         clear_session_and_channel(session, ast);
2342         ao2_cleanup(session);
2343         ao2_cleanup(channel);
2344         ao2_cleanup(h_data);
2345         return 0;
2346 }
2347
2348 /*! \brief Function called by core to hang up a PJSIP session */
2349 static int chan_pjsip_hangup(struct ast_channel *ast)
2350 {
2351         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2352         int cause;
2353         struct hangup_data *h_data;
2354
2355         if (!channel || !channel->session) {
2356                 return -1;
2357         }
2358
2359         cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
2360         h_data = hangup_data_alloc(cause, ast);
2361
2362         if (!h_data) {
2363                 goto failure;
2364         }
2365
2366         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
2367                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
2368                 goto failure;
2369         }
2370
2371         return 0;
2372
2373 failure:
2374         /* Go ahead and do our cleanup of the session and channel even if we're not going
2375          * to be able to send our SIP request/response
2376          */
2377         clear_session_and_channel(channel->session, ast);
2378         ao2_cleanup(channel);
2379         ao2_cleanup(h_data);
2380
2381         return -1;
2382 }
2383
2384 struct request_data {
2385         struct ast_sip_session *session;
2386         struct ast_stream_topology *topology;
2387         const char *dest;
2388         int cause;
2389 };
2390
2391 static int request(void *obj)
2392 {
2393         struct request_data *req_data = obj;
2394         struct ast_sip_session *session = NULL;
2395         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
2396         struct ast_sip_endpoint *endpoint;
2397
2398         AST_DECLARE_APP_ARGS(args,
2399                 AST_APP_ARG(endpoint);
2400                 AST_APP_ARG(aor);
2401         );
2402
2403         if (ast_strlen_zero(tmp)) {
2404                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
2405                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2406                 return -1;
2407         }
2408
2409         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
2410
2411         if (ast_sip_get_disable_multi_domain()) {
2412                 /* If a request user has been specified extract it from the endpoint name portion */
2413                 if ((endpoint_name = strchr(args.endpoint, '@'))) {
2414                         request_user = args.endpoint;
2415                         *endpoint_name++ = '\0';
2416                 } else {
2417                         endpoint_name = args.endpoint;
2418                 }
2419
2420                 if (ast_strlen_zero(endpoint_name)) {
2421                         if (request_user) {
2422                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2423                                         request_user);
2424                         } else {
2425                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2426                         }
2427                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2428                         return -1;
2429                 }
2430                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2431                         endpoint_name);
2432                 if (!endpoint) {
2433                         ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2434                         req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2435                         return -1;
2436                 }
2437         } else {
2438                 /* First try to find an exact endpoint match, for single (user) or multi-domain (user@domain) */
2439                 endpoint_name = args.endpoint;
2440                 if (ast_strlen_zero(endpoint_name)) {
2441                         ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2442                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2443                         return -1;
2444                 }
2445                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2446                         endpoint_name);
2447                 if (!endpoint) {
2448                         /* It seems it's not a multi-domain endpoint or single endpoint exact match,
2449                          * it's possible that it's a SIP trunk with a specified user (user@trunkname),
2450                          * so extract the user before @ sign.
2451                          */
2452                         endpoint_name = strchr(args.endpoint, '@');
2453                         if (!endpoint_name) {
2454                                 /*
2455                                  * Couldn't find an '@' so it had to be an endpoint
2456                                  * name that doesn't exist.
2457                                  */
2458                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n",
2459                                         args.endpoint);
2460                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2461                                 return -1;
2462                         }
2463                         request_user = args.endpoint;
2464                         *endpoint_name++ = '\0';
2465
2466                         if (ast_strlen_zero(endpoint_name)) {
2467                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2468                                         request_user);
2469                                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2470                                 return -1;
2471                         }
2472
2473                         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2474                                 endpoint_name);
2475                         if (!endpoint) {
2476                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2477                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2478                                 return -1;
2479                         }
2480                 }
2481         }
2482
2483         session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user,
2484                 req_data->topology);
2485         ao2_ref(endpoint, -1);
2486         if (!session) {
2487                 ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
2488                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2489                 return -1;
2490         }
2491
2492         req_data->session = session;
2493
2494         return 0;
2495 }
2496
2497 /*! \brief Function called by core to create a new outgoing PJSIP session */
2498 static struct ast_channel *chan_pjsip_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
2499 {
2500         struct request_data req_data;
2501         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2502
2503         req_data.topology = topology;
2504         req_data.dest = data;
2505         /* Default failure value in case ast_sip_push_task_synchronous() itself fails. */
2506         req_data.cause = AST_CAUSE_FAILURE;
2507
2508         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
2509                 *cause = req_data.cause;
2510                 return NULL;
2511         }
2512
2513         session = req_data.session;
2514
2515         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
2516                 /* Session needs to be terminated prematurely */
2517                 return NULL;
2518         }
2519
2520         return session->channel;
2521 }
2522
2523 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)
2524 {
2525         struct ast_stream_topology *topology;
2526         struct ast_channel *chan;
2527
2528         topology = ast_stream_topology_create_from_format_cap(cap);
2529         if (!topology) {
2530                 return NULL;
2531         }
2532
2533         chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
2534
2535         ast_stream_topology_free(topology);
2536
2537         return chan;
2538 }
2539
2540 struct sendtext_data {
2541         struct ast_sip_session *session;
2542         char text[0];
2543 };
2544
2545 static void sendtext_data_destroy(void *obj)
2546 {
2547         struct sendtext_data *data = obj;
2548         ao2_ref(data->session, -1);
2549 }
2550
2551 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
2552 {
2553         int size = strlen(text) + 1;
2554         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
2555
2556         if (!data) {
2557                 return NULL;
2558         }
2559
2560         data->session = session;
2561         ao2_ref(data->session, +1);
2562         ast_copy_string(data->text, text, size);
2563         return data;
2564 }
2565
2566 static int sendtext(void *obj)
2567 {
2568         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
2569         pjsip_tx_data *tdata;
2570
2571         const struct ast_sip_body body = {
2572                 .type = "text",
2573                 .subtype = "plain",
2574                 .body_text = data->text
2575         };
2576
2577         if (data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2578                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2579                         data->session->inv_session->cause,
2580                         pjsip_get_status_text(data->session->inv_session->cause)->ptr);
2581         } else {
2582                 ast_debug(3, "Sending in dialog SIP message\n");
2583
2584                 ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
2585                 ast_sip_add_body(tdata, &body);
2586                 ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
2587         }
2588
2589 #ifdef HAVE_PJSIP_INV_SESSION_REF
2590         pjsip_inv_dec_ref(data->session->inv_session);
2591 #endif
2592
2593         return 0;
2594 }
2595
2596 /*! \brief Function called by core to send text on PJSIP session */
2597 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
2598 {
2599         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2600         struct sendtext_data *data = sendtext_data_create(channel->session, text);
2601
2602         if (!data) {
2603                 return -1;
2604         }
2605
2606 #ifdef HAVE_PJSIP_INV_SESSION_REF
2607         if (pjsip_inv_add_ref(data->session->inv_session) != PJ_SUCCESS) {
2608                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2609                 ao2_ref(data, -1);
2610                 return -1;
2611         }
2612 #endif
2613
2614         if (ast_sip_push_task(channel->session->serializer, sendtext, data)) {
2615 #ifdef HAVE_PJSIP_INV_SESSION_REF
2616                 pjsip_inv_dec_ref(data->session->inv_session);
2617 #endif
2618                 ao2_ref(data, -1);
2619                 return -1;
2620         }
2621         return 0;
2622 }
2623
2624 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2625 static int hangup_sip2cause(int cause)
2626 {
2627         /* Possible values taken from causes.h */
2628
2629         switch(cause) {
2630         case 401:       /* Unauthorized */
2631                 return AST_CAUSE_CALL_REJECTED;
2632         case 403:       /* Not found */
2633                 return AST_CAUSE_CALL_REJECTED;
2634         case 404:       /* Not found */
2635                 return AST_CAUSE_UNALLOCATED;
2636         case 405:       /* Method not allowed */
2637                 return AST_CAUSE_INTERWORKING;
2638         case 407:       /* Proxy authentication required */
2639                 return AST_CAUSE_CALL_REJECTED;
2640         case 408:       /* No reaction */
2641                 return AST_CAUSE_NO_USER_RESPONSE;
2642         case 409:       /* Conflict */
2643                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2644         case 410:       /* Gone */
2645                 return AST_CAUSE_NUMBER_CHANGED;
2646         case 411:       /* Length required */
2647                 return AST_CAUSE_INTERWORKING;
2648         case 413:       /* Request entity too large */
2649                 return AST_CAUSE_INTERWORKING;
2650         case 414:       /* Request URI too large */
2651                 return AST_CAUSE_INTERWORKING;
2652         case 415:       /* Unsupported media type */
2653                 return AST_CAUSE_INTERWORKING;
2654         case 420:       /* Bad extension */
2655                 return AST_CAUSE_NO_ROUTE_DESTINATION;
2656         case 480:       /* No answer */
2657                 return AST_CAUSE_NO_ANSWER;
2658         case 481:       /* No answer */
2659                 return AST_CAUSE_INTERWORKING;
2660         case 482:       /* Loop detected */
2661                 return AST_CAUSE_INTERWORKING;
2662         case 483:       /* Too many hops */
2663                 return AST_CAUSE_NO_ANSWER;
2664         case 484:       /* Address incomplete */
2665                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2666         case 485:       /* Ambiguous */
2667                 return AST_CAUSE_UNALLOCATED;
2668         case 486:       /* Busy everywhere */
2669                 return AST_CAUSE_BUSY;
2670         case 487:       /* Request terminated */
2671                 return AST_CAUSE_INTERWORKING;
2672         case 488:       /* No codecs approved */
2673                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2674         case 491:       /* Request pending */
2675                 return AST_CAUSE_INTERWORKING;
2676         case 493:       /* Undecipherable */
2677                 return AST_CAUSE_INTERWORKING;
2678         case 500:       /* Server internal failure */
2679                 return AST_CAUSE_FAILURE;
2680         case 501:       /* Call rejected */
2681                 return AST_CAUSE_FACILITY_REJECTED;
2682         case 502:
2683                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2684         case 503:       /* Service unavailable */
2685                 return AST_CAUSE_CONGESTION;
2686         case 504:       /* Gateway timeout */
2687                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2688         case 505:       /* SIP version not supported */
2689                 return AST_CAUSE_INTERWORKING;
2690         case 600:       /* Busy everywhere */
2691                 return AST_CAUSE_USER_BUSY;
2692         case 603:       /* Decline */
2693                 return AST_CAUSE_CALL_REJECTED;
2694         case 604:       /* Does not exist anywhere */
2695                 return AST_CAUSE_UNALLOCATED;
2696         case 606:       /* Not acceptable */
2697                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2698         default:
2699                 if (cause < 500 && cause >= 400) {
2700                         /* 4xx class error that is unknown - someting wrong with our request */
2701                         return AST_CAUSE_INTERWORKING;
2702                 } else if (cause < 600 && cause >= 500) {
2703                         /* 5xx class error - problem in the remote end */
2704                         return AST_CAUSE_CONGESTION;
2705                 } else if (cause < 700 && cause >= 600) {
2706                         /* 6xx - global errors in the 4xx class */
2707                         return AST_CAUSE_INTERWORKING;
2708                 }
2709                 return AST_CAUSE_NORMAL;
2710         }
2711         /* Never reached */
2712         return 0;
2713 }
2714
2715 static void chan_pjsip_session_begin(struct ast_sip_session *session)
2716 {
2717         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2718
2719         if (session->endpoint->media.direct_media.glare_mitigation ==
2720                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
2721                 return;
2722         }
2723
2724         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
2725                         "direct_media_glare_mitigation");
2726
2727         if (!datastore) {
2728                 return;
2729         }
2730
2731         ast_sip_session_add_datastore(session, datastore);
2732 }
2733
2734 /*! \brief Function called when the session ends */
2735 static void chan_pjsip_session_end(struct ast_sip_session *session)
2736 {
2737         if (!session->channel) {
2738                 return;
2739         }
2740
2741         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
2742
2743         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2744         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
2745                 int cause = hangup_sip2cause(session->inv_session->cause);
2746
2747                 ast_queue_hangup_with_cause(session->channel, cause);
2748         } else {
2749                 ast_queue_hangup(session->channel);
2750         }
2751 }
2752
2753 /*! \brief Function called when a request is received on the session */
2754 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2755 {
2756         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2757         struct transport_info_data *transport_data;
2758         pjsip_tx_data *packet = NULL;
2759
2760         if (session->channel) {
2761                 return 0;
2762         }
2763
2764         /* Check for a to-tag to determine if this is a reinvite */
2765         if (rdata->msg_info.to->tag.slen) {
2766                 /* Weird case. We've received a reinvite but we don't have a channel. The most
2767                  * typical case for this happening is that a blind transfer fails, and so the
2768                  * transferer attempts to reinvite himself back into the call. We already got
2769                  * rid of that channel, and the other side of the call is unrecoverable.
2770                  *
2771                  * We treat this as a failure, so our best bet is to just hang this call
2772                  * up and not create a new channel. Clearing defer_terminate here ensures that
2773                  * calling ast_sip_session_terminate() can result in a BYE being sent ASAP.
2774                  */
2775                 session->defer_terminate = 0;
2776                 ast_sip_session_terminate(session, 400);
2777                 return -1;
2778         }
2779
2780         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
2781         if (!datastore) {
2782                 return -1;
2783         }
2784
2785         transport_data = ast_calloc(1, sizeof(*transport_data));
2786         if (!transport_data) {
2787                 return -1;
2788         }
2789         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
2790         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
2791         datastore->data = transport_data;
2792         ast_sip_session_add_datastore(session, datastore);
2793
2794         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2795                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS
2796                         && packet) {
2797                         ast_sip_session_send_response(session, packet);
2798                 }
2799
2800                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2801                 return -1;
2802         }
2803         /* channel gets created on incoming request, but we wait to call start
2804            so other supplements have a chance to run */
2805         return 0;
2806 }
2807
2808 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2809 {
2810         struct ast_features_pickup_config *pickup_cfg;
2811         struct ast_channel *chan;
2812
2813         /* Check for a to-tag to determine if this is a reinvite */
2814         if (rdata->msg_info.to->tag.slen) {
2815                 /* We don't care about reinvites */
2816                 return 0;
2817         }
2818
2819         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2820         if (!pickup_cfg) {
2821                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2822                 return 0;
2823         }
2824
2825         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2826                 ao2_ref(pickup_cfg, -1);
2827                 return 0;
2828         }
2829         ao2_ref(pickup_cfg, -1);
2830
2831         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2832          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2833          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2834          */
2835         chan = ast_channel_ref(session->channel);
2836         if (ast_pickup_call(chan)) {
2837                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2838         } else {
2839                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2840         }
2841         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2842          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2843          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2844          * to anything at all.
2845          */
2846         ast_hangup(chan);
2847         ast_channel_unref(chan);
2848
2849         return 1;
2850 }
2851
2852 static struct ast_sip_session_supplement call_pickup_supplement = {
2853         .method = "INVITE",
2854         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2855         .incoming_request = call_pickup_incoming_request,
2856 };
2857
2858 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2859 {
2860         int res;
2861
2862         /* Check for a to-tag to determine if this is a reinvite */
2863         if (rdata->msg_info.to->tag.slen) {
2864                 /* We don't care about reinvites */
2865                 return 0;
2866         }
2867
2868         res = ast_pbx_start(session->channel);
2869
2870         switch (res) {
2871         case AST_PBX_FAILED:
2872                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2873                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2874                 ast_hangup(session->channel);
2875                 break;
2876         case AST_PBX_CALL_LIMIT:
2877                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2878                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2879                 ast_hangup(session->channel);
2880                 break;
2881         case AST_PBX_SUCCESS:
2882         default:
2883                 break;
2884         }
2885
2886         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2887
2888         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2889 }
2890
2891 static struct ast_sip_session_supplement pbx_start_supplement = {
2892         .method = "INVITE",
2893         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2894         .incoming_request = pbx_start_incoming_request,
2895 };
2896
2897 /*! \brief Function called when a response is received on the session */
2898 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2899 {
2900         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2901         struct ast_control_pvt_cause_code *cause_code;
2902         int data_size = sizeof(*cause_code);
2903
2904         if (!session->channel) {
2905                 return;
2906         }
2907
2908         /* Build and send the tech-specific cause information */
2909         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2910         data_size += 4 + 4 + pj_strlen(&status.reason);
2911         cause_code = ast_alloca(data_size);
2912         memset(cause_code, 0, data_size);
2913
2914         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2915
2916         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2917         (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2918
2919         cause_code->ast_cause = hangup_sip2cause(status.code);
2920         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2921         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2922
2923         switch (status.code) {
2924         case 180:
2925                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2926                 ast_channel_lock(session->channel);
2927                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2928                         ast_setstate(session->channel, AST_STATE_RINGING);
2929                 }
2930                 ast_channel_unlock(session->channel);
2931                 break;
2932         case 183:
2933                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2934                 break;
2935         case 200:
2936                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2937                 break;
2938         default:
2939                 break;
2940         }
2941 }
2942
2943 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2944 {
2945         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2946                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2947                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2948                 }
2949         }
2950         return 0;
2951 }
2952
2953 static int update_devstate(void *obj, void *arg, int flags)
2954 {
2955         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2956                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2957         return 0;
2958 }
2959
2960 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2961         .name = "PJSIP_DIAL_CONTACTS",
2962         .read = pjsip_acf_dial_contacts_read,
2963 };
2964
2965 static struct ast_custom_function media_offer_function = {
2966         .name = "PJSIP_MEDIA_OFFER",
2967         .read = pjsip_acf_media_offer_read,
2968         .write = pjsip_acf_media_offer_write
2969 };
2970
2971 static struct ast_custom_function dtmf_mode_function = {
2972         .name = "PJSIP_DTMF_MODE",
2973         .read = pjsip_acf_dtmf_mode_read,
2974         .write = pjsip_acf_dtmf_mode_write
2975 };
2976
2977 static struct ast_custom_function session_refresh_function = {
2978         .name = "PJSIP_SEND_SESSION_REFRESH",
2979         .write = pjsip_acf_session_refresh_write,
2980 };
2981
2982 /*!
2983  * \brief Load the module
2984  *
2985  * Module loading including tests for configuration or dependencies.
2986  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2987  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2988  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2989  * configuration file or other non-critical problem return
2990  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2991  */
2992 static int load_module(void)
2993 {
2994         struct ao2_container *endpoints;
2995
2996         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2997                 return AST_MODULE_LOAD_DECLINE;
2998         }
2999
3000         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
3001
3002         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
3003
3004         if (ast_channel_register(&chan_pjsip_tech)) {
3005                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
3006                 goto end;
3007         }
3008
3009         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
3010                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
3011                 goto end;
3012         }
3013
3014         if (ast_custom_function_register(&media_offer_function)) {
3015                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
3016                 goto end;
3017         }
3018
3019         if (ast_custom_function_register(&dtmf_mode_function)) {
3020                 ast_log(LOG_WARNING, "Unable to register PJSIP_DTMF_MODE dialplan function\n");
3021                 goto end;
3022         }
3023
3024         if (ast_custom_function_register(&session_refresh_function)) {
3025                 ast_log(LOG_WARNING, "Unable to register PJSIP_SEND_SESSION_REFRESH dialplan function\n");
3026                 goto end;
3027         }
3028
3029         ast_sip_session_register_supplement(&chan_pjsip_supplement);
3030
3031         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
3032                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
3033                         uid_hold_sort_fn, NULL))) {
3034                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
3035                 goto end;
3036         }
3037
3038         ast_sip_session_register_supplement(&call_pickup_supplement);
3039         ast_sip_session_register_supplement(&pbx_start_supplement);
3040         ast_sip_session_register_supplement(&chan_pjsip_ack_supplement);
3041
3042         if (pjsip_channel_cli_register()) {
3043                 ast_log(LOG_ERROR, "Unable to register PJSIP Channel CLI\n");
3044                 ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3045                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
3046                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3047                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
3048                 goto end;
3049         }
3050
3051         /* since endpoints are loaded before the channel driver their device
3052            states get set to 'invalid', so they need to be updated */
3053         if ((endpoints = ast_sip_get_endpoints())) {
3054                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
3055                 ao2_ref(endpoints, -1);
3056         }
3057
3058         return 0;
3059
3060 end:
3061         ao2_cleanup(pjsip_uids_onhold);
3062         pjsip_uids_onhold = NULL;
3063         ast_custom_function_unregister(&dtmf_mode_function);
3064         ast_custom_function_unregister(&media_offer_function);
3065         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3066         ast_custom_function_unregister(&session_refresh_function);
3067         ast_channel_unregister(&chan_pjsip_tech);
3068         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3069
3070         return AST_MODULE_LOAD_DECLINE;
3071 }
3072
3073 /*! \brief Unload the PJSIP channel from Asterisk */
3074 static int unload_module(void)
3075 {
3076         ao2_cleanup(pjsip_uids_onhold);
3077         pjsip_uids_onhold = NULL;
3078
3079         pjsip_channel_cli_unregister();
3080
3081         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3082         ast_sip_session_unregister_supplement(&pbx_start_supplement);
3083         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3084         ast_sip_session_unregister_supplement(&call_pickup_supplement);
3085
3086         ast_custom_function_unregister(&dtmf_mode_function);
3087         ast_custom_function_unregister(&media_offer_function);
3088         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3089         ast_custom_function_unregister(&session_refresh_function);
3090
3091         ast_channel_unregister(&chan_pjsip_tech);
3092         ao2_ref(chan_pjsip_tech.capabilities, -1);
3093         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3094
3095         return 0;
3096 }
3097
3098 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
3099         .support_level = AST_MODULE_SUPPORT_CORE,
3100         .load = load_module,
3101         .unload = unload_module,
3102         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
3103         .requires = "res_pjsip,res_pjsip_session",
3104 );