4c30d335b24df51cbc8d5d369c77ba4cae60461c
[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         default:
969                 ast_log(LOG_WARNING, "Can't send %u type frames with PJSIP\n", frame->frametype);
970                 break;
971         }
972
973         return res;
974 }
975
976 static int chan_pjsip_write(struct ast_channel *ast, struct ast_frame *frame)
977 {
978         return chan_pjsip_write_stream(ast, -1, frame);
979 }
980
981 /*! \brief Function called by core to change the underlying owner channel */
982 static int chan_pjsip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
983 {
984         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(newchan);
985
986         if (channel->session->channel != oldchan) {
987                 return -1;
988         }
989
990         /*
991          * The masquerade has suspended the channel's session
992          * serializer so we can safely change it outside of
993          * the serializer thread.
994          */
995         channel->session->channel = newchan;
996
997         set_channel_on_rtp_instance(channel->session, ast_channel_uniqueid(newchan));
998
999         return 0;
1000 }
1001
1002 /*! AO2 hash function for on hold UIDs */
1003 static int uid_hold_hash_fn(const void *obj, const int flags)
1004 {
1005         const char *key = obj;
1006
1007         switch (flags & OBJ_SEARCH_MASK) {
1008         case OBJ_SEARCH_KEY:
1009                 break;
1010         case OBJ_SEARCH_OBJECT:
1011                 break;
1012         default:
1013                 /* Hash can only work on something with a full key. */
1014                 ast_assert(0);
1015                 return 0;
1016         }
1017         return ast_str_hash(key);
1018 }
1019
1020 /*! AO2 sort function for on hold UIDs */
1021 static int uid_hold_sort_fn(const void *obj_left, const void *obj_right, const int flags)
1022 {
1023         const char *left = obj_left;
1024         const char *right = obj_right;
1025         int cmp;
1026
1027         switch (flags & OBJ_SEARCH_MASK) {
1028         case OBJ_SEARCH_OBJECT:
1029         case OBJ_SEARCH_KEY:
1030                 cmp = strcmp(left, right);
1031                 break;
1032         case OBJ_SEARCH_PARTIAL_KEY:
1033                 cmp = strncmp(left, right, strlen(right));
1034                 break;
1035         default:
1036                 /* Sort can only work on something with a full or partial key. */
1037                 ast_assert(0);
1038                 cmp = 0;
1039                 break;
1040         }
1041         return cmp;
1042 }
1043
1044 static struct ao2_container *pjsip_uids_onhold;
1045
1046 /*!
1047  * \brief Add a channel ID to the list of PJSIP channels on hold
1048  *
1049  * \param chan_uid - Unique ID of the channel being put into the hold list
1050  *
1051  * \retval 0 Channel has been added to or was already in the hold list
1052  * \retval -1 Failed to add channel to the hold list
1053  */
1054 static int chan_pjsip_add_hold(const char *chan_uid)
1055 {
1056         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1057
1058         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1059         if (hold_uid) {
1060                 /* Device is already on hold. Nothing to do. */
1061                 return 0;
1062         }
1063
1064         /* Device wasn't in hold list already. Create a new one. */
1065         hold_uid = ao2_alloc_options(strlen(chan_uid) + 1, NULL,
1066                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1067         if (!hold_uid) {
1068                 return -1;
1069         }
1070
1071         ast_copy_string(hold_uid, chan_uid, strlen(chan_uid) + 1);
1072
1073         if (ao2_link(pjsip_uids_onhold, hold_uid) == 0) {
1074                 return -1;
1075         }
1076
1077         return 0;
1078 }
1079
1080 /*!
1081  * \brief Remove a channel ID from the list of PJSIP channels on hold
1082  *
1083  * \param chan_uid - Unique ID of the channel being taken out of the hold list
1084  */
1085 static void chan_pjsip_remove_hold(const char *chan_uid)
1086 {
1087         ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY | OBJ_UNLINK | OBJ_NODATA);
1088 }
1089
1090 /*!
1091  * \brief Determine whether a channel ID is in the list of PJSIP channels on hold
1092  *
1093  * \param chan_uid - Channel being checked
1094  *
1095  * \retval 0 The channel is not in the hold list
1096  * \retval 1 The channel is in the hold list
1097  */
1098 static int chan_pjsip_get_hold(const char *chan_uid)
1099 {
1100         RAII_VAR(char *, hold_uid, NULL, ao2_cleanup);
1101
1102         hold_uid = ao2_find(pjsip_uids_onhold, chan_uid, OBJ_SEARCH_KEY);
1103         if (!hold_uid) {
1104                 return 0;
1105         }
1106
1107         return 1;
1108 }
1109
1110 /*! \brief Function called to get the device state of an endpoint */
1111 static int chan_pjsip_devicestate(const char *data)
1112 {
1113         RAII_VAR(struct ast_sip_endpoint *, endpoint, ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", data), ao2_cleanup);
1114         enum ast_device_state state = AST_DEVICE_UNKNOWN;
1115         RAII_VAR(struct ast_endpoint_snapshot *, endpoint_snapshot, NULL, ao2_cleanup);
1116         RAII_VAR(struct stasis_cache *, cache, NULL, ao2_cleanup);
1117         struct ast_devstate_aggregate aggregate;
1118         int num, inuse = 0;
1119
1120         if (!endpoint) {
1121                 return AST_DEVICE_INVALID;
1122         }
1123
1124         endpoint_snapshot = ast_endpoint_latest_snapshot(ast_endpoint_get_tech(endpoint->persistent),
1125                 ast_endpoint_get_resource(endpoint->persistent));
1126
1127         if (!endpoint_snapshot) {
1128                 return AST_DEVICE_INVALID;
1129         }
1130
1131         if (endpoint_snapshot->state == AST_ENDPOINT_OFFLINE) {
1132                 state = AST_DEVICE_UNAVAILABLE;
1133         } else if (endpoint_snapshot->state == AST_ENDPOINT_ONLINE) {
1134                 state = AST_DEVICE_NOT_INUSE;
1135         }
1136
1137         if (!endpoint_snapshot->num_channels || !(cache = ast_channel_cache())) {
1138                 return state;
1139         }
1140
1141         ast_devstate_aggregate_init(&aggregate);
1142
1143         ao2_ref(cache, +1);
1144
1145         for (num = 0; num < endpoint_snapshot->num_channels; num++) {
1146                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
1147                 struct ast_channel_snapshot *snapshot;
1148
1149                 msg = stasis_cache_get(cache, ast_channel_snapshot_type(),
1150                         endpoint_snapshot->channel_ids[num]);
1151
1152                 if (!msg) {
1153                         continue;
1154                 }
1155
1156                 snapshot = stasis_message_data(msg);
1157
1158                 if (chan_pjsip_get_hold(snapshot->uniqueid)) {
1159                         ast_devstate_aggregate_add(&aggregate, AST_DEVICE_ONHOLD);
1160                 } else {
1161                         ast_devstate_aggregate_add(&aggregate, ast_state_chan2dev(snapshot->state));
1162                 }
1163
1164                 if ((snapshot->state == AST_STATE_UP) || (snapshot->state == AST_STATE_RING) ||
1165                         (snapshot->state == AST_STATE_BUSY)) {
1166                         inuse++;
1167                 }
1168         }
1169
1170         if (endpoint->devicestate_busy_at && (inuse == endpoint->devicestate_busy_at)) {
1171                 state = AST_DEVICE_BUSY;
1172         } else if (ast_devstate_aggregate_result(&aggregate) != AST_DEVICE_INVALID) {
1173                 state = ast_devstate_aggregate_result(&aggregate);
1174         }
1175
1176         return state;
1177 }
1178
1179 /*! \brief Function called to query options on a channel */
1180 static int chan_pjsip_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
1181 {
1182         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1183         struct ast_sip_session *session = channel->session;
1184         int res = -1;
1185         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
1186
1187         switch (option) {
1188         case AST_OPTION_T38_STATE:
1189                 if (session->endpoint->media.t38.enabled) {
1190                         switch (session->t38state) {
1191                         case T38_LOCAL_REINVITE:
1192                         case T38_PEER_REINVITE:
1193                                 state = T38_STATE_NEGOTIATING;
1194                                 break;
1195                         case T38_ENABLED:
1196                                 state = T38_STATE_NEGOTIATED;
1197                                 break;
1198                         case T38_REJECTED:
1199                                 state = T38_STATE_REJECTED;
1200                                 break;
1201                         default:
1202                                 state = T38_STATE_UNKNOWN;
1203                                 break;
1204                         }
1205                 }
1206
1207                 *((enum ast_t38_state *) data) = state;
1208                 res = 0;
1209
1210                 break;
1211         default:
1212                 break;
1213         }
1214
1215         return res;
1216 }
1217
1218 static const char *chan_pjsip_get_uniqueid(struct ast_channel *ast)
1219 {
1220         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1221         char *uniqueid = ast_threadstorage_get(&uniqueid_threadbuf, UNIQUEID_BUFSIZE);
1222
1223         if (!uniqueid) {
1224                 return "";
1225         }
1226
1227         ast_copy_pj_str(uniqueid, &channel->session->inv_session->dlg->call_id->id, UNIQUEID_BUFSIZE);
1228
1229         return uniqueid;
1230 }
1231
1232 struct indicate_data {
1233         struct ast_sip_session *session;
1234         int condition;
1235         int response_code;
1236         void *frame_data;
1237         size_t datalen;
1238 };
1239
1240 static void indicate_data_destroy(void *obj)
1241 {
1242         struct indicate_data *ind_data = obj;
1243
1244         ast_free(ind_data->frame_data);
1245         ao2_ref(ind_data->session, -1);
1246 }
1247
1248 static struct indicate_data *indicate_data_alloc(struct ast_sip_session *session,
1249                 int condition, int response_code, const void *frame_data, size_t datalen)
1250 {
1251         struct indicate_data *ind_data = ao2_alloc(sizeof(*ind_data), indicate_data_destroy);
1252
1253         if (!ind_data) {
1254                 return NULL;
1255         }
1256
1257         ind_data->frame_data = ast_malloc(datalen);
1258         if (!ind_data->frame_data) {
1259                 ao2_ref(ind_data, -1);
1260                 return NULL;
1261         }
1262
1263         memcpy(ind_data->frame_data, frame_data, datalen);
1264         ind_data->datalen = datalen;
1265         ind_data->condition = condition;
1266         ind_data->response_code = response_code;
1267         ao2_ref(session, +1);
1268         ind_data->session = session;
1269
1270         return ind_data;
1271 }
1272
1273 static int indicate(void *data)
1274 {
1275         pjsip_tx_data *packet = NULL;
1276         struct indicate_data *ind_data = data;
1277         struct ast_sip_session *session = ind_data->session;
1278         int response_code = ind_data->response_code;
1279
1280         if ((session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED) &&
1281                 (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS)) {
1282                 ast_sip_session_send_response(session, packet);
1283         }
1284
1285 #ifdef HAVE_PJSIP_INV_SESSION_REF
1286         pjsip_inv_dec_ref(session->inv_session);
1287 #endif
1288         ao2_ref(ind_data, -1);
1289
1290         return 0;
1291 }
1292
1293 /*! \brief Send SIP INFO with video update request */
1294 static int transmit_info_with_vidupdate(void *data)
1295 {
1296         const char * xml =
1297                 "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
1298                 " <media_control>\r\n"
1299                 "  <vc_primitive>\r\n"
1300                 "   <to_encoder>\r\n"
1301                 "    <picture_fast_update/>\r\n"
1302                 "   </to_encoder>\r\n"
1303                 "  </vc_primitive>\r\n"
1304                 " </media_control>\r\n";
1305
1306         const struct ast_sip_body body = {
1307                 .type = "application",
1308                 .subtype = "media_control+xml",
1309                 .body_text = xml
1310         };
1311
1312         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1313         struct pjsip_tx_data *tdata;
1314
1315         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1316                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1317                         session->inv_session->cause,
1318                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1319                 goto failure;
1320         }
1321
1322         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
1323                 ast_log(LOG_ERROR, "Could not create text video update INFO request\n");
1324                 goto failure;
1325         }
1326         if (ast_sip_add_body(tdata, &body)) {
1327                 ast_log(LOG_ERROR, "Could not add body to text video update INFO request\n");
1328                 goto failure;
1329         }
1330         ast_sip_session_send_request(session, tdata);
1331
1332 #ifdef HAVE_PJSIP_INV_SESSION_REF
1333         pjsip_inv_dec_ref(session->inv_session);
1334 #endif
1335
1336         return 0;
1337
1338 failure:
1339 #ifdef HAVE_PJSIP_INV_SESSION_REF
1340         pjsip_inv_dec_ref(session->inv_session);
1341 #endif
1342         return -1;
1343
1344 }
1345
1346 /*!
1347  * \internal
1348  * \brief TRUE if a COLP update can be sent to the peer.
1349  * \since 13.3.0
1350  *
1351  * \param session The session to see if the COLP update is allowed.
1352  *
1353  * \retval 0 Update is not allowed.
1354  * \retval 1 Update is allowed.
1355  */
1356 static int is_colp_update_allowed(struct ast_sip_session *session)
1357 {
1358         struct ast_party_id connected_id;
1359         int update_allowed = 0;
1360
1361         if (!session->endpoint->id.send_pai && !session->endpoint->id.send_rpid) {
1362                 return 0;
1363         }
1364
1365         /*
1366          * Check if privacy allows the update.  Check while the channel
1367          * is locked so we can work with the shallow connected_id copy.
1368          */
1369         ast_channel_lock(session->channel);
1370         connected_id = ast_channel_connected_effective_id(session->channel);
1371         if (connected_id.number.valid
1372                 && (session->endpoint->id.trust_outbound
1373                         || (ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED)) {
1374                 update_allowed = 1;
1375         }
1376         ast_channel_unlock(session->channel);
1377
1378         return update_allowed;
1379 }
1380
1381 /*! \brief Update connected line information */
1382 static int update_connected_line_information(void *data)
1383 {
1384         struct ast_sip_session *session = data;
1385
1386         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1387                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1388                         session->inv_session->cause,
1389                         pjsip_get_status_text(session->inv_session->cause)->ptr);
1390 #ifdef HAVE_PJSIP_INV_SESSION_REF
1391                 pjsip_inv_dec_ref(session->inv_session);
1392 #endif
1393                 ao2_ref(session, -1);
1394                 return -1;
1395         }
1396
1397         if (ast_channel_state(session->channel) == AST_STATE_UP
1398                 || session->inv_session->role == PJSIP_ROLE_UAC) {
1399                 if (is_colp_update_allowed(session)) {
1400                         enum ast_sip_session_refresh_method method;
1401                         int generate_new_sdp;
1402
1403                         method = session->endpoint->id.refresh_method;
1404                         if (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE) {
1405                                 method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1406                         }
1407
1408                         /* Only the INVITE method actually needs SDP, UPDATE can do without */
1409                         generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
1410
1411                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
1412                 }
1413         } else if (session->endpoint->id.rpid_immediate
1414                 && session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
1415                 && is_colp_update_allowed(session)) {
1416                 int response_code = 0;
1417
1418                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1419                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1420                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1421                         response_code = 183;
1422                 }
1423
1424                 if (response_code) {
1425                         struct pjsip_tx_data *packet = NULL;
1426
1427                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1428                                 ast_sip_session_send_response(session, packet);
1429                         }
1430                 }
1431         }
1432
1433 #ifdef HAVE_PJSIP_INV_SESSION_REF
1434         pjsip_inv_dec_ref(session->inv_session);
1435 #endif
1436
1437         ao2_ref(session, -1);
1438         return 0;
1439 }
1440
1441 /*! \brief Callback which changes the value of locally held on the media stream */
1442 static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
1443 {
1444         if (session_media) {
1445                 session_media->locally_held = held;
1446         }
1447 }
1448
1449 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
1450 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
1451 {
1452         AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
1453         ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
1454         ao2_ref(session, -1);
1455
1456         return 0;
1457 }
1458
1459 /*! \brief Update local hold state to be held */
1460 static int remote_send_hold(void *data)
1461 {
1462         return remote_send_hold_refresh(data, 1);
1463 }
1464
1465 /*! \brief Update local hold state to be unheld */
1466 static int remote_send_unhold(void *data)
1467 {
1468         return remote_send_hold_refresh(data, 0);
1469 }
1470
1471 struct topology_change_refresh_data {
1472         struct ast_sip_session *session;
1473         struct ast_sip_session_media_state *media_state;
1474 };
1475
1476 static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
1477 {
1478         ao2_cleanup(refresh_data->session);
1479
1480         ast_sip_session_media_state_free(refresh_data->media_state);
1481         ast_free(refresh_data);
1482 }
1483
1484 static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
1485         struct ast_sip_session *session, const struct ast_stream_topology *topology)
1486 {
1487         struct topology_change_refresh_data *refresh_data;
1488
1489         refresh_data = ast_calloc(1, sizeof(*refresh_data));
1490         if (!refresh_data) {
1491                 return NULL;
1492         }
1493
1494         refresh_data->session = ao2_bump(session);
1495         refresh_data->media_state = ast_sip_session_media_state_alloc();
1496         if (!refresh_data->media_state) {
1497                 topology_change_refresh_data_free(refresh_data);
1498                 return NULL;
1499         }
1500         refresh_data->media_state->topology = ast_stream_topology_clone(topology);
1501         if (!refresh_data->media_state->topology) {
1502                 topology_change_refresh_data_free(refresh_data);
1503                 return NULL;
1504         }
1505
1506         return refresh_data;
1507 }
1508
1509 static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
1510 {
1511         if (PJSIP_IS_STATUS_IN_CLASS(rdata->msg_info.msg->line.status.code, 200)) {
1512                 /* The topology was changed to something new so give notice to what requested
1513                  * it so it queries the channel and updates accordingly.
1514                  */
1515                 if (session->channel) {
1516                         ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
1517                 }
1518         } else if (300 <= rdata->msg_info.msg->line.status.code) {
1519                 /* The topology change failed, so drop the current pending media state */
1520                 ast_sip_session_media_state_reset(session->pending_media_state);
1521         }
1522
1523         return 0;
1524 }
1525
1526 static int send_topology_change_refresh(void *data)
1527 {
1528         struct topology_change_refresh_data *refresh_data = data;
1529         int ret;
1530
1531         ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
1532                 AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
1533         refresh_data->media_state = NULL;
1534         topology_change_refresh_data_free(refresh_data);
1535
1536         return ret;
1537 }
1538
1539 static int handle_topology_request_change(struct ast_sip_session *session,
1540         const struct ast_stream_topology *proposed)
1541 {
1542         struct topology_change_refresh_data *refresh_data;
1543         int res;
1544
1545         refresh_data = topology_change_refresh_data_alloc(session, proposed);
1546         if (!refresh_data) {
1547                 return -1;
1548         }
1549
1550         res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
1551         if (res) {
1552                 topology_change_refresh_data_free(refresh_data);
1553         }
1554         return res;
1555 }
1556
1557 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1558 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1559 {
1560         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1561         struct ast_sip_session_media *media;
1562         int response_code = 0;
1563         int res = 0;
1564         char *device_buf;
1565         size_t device_buf_size;
1566         int i;
1567         const struct ast_stream_topology *topology;
1568
1569         switch (condition) {
1570         case AST_CONTROL_RINGING:
1571                 if (ast_channel_state(ast) == AST_STATE_RING) {
1572                         if (channel->session->endpoint->inband_progress) {
1573                                 response_code = 183;
1574                                 res = -1;
1575                         } else {
1576                                 response_code = 180;
1577                         }
1578                 } else {
1579                         res = -1;
1580                 }
1581                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1582                 break;
1583         case AST_CONTROL_BUSY:
1584                 if (ast_channel_state(ast) != AST_STATE_UP) {
1585                         response_code = 486;
1586                 } else {
1587                         res = -1;
1588                 }
1589                 break;
1590         case AST_CONTROL_CONGESTION:
1591                 if (ast_channel_state(ast) != AST_STATE_UP) {
1592                         response_code = 503;
1593                 } else {
1594                         res = -1;
1595                 }
1596                 break;
1597         case AST_CONTROL_INCOMPLETE:
1598                 if (ast_channel_state(ast) != AST_STATE_UP) {
1599                         response_code = 484;
1600                 } else {
1601                         res = -1;
1602                 }
1603                 break;
1604         case AST_CONTROL_PROCEEDING:
1605                 if (ast_channel_state(ast) != AST_STATE_UP) {
1606                         response_code = 100;
1607                 } else {
1608                         res = -1;
1609                 }
1610                 break;
1611         case AST_CONTROL_PROGRESS:
1612                 if (ast_channel_state(ast) != AST_STATE_UP) {
1613                         response_code = 183;
1614                 } else {
1615                         res = -1;
1616                 }
1617                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1618                 break;
1619         case AST_CONTROL_VIDUPDATE:
1620                 for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
1621                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
1622                         if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
1623                                 continue;
1624                         }
1625                         if (media->rtp) {
1626                                 /* FIXME: Only use this for VP8. Additional work would have to be done to
1627                                  * fully support other video codecs */
1628
1629                                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL ||
1630                                         ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp9) != AST_FORMAT_CMP_NOT_EQUAL ||
1631                                         (channel->session->endpoint->media.webrtc &&
1632                                          ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_h264) != AST_FORMAT_CMP_NOT_EQUAL)) {
1633                                         /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1634                                          * RTP engine would provide a way to externally write/schedule RTCP
1635                                          * packets */
1636                                         struct ast_frame fr;
1637                                         fr.frametype = AST_FRAME_CONTROL;
1638                                         fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1639                                         res = ast_rtp_instance_write(media->rtp, &fr);
1640                                 } else {
1641                                         ao2_ref(channel->session, +1);
1642 #ifdef HAVE_PJSIP_INV_SESSION_REF
1643                                         if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1644                                                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1645                                                 ao2_cleanup(channel->session);
1646                                         } else {
1647 #endif
1648                                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1649                                                         ao2_cleanup(channel->session);
1650                                                 }
1651 #ifdef HAVE_PJSIP_INV_SESSION_REF
1652                                         }
1653 #endif
1654                                 }
1655                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1656                         } else {
1657                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1658                                 res = -1;
1659                         }
1660                 }
1661                 /* XXX If there were no video streams, then this should set
1662                  * res to -1
1663                  */
1664                 break;
1665         case AST_CONTROL_CONNECTED_LINE:
1666                 ao2_ref(channel->session, +1);
1667 #ifdef HAVE_PJSIP_INV_SESSION_REF
1668                 if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1669                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1670                         ao2_cleanup(channel->session);
1671                         return -1;
1672                 }
1673 #endif
1674                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1675 #ifdef HAVE_PJSIP_INV_SESSION_REF
1676                         pjsip_inv_dec_ref(channel->session->inv_session);
1677 #endif
1678                         ao2_cleanup(channel->session);
1679                 }
1680                 break;
1681         case AST_CONTROL_UPDATE_RTP_PEER:
1682                 break;
1683         case AST_CONTROL_PVT_CAUSE_CODE:
1684                 res = -1;
1685                 break;
1686         case AST_CONTROL_MASQUERADE_NOTIFY:
1687                 ast_assert(datalen == sizeof(int));
1688                 if (*(int *) data) {
1689                         /*
1690                          * Masquerade is beginning:
1691                          * Wait for session serializer to get suspended.
1692                          */
1693                         ast_channel_unlock(ast);
1694                         ast_sip_session_suspend(channel->session);
1695                         ast_channel_lock(ast);
1696                 } else {
1697                         /*
1698                          * Masquerade is complete:
1699                          * Unsuspend the session serializer.
1700                          */
1701                         ast_sip_session_unsuspend(channel->session);
1702                 }
1703                 break;
1704         case AST_CONTROL_HOLD:
1705                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1706                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1707                 device_buf = alloca(device_buf_size);
1708                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1709                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1710                 if (!channel->session->endpoint->moh_passthrough) {
1711                         ast_moh_start(ast, data, NULL);
1712                 } else {
1713                         if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
1714                                 ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
1715                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1716                                 ao2_ref(channel->session, -1);
1717                         }
1718                 }
1719                 break;
1720         case AST_CONTROL_UNHOLD:
1721                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1722                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1723                 device_buf = alloca(device_buf_size);
1724                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1725                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1726                 if (!channel->session->endpoint->moh_passthrough) {
1727                         ast_moh_stop(ast);
1728                 } else {
1729                         if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
1730                                 ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
1731                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1732                                 ao2_ref(channel->session, -1);
1733                         }
1734                 }
1735                 break;
1736         case AST_CONTROL_SRCUPDATE:
1737                 break;
1738         case AST_CONTROL_SRCCHANGE:
1739                 break;
1740         case AST_CONTROL_REDIRECTING:
1741                 if (ast_channel_state(ast) != AST_STATE_UP) {
1742                         response_code = 181;
1743                 } else {
1744                         res = -1;
1745                 }
1746                 break;
1747         case AST_CONTROL_T38_PARAMETERS:
1748                 res = 0;
1749
1750                 if (channel->session->t38state == T38_PEER_REINVITE) {
1751                         const struct ast_control_t38_parameters *parameters = data;
1752
1753                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1754                                 res = AST_T38_REQUEST_PARMS;
1755                         }
1756                 }
1757
1758                 break;
1759         case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1760                 topology = data;
1761                 res = handle_topology_request_change(channel->session, topology);
1762                 break;
1763         case AST_CONTROL_STREAM_TOPOLOGY_CHANGED:
1764                 break;
1765         case AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED:
1766                 break;
1767         case -1:
1768                 res = -1;
1769                 break;
1770         default:
1771                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1772                 res = -1;
1773                 break;
1774         }
1775
1776         if (response_code) {
1777                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1778
1779                 if (!ind_data) {
1780                         return -1;
1781                 }
1782 #ifdef HAVE_PJSIP_INV_SESSION_REF
1783                 if (pjsip_inv_add_ref(ind_data->session->inv_session) != PJ_SUCCESS) {
1784                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1785                         ao2_cleanup(ind_data);
1786                         return -1;
1787                 }
1788 #endif
1789                 if (ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1790                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1791                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1792 #ifdef HAVE_PJSIP_INV_SESSION_REF
1793                         pjsip_inv_dec_ref(ind_data->session->inv_session);
1794 #endif
1795                         ao2_cleanup(ind_data);
1796                         res = -1;
1797                 }
1798         }
1799
1800         return res;
1801 }
1802
1803 struct transfer_data {
1804         struct ast_sip_session *session;
1805         char *target;
1806 };
1807
1808 static void transfer_data_destroy(void *obj)
1809 {
1810         struct transfer_data *trnf_data = obj;
1811
1812         ast_free(trnf_data->target);
1813         ao2_cleanup(trnf_data->session);
1814 }
1815
1816 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1817 {
1818         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1819
1820         if (!trnf_data) {
1821                 return NULL;
1822         }
1823
1824         if (!(trnf_data->target = ast_strdup(target))) {
1825                 ao2_ref(trnf_data, -1);
1826                 return NULL;
1827         }
1828
1829         ao2_ref(session, +1);
1830         trnf_data->session = session;
1831
1832         return trnf_data;
1833 }
1834
1835 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1836 {
1837         pjsip_tx_data *packet;
1838         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1839         pjsip_contact_hdr *contact;
1840         pj_str_t tmp;
1841
1842         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS
1843                 || !packet) {
1844                 ast_log(LOG_WARNING, "Failed to redirect PJSIP session for channel %s\n",
1845                         ast_channel_name(session->channel));
1846                 message = AST_TRANSFER_FAILED;
1847                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1848
1849                 return;
1850         }
1851
1852         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1853                 contact = pjsip_contact_hdr_create(packet->pool);
1854         }
1855
1856         pj_strdup2_with_null(packet->pool, &tmp, target);
1857         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1858                 ast_log(LOG_WARNING, "Failed to parse destination URI '%s' for channel %s\n",
1859                         target, ast_channel_name(session->channel));
1860                 message = AST_TRANSFER_FAILED;
1861                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1862                 pjsip_tx_data_dec_ref(packet);
1863
1864                 return;
1865         }
1866         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1867
1868         ast_sip_session_send_response(session, packet);
1869         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1870 }
1871
1872 static void transfer_refer(struct ast_sip_session *session, const char *target)
1873 {
1874         pjsip_evsub *sub;
1875         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1876         pj_str_t tmp;
1877         pjsip_tx_data *packet;
1878         const char *ref_by_val;
1879         char local_info[pj_strlen(&session->inv_session->dlg->local.info_str) + 1];
1880
1881         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1882                 message = AST_TRANSFER_FAILED;
1883                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1884
1885                 return;
1886         }
1887
1888         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1889                 message = AST_TRANSFER_FAILED;
1890                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1891                 pjsip_evsub_terminate(sub, PJ_FALSE);
1892
1893                 return;
1894         }
1895
1896         ref_by_val = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
1897         if (!ast_strlen_zero(ref_by_val)) {
1898                 ast_sip_add_header(packet, "Referred-By", ref_by_val);
1899         } else {
1900                 ast_copy_pj_str(local_info, &session->inv_session->dlg->local.info_str, sizeof(local_info));
1901                 ast_sip_add_header(packet, "Referred-By", local_info);
1902         }
1903
1904         pjsip_xfer_send_request(sub, packet);
1905         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1906 }
1907
1908 static int transfer(void *data)
1909 {
1910         struct transfer_data *trnf_data = data;
1911         struct ast_sip_endpoint *endpoint = NULL;
1912         struct ast_sip_contact *contact = NULL;
1913         const char *target = trnf_data->target;
1914
1915         if (trnf_data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1916                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1917                         trnf_data->session->inv_session->cause,
1918                         pjsip_get_status_text(trnf_data->session->inv_session->cause)->ptr);
1919         } else {
1920                 /* See if we have an endpoint; if so, use its contact */
1921                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", target);
1922                 if (endpoint) {
1923                         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
1924                         if (contact && !ast_strlen_zero(contact->uri)) {
1925                                 target = contact->uri;
1926                         }
1927                 }
1928
1929                 if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1930                         transfer_redirect(trnf_data->session, target);
1931                 } else {
1932                         transfer_refer(trnf_data->session, target);
1933                 }
1934         }
1935
1936 #ifdef HAVE_PJSIP_INV_SESSION_REF
1937         pjsip_inv_dec_ref(trnf_data->session->inv_session);
1938 #endif
1939
1940         ao2_ref(trnf_data, -1);
1941         ao2_cleanup(endpoint);
1942         ao2_cleanup(contact);
1943         return 0;
1944 }
1945
1946 /*! \brief Function called by core for Asterisk initiated transfer */
1947 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1948 {
1949         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1950         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1951
1952         if (!trnf_data) {
1953                 return -1;
1954         }
1955
1956 #ifdef HAVE_PJSIP_INV_SESSION_REF
1957         if (pjsip_inv_add_ref(trnf_data->session->inv_session) != PJ_SUCCESS) {
1958                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1959                 ao2_cleanup(trnf_data);
1960                 return -1;
1961         }
1962 #endif
1963
1964         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1965                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1966 #ifdef HAVE_PJSIP_INV_SESSION_REF
1967                 pjsip_inv_dec_ref(trnf_data->session->inv_session);
1968 #endif
1969                 ao2_cleanup(trnf_data);
1970                 return -1;
1971         }
1972
1973         return 0;
1974 }
1975
1976 /*! \brief Function called by core to start a DTMF digit */
1977 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1978 {
1979         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1980         struct ast_sip_session_media *media;
1981         int res = 0;
1982
1983         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
1984
1985         switch (channel->session->dtmf) {
1986         case AST_SIP_DTMF_RFC_4733:
1987                 if (!media || !media->rtp) {
1988                         return -1;
1989                 }
1990
1991                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1992                 break;
1993         case AST_SIP_DTMF_AUTO:
1994                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
1995                         return -1;
1996                 }
1997
1998                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1999                 break;
2000         case AST_SIP_DTMF_AUTO_INFO:
2001                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_NONE)) {
2002                         return -1;
2003                 }
2004                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
2005                 break;
2006         case AST_SIP_DTMF_NONE:
2007                 break;
2008         case AST_SIP_DTMF_INBAND:
2009                 res = -1;
2010                 break;
2011         default:
2012                 break;
2013         }
2014
2015         return res;
2016 }
2017
2018 struct info_dtmf_data {
2019         struct ast_sip_session *session;
2020         char digit;
2021         unsigned int duration;
2022 };
2023
2024 static void info_dtmf_data_destroy(void *obj)
2025 {
2026         struct info_dtmf_data *dtmf_data = obj;
2027         ao2_ref(dtmf_data->session, -1);
2028 }
2029
2030 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
2031 {
2032         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
2033         if (!dtmf_data) {
2034                 return NULL;
2035         }
2036         ao2_ref(session, +1);
2037         dtmf_data->session = session;
2038         dtmf_data->digit = digit;
2039         dtmf_data->duration = duration;
2040         return dtmf_data;
2041 }
2042
2043 static int transmit_info_dtmf(void *data)
2044 {
2045         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
2046
2047         struct ast_sip_session *session = dtmf_data->session;
2048         struct pjsip_tx_data *tdata;
2049
2050         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
2051
2052         struct ast_sip_body body = {
2053                 .type = "application",
2054                 .subtype = "dtmf-relay",
2055         };
2056
2057         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2058                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2059                         session->inv_session->cause,
2060                         pjsip_get_status_text(session->inv_session->cause)->ptr);
2061                 goto failure;
2062         }
2063
2064         if (!(body_text = ast_str_create(32))) {
2065                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
2066                 goto failure;
2067         }
2068         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
2069
2070         body.body_text = ast_str_buffer(body_text);
2071
2072         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
2073                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
2074                 goto failure;
2075         }
2076         if (ast_sip_add_body(tdata, &body)) {
2077                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
2078                 pjsip_tx_data_dec_ref(tdata);
2079                 goto failure;
2080         }
2081         ast_sip_session_send_request(session, tdata);
2082
2083 #ifdef HAVE_PJSIP_INV_SESSION_REF
2084         pjsip_inv_dec_ref(session->inv_session);
2085 #endif
2086
2087         return 0;
2088
2089 failure:
2090 #ifdef HAVE_PJSIP_INV_SESSION_REF
2091         pjsip_inv_dec_ref(session->inv_session);
2092 #endif
2093         return -1;
2094
2095 }
2096
2097 /*! \brief Function called by core to stop a DTMF digit */
2098 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2099 {
2100         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2101         struct ast_sip_session_media *media;
2102         int res = 0;
2103
2104         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
2105
2106         switch (channel->session->dtmf) {
2107         case AST_SIP_DTMF_AUTO_INFO:
2108         {
2109                 if (!media || !media->rtp) {
2110                         return -1;
2111                 }
2112                 if (ast_rtp_instance_dtmf_mode_get(media->rtp) != AST_RTP_DTMF_MODE_NONE) {
2113                         ast_debug(3, "Told to send end of digit on Auto-Info channel %s RFC4733 negotiated so using it.\n", ast_channel_name(ast));
2114                         ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2115                         break;
2116                 }
2117                 /* If RFC_4733 was not negotiated, fail through to the DTMF_INFO processing */
2118                 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));
2119         }
2120
2121         case AST_SIP_DTMF_INFO:
2122         {
2123                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
2124
2125                 if (!dtmf_data) {
2126                         return -1;
2127                 }
2128
2129 #ifdef HAVE_PJSIP_INV_SESSION_REF
2130                 if (pjsip_inv_add_ref(dtmf_data->session->inv_session) != PJ_SUCCESS) {
2131                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2132                         ao2_cleanup(dtmf_data);
2133                         return -1;
2134                 }
2135 #endif
2136
2137                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
2138                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
2139 #ifdef HAVE_PJSIP_INV_SESSION_REF
2140                         pjsip_inv_dec_ref(dtmf_data->session->inv_session);
2141 #endif
2142                         ao2_cleanup(dtmf_data);
2143                         return -1;
2144                 }
2145                 break;
2146         }
2147         case AST_SIP_DTMF_RFC_4733:
2148                 if (!media || !media->rtp) {
2149                         return -1;
2150                 }
2151
2152                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2153                 break;
2154         case AST_SIP_DTMF_AUTO:
2155                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
2156                          return -1;
2157                 }
2158
2159                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2160                 break;
2161
2162
2163         case AST_SIP_DTMF_NONE:
2164                 break;
2165         case AST_SIP_DTMF_INBAND:
2166                 res = -1;
2167                 break;
2168         }
2169
2170         return res;
2171 }
2172
2173 static void update_initial_connected_line(struct ast_sip_session *session)
2174 {
2175         struct ast_party_connected_line connected;
2176
2177         /*
2178          * Use the channel CALLERID() as the initial connected line data.
2179          * The core or a predial handler may have supplied missing values
2180          * from the session->endpoint->id.self about who we are calling.
2181          */
2182         ast_channel_lock(session->channel);
2183         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
2184         ast_channel_unlock(session->channel);
2185
2186         /* Supply initial connected line information if available. */
2187         if (!session->id.number.valid && !session->id.name.valid) {
2188                 return;
2189         }
2190
2191         ast_party_connected_line_init(&connected);
2192         connected.id = session->id;
2193         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2194
2195         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
2196 }
2197
2198 static int call(void *data)
2199 {
2200         struct ast_sip_channel_pvt *channel = data;
2201         struct ast_sip_session *session = channel->session;
2202         pjsip_tx_data *tdata;
2203
2204         int res = ast_sip_session_create_invite(session, &tdata);
2205
2206         if (res) {
2207                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2208                 ast_queue_hangup(session->channel);
2209         } else {
2210                 set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
2211                 update_initial_connected_line(session);
2212                 ast_sip_session_send_request(session, tdata);
2213         }
2214         ao2_ref(channel, -1);
2215         return res;
2216 }
2217
2218 /*! \brief Function called by core to actually start calling a remote party */
2219 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
2220 {
2221         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2222
2223         ao2_ref(channel, +1);
2224         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
2225                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
2226                 ao2_cleanup(channel);
2227                 return -1;
2228         }
2229
2230         return 0;
2231 }
2232
2233 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
2234 static int hangup_cause2sip(int cause)
2235 {
2236         switch (cause) {
2237         case AST_CAUSE_UNALLOCATED:             /* 1 */
2238         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2239         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2240                 return 404;
2241         case AST_CAUSE_CONGESTION:              /* 34 */
2242         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2243                 return 503;
2244         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2245                 return 408;
2246         case AST_CAUSE_NO_ANSWER:               /* 19 */
2247         case AST_CAUSE_UNREGISTERED:        /* 20 */
2248                 return 480;
2249         case AST_CAUSE_CALL_REJECTED:           /* 21 */
2250                 return 403;
2251         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2252                 return 410;
2253         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2254                 return 480;
2255         case AST_CAUSE_INVALID_NUMBER_FORMAT:
2256                 return 484;
2257         case AST_CAUSE_USER_BUSY:
2258                 return 486;
2259         case AST_CAUSE_FAILURE:
2260                 return 500;
2261         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2262                 return 501;
2263         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2264                 return 503;
2265         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2266                 return 502;
2267         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2268                 return 488;
2269         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
2270                 return 500;
2271         case AST_CAUSE_NOTDEFINED:
2272         default:
2273                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
2274                 return 0;
2275         }
2276
2277         /* Never reached */
2278         return 0;
2279 }
2280
2281 struct hangup_data {
2282         int cause;
2283         struct ast_channel *chan;
2284 };
2285
2286 static void hangup_data_destroy(void *obj)
2287 {
2288         struct hangup_data *h_data = obj;
2289
2290         h_data->chan = ast_channel_unref(h_data->chan);
2291 }
2292
2293 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
2294 {
2295         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
2296
2297         if (!h_data) {
2298                 return NULL;
2299         }
2300
2301         h_data->cause = cause;
2302         h_data->chan = ast_channel_ref(chan);
2303
2304         return h_data;
2305 }
2306
2307 /*! \brief Clear a channel from a session along with its PVT */
2308 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
2309 {
2310         session->channel = NULL;
2311         set_channel_on_rtp_instance(session, "");
2312         ast_channel_tech_pvt_set(ast, NULL);
2313 }
2314
2315 static int hangup(void *data)
2316 {
2317         struct hangup_data *h_data = data;
2318         struct ast_channel *ast = h_data->chan;
2319         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2320         struct ast_sip_session *session = channel->session;
2321         int cause = h_data->cause;
2322
2323         /*
2324          * It's possible that session_terminate might cause the session to be destroyed
2325          * immediately so we need to keep a reference to it so we can NULL session->channel
2326          * afterwards.
2327          */
2328         ast_sip_session_terminate(ao2_bump(session), cause);
2329         clear_session_and_channel(session, ast);
2330         ao2_cleanup(session);
2331         ao2_cleanup(channel);
2332         ao2_cleanup(h_data);
2333         return 0;
2334 }
2335
2336 /*! \brief Function called by core to hang up a PJSIP session */
2337 static int chan_pjsip_hangup(struct ast_channel *ast)
2338 {
2339         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2340         int cause;
2341         struct hangup_data *h_data;
2342
2343         if (!channel || !channel->session) {
2344                 return -1;
2345         }
2346
2347         cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
2348         h_data = hangup_data_alloc(cause, ast);
2349
2350         if (!h_data) {
2351                 goto failure;
2352         }
2353
2354         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
2355                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
2356                 goto failure;
2357         }
2358
2359         return 0;
2360
2361 failure:
2362         /* Go ahead and do our cleanup of the session and channel even if we're not going
2363          * to be able to send our SIP request/response
2364          */
2365         clear_session_and_channel(channel->session, ast);
2366         ao2_cleanup(channel);
2367         ao2_cleanup(h_data);
2368
2369         return -1;
2370 }
2371
2372 struct request_data {
2373         struct ast_sip_session *session;
2374         struct ast_stream_topology *topology;
2375         const char *dest;
2376         int cause;
2377 };
2378
2379 static int request(void *obj)
2380 {
2381         struct request_data *req_data = obj;
2382         struct ast_sip_session *session = NULL;
2383         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
2384         struct ast_sip_endpoint *endpoint;
2385
2386         AST_DECLARE_APP_ARGS(args,
2387                 AST_APP_ARG(endpoint);
2388                 AST_APP_ARG(aor);
2389         );
2390
2391         if (ast_strlen_zero(tmp)) {
2392                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
2393                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2394                 return -1;
2395         }
2396
2397         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
2398
2399         if (ast_sip_get_disable_multi_domain()) {
2400                 /* If a request user has been specified extract it from the endpoint name portion */
2401                 if ((endpoint_name = strchr(args.endpoint, '@'))) {
2402                         request_user = args.endpoint;
2403                         *endpoint_name++ = '\0';
2404                 } else {
2405                         endpoint_name = args.endpoint;
2406                 }
2407
2408                 if (ast_strlen_zero(endpoint_name)) {
2409                         if (request_user) {
2410                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2411                                         request_user);
2412                         } else {
2413                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2414                         }
2415                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2416                         return -1;
2417                 }
2418                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2419                         endpoint_name);
2420                 if (!endpoint) {
2421                         ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2422                         req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2423                         return -1;
2424                 }
2425         } else {
2426                 /* First try to find an exact endpoint match, for single (user) or multi-domain (user@domain) */
2427                 endpoint_name = args.endpoint;
2428                 if (ast_strlen_zero(endpoint_name)) {
2429                         ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2430                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2431                         return -1;
2432                 }
2433                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2434                         endpoint_name);
2435                 if (!endpoint) {
2436                         /* It seems it's not a multi-domain endpoint or single endpoint exact match,
2437                          * it's possible that it's a SIP trunk with a specified user (user@trunkname),
2438                          * so extract the user before @ sign.
2439                          */
2440                         endpoint_name = strchr(args.endpoint, '@');
2441                         if (!endpoint_name) {
2442                                 /*
2443                                  * Couldn't find an '@' so it had to be an endpoint
2444                                  * name that doesn't exist.
2445                                  */
2446                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n",
2447                                         args.endpoint);
2448                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2449                                 return -1;
2450                         }
2451                         request_user = args.endpoint;
2452                         *endpoint_name++ = '\0';
2453
2454                         if (ast_strlen_zero(endpoint_name)) {
2455                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name: %s@<endpoint-name>\n",
2456                                         request_user);
2457                                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2458                                 return -1;
2459                         }
2460
2461                         endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint",
2462                                 endpoint_name);
2463                         if (!endpoint) {
2464                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2465                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2466                                 return -1;
2467                         }
2468                 }
2469         }
2470
2471         session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user,
2472                 req_data->topology);
2473         ao2_ref(endpoint, -1);
2474         if (!session) {
2475                 ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
2476                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2477                 return -1;
2478         }
2479
2480         req_data->session = session;
2481
2482         return 0;
2483 }
2484
2485 /*! \brief Function called by core to create a new outgoing PJSIP session */
2486 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)
2487 {
2488         struct request_data req_data;
2489         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2490
2491         req_data.topology = topology;
2492         req_data.dest = data;
2493         /* Default failure value in case ast_sip_push_task_synchronous() itself fails. */
2494         req_data.cause = AST_CAUSE_FAILURE;
2495
2496         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
2497                 *cause = req_data.cause;
2498                 return NULL;
2499         }
2500
2501         session = req_data.session;
2502
2503         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
2504                 /* Session needs to be terminated prematurely */
2505                 return NULL;
2506         }
2507
2508         return session->channel;
2509 }
2510
2511 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)
2512 {
2513         struct ast_stream_topology *topology;
2514         struct ast_channel *chan;
2515
2516         topology = ast_stream_topology_create_from_format_cap(cap);
2517         if (!topology) {
2518                 return NULL;
2519         }
2520
2521         chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
2522
2523         ast_stream_topology_free(topology);
2524
2525         return chan;
2526 }
2527
2528 struct sendtext_data {
2529         struct ast_sip_session *session;
2530         char text[0];
2531 };
2532
2533 static void sendtext_data_destroy(void *obj)
2534 {
2535         struct sendtext_data *data = obj;
2536         ao2_ref(data->session, -1);
2537 }
2538
2539 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
2540 {
2541         int size = strlen(text) + 1;
2542         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
2543
2544         if (!data) {
2545                 return NULL;
2546         }
2547
2548         data->session = session;
2549         ao2_ref(data->session, +1);
2550         ast_copy_string(data->text, text, size);
2551         return data;
2552 }
2553
2554 static int sendtext(void *obj)
2555 {
2556         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
2557         pjsip_tx_data *tdata;
2558
2559         const struct ast_sip_body body = {
2560                 .type = "text",
2561                 .subtype = "plain",
2562                 .body_text = data->text
2563         };
2564
2565         if (data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2566                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2567                         data->session->inv_session->cause,
2568                         pjsip_get_status_text(data->session->inv_session->cause)->ptr);
2569         } else {
2570                 ast_debug(3, "Sending in dialog SIP message\n");
2571
2572                 ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
2573                 ast_sip_add_body(tdata, &body);
2574                 ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
2575         }
2576
2577 #ifdef HAVE_PJSIP_INV_SESSION_REF
2578         pjsip_inv_dec_ref(data->session->inv_session);
2579 #endif
2580
2581         return 0;
2582 }
2583
2584 /*! \brief Function called by core to send text on PJSIP session */
2585 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
2586 {
2587         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2588         struct sendtext_data *data = sendtext_data_create(channel->session, text);
2589
2590         if (!data) {
2591                 return -1;
2592         }
2593
2594 #ifdef HAVE_PJSIP_INV_SESSION_REF
2595         if (pjsip_inv_add_ref(data->session->inv_session) != PJ_SUCCESS) {
2596                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2597                 ao2_ref(data, -1);
2598                 return -1;
2599         }
2600 #endif
2601
2602         if (ast_sip_push_task(channel->session->serializer, sendtext, data)) {
2603 #ifdef HAVE_PJSIP_INV_SESSION_REF
2604                 pjsip_inv_dec_ref(data->session->inv_session);
2605 #endif
2606                 ao2_ref(data, -1);
2607                 return -1;
2608         }
2609         return 0;
2610 }
2611
2612 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2613 static int hangup_sip2cause(int cause)
2614 {
2615         /* Possible values taken from causes.h */
2616
2617         switch(cause) {
2618         case 401:       /* Unauthorized */
2619                 return AST_CAUSE_CALL_REJECTED;
2620         case 403:       /* Not found */
2621                 return AST_CAUSE_CALL_REJECTED;
2622         case 404:       /* Not found */
2623                 return AST_CAUSE_UNALLOCATED;
2624         case 405:       /* Method not allowed */
2625                 return AST_CAUSE_INTERWORKING;
2626         case 407:       /* Proxy authentication required */
2627                 return AST_CAUSE_CALL_REJECTED;
2628         case 408:       /* No reaction */
2629                 return AST_CAUSE_NO_USER_RESPONSE;
2630         case 409:       /* Conflict */
2631                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2632         case 410:       /* Gone */
2633                 return AST_CAUSE_NUMBER_CHANGED;
2634         case 411:       /* Length required */
2635                 return AST_CAUSE_INTERWORKING;
2636         case 413:       /* Request entity too large */
2637                 return AST_CAUSE_INTERWORKING;
2638         case 414:       /* Request URI too large */
2639                 return AST_CAUSE_INTERWORKING;
2640         case 415:       /* Unsupported media type */
2641                 return AST_CAUSE_INTERWORKING;
2642         case 420:       /* Bad extension */
2643                 return AST_CAUSE_NO_ROUTE_DESTINATION;
2644         case 480:       /* No answer */
2645                 return AST_CAUSE_NO_ANSWER;
2646         case 481:       /* No answer */
2647                 return AST_CAUSE_INTERWORKING;
2648         case 482:       /* Loop detected */
2649                 return AST_CAUSE_INTERWORKING;
2650         case 483:       /* Too many hops */
2651                 return AST_CAUSE_NO_ANSWER;
2652         case 484:       /* Address incomplete */
2653                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2654         case 485:       /* Ambiguous */
2655                 return AST_CAUSE_UNALLOCATED;
2656         case 486:       /* Busy everywhere */
2657                 return AST_CAUSE_BUSY;
2658         case 487:       /* Request terminated */
2659                 return AST_CAUSE_INTERWORKING;
2660         case 488:       /* No codecs approved */
2661                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2662         case 491:       /* Request pending */
2663                 return AST_CAUSE_INTERWORKING;
2664         case 493:       /* Undecipherable */
2665                 return AST_CAUSE_INTERWORKING;
2666         case 500:       /* Server internal failure */
2667                 return AST_CAUSE_FAILURE;
2668         case 501:       /* Call rejected */
2669                 return AST_CAUSE_FACILITY_REJECTED;
2670         case 502:
2671                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2672         case 503:       /* Service unavailable */
2673                 return AST_CAUSE_CONGESTION;
2674         case 504:       /* Gateway timeout */
2675                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2676         case 505:       /* SIP version not supported */
2677                 return AST_CAUSE_INTERWORKING;
2678         case 600:       /* Busy everywhere */
2679                 return AST_CAUSE_USER_BUSY;
2680         case 603:       /* Decline */
2681                 return AST_CAUSE_CALL_REJECTED;
2682         case 604:       /* Does not exist anywhere */
2683                 return AST_CAUSE_UNALLOCATED;
2684         case 606:       /* Not acceptable */
2685                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2686         default:
2687                 if (cause < 500 && cause >= 400) {
2688                         /* 4xx class error that is unknown - someting wrong with our request */
2689                         return AST_CAUSE_INTERWORKING;
2690                 } else if (cause < 600 && cause >= 500) {
2691                         /* 5xx class error - problem in the remote end */
2692                         return AST_CAUSE_CONGESTION;
2693                 } else if (cause < 700 && cause >= 600) {
2694                         /* 6xx - global errors in the 4xx class */
2695                         return AST_CAUSE_INTERWORKING;
2696                 }
2697                 return AST_CAUSE_NORMAL;
2698         }
2699         /* Never reached */
2700         return 0;
2701 }
2702
2703 static void chan_pjsip_session_begin(struct ast_sip_session *session)
2704 {
2705         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2706
2707         if (session->endpoint->media.direct_media.glare_mitigation ==
2708                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
2709                 return;
2710         }
2711
2712         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
2713                         "direct_media_glare_mitigation");
2714
2715         if (!datastore) {
2716                 return;
2717         }
2718
2719         ast_sip_session_add_datastore(session, datastore);
2720 }
2721
2722 /*! \brief Function called when the session ends */
2723 static void chan_pjsip_session_end(struct ast_sip_session *session)
2724 {
2725         if (!session->channel) {
2726                 return;
2727         }
2728
2729         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
2730
2731         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2732         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
2733                 int cause = hangup_sip2cause(session->inv_session->cause);
2734
2735                 ast_queue_hangup_with_cause(session->channel, cause);
2736         } else {
2737                 ast_queue_hangup(session->channel);
2738         }
2739 }
2740
2741 /*! \brief Function called when a request is received on the session */
2742 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2743 {
2744         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2745         struct transport_info_data *transport_data;
2746         pjsip_tx_data *packet = NULL;
2747
2748         if (session->channel) {
2749                 return 0;
2750         }
2751
2752         /* Check for a to-tag to determine if this is a reinvite */
2753         if (rdata->msg_info.to->tag.slen) {
2754                 /* Weird case. We've received a reinvite but we don't have a channel. The most
2755                  * typical case for this happening is that a blind transfer fails, and so the
2756                  * transferer attempts to reinvite himself back into the call. We already got
2757                  * rid of that channel, and the other side of the call is unrecoverable.
2758                  *
2759                  * We treat this as a failure, so our best bet is to just hang this call
2760                  * up and not create a new channel. Clearing defer_terminate here ensures that
2761                  * calling ast_sip_session_terminate() can result in a BYE being sent ASAP.
2762                  */
2763                 session->defer_terminate = 0;
2764                 ast_sip_session_terminate(session, 400);
2765                 return -1;
2766         }
2767
2768         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
2769         if (!datastore) {
2770                 return -1;
2771         }
2772
2773         transport_data = ast_calloc(1, sizeof(*transport_data));
2774         if (!transport_data) {
2775                 return -1;
2776         }
2777         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
2778         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
2779         datastore->data = transport_data;
2780         ast_sip_session_add_datastore(session, datastore);
2781
2782         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2783                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS
2784                         && packet) {
2785                         ast_sip_session_send_response(session, packet);
2786                 }
2787
2788                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2789                 return -1;
2790         }
2791         /* channel gets created on incoming request, but we wait to call start
2792            so other supplements have a chance to run */
2793         return 0;
2794 }
2795
2796 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2797 {
2798         struct ast_features_pickup_config *pickup_cfg;
2799         struct ast_channel *chan;
2800
2801         /* Check for a to-tag to determine if this is a reinvite */
2802         if (rdata->msg_info.to->tag.slen) {
2803                 /* We don't care about reinvites */
2804                 return 0;
2805         }
2806
2807         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2808         if (!pickup_cfg) {
2809                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2810                 return 0;
2811         }
2812
2813         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2814                 ao2_ref(pickup_cfg, -1);
2815                 return 0;
2816         }
2817         ao2_ref(pickup_cfg, -1);
2818
2819         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2820          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2821          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2822          */
2823         chan = ast_channel_ref(session->channel);
2824         if (ast_pickup_call(chan)) {
2825                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2826         } else {
2827                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2828         }
2829         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2830          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2831          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2832          * to anything at all.
2833          */
2834         ast_hangup(chan);
2835         ast_channel_unref(chan);
2836
2837         return 1;
2838 }
2839
2840 static struct ast_sip_session_supplement call_pickup_supplement = {
2841         .method = "INVITE",
2842         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2843         .incoming_request = call_pickup_incoming_request,
2844 };
2845
2846 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2847 {
2848         int res;
2849
2850         /* Check for a to-tag to determine if this is a reinvite */
2851         if (rdata->msg_info.to->tag.slen) {
2852                 /* We don't care about reinvites */
2853                 return 0;
2854         }
2855
2856         res = ast_pbx_start(session->channel);
2857
2858         switch (res) {
2859         case AST_PBX_FAILED:
2860                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2861                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2862                 ast_hangup(session->channel);
2863                 break;
2864         case AST_PBX_CALL_LIMIT:
2865                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2866                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2867                 ast_hangup(session->channel);
2868                 break;
2869         case AST_PBX_SUCCESS:
2870         default:
2871                 break;
2872         }
2873
2874         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2875
2876         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2877 }
2878
2879 static struct ast_sip_session_supplement pbx_start_supplement = {
2880         .method = "INVITE",
2881         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2882         .incoming_request = pbx_start_incoming_request,
2883 };
2884
2885 /*! \brief Function called when a response is received on the session */
2886 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2887 {
2888         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2889         struct ast_control_pvt_cause_code *cause_code;
2890         int data_size = sizeof(*cause_code);
2891
2892         if (!session->channel) {
2893                 return;
2894         }
2895
2896         /* Build and send the tech-specific cause information */
2897         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2898         data_size += 4 + 4 + pj_strlen(&status.reason);
2899         cause_code = ast_alloca(data_size);
2900         memset(cause_code, 0, data_size);
2901
2902         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2903
2904         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2905         (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2906
2907         cause_code->ast_cause = hangup_sip2cause(status.code);
2908         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2909         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2910
2911         switch (status.code) {
2912         case 180:
2913                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2914                 ast_channel_lock(session->channel);
2915                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2916                         ast_setstate(session->channel, AST_STATE_RINGING);
2917                 }
2918                 ast_channel_unlock(session->channel);
2919                 break;
2920         case 183:
2921                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2922                 break;
2923         case 200:
2924                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2925                 break;
2926         default:
2927                 break;
2928         }
2929 }
2930
2931 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2932 {
2933         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2934                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2935                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2936                 }
2937         }
2938         return 0;
2939 }
2940
2941 static int update_devstate(void *obj, void *arg, int flags)
2942 {
2943         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2944                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2945         return 0;
2946 }
2947
2948 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2949         .name = "PJSIP_DIAL_CONTACTS",
2950         .read = pjsip_acf_dial_contacts_read,
2951 };
2952
2953 static struct ast_custom_function media_offer_function = {
2954         .name = "PJSIP_MEDIA_OFFER",
2955         .read = pjsip_acf_media_offer_read,
2956         .write = pjsip_acf_media_offer_write
2957 };
2958
2959 static struct ast_custom_function dtmf_mode_function = {
2960         .name = "PJSIP_DTMF_MODE",
2961         .read = pjsip_acf_dtmf_mode_read,
2962         .write = pjsip_acf_dtmf_mode_write
2963 };
2964
2965 static struct ast_custom_function session_refresh_function = {
2966         .name = "PJSIP_SEND_SESSION_REFRESH",
2967         .write = pjsip_acf_session_refresh_write,
2968 };
2969
2970 /*!
2971  * \brief Load the module
2972  *
2973  * Module loading including tests for configuration or dependencies.
2974  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2975  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2976  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2977  * configuration file or other non-critical problem return
2978  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2979  */
2980 static int load_module(void)
2981 {
2982         struct ao2_container *endpoints;
2983
2984         CHECK_PJSIP_SESSION_MODULE_LOADED();
2985
2986         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2987                 return AST_MODULE_LOAD_DECLINE;
2988         }
2989
2990         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
2991
2992         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2993
2994         if (ast_channel_register(&chan_pjsip_tech)) {
2995                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2996                 goto end;
2997         }
2998
2999         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
3000                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
3001                 goto end;
3002         }
3003
3004         if (ast_custom_function_register(&media_offer_function)) {
3005                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
3006                 goto end;
3007         }
3008
3009         if (ast_custom_function_register(&dtmf_mode_function)) {
3010                 ast_log(LOG_WARNING, "Unable to register PJSIP_DTMF_MODE dialplan function\n");
3011                 goto end;
3012         }
3013
3014         if (ast_custom_function_register(&session_refresh_function)) {
3015                 ast_log(LOG_WARNING, "Unable to register PJSIP_SEND_SESSION_REFRESH dialplan function\n");
3016                 goto end;
3017         }
3018
3019         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
3020                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
3021                 goto end;
3022         }
3023
3024         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
3025                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
3026                         uid_hold_sort_fn, NULL))) {
3027                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
3028                 goto end;
3029         }
3030
3031         if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
3032                 ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
3033                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3034                 goto end;
3035         }
3036
3037         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
3038                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
3039                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3040                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
3041                 goto end;
3042         }
3043
3044         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
3045                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
3046                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
3047                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3048                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
3049                 goto end;
3050         }
3051
3052         if (pjsip_channel_cli_register()) {
3053                 ast_log(LOG_ERROR, "Unable to register PJSIP Channel CLI\n");
3054                 ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3055                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
3056                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3057                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
3058                 goto end;
3059         }
3060
3061         /* since endpoints are loaded before the channel driver their device
3062            states get set to 'invalid', so they need to be updated */
3063         if ((endpoints = ast_sip_get_endpoints())) {
3064                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
3065                 ao2_ref(endpoints, -1);
3066         }
3067
3068         return 0;
3069
3070 end:
3071         ao2_cleanup(pjsip_uids_onhold);
3072         pjsip_uids_onhold = NULL;
3073         ast_custom_function_unregister(&dtmf_mode_function);
3074         ast_custom_function_unregister(&media_offer_function);
3075         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3076         ast_custom_function_unregister(&session_refresh_function);
3077         ast_channel_unregister(&chan_pjsip_tech);
3078         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3079
3080         return AST_MODULE_LOAD_DECLINE;
3081 }
3082
3083 /*! \brief Unload the PJSIP channel from Asterisk */
3084 static int unload_module(void)
3085 {
3086         ao2_cleanup(pjsip_uids_onhold);
3087         pjsip_uids_onhold = NULL;
3088
3089         pjsip_channel_cli_unregister();
3090
3091         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
3092         ast_sip_session_unregister_supplement(&pbx_start_supplement);
3093         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
3094         ast_sip_session_unregister_supplement(&call_pickup_supplement);
3095
3096         ast_custom_function_unregister(&dtmf_mode_function);
3097         ast_custom_function_unregister(&media_offer_function);
3098         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3099         ast_custom_function_unregister(&session_refresh_function);
3100
3101         ast_channel_unregister(&chan_pjsip_tech);
3102         ao2_ref(chan_pjsip_tech.capabilities, -1);
3103         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3104
3105         return 0;
3106 }
3107
3108 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
3109         .support_level = AST_MODULE_SUPPORT_CORE,
3110         .load = load_module,
3111         .unload = unload_module,
3112         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
3113 );