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