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