Debian Codegraph @

channels/chan_pjsip.c

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