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