7cab428731ebaa905bf84cd9f86c7194ae51693e
[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->invite_tsx
1376                                 && (session->inv_session->options & PJSIP_INV_SUPPORT_UPDATE)) {
1377                                 method = AST_SIP_SESSION_REFRESH_METHOD_UPDATE;
1378                         }
1379
1380                         /* Only the INVITE method actually needs SDP, UPDATE can do without */
1381                         generate_new_sdp = (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE);
1382
1383                         ast_sip_session_refresh(session, NULL, NULL, NULL, method, generate_new_sdp, NULL);
1384                 }
1385         } else if (session->endpoint->id.rpid_immediate
1386                 && session->inv_session->state != PJSIP_INV_STATE_DISCONNECTED
1387                 && is_colp_update_allowed(session)) {
1388                 int response_code = 0;
1389
1390                 if (ast_channel_state(session->channel) == AST_STATE_RING) {
1391                         response_code = !session->endpoint->inband_progress ? 180 : 183;
1392                 } else if (ast_channel_state(session->channel) == AST_STATE_RINGING) {
1393                         response_code = 183;
1394                 }
1395
1396                 if (response_code) {
1397                         struct pjsip_tx_data *packet = NULL;
1398
1399                         if (pjsip_inv_answer(session->inv_session, response_code, NULL, NULL, &packet) == PJ_SUCCESS) {
1400                                 ast_sip_session_send_response(session, packet);
1401                         }
1402                 }
1403         }
1404
1405 #ifdef HAVE_PJSIP_INV_SESSION_REF
1406         pjsip_inv_dec_ref(session->inv_session);
1407 #endif
1408
1409         ao2_ref(session, -1);
1410         return 0;
1411 }
1412
1413 /*! \brief Callback which changes the value of locally held on the media stream */
1414 static void local_hold_set_state(struct ast_sip_session_media *session_media, unsigned int held)
1415 {
1416         if (session_media) {
1417                 session_media->locally_held = held;
1418         }
1419 }
1420
1421 /*! \brief Update local hold state and send a re-INVITE with the new SDP */
1422 static int remote_send_hold_refresh(struct ast_sip_session *session, unsigned int held)
1423 {
1424         AST_VECTOR_CALLBACK_VOID(&session->active_media_state->sessions, local_hold_set_state, held);
1425         ast_sip_session_refresh(session, NULL, NULL, NULL, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, NULL);
1426         ao2_ref(session, -1);
1427
1428         return 0;
1429 }
1430
1431 /*! \brief Update local hold state to be held */
1432 static int remote_send_hold(void *data)
1433 {
1434         return remote_send_hold_refresh(data, 1);
1435 }
1436
1437 /*! \brief Update local hold state to be unheld */
1438 static int remote_send_unhold(void *data)
1439 {
1440         return remote_send_hold_refresh(data, 0);
1441 }
1442
1443 struct topology_change_refresh_data {
1444         struct ast_sip_session *session;
1445         struct ast_sip_session_media_state *media_state;
1446 };
1447
1448 static void topology_change_refresh_data_free(struct topology_change_refresh_data *refresh_data)
1449 {
1450         ao2_cleanup(refresh_data->session);
1451
1452         ast_sip_session_media_state_free(refresh_data->media_state);
1453         ast_free(refresh_data);
1454 }
1455
1456 static struct topology_change_refresh_data *topology_change_refresh_data_alloc(
1457         struct ast_sip_session *session, const struct ast_stream_topology *topology)
1458 {
1459         struct topology_change_refresh_data *refresh_data;
1460
1461         refresh_data = ast_calloc(1, sizeof(*refresh_data));
1462         if (!refresh_data) {
1463                 return NULL;
1464         }
1465
1466         refresh_data->session = ao2_bump(session);
1467         refresh_data->media_state = ast_sip_session_media_state_alloc();
1468         if (!refresh_data->media_state) {
1469                 topology_change_refresh_data_free(refresh_data);
1470                 return NULL;
1471         }
1472         refresh_data->media_state->topology = ast_stream_topology_clone(topology);
1473         if (!refresh_data->media_state->topology) {
1474                 topology_change_refresh_data_free(refresh_data);
1475                 return NULL;
1476         }
1477
1478         return refresh_data;
1479 }
1480
1481 static int on_topology_change_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
1482 {
1483         if (rdata->msg_info.msg->line.status.code == 200) {
1484                 /* The topology was changed to something new so give notice to what requested
1485                  * it so it queries the channel and updates accordingly.
1486                  */
1487                 if (session->channel) {
1488                         ast_queue_control(session->channel, AST_CONTROL_STREAM_TOPOLOGY_CHANGED);
1489                 }
1490         } else if (rdata->msg_info.msg->line.status.code != 100) {
1491                 /* The topology change failed, so drop the current pending media state */
1492                 ast_sip_session_media_state_reset(session->pending_media_state);
1493         }
1494
1495         return 0;
1496 }
1497
1498 static int send_topology_change_refresh(void *data)
1499 {
1500         struct topology_change_refresh_data *refresh_data = data;
1501         int ret;
1502
1503         ret = ast_sip_session_refresh(refresh_data->session, NULL, NULL, on_topology_change_response,
1504                 AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1, refresh_data->media_state);
1505         refresh_data->media_state = NULL;
1506         topology_change_refresh_data_free(refresh_data);
1507
1508         return ret;
1509 }
1510
1511 static int handle_topology_request_change(struct ast_sip_session *session,
1512         const struct ast_stream_topology *proposed)
1513 {
1514         struct topology_change_refresh_data *refresh_data;
1515         int res;
1516
1517         refresh_data = topology_change_refresh_data_alloc(session, proposed);
1518         if (!refresh_data) {
1519                 return -1;
1520         }
1521
1522         res = ast_sip_push_task(session->serializer, send_topology_change_refresh, refresh_data);
1523         if (res) {
1524                 topology_change_refresh_data_free(refresh_data);
1525         }
1526         return res;
1527 }
1528
1529 /*! \brief Function called by core to ask the channel to indicate some sort of condition */
1530 static int chan_pjsip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
1531 {
1532         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
1533         struct ast_sip_session_media *media;
1534         int response_code = 0;
1535         int res = 0;
1536         char *device_buf;
1537         size_t device_buf_size;
1538         int i;
1539         const struct ast_stream_topology *topology;
1540
1541         switch (condition) {
1542         case AST_CONTROL_RINGING:
1543                 if (ast_channel_state(ast) == AST_STATE_RING) {
1544                         if (channel->session->endpoint->inband_progress) {
1545                                 response_code = 183;
1546                                 res = -1;
1547                         } else {
1548                                 response_code = 180;
1549                         }
1550                 } else {
1551                         res = -1;
1552                 }
1553                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1554                 break;
1555         case AST_CONTROL_BUSY:
1556                 if (ast_channel_state(ast) != AST_STATE_UP) {
1557                         response_code = 486;
1558                 } else {
1559                         res = -1;
1560                 }
1561                 break;
1562         case AST_CONTROL_CONGESTION:
1563                 if (ast_channel_state(ast) != AST_STATE_UP) {
1564                         response_code = 503;
1565                 } else {
1566                         res = -1;
1567                 }
1568                 break;
1569         case AST_CONTROL_INCOMPLETE:
1570                 if (ast_channel_state(ast) != AST_STATE_UP) {
1571                         response_code = 484;
1572                 } else {
1573                         res = -1;
1574                 }
1575                 break;
1576         case AST_CONTROL_PROCEEDING:
1577                 if (ast_channel_state(ast) != AST_STATE_UP) {
1578                         response_code = 100;
1579                 } else {
1580                         res = -1;
1581                 }
1582                 break;
1583         case AST_CONTROL_PROGRESS:
1584                 if (ast_channel_state(ast) != AST_STATE_UP) {
1585                         response_code = 183;
1586                 } else {
1587                         res = -1;
1588                 }
1589                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "PJSIP/%s", ast_sorcery_object_get_id(channel->session->endpoint));
1590                 break;
1591         case AST_CONTROL_VIDUPDATE:
1592                 for (i = 0; i < AST_VECTOR_SIZE(&channel->session->active_media_state->sessions); ++i) {
1593                         media = AST_VECTOR_GET(&channel->session->active_media_state->sessions, i);
1594                         if (!media || media->type != AST_MEDIA_TYPE_VIDEO) {
1595                                 continue;
1596                         }
1597                         if (media->rtp) {
1598                                 /* FIXME: Only use this for VP8. Additional work would have to be done to
1599                                  * fully support other video codecs */
1600
1601                                 if (ast_format_cap_iscompatible_format(ast_channel_nativeformats(ast), ast_format_vp8) != AST_FORMAT_CMP_NOT_EQUAL) {
1602                                         /* FIXME Fake RTP write, this will be sent as an RTCP packet. Ideally the
1603                                          * RTP engine would provide a way to externally write/schedule RTCP
1604                                          * packets */
1605                                         struct ast_frame fr;
1606                                         fr.frametype = AST_FRAME_CONTROL;
1607                                         fr.subclass.integer = AST_CONTROL_VIDUPDATE;
1608                                         res = ast_rtp_instance_write(media->rtp, &fr);
1609                                 } else {
1610                                         ao2_ref(channel->session, +1);
1611 #ifdef HAVE_PJSIP_INV_SESSION_REF
1612                                         if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1613                                                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1614                                                 ao2_cleanup(channel->session);
1615                                         } else {
1616 #endif
1617                                                 if (ast_sip_push_task(channel->session->serializer, transmit_info_with_vidupdate, channel->session)) {
1618                                                         ao2_cleanup(channel->session);
1619                                                 }
1620 #ifdef HAVE_PJSIP_INV_SESSION_REF
1621                                         }
1622 #endif
1623                                 }
1624                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Success");
1625                         } else {
1626                                 ast_test_suite_event_notify("AST_CONTROL_VIDUPDATE", "Result: Failure");
1627                                 res = -1;
1628                         }
1629                 }
1630                 /* XXX If there were no video streams, then this should set
1631                  * res to -1
1632                  */
1633                 break;
1634         case AST_CONTROL_CONNECTED_LINE:
1635                 ao2_ref(channel->session, +1);
1636 #ifdef HAVE_PJSIP_INV_SESSION_REF
1637                 if (pjsip_inv_add_ref(channel->session->inv_session) != PJ_SUCCESS) {
1638                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1639                         ao2_cleanup(channel->session);
1640                         return -1;
1641                 }
1642 #endif
1643                 if (ast_sip_push_task(channel->session->serializer, update_connected_line_information, channel->session)) {
1644 #ifdef HAVE_PJSIP_INV_SESSION_REF
1645                         pjsip_inv_dec_ref(channel->session->inv_session);
1646 #endif
1647                         ao2_cleanup(channel->session);
1648                 }
1649                 break;
1650         case AST_CONTROL_UPDATE_RTP_PEER:
1651                 break;
1652         case AST_CONTROL_PVT_CAUSE_CODE:
1653                 res = -1;
1654                 break;
1655         case AST_CONTROL_MASQUERADE_NOTIFY:
1656                 ast_assert(datalen == sizeof(int));
1657                 if (*(int *) data) {
1658                         /*
1659                          * Masquerade is beginning:
1660                          * Wait for session serializer to get suspended.
1661                          */
1662                         ast_channel_unlock(ast);
1663                         ast_sip_session_suspend(channel->session);
1664                         ast_channel_lock(ast);
1665                 } else {
1666                         /*
1667                          * Masquerade is complete:
1668                          * Unsuspend the session serializer.
1669                          */
1670                         ast_sip_session_unsuspend(channel->session);
1671                 }
1672                 break;
1673         case AST_CONTROL_HOLD:
1674                 chan_pjsip_add_hold(ast_channel_uniqueid(ast));
1675                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1676                 device_buf = alloca(device_buf_size);
1677                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1678                 ast_devstate_changed_literal(AST_DEVICE_ONHOLD, 1, device_buf);
1679                 if (!channel->session->endpoint->moh_passthrough) {
1680                         ast_moh_start(ast, data, NULL);
1681                 } else {
1682                         if (ast_sip_push_task(channel->session->serializer, remote_send_hold, ao2_bump(channel->session))) {
1683                                 ast_log(LOG_WARNING, "Could not queue task to remotely put session '%s' on hold with endpoint '%s'\n",
1684                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1685                                 ao2_ref(channel->session, -1);
1686                         }
1687                 }
1688                 break;
1689         case AST_CONTROL_UNHOLD:
1690                 chan_pjsip_remove_hold(ast_channel_uniqueid(ast));
1691                 device_buf_size = strlen(ast_channel_name(ast)) + 1;
1692                 device_buf = alloca(device_buf_size);
1693                 ast_channel_get_device_name(ast, device_buf, device_buf_size);
1694                 ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, 1, device_buf);
1695                 if (!channel->session->endpoint->moh_passthrough) {
1696                         ast_moh_stop(ast);
1697                 } else {
1698                         if (ast_sip_push_task(channel->session->serializer, remote_send_unhold, ao2_bump(channel->session))) {
1699                                 ast_log(LOG_WARNING, "Could not queue task to remotely take session '%s' off hold with endpoint '%s'\n",
1700                                         ast_sorcery_object_get_id(channel->session), ast_sorcery_object_get_id(channel->session->endpoint));
1701                                 ao2_ref(channel->session, -1);
1702                         }
1703                 }
1704                 break;
1705         case AST_CONTROL_SRCUPDATE:
1706                 break;
1707         case AST_CONTROL_SRCCHANGE:
1708                 break;
1709         case AST_CONTROL_REDIRECTING:
1710                 if (ast_channel_state(ast) != AST_STATE_UP) {
1711                         response_code = 181;
1712                 } else {
1713                         res = -1;
1714                 }
1715                 break;
1716         case AST_CONTROL_T38_PARAMETERS:
1717                 res = 0;
1718
1719                 if (channel->session->t38state == T38_PEER_REINVITE) {
1720                         const struct ast_control_t38_parameters *parameters = data;
1721
1722                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
1723                                 res = AST_T38_REQUEST_PARMS;
1724                         }
1725                 }
1726
1727                 break;
1728         case AST_CONTROL_STREAM_TOPOLOGY_REQUEST_CHANGE:
1729                 topology = data;
1730                 res = handle_topology_request_change(channel->session, topology);
1731                 break;
1732         case -1:
1733                 res = -1;
1734                 break;
1735         default:
1736                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1737                 res = -1;
1738                 break;
1739         }
1740
1741         if (response_code) {
1742                 struct indicate_data *ind_data = indicate_data_alloc(channel->session, condition, response_code, data, datalen);
1743
1744                 if (!ind_data) {
1745                         return -1;
1746                 }
1747 #ifdef HAVE_PJSIP_INV_SESSION_REF
1748                 if (pjsip_inv_add_ref(ind_data->session->inv_session) != PJ_SUCCESS) {
1749                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1750                         ao2_cleanup(ind_data);
1751                         return -1;
1752                 }
1753 #endif
1754                 if (ast_sip_push_task(channel->session->serializer, indicate, ind_data)) {
1755                         ast_log(LOG_NOTICE, "Cannot send response code %d to endpoint %s. Could not queue task properly\n",
1756                                         response_code, ast_sorcery_object_get_id(channel->session->endpoint));
1757 #ifdef HAVE_PJSIP_INV_SESSION_REF
1758                         pjsip_inv_dec_ref(ind_data->session->inv_session);
1759 #endif
1760                         ao2_cleanup(ind_data);
1761                         res = -1;
1762                 }
1763         }
1764
1765         return res;
1766 }
1767
1768 struct transfer_data {
1769         struct ast_sip_session *session;
1770         char *target;
1771 };
1772
1773 static void transfer_data_destroy(void *obj)
1774 {
1775         struct transfer_data *trnf_data = obj;
1776
1777         ast_free(trnf_data->target);
1778         ao2_cleanup(trnf_data->session);
1779 }
1780
1781 static struct transfer_data *transfer_data_alloc(struct ast_sip_session *session, const char *target)
1782 {
1783         struct transfer_data *trnf_data = ao2_alloc(sizeof(*trnf_data), transfer_data_destroy);
1784
1785         if (!trnf_data) {
1786                 return NULL;
1787         }
1788
1789         if (!(trnf_data->target = ast_strdup(target))) {
1790                 ao2_ref(trnf_data, -1);
1791                 return NULL;
1792         }
1793
1794         ao2_ref(session, +1);
1795         trnf_data->session = session;
1796
1797         return trnf_data;
1798 }
1799
1800 static void transfer_redirect(struct ast_sip_session *session, const char *target)
1801 {
1802         pjsip_tx_data *packet;
1803         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1804         pjsip_contact_hdr *contact;
1805         pj_str_t tmp;
1806
1807         if (pjsip_inv_end_session(session->inv_session, 302, NULL, &packet) != PJ_SUCCESS
1808                 || !packet) {
1809                 ast_log(LOG_WARNING, "Failed to redirect PJSIP session for channel %s\n",
1810                         ast_channel_name(session->channel));
1811                 message = AST_TRANSFER_FAILED;
1812                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1813
1814                 return;
1815         }
1816
1817         if (!(contact = pjsip_msg_find_hdr(packet->msg, PJSIP_H_CONTACT, NULL))) {
1818                 contact = pjsip_contact_hdr_create(packet->pool);
1819         }
1820
1821         pj_strdup2_with_null(packet->pool, &tmp, target);
1822         if (!(contact->uri = pjsip_parse_uri(packet->pool, tmp.ptr, tmp.slen, PJSIP_PARSE_URI_AS_NAMEADDR))) {
1823                 ast_log(LOG_WARNING, "Failed to parse destination URI '%s' for channel %s\n",
1824                         target, ast_channel_name(session->channel));
1825                 message = AST_TRANSFER_FAILED;
1826                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1827                 pjsip_tx_data_dec_ref(packet);
1828
1829                 return;
1830         }
1831         pjsip_msg_add_hdr(packet->msg, (pjsip_hdr *) contact);
1832
1833         ast_sip_session_send_response(session, packet);
1834         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1835 }
1836
1837 static void transfer_refer(struct ast_sip_session *session, const char *target)
1838 {
1839         pjsip_evsub *sub;
1840         enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
1841         pj_str_t tmp;
1842         pjsip_tx_data *packet;
1843         const char *ref_by_val;
1844         char local_info[pj_strlen(&session->inv_session->dlg->local.info_str) + 1];
1845
1846         if (pjsip_xfer_create_uac(session->inv_session->dlg, NULL, &sub) != PJ_SUCCESS) {
1847                 message = AST_TRANSFER_FAILED;
1848                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1849
1850                 return;
1851         }
1852
1853         if (pjsip_xfer_initiate(sub, pj_cstr(&tmp, target), &packet) != PJ_SUCCESS) {
1854                 message = AST_TRANSFER_FAILED;
1855                 ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1856                 pjsip_evsub_terminate(sub, PJ_FALSE);
1857
1858                 return;
1859         }
1860
1861         ref_by_val = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
1862         if (!ast_strlen_zero(ref_by_val)) {
1863                 ast_sip_add_header(packet, "Referred-By", ref_by_val);
1864         } else {
1865                 ast_copy_pj_str(local_info, &session->inv_session->dlg->local.info_str, sizeof(local_info));
1866                 ast_sip_add_header(packet, "Referred-By", local_info);
1867         }
1868
1869         pjsip_xfer_send_request(sub, packet);
1870         ast_queue_control_data(session->channel, AST_CONTROL_TRANSFER, &message, sizeof(message));
1871 }
1872
1873 static int transfer(void *data)
1874 {
1875         struct transfer_data *trnf_data = data;
1876         struct ast_sip_endpoint *endpoint = NULL;
1877         struct ast_sip_contact *contact = NULL;
1878         const char *target = trnf_data->target;
1879
1880         if (trnf_data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1881                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
1882                         trnf_data->session->inv_session->cause,
1883                         pjsip_get_status_text(trnf_data->session->inv_session->cause)->ptr);
1884         } else {
1885                 /* See if we have an endpoint; if so, use its contact */
1886                 endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", target);
1887                 if (endpoint) {
1888                         contact = ast_sip_location_retrieve_contact_from_aor_list(endpoint->aors);
1889                         if (contact && !ast_strlen_zero(contact->uri)) {
1890                                 target = contact->uri;
1891                         }
1892                 }
1893
1894                 if (ast_channel_state(trnf_data->session->channel) == AST_STATE_RING) {
1895                         transfer_redirect(trnf_data->session, target);
1896                 } else {
1897                         transfer_refer(trnf_data->session, target);
1898                 }
1899         }
1900
1901 #ifdef HAVE_PJSIP_INV_SESSION_REF
1902         pjsip_inv_dec_ref(trnf_data->session->inv_session);
1903 #endif
1904
1905         ao2_ref(trnf_data, -1);
1906         ao2_cleanup(endpoint);
1907         ao2_cleanup(contact);
1908         return 0;
1909 }
1910
1911 /*! \brief Function called by core for Asterisk initiated transfer */
1912 static int chan_pjsip_transfer(struct ast_channel *chan, const char *target)
1913 {
1914         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1915         struct transfer_data *trnf_data = transfer_data_alloc(channel->session, target);
1916
1917         if (!trnf_data) {
1918                 return -1;
1919         }
1920
1921 #ifdef HAVE_PJSIP_INV_SESSION_REF
1922         if (pjsip_inv_add_ref(trnf_data->session->inv_session) != PJ_SUCCESS) {
1923                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
1924                 ao2_cleanup(trnf_data);
1925                 return -1;
1926         }
1927 #endif
1928
1929         if (ast_sip_push_task(channel->session->serializer, transfer, trnf_data)) {
1930                 ast_log(LOG_WARNING, "Error requesting transfer\n");
1931 #ifdef HAVE_PJSIP_INV_SESSION_REF
1932                 pjsip_inv_dec_ref(trnf_data->session->inv_session);
1933 #endif
1934                 ao2_cleanup(trnf_data);
1935                 return -1;
1936         }
1937
1938         return 0;
1939 }
1940
1941 /*! \brief Function called by core to start a DTMF digit */
1942 static int chan_pjsip_digit_begin(struct ast_channel *chan, char digit)
1943 {
1944         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(chan);
1945         struct ast_sip_session_media *media;
1946         int res = 0;
1947
1948         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
1949
1950         switch (channel->session->endpoint->dtmf) {
1951         case AST_SIP_DTMF_RFC_4733:
1952                 if (!media || !media->rtp) {
1953                         return -1;
1954                 }
1955
1956                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1957                 break;
1958         case AST_SIP_DTMF_AUTO:
1959                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
1960                         return -1;
1961                 }
1962
1963                 ast_rtp_instance_dtmf_begin(media->rtp, digit);
1964                 break;
1965         case AST_SIP_DTMF_NONE:
1966                 break;
1967         case AST_SIP_DTMF_INBAND:
1968                 res = -1;
1969                 break;
1970         default:
1971                 break;
1972         }
1973
1974         return res;
1975 }
1976
1977 struct info_dtmf_data {
1978         struct ast_sip_session *session;
1979         char digit;
1980         unsigned int duration;
1981 };
1982
1983 static void info_dtmf_data_destroy(void *obj)
1984 {
1985         struct info_dtmf_data *dtmf_data = obj;
1986         ao2_ref(dtmf_data->session, -1);
1987 }
1988
1989 static struct info_dtmf_data *info_dtmf_data_alloc(struct ast_sip_session *session, char digit, unsigned int duration)
1990 {
1991         struct info_dtmf_data *dtmf_data = ao2_alloc(sizeof(*dtmf_data), info_dtmf_data_destroy);
1992         if (!dtmf_data) {
1993                 return NULL;
1994         }
1995         ao2_ref(session, +1);
1996         dtmf_data->session = session;
1997         dtmf_data->digit = digit;
1998         dtmf_data->duration = duration;
1999         return dtmf_data;
2000 }
2001
2002 static int transmit_info_dtmf(void *data)
2003 {
2004         RAII_VAR(struct info_dtmf_data *, dtmf_data, data, ao2_cleanup);
2005
2006         struct ast_sip_session *session = dtmf_data->session;
2007         struct pjsip_tx_data *tdata;
2008
2009         RAII_VAR(struct ast_str *, body_text, NULL, ast_free_ptr);
2010
2011         struct ast_sip_body body = {
2012                 .type = "application",
2013                 .subtype = "dtmf-relay",
2014         };
2015
2016         if (session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2017                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2018                         session->inv_session->cause,
2019                         pjsip_get_status_text(session->inv_session->cause)->ptr);
2020                 goto failure;
2021         }
2022
2023         if (!(body_text = ast_str_create(32))) {
2024                 ast_log(LOG_ERROR, "Could not allocate buffer for INFO DTMF.\n");
2025                 goto failure;
2026         }
2027         ast_str_set(&body_text, 0, "Signal=%c\r\nDuration=%u\r\n", dtmf_data->digit, dtmf_data->duration);
2028
2029         body.body_text = ast_str_buffer(body_text);
2030
2031         if (ast_sip_create_request("INFO", session->inv_session->dlg, session->endpoint, NULL, NULL, &tdata)) {
2032                 ast_log(LOG_ERROR, "Could not create DTMF INFO request\n");
2033                 goto failure;
2034         }
2035         if (ast_sip_add_body(tdata, &body)) {
2036                 ast_log(LOG_ERROR, "Could not add body to DTMF INFO request\n");
2037                 pjsip_tx_data_dec_ref(tdata);
2038                 goto failure;
2039         }
2040         ast_sip_session_send_request(session, tdata);
2041
2042 #ifdef HAVE_PJSIP_INV_SESSION_REF
2043         pjsip_inv_dec_ref(session->inv_session);
2044 #endif
2045
2046         return 0;
2047
2048 failure:
2049 #ifdef HAVE_PJSIP_INV_SESSION_REF
2050         pjsip_inv_dec_ref(session->inv_session);
2051 #endif
2052         return -1;
2053
2054 }
2055
2056 /*! \brief Function called by core to stop a DTMF digit */
2057 static int chan_pjsip_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
2058 {
2059         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2060         struct ast_sip_session_media *media;
2061         int res = 0;
2062
2063         media = channel->session->active_media_state->default_session[AST_MEDIA_TYPE_AUDIO];
2064
2065         switch (channel->session->endpoint->dtmf) {
2066         case AST_SIP_DTMF_INFO:
2067         {
2068                 struct info_dtmf_data *dtmf_data = info_dtmf_data_alloc(channel->session, digit, duration);
2069
2070                 if (!dtmf_data) {
2071                         return -1;
2072                 }
2073
2074 #ifdef HAVE_PJSIP_INV_SESSION_REF
2075                 if (pjsip_inv_add_ref(dtmf_data->session->inv_session) != PJ_SUCCESS) {
2076                         ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2077                         ao2_cleanup(dtmf_data);
2078                         return -1;
2079                 }
2080 #endif
2081
2082                 if (ast_sip_push_task(channel->session->serializer, transmit_info_dtmf, dtmf_data)) {
2083                         ast_log(LOG_WARNING, "Error sending DTMF via INFO.\n");
2084 #ifdef HAVE_PJSIP_INV_SESSION_REF
2085                         pjsip_inv_dec_ref(dtmf_data->session->inv_session);
2086 #endif
2087                         ao2_cleanup(dtmf_data);
2088                         return -1;
2089                 }
2090                 break;
2091         }
2092         case AST_SIP_DTMF_RFC_4733:
2093                 if (!media || !media->rtp) {
2094                         return -1;
2095                 }
2096
2097                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2098                 break;
2099         case AST_SIP_DTMF_AUTO:
2100                 if (!media || !media->rtp || (ast_rtp_instance_dtmf_mode_get(media->rtp) == AST_RTP_DTMF_MODE_INBAND)) {
2101                         return -1;
2102                 }
2103
2104                 ast_rtp_instance_dtmf_end_with_duration(media->rtp, digit, duration);
2105                 break;
2106
2107         case AST_SIP_DTMF_NONE:
2108                 break;
2109         case AST_SIP_DTMF_INBAND:
2110                 res = -1;
2111                 break;
2112         }
2113
2114         return res;
2115 }
2116
2117 static void update_initial_connected_line(struct ast_sip_session *session)
2118 {
2119         struct ast_party_connected_line connected;
2120
2121         /*
2122          * Use the channel CALLERID() as the initial connected line data.
2123          * The core or a predial handler may have supplied missing values
2124          * from the session->endpoint->id.self about who we are calling.
2125          */
2126         ast_channel_lock(session->channel);
2127         ast_party_id_copy(&session->id, &ast_channel_caller(session->channel)->id);
2128         ast_channel_unlock(session->channel);
2129
2130         /* Supply initial connected line information if available. */
2131         if (!session->id.number.valid && !session->id.name.valid) {
2132                 return;
2133         }
2134
2135         ast_party_connected_line_init(&connected);
2136         connected.id = session->id;
2137         connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
2138
2139         ast_channel_queue_connected_line_update(session->channel, &connected, NULL);
2140 }
2141
2142 static int call(void *data)
2143 {
2144         struct ast_sip_channel_pvt *channel = data;
2145         struct ast_sip_session *session = channel->session;
2146         pjsip_tx_data *tdata;
2147
2148         int res = ast_sip_session_create_invite(session, &tdata);
2149
2150         if (res) {
2151                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2152                 ast_queue_hangup(session->channel);
2153         } else {
2154                 set_channel_on_rtp_instance(session, ast_channel_uniqueid(session->channel));
2155                 update_initial_connected_line(session);
2156                 ast_sip_session_send_request(session, tdata);
2157         }
2158         ao2_ref(channel, -1);
2159         return res;
2160 }
2161
2162 /*! \brief Function called by core to actually start calling a remote party */
2163 static int chan_pjsip_call(struct ast_channel *ast, const char *dest, int timeout)
2164 {
2165         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2166
2167         ao2_ref(channel, +1);
2168         if (ast_sip_push_task(channel->session->serializer, call, channel)) {
2169                 ast_log(LOG_WARNING, "Error attempting to place outbound call to '%s'\n", dest);
2170                 ao2_cleanup(channel);
2171                 return -1;
2172         }
2173
2174         return 0;
2175 }
2176
2177 /*! \brief Internal function which translates from Asterisk cause codes to SIP response codes */
2178 static int hangup_cause2sip(int cause)
2179 {
2180         switch (cause) {
2181         case AST_CAUSE_UNALLOCATED:             /* 1 */
2182         case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2183         case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2184                 return 404;
2185         case AST_CAUSE_CONGESTION:              /* 34 */
2186         case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2187                 return 503;
2188         case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2189                 return 408;
2190         case AST_CAUSE_NO_ANSWER:               /* 19 */
2191         case AST_CAUSE_UNREGISTERED:        /* 20 */
2192                 return 480;
2193         case AST_CAUSE_CALL_REJECTED:           /* 21 */
2194                 return 403;
2195         case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2196                 return 410;
2197         case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2198                 return 480;
2199         case AST_CAUSE_INVALID_NUMBER_FORMAT:
2200                 return 484;
2201         case AST_CAUSE_USER_BUSY:
2202                 return 486;
2203         case AST_CAUSE_FAILURE:
2204                 return 500;
2205         case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2206                 return 501;
2207         case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2208                 return 503;
2209         case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2210                 return 502;
2211         case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2212                 return 488;
2213         case AST_CAUSE_INTERWORKING:    /* Unspecified Interworking issues */
2214                 return 500;
2215         case AST_CAUSE_NOTDEFINED:
2216         default:
2217                 ast_debug(1, "AST hangup cause %d (no match found in PJSIP)\n", cause);
2218                 return 0;
2219         }
2220
2221         /* Never reached */
2222         return 0;
2223 }
2224
2225 struct hangup_data {
2226         int cause;
2227         struct ast_channel *chan;
2228 };
2229
2230 static void hangup_data_destroy(void *obj)
2231 {
2232         struct hangup_data *h_data = obj;
2233
2234         h_data->chan = ast_channel_unref(h_data->chan);
2235 }
2236
2237 static struct hangup_data *hangup_data_alloc(int cause, struct ast_channel *chan)
2238 {
2239         struct hangup_data *h_data = ao2_alloc(sizeof(*h_data), hangup_data_destroy);
2240
2241         if (!h_data) {
2242                 return NULL;
2243         }
2244
2245         h_data->cause = cause;
2246         h_data->chan = ast_channel_ref(chan);
2247
2248         return h_data;
2249 }
2250
2251 /*! \brief Clear a channel from a session along with its PVT */
2252 static void clear_session_and_channel(struct ast_sip_session *session, struct ast_channel *ast)
2253 {
2254         session->channel = NULL;
2255         set_channel_on_rtp_instance(session, "");
2256         ast_channel_tech_pvt_set(ast, NULL);
2257 }
2258
2259 static int hangup(void *data)
2260 {
2261         struct hangup_data *h_data = data;
2262         struct ast_channel *ast = h_data->chan;
2263         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2264         struct ast_sip_session *session = channel->session;
2265         int cause = h_data->cause;
2266
2267         /*
2268          * It's possible that session_terminate might cause the session to be destroyed
2269          * immediately so we need to keep a reference to it so we can NULL session->channel
2270          * afterwards.
2271          */
2272         ast_sip_session_terminate(ao2_bump(session), cause);
2273         clear_session_and_channel(session, ast);
2274         ao2_cleanup(session);
2275         ao2_cleanup(channel);
2276         ao2_cleanup(h_data);
2277         return 0;
2278 }
2279
2280 /*! \brief Function called by core to hang up a PJSIP session */
2281 static int chan_pjsip_hangup(struct ast_channel *ast)
2282 {
2283         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2284         int cause;
2285         struct hangup_data *h_data;
2286
2287         if (!channel || !channel->session) {
2288                 return -1;
2289         }
2290
2291         cause = hangup_cause2sip(ast_channel_hangupcause(channel->session->channel));
2292         h_data = hangup_data_alloc(cause, ast);
2293
2294         if (!h_data) {
2295                 goto failure;
2296         }
2297
2298         if (ast_sip_push_task(channel->session->serializer, hangup, h_data)) {
2299                 ast_log(LOG_WARNING, "Unable to push hangup task to the threadpool. Expect bad things\n");
2300                 goto failure;
2301         }
2302
2303         return 0;
2304
2305 failure:
2306         /* Go ahead and do our cleanup of the session and channel even if we're not going
2307          * to be able to send our SIP request/response
2308          */
2309         clear_session_and_channel(channel->session, ast);
2310         ao2_cleanup(channel);
2311         ao2_cleanup(h_data);
2312
2313         return -1;
2314 }
2315
2316 struct request_data {
2317         struct ast_sip_session *session;
2318         struct ast_stream_topology *topology;
2319         const char *dest;
2320         int cause;
2321 };
2322
2323 static int request(void *obj)
2324 {
2325         struct request_data *req_data = obj;
2326         struct ast_sip_session *session = NULL;
2327         char *tmp = ast_strdupa(req_data->dest), *endpoint_name = NULL, *request_user = NULL;
2328         RAII_VAR(struct ast_sip_endpoint *, endpoint, NULL, ao2_cleanup);
2329
2330         AST_DECLARE_APP_ARGS(args,
2331                 AST_APP_ARG(endpoint);
2332                 AST_APP_ARG(aor);
2333         );
2334
2335         if (ast_strlen_zero(tmp)) {
2336                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty destination\n");
2337                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2338                 return -1;
2339         }
2340
2341         AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
2342
2343         if (ast_sip_get_disable_multi_domain()) {
2344                 /* If a request user has been specified extract it from the endpoint name portion */
2345                 if ((endpoint_name = strchr(args.endpoint, '@'))) {
2346                         request_user = args.endpoint;
2347                         *endpoint_name++ = '\0';
2348                 } else {
2349                         endpoint_name = args.endpoint;
2350                 }
2351
2352                 if (ast_strlen_zero(endpoint_name)) {
2353                         ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2354                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2355                         return -1;
2356                 } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
2357                         ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2358                         req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2359                         return -1;
2360                 }
2361         } else {
2362                 /* First try to find an exact endpoint match, for single (user) or multi-domain (user@domain) */
2363                 endpoint_name = args.endpoint;
2364                 if (ast_strlen_zero(endpoint_name)) {
2365                         ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2366                         req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2367                         return -1;
2368                 } else if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
2369                         /* It seems it's not a multi-domain endpoint or single endpoint exact match,
2370                          * it's possible that it's a SIP trunk with a specified user (user@trunkname),
2371                          * so extract the user before @ sign.
2372                          */
2373                         if ((endpoint_name = strchr(args.endpoint, '@'))) {
2374                                 request_user = args.endpoint;
2375                                 *endpoint_name++ = '\0';
2376                         }
2377
2378                         if (ast_strlen_zero(endpoint_name)) {
2379                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel with empty endpoint name\n");
2380                                 req_data->cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
2381                                 return -1;
2382                         }
2383
2384                         if (!(endpoint = ast_sorcery_retrieve_by_id(ast_sip_get_sorcery(), "endpoint", endpoint_name))) {
2385                                 ast_log(LOG_ERROR, "Unable to create PJSIP channel - endpoint '%s' was not found\n", endpoint_name);
2386                                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2387                                 return -1;
2388                         }
2389                 }
2390         }
2391
2392         if (!(session = ast_sip_session_create_outgoing(endpoint, NULL, args.aor, request_user, req_data->topology))) {
2393                 ast_log(LOG_ERROR, "Failed to create outgoing session to endpoint '%s'\n", endpoint_name);
2394                 req_data->cause = AST_CAUSE_NO_ROUTE_DESTINATION;
2395                 return -1;
2396         }
2397
2398         req_data->session = session;
2399
2400         return 0;
2401 }
2402
2403 /*! \brief Function called by core to create a new outgoing PJSIP session */
2404 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)
2405 {
2406         struct request_data req_data;
2407         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2408
2409         req_data.topology = topology;
2410         req_data.dest = data;
2411
2412         if (ast_sip_push_task_synchronous(NULL, request, &req_data)) {
2413                 *cause = req_data.cause;
2414                 return NULL;
2415         }
2416
2417         session = req_data.session;
2418
2419         if (!(session->channel = chan_pjsip_new(session, AST_STATE_DOWN, NULL, NULL, assignedids, requestor, NULL))) {
2420                 /* Session needs to be terminated prematurely */
2421                 return NULL;
2422         }
2423
2424         return session->channel;
2425 }
2426
2427 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)
2428 {
2429         struct ast_stream_topology *topology;
2430         struct ast_channel *chan;
2431
2432         topology = ast_stream_topology_create_from_format_cap(cap);
2433         if (!topology) {
2434                 return NULL;
2435         }
2436
2437         chan = chan_pjsip_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
2438
2439         ast_stream_topology_free(topology);
2440
2441         return chan;
2442 }
2443
2444 struct sendtext_data {
2445         struct ast_sip_session *session;
2446         char text[0];
2447 };
2448
2449 static void sendtext_data_destroy(void *obj)
2450 {
2451         struct sendtext_data *data = obj;
2452         ao2_ref(data->session, -1);
2453 }
2454
2455 static struct sendtext_data* sendtext_data_create(struct ast_sip_session *session, const char *text)
2456 {
2457         int size = strlen(text) + 1;
2458         struct sendtext_data *data = ao2_alloc(sizeof(*data)+size, sendtext_data_destroy);
2459
2460         if (!data) {
2461                 return NULL;
2462         }
2463
2464         data->session = session;
2465         ao2_ref(data->session, +1);
2466         ast_copy_string(data->text, text, size);
2467         return data;
2468 }
2469
2470 static int sendtext(void *obj)
2471 {
2472         RAII_VAR(struct sendtext_data *, data, obj, ao2_cleanup);
2473         pjsip_tx_data *tdata;
2474
2475         const struct ast_sip_body body = {
2476                 .type = "text",
2477                 .subtype = "plain",
2478                 .body_text = data->text
2479         };
2480
2481         if (data->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2482                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2483                         data->session->inv_session->cause,
2484                         pjsip_get_status_text(data->session->inv_session->cause)->ptr);
2485         } else {
2486                 ast_debug(3, "Sending in dialog SIP message\n");
2487
2488                 ast_sip_create_request("MESSAGE", data->session->inv_session->dlg, data->session->endpoint, NULL, NULL, &tdata);
2489                 ast_sip_add_body(tdata, &body);
2490                 ast_sip_send_request(tdata, data->session->inv_session->dlg, data->session->endpoint, NULL, NULL);
2491         }
2492
2493 #ifdef HAVE_PJSIP_INV_SESSION_REF
2494         pjsip_inv_dec_ref(data->session->inv_session);
2495 #endif
2496
2497         return 0;
2498 }
2499
2500 /*! \brief Function called by core to send text on PJSIP session */
2501 static int chan_pjsip_sendtext(struct ast_channel *ast, const char *text)
2502 {
2503         struct ast_sip_channel_pvt *channel = ast_channel_tech_pvt(ast);
2504         struct sendtext_data *data = sendtext_data_create(channel->session, text);
2505
2506         if (!data) {
2507                 return -1;
2508         }
2509
2510 #ifdef HAVE_PJSIP_INV_SESSION_REF
2511         if (pjsip_inv_add_ref(data->session->inv_session) != PJ_SUCCESS) {
2512                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2513                 ao2_ref(data, -1);
2514                 return -1;
2515         }
2516 #endif
2517
2518         if (ast_sip_push_task(channel->session->serializer, sendtext, data)) {
2519 #ifdef HAVE_PJSIP_INV_SESSION_REF
2520                 pjsip_inv_dec_ref(data->session->inv_session);
2521 #endif
2522                 ao2_ref(data, -1);
2523                 return -1;
2524         }
2525         return 0;
2526 }
2527
2528 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
2529 static int hangup_sip2cause(int cause)
2530 {
2531         /* Possible values taken from causes.h */
2532
2533         switch(cause) {
2534         case 401:       /* Unauthorized */
2535                 return AST_CAUSE_CALL_REJECTED;
2536         case 403:       /* Not found */
2537                 return AST_CAUSE_CALL_REJECTED;
2538         case 404:       /* Not found */
2539                 return AST_CAUSE_UNALLOCATED;
2540         case 405:       /* Method not allowed */
2541                 return AST_CAUSE_INTERWORKING;
2542         case 407:       /* Proxy authentication required */
2543                 return AST_CAUSE_CALL_REJECTED;
2544         case 408:       /* No reaction */
2545                 return AST_CAUSE_NO_USER_RESPONSE;
2546         case 409:       /* Conflict */
2547                 return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
2548         case 410:       /* Gone */
2549                 return AST_CAUSE_NUMBER_CHANGED;
2550         case 411:       /* Length required */
2551                 return AST_CAUSE_INTERWORKING;
2552         case 413:       /* Request entity too large */
2553                 return AST_CAUSE_INTERWORKING;
2554         case 414:       /* Request URI too large */
2555                 return AST_CAUSE_INTERWORKING;
2556         case 415:       /* Unsupported media type */
2557                 return AST_CAUSE_INTERWORKING;
2558         case 420:       /* Bad extension */
2559                 return AST_CAUSE_NO_ROUTE_DESTINATION;
2560         case 480:       /* No answer */
2561                 return AST_CAUSE_NO_ANSWER;
2562         case 481:       /* No answer */
2563                 return AST_CAUSE_INTERWORKING;
2564         case 482:       /* Loop detected */
2565                 return AST_CAUSE_INTERWORKING;
2566         case 483:       /* Too many hops */
2567                 return AST_CAUSE_NO_ANSWER;
2568         case 484:       /* Address incomplete */
2569                 return AST_CAUSE_INVALID_NUMBER_FORMAT;
2570         case 485:       /* Ambiguous */
2571                 return AST_CAUSE_UNALLOCATED;
2572         case 486:       /* Busy everywhere */
2573                 return AST_CAUSE_BUSY;
2574         case 487:       /* Request terminated */
2575                 return AST_CAUSE_INTERWORKING;
2576         case 488:       /* No codecs approved */
2577                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2578         case 491:       /* Request pending */
2579                 return AST_CAUSE_INTERWORKING;
2580         case 493:       /* Undecipherable */
2581                 return AST_CAUSE_INTERWORKING;
2582         case 500:       /* Server internal failure */
2583                 return AST_CAUSE_FAILURE;
2584         case 501:       /* Call rejected */
2585                 return AST_CAUSE_FACILITY_REJECTED;
2586         case 502:
2587                 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2588         case 503:       /* Service unavailable */
2589                 return AST_CAUSE_CONGESTION;
2590         case 504:       /* Gateway timeout */
2591                 return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
2592         case 505:       /* SIP version not supported */
2593                 return AST_CAUSE_INTERWORKING;
2594         case 600:       /* Busy everywhere */
2595                 return AST_CAUSE_USER_BUSY;
2596         case 603:       /* Decline */
2597                 return AST_CAUSE_CALL_REJECTED;
2598         case 604:       /* Does not exist anywhere */
2599                 return AST_CAUSE_UNALLOCATED;
2600         case 606:       /* Not acceptable */
2601                 return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2602         default:
2603                 if (cause < 500 && cause >= 400) {
2604                         /* 4xx class error that is unknown - someting wrong with our request */
2605                         return AST_CAUSE_INTERWORKING;
2606                 } else if (cause < 600 && cause >= 500) {
2607                         /* 5xx class error - problem in the remote end */
2608                         return AST_CAUSE_CONGESTION;
2609                 } else if (cause < 700 && cause >= 600) {
2610                         /* 6xx - global errors in the 4xx class */
2611                         return AST_CAUSE_INTERWORKING;
2612                 }
2613                 return AST_CAUSE_NORMAL;
2614         }
2615         /* Never reached */
2616         return 0;
2617 }
2618
2619 static void chan_pjsip_session_begin(struct ast_sip_session *session)
2620 {
2621         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2622
2623         if (session->endpoint->media.direct_media.glare_mitigation ==
2624                         AST_SIP_DIRECT_MEDIA_GLARE_MITIGATION_NONE) {
2625                 return;
2626         }
2627
2628         datastore = ast_sip_session_alloc_datastore(&direct_media_mitigation_info,
2629                         "direct_media_glare_mitigation");
2630
2631         if (!datastore) {
2632                 return;
2633         }
2634
2635         ast_sip_session_add_datastore(session, datastore);
2636 }
2637
2638 /*! \brief Function called when the session ends */
2639 static void chan_pjsip_session_end(struct ast_sip_session *session)
2640 {
2641         if (!session->channel) {
2642                 return;
2643         }
2644
2645         chan_pjsip_remove_hold(ast_channel_uniqueid(session->channel));
2646
2647         ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2648         if (!ast_channel_hangupcause(session->channel) && session->inv_session) {
2649                 int cause = hangup_sip2cause(session->inv_session->cause);
2650
2651                 ast_queue_hangup_with_cause(session->channel, cause);
2652         } else {
2653                 ast_queue_hangup(session->channel);
2654         }
2655 }
2656
2657 /*! \brief Function called when a request is received on the session */
2658 static int chan_pjsip_incoming_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2659 {
2660         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
2661         struct transport_info_data *transport_data;
2662         pjsip_tx_data *packet = NULL;
2663
2664         if (session->channel) {
2665                 return 0;
2666         }
2667
2668         /* Check for a to-tag to determine if this is a reinvite */
2669         if (rdata->msg_info.to->tag.slen) {
2670                 /* Weird case. We've received a reinvite but we don't have a channel. The most
2671                  * typical case for this happening is that a blind transfer fails, and so the
2672                  * transferer attempts to reinvite himself back into the call. We already got
2673                  * rid of that channel, and the other side of the call is unrecoverable.
2674                  *
2675                  * We treat this as a failure, so our best bet is to just hang this call
2676                  * up and not create a new channel. Clearing defer_terminate here ensures that
2677                  * calling ast_sip_session_terminate() can result in a BYE being sent ASAP.
2678                  */
2679                 session->defer_terminate = 0;
2680                 ast_sip_session_terminate(session, 400);
2681                 return -1;
2682         }
2683
2684         datastore = ast_sip_session_alloc_datastore(&transport_info, "transport_info");
2685         if (!datastore) {
2686                 return -1;
2687         }
2688
2689         transport_data = ast_calloc(1, sizeof(*transport_data));
2690         if (!transport_data) {
2691                 return -1;
2692         }
2693         pj_sockaddr_cp(&transport_data->local_addr, &rdata->tp_info.transport->local_addr);
2694         pj_sockaddr_cp(&transport_data->remote_addr, &rdata->pkt_info.src_addr);
2695         datastore->data = transport_data;
2696         ast_sip_session_add_datastore(session, datastore);
2697
2698         if (!(session->channel = chan_pjsip_new(session, AST_STATE_RING, session->exten, NULL, NULL, NULL, NULL))) {
2699                 if (pjsip_inv_end_session(session->inv_session, 503, NULL, &packet) == PJ_SUCCESS
2700                         && packet) {
2701                         ast_sip_session_send_response(session, packet);
2702                 }
2703
2704                 ast_log(LOG_ERROR, "Failed to allocate new PJSIP channel on incoming SIP INVITE\n");
2705                 return -1;
2706         }
2707         /* channel gets created on incoming request, but we wait to call start
2708            so other supplements have a chance to run */
2709         return 0;
2710 }
2711
2712 static int call_pickup_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2713 {
2714         struct ast_features_pickup_config *pickup_cfg;
2715         struct ast_channel *chan;
2716
2717         /* Check for a to-tag to determine if this is a reinvite */
2718         if (rdata->msg_info.to->tag.slen) {
2719                 /* We don't care about reinvites */
2720                 return 0;
2721         }
2722
2723         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2724         if (!pickup_cfg) {
2725                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension.\n");
2726                 return 0;
2727         }
2728
2729         if (strcmp(session->exten, pickup_cfg->pickupexten)) {
2730                 ao2_ref(pickup_cfg, -1);
2731                 return 0;
2732         }
2733         ao2_ref(pickup_cfg, -1);
2734
2735         /* We can't directly use session->channel because the pickup operation will cause a masquerade to occur,
2736          * changing the channel pointer in session to a different channel. To ensure we work on the right channel
2737          * we store a pointer locally before we begin and keep a reference so it remains valid no matter what.
2738          */
2739         chan = ast_channel_ref(session->channel);
2740         if (ast_pickup_call(chan)) {
2741                 ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
2742         } else {
2743                 ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
2744         }
2745         /* A hangup always occurs because the pickup operation will have either failed resulting in the call
2746          * needing to be hung up OR the pickup operation was a success and the channel we now have is actually
2747          * the channel that was replaced, which should be hung up since it is literally in limbo not connected
2748          * to anything at all.
2749          */
2750         ast_hangup(chan);
2751         ast_channel_unref(chan);
2752
2753         return 1;
2754 }
2755
2756 static struct ast_sip_session_supplement call_pickup_supplement = {
2757         .method = "INVITE",
2758         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST - 1,
2759         .incoming_request = call_pickup_incoming_request,
2760 };
2761
2762 static int pbx_start_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2763 {
2764         int res;
2765
2766         /* Check for a to-tag to determine if this is a reinvite */
2767         if (rdata->msg_info.to->tag.slen) {
2768                 /* We don't care about reinvites */
2769                 return 0;
2770         }
2771
2772         res = ast_pbx_start(session->channel);
2773
2774         switch (res) {
2775         case AST_PBX_FAILED:
2776                 ast_log(LOG_WARNING, "Failed to start PBX ;(\n");
2777                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2778                 ast_hangup(session->channel);
2779                 break;
2780         case AST_PBX_CALL_LIMIT:
2781                 ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
2782                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_SWITCH_CONGESTION);
2783                 ast_hangup(session->channel);
2784                 break;
2785         case AST_PBX_SUCCESS:
2786         default:
2787                 break;
2788         }
2789
2790         ast_debug(3, "Started PBX on new PJSIP channel %s\n", ast_channel_name(session->channel));
2791
2792         return (res == AST_PBX_SUCCESS) ? 0 : -1;
2793 }
2794
2795 static struct ast_sip_session_supplement pbx_start_supplement = {
2796         .method = "INVITE",
2797         .priority = AST_SIP_SUPPLEMENT_PRIORITY_LAST,
2798         .incoming_request = pbx_start_incoming_request,
2799 };
2800
2801 /*! \brief Function called when a response is received on the session */
2802 static void chan_pjsip_incoming_response(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2803 {
2804         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2805         struct ast_control_pvt_cause_code *cause_code;
2806         int data_size = sizeof(*cause_code);
2807
2808         if (!session->channel) {
2809                 return;
2810         }
2811
2812         /* Build and send the tech-specific cause information */
2813         /* size of the string making up the cause code is "SIP " number + " " + reason length */
2814         data_size += 4 + 4 + pj_strlen(&status.reason);
2815         cause_code = ast_alloca(data_size);
2816         memset(cause_code, 0, data_size);
2817
2818         ast_copy_string(cause_code->chan_name, ast_channel_name(session->channel), AST_CHANNEL_NAME);
2819
2820         snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %d %.*s", status.code,
2821         (int) pj_strlen(&status.reason), pj_strbuf(&status.reason));
2822
2823         cause_code->ast_cause = hangup_sip2cause(status.code);
2824         ast_queue_control_data(session->channel, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
2825         ast_channel_hangupcause_hash_set(session->channel, cause_code, data_size);
2826
2827         switch (status.code) {
2828         case 180:
2829                 ast_queue_control(session->channel, AST_CONTROL_RINGING);
2830                 ast_channel_lock(session->channel);
2831                 if (ast_channel_state(session->channel) != AST_STATE_UP) {
2832                         ast_setstate(session->channel, AST_STATE_RINGING);
2833                 }
2834                 ast_channel_unlock(session->channel);
2835                 break;
2836         case 183:
2837                 ast_queue_control(session->channel, AST_CONTROL_PROGRESS);
2838                 break;
2839         case 200:
2840                 ast_queue_control(session->channel, AST_CONTROL_ANSWER);
2841                 break;
2842         default:
2843                 break;
2844         }
2845 }
2846
2847 static int chan_pjsip_incoming_ack(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
2848 {
2849         if (rdata->msg_info.msg->line.req.method.id == PJSIP_ACK_METHOD) {
2850                 if (session->endpoint->media.direct_media.enabled && session->channel) {
2851                         ast_queue_control(session->channel, AST_CONTROL_SRCCHANGE);
2852                 }
2853         }
2854         return 0;
2855 }
2856
2857 static int update_devstate(void *obj, void *arg, int flags)
2858 {
2859         ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE,
2860                              "PJSIP/%s", ast_sorcery_object_get_id(obj));
2861         return 0;
2862 }
2863
2864 static struct ast_custom_function chan_pjsip_dial_contacts_function = {
2865         .name = "PJSIP_DIAL_CONTACTS",
2866         .read = pjsip_acf_dial_contacts_read,
2867 };
2868
2869 static struct ast_custom_function media_offer_function = {
2870         .name = "PJSIP_MEDIA_OFFER",
2871         .read = pjsip_acf_media_offer_read,
2872         .write = pjsip_acf_media_offer_write
2873 };
2874
2875 static struct ast_custom_function session_refresh_function = {
2876         .name = "PJSIP_SEND_SESSION_REFRESH",
2877         .write = pjsip_acf_session_refresh_write,
2878 };
2879
2880 /*!
2881  * \brief Load the module
2882  *
2883  * Module loading including tests for configuration or dependencies.
2884  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2885  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2886  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2887  * configuration file or other non-critical problem return
2888  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2889  */
2890 static int load_module(void)
2891 {
2892         struct ao2_container *endpoints;
2893
2894         CHECK_PJSIP_SESSION_MODULE_LOADED();
2895
2896         if (!(chan_pjsip_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
2897                 return AST_MODULE_LOAD_DECLINE;
2898         }
2899
2900         ast_format_cap_append_by_type(chan_pjsip_tech.capabilities, AST_MEDIA_TYPE_AUDIO);
2901
2902         ast_rtp_glue_register(&chan_pjsip_rtp_glue);
2903
2904         if (ast_channel_register(&chan_pjsip_tech)) {
2905                 ast_log(LOG_ERROR, "Unable to register channel class %s\n", channel_type);
2906                 goto end;
2907         }
2908
2909         if (ast_custom_function_register(&chan_pjsip_dial_contacts_function)) {
2910                 ast_log(LOG_ERROR, "Unable to register PJSIP_DIAL_CONTACTS dialplan function\n");
2911                 goto end;
2912         }
2913
2914         if (ast_custom_function_register(&media_offer_function)) {
2915                 ast_log(LOG_WARNING, "Unable to register PJSIP_MEDIA_OFFER dialplan function\n");
2916                 goto end;
2917         }
2918
2919         if (ast_custom_function_register(&session_refresh_function)) {
2920                 ast_log(LOG_WARNING, "Unable to register PJSIP_SEND_SESSION_REFRESH dialplan function\n");
2921                 goto end;
2922         }
2923
2924         if (ast_sip_session_register_supplement(&chan_pjsip_supplement)) {
2925                 ast_log(LOG_ERROR, "Unable to register PJSIP supplement\n");
2926                 goto end;
2927         }
2928
2929         if (!(pjsip_uids_onhold = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_RWLOCK,
2930                         AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, 37, uid_hold_hash_fn,
2931                         uid_hold_sort_fn, NULL))) {
2932                 ast_log(LOG_ERROR, "Unable to create held channels container\n");
2933                 goto end;
2934         }
2935
2936         if (ast_sip_session_register_supplement(&call_pickup_supplement)) {
2937                 ast_log(LOG_ERROR, "Unable to register PJSIP call pickup supplement\n");
2938                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2939                 goto end;
2940         }
2941
2942         if (ast_sip_session_register_supplement(&pbx_start_supplement)) {
2943                 ast_log(LOG_ERROR, "Unable to register PJSIP pbx start supplement\n");
2944                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2945                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2946                 goto end;
2947         }
2948
2949         if (ast_sip_session_register_supplement(&chan_pjsip_ack_supplement)) {
2950                 ast_log(LOG_ERROR, "Unable to register PJSIP ACK supplement\n");
2951                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2952                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2953                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2954                 goto end;
2955         }
2956
2957         if (pjsip_channel_cli_register()) {
2958                 ast_log(LOG_ERROR, "Unable to register PJSIP Channel CLI\n");
2959                 ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2960                 ast_sip_session_unregister_supplement(&pbx_start_supplement);
2961                 ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2962                 ast_sip_session_unregister_supplement(&call_pickup_supplement);
2963                 goto end;
2964         }
2965
2966         /* since endpoints are loaded before the channel driver their device
2967            states get set to 'invalid', so they need to be updated */
2968         if ((endpoints = ast_sip_get_endpoints())) {
2969                 ao2_callback(endpoints, OBJ_NODATA, update_devstate, NULL);
2970                 ao2_ref(endpoints, -1);
2971         }
2972
2973         return 0;
2974
2975 end:
2976         ao2_cleanup(pjsip_uids_onhold);
2977         pjsip_uids_onhold = NULL;
2978         ast_custom_function_unregister(&media_offer_function);
2979         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
2980         ast_custom_function_unregister(&session_refresh_function);
2981         ast_channel_unregister(&chan_pjsip_tech);
2982         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
2983
2984         return AST_MODULE_LOAD_DECLINE;
2985 }
2986
2987 /*! \brief Unload the PJSIP channel from Asterisk */
2988 static int unload_module(void)
2989 {
2990         ao2_cleanup(pjsip_uids_onhold);
2991         pjsip_uids_onhold = NULL;
2992
2993         pjsip_channel_cli_unregister();
2994
2995         ast_sip_session_unregister_supplement(&chan_pjsip_supplement);
2996         ast_sip_session_unregister_supplement(&pbx_start_supplement);
2997         ast_sip_session_unregister_supplement(&chan_pjsip_ack_supplement);
2998         ast_sip_session_unregister_supplement(&call_pickup_supplement);
2999
3000         ast_custom_function_unregister(&media_offer_function);
3001         ast_custom_function_unregister(&chan_pjsip_dial_contacts_function);
3002         ast_custom_function_unregister(&session_refresh_function);
3003
3004         ast_channel_unregister(&chan_pjsip_tech);
3005         ao2_ref(chan_pjsip_tech.capabilities, -1);
3006         ast_rtp_glue_unregister(&chan_pjsip_rtp_glue);
3007
3008         return 0;
3009 }
3010
3011 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Channel Driver",
3012         .support_level = AST_MODULE_SUPPORT_CORE,
3013         .load = load_module,
3014         .unload = unload_module,
3015         .load_pri = AST_MODPRI_CHANNEL_DRIVER,
3016 );