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