Asterisk - The Open Source Telephony Project GIT-master-85241bd
res_pjsip_session.c
Go to the documentation of this file.
1/*
2* Asterisk -- An open source telephony toolkit.
3*
4* Copyright (C) 2013, Digium, Inc.
5*
6* Mark Michelson <mmichelson@digium.com>
7*
8* See http://www.asterisk.org for more information about
9* the Asterisk project. Please do not directly contact
10* any of the maintainers of this project for assistance;
11* the project provides a web site, mailing lists and IRC
12* channels for your use.
13*
14* This program is free software, distributed under the terms of
15* the GNU General Public License Version 2. See the LICENSE file
16* at the top of the source tree.
17*/
18
19/*** MODULEINFO
20 <depend>pjproject</depend>
21 <depend>res_pjsip</depend>
22 <support_level>core</support_level>
23 ***/
24
25#include "asterisk.h"
26
27#include <pjsip.h>
28#include <pjsip_ua.h>
29#include <pjlib.h>
30#include <pjmedia.h>
31
32#include "asterisk/res_pjsip.h"
35#include "asterisk/callerid.h"
36#include "asterisk/datastore.h"
37#include "asterisk/module.h"
38#include "asterisk/logger.h"
39#include "asterisk/res_pjsip.h"
40#include "asterisk/astobj2.h"
41#include "asterisk/lock.h"
42#include "asterisk/uuid.h"
43#include "asterisk/pbx.h"
45#include "asterisk/causes.h"
46#include "asterisk/sdp_srtp.h"
47#include "asterisk/dsp.h"
48#include "asterisk/acl.h"
50#include "asterisk/pickup.h"
51#include "asterisk/test.h"
52#include "asterisk/stream.h"
53#include "asterisk/vector.h"
54
56
57#define SDP_HANDLER_BUCKETS 11
58
59#define MOD_DATA_ON_RESPONSE "on_response"
60#define MOD_DATA_NAT_HOOK "nat_hook"
61
62/* Most common case is one audio and one video stream */
63#define DEFAULT_NUM_SESSION_MEDIA 2
64
65/* Some forward declarations */
67static void handle_session_end(struct ast_sip_session *session);
69static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata);
70static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
71 enum ast_sip_session_response_priority response_priority);
72static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,
73 enum ast_sip_session_response_priority response_priority);
74static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);
75static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);
77 ast_sip_session_request_creation_cb on_request_creation,
78 ast_sip_session_sdp_creation_cb on_sdp_creation,
80 enum ast_sip_session_refresh_method method, int generate_new_sdp,
81 struct ast_sip_session_media_state *pending_media_state,
82 struct ast_sip_session_media_state *active_media_state,
83 int queued);
84
85/*! \brief NAT hook for modifying outgoing messages with SDP */
87
88/*!
89 * \brief Registered SDP stream handlers
90 *
91 * This container is keyed on stream types. Each
92 * object in the container is a linked list of
93 * handlers for the stream type.
94 */
96
97/*!
98 * These are the objects in the sdp_handlers container
99 */
101 /* The list of handlers to visit */
103 /* The handlers in this list handle streams of this type */
104 char stream_type[1];
105};
106
107static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer, const unsigned int ignore_active_stream_topology);
108
109static int sdp_handler_list_hash(const void *obj, int flags)
110{
111 const struct sdp_handler_list *handler_list = obj;
112 const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
113
115}
116
118{
119 if (!session) {
120 return "(null session)";
121 }
122 if (session->channel) {
123 return ast_channel_name(session->channel);
124 } else if (session->endpoint) {
125 return ast_sorcery_object_get_id(session->endpoint);
126 } else {
127 return "unknown";
128 }
129}
130
132{
133 return id->number.valid
134 && (session->endpoint->id.trust_outbound
136}
137
138static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
139{
140 struct sdp_handler_list *handler_list1 = obj;
141 struct sdp_handler_list *handler_list2 = arg;
142 const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;
143
144 return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
145}
146
148{
149 RAII_VAR(struct sdp_handler_list *, handler_list,
152
153 if (handler_list) {
154 struct ast_sip_session_sdp_handler *iter;
155 /* Check if this handler is already registered for this stream type */
156 AST_LIST_TRAVERSE(&handler_list->list, iter, next) {
157 if (!strcmp(iter->id, handler->id)) {
158 ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);
159 return -1;
160 }
161 }
162 AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
163 ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
164
165 return 0;
166 }
167
168 /* No stream of this type has been registered yet, so we need to create a new list */
169 handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);
170 if (!handler_list) {
171 return -1;
172 }
173 /* Safe use of strcpy */
174 strcpy(handler_list->stream_type, stream_type);
175 AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);
176 AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
177 if (!ao2_link(sdp_handlers, handler_list)) {
178 return -1;
179 }
180 ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
181
182 return 0;
183}
184
185static int remove_handler(void *obj, void *arg, void *data, int flags)
186{
187 struct sdp_handler_list *handler_list = obj;
189 struct ast_sip_session_sdp_handler *iter;
190 const char *stream_type = arg;
191
192 AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {
193 if (!strcmp(iter->id, handler->id)) {
195 ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
196 }
197 }
199
200 if (AST_LIST_EMPTY(&handler_list->list)) {
201 ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
202 return CMP_MATCH;
203 } else {
204 return CMP_STOP;
205 }
206}
207
209{
211}
212
214 const struct ast_rtp_instance_stats *vec_elem, const struct ast_rtp_instance_stats *srch)
215{
216 if (vec_elem->local_ssrc == srch->local_ssrc) {
217 return 1;
218 }
219
220 return 0;
221}
222
224 size_t sessions, size_t read_callbacks)
225{
226 struct ast_sip_session_media_state *media_state;
227
228 media_state = ast_calloc(1, sizeof(*media_state));
229 if (!media_state) {
230 return NULL;
231 }
232
233 if (AST_VECTOR_INIT(&media_state->sessions, sessions) < 0) {
234 ast_free(media_state);
235 return NULL;
236 }
237
238 if (AST_VECTOR_INIT(&media_state->read_callbacks, read_callbacks) < 0) {
239 AST_VECTOR_FREE(&media_state->sessions);
240 ast_free(media_state);
241 return NULL;
242 }
243
244 return media_state;
245}
246
248{
251}
252
254{
255 int i;
256 int ret;
257
258 if (!media_state || !sip_session) {
259 return;
260 }
261
262 for (i = 0; i < AST_VECTOR_SIZE(&media_state->sessions); i++) {
263 struct ast_rtp_instance_stats *stats_tmp = NULL;
264 struct ast_sip_session_media *media = AST_VECTOR_GET(&media_state->sessions, i);
265 if (!media || !media->rtp) {
266 continue;
267 }
268
269 stats_tmp = ast_calloc(1, sizeof(struct ast_rtp_instance_stats));
270 if (!stats_tmp) {
271 return;
272 }
273
275 if (ret) {
276 ast_free(stats_tmp);
277 continue;
278 }
279
280 /* remove all the duplicated stats if exist */
282
283 AST_VECTOR_APPEND(&sip_session->media_stats, stats_tmp);
284 }
285}
286
288{
289 int index;
290
291 if (!media_state) {
292 return;
293 }
294
295 AST_VECTOR_RESET(&media_state->sessions, ao2_cleanup);
297
298 for (index = 0; index < AST_MEDIA_TYPE_END; ++index) {
299 media_state->default_session[index] = NULL;
300 }
301
303 media_state->topology = NULL;
304}
305
307{
308 struct ast_sip_session_media_state *cloned;
309 int index;
310
311 if (!media_state) {
312 return NULL;
313 }
314
316 AST_VECTOR_SIZE(&media_state->sessions),
317 AST_VECTOR_SIZE(&media_state->read_callbacks));
318 if (!cloned) {
319 return NULL;
320 }
321
322 if (media_state->topology) {
323 cloned->topology = ast_stream_topology_clone(media_state->topology);
324 if (!cloned->topology) {
326 return NULL;
327 }
328 }
329
330 for (index = 0; index < AST_VECTOR_SIZE(&media_state->sessions); ++index) {
331 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&media_state->sessions, index);
333
334 ao2_bump(session_media);
335 if (AST_VECTOR_REPLACE(&cloned->sessions, index, session_media)) {
336 ao2_cleanup(session_media);
337 }
339 !cloned->default_session[type]) {
340 cloned->default_session[type] = session_media;
341 }
342 }
343
344 for (index = 0; index < AST_VECTOR_SIZE(&media_state->read_callbacks); ++index) {
346
348 }
349
350 return cloned;
351}
352
354{
355 if (!media_state) {
356 return;
357 }
358
359 /* This will reset the internal state so we only have to free persistent things */
361
362 AST_VECTOR_FREE(&media_state->sessions);
363 AST_VECTOR_FREE(&media_state->read_callbacks);
364
365 ast_free(media_state);
366}
367
369{
370 int index;
371
372 if (!session->pending_media_state->topology) {
373 ast_log(LOG_WARNING, "Pending topology was NULL for channel '%s'\n",
374 session->channel ? ast_channel_name(session->channel) : "unknown");
375 return 0;
376 }
377
379 return 0;
380 }
381
382 for (index = 0; index < ast_stream_topology_get_count(session->pending_media_state->topology); ++index) {
383 if (ast_stream_get_type(ast_stream_topology_get_stream(session->pending_media_state->topology, index)) !=
384 ast_stream_get_type(stream)) {
385 continue;
386 }
387
388 return ast_stream_topology_get_stream(session->pending_media_state->topology, index) == stream ? 1 : 0;
389 }
390
391 return 0;
392}
393
395 int fd, ast_sip_session_media_read_cb callback)
396{
397 struct ast_sip_session_media_read_callback_state callback_state = {
398 .fd = fd,
399 .read_callback = callback,
400 .session = session_media,
401 };
402
403 /* The contents of the vector are whole structs and not pointers */
404 return AST_VECTOR_APPEND(&session->pending_media_state->read_callbacks, callback_state);
405}
406
409{
410 if (session_media->write_callback) {
411 if (session_media->write_callback == callback) {
412 return 0;
413 }
414
415 return -1;
416 }
417
418 session_media->write_callback = callback;
419
420 return 0;
421}
422
424{
425 int index;
426
427 if (!session->endpoint->media.bundle || ast_strlen_zero(session_media->mid)) {
428 return session_media;
429 }
430
431 for (index = 0; index < AST_VECTOR_SIZE(&session->pending_media_state->sessions); ++index) {
432 struct ast_sip_session_media *bundle_group_session_media;
433
434 bundle_group_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
435
436 /* The first session which is in the bundle group is considered the authoritative session for transport */
437 if (bundle_group_session_media->bundle_group == session_media->bundle_group) {
438 return bundle_group_session_media;
439 }
440 }
441
442 return session_media;
443}
444
445/*!
446 * \brief Set an SDP stream handler for a corresponding session media.
447 *
448 * \note Always use this function to set the SDP handler for a session media.
449 *
450 * This function will properly free resources on the SDP handler currently being
451 * used by the session media, then set the session media to use the new SDP
452 * handler.
453 */
454static void session_media_set_handler(struct ast_sip_session_media *session_media,
456{
457 ast_assert(session_media->handler != handler);
458
459 if (session_media->handler) {
460 session_media->handler->stream_destroy(session_media);
461 }
462 session_media->handler = handler;
463}
464
465static int stream_destroy(void *obj, void *arg, int flags)
466{
467 struct sdp_handler_list *handler_list = obj;
468 struct ast_sip_session_media *session_media = arg;
470
471 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
472 handler->stream_destroy(session_media);
473 }
474
475 return 0;
476}
477
478static void session_media_dtor(void *obj)
479{
480 struct ast_sip_session_media *session_media = obj;
481
482 /* It is possible for multiple handlers to have allocated memory on the
483 * session media (usually through a stream changing types). Therefore, we
484 * traverse all the SDP handlers and let them all call stream_destroy on
485 * the session_media
486 */
487 ao2_callback(sdp_handlers, 0, stream_destroy, session_media);
488
489 if (session_media->srtp) {
490 ast_sdp_srtp_destroy(session_media->srtp);
491 }
492
493 ast_free(session_media->mid);
494 ast_free(session_media->remote_mslabel);
495 ast_free(session_media->remote_label);
496 ast_free(session_media->stream_name);
497}
498
500 struct ast_sip_session_media_state *media_state, enum ast_media_type type, int position)
501{
502 struct ast_sip_session_media *session_media = NULL;
503 struct ast_sip_session_media *current_session_media = NULL;
504 SCOPE_ENTER(1, "%s Adding position %d\n", ast_sip_session_get_name(session), position);
505
506 /* It is possible for this media state to already contain a session for the stream. If this
507 * is the case we simply return it.
508 */
509 if (position < AST_VECTOR_SIZE(&media_state->sessions)) {
510 current_session_media = AST_VECTOR_GET(&media_state->sessions, position);
511 if (current_session_media && current_session_media->type == type) {
512 SCOPE_EXIT_RTN_VALUE(current_session_media, "Using existing media_session\n");
513 }
514 }
515
516 /* Determine if we can reuse the session media from the active media state if present */
517 if (position < AST_VECTOR_SIZE(&session->active_media_state->sessions)) {
518 session_media = AST_VECTOR_GET(&session->active_media_state->sessions, position);
519 /* A stream can never exist without an accompanying media session */
520 if (session_media->type == type) {
521 ao2_ref(session_media, +1);
522 ast_trace(1, "Reusing existing media session\n");
523 /*
524 * If this session_media was previously removed, its bundle group was probably reset
525 * to -1 so if bundling is enabled on the endpoint, we need to reset it to 0, set
526 * the bundled flag and reset its mid.
527 */
528 if (session->endpoint->media.bundle && session_media->bundle_group == -1) {
529 session_media->bundled = session->endpoint->media.webrtc;
530 session_media->bundle_group = 0;
531 ast_free(session_media->mid);
532 if (ast_asprintf(&session_media->mid, "%s-%d", ast_codec_media_type2str(type), position) < 0) {
533 ao2_ref(session_media, -1);
534 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't alloc mid\n");
535 }
536 }
537 } else {
538 ast_trace(1, "Can't reuse existing media session because the types are different. %s <> %s\n",
540 session_media = NULL;
541 }
542 }
543
544 if (!session_media) {
545 /* No existing media session we can use so create a new one */
546 session_media = ao2_alloc_options(sizeof(*session_media), session_media_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
547 if (!session_media) {
548 return NULL;
549 }
550 ast_trace(1, "Creating new media session\n");
551
552 session_media->encryption = session->endpoint->media.rtp.encryption;
553 session_media->remote_ice = session->endpoint->media.rtp.ice_support;
554 session_media->remote_rtcp_mux = session->endpoint->media.rtcp_mux;
555 session_media->keepalive_sched_id = -1;
556 session_media->timeout_sched_id = -1;
557 session_media->type = type;
558 session_media->stream_num = position;
559
560 if (session->endpoint->media.bundle) {
561 /* This is a new stream so create a new mid based on media type and position, which makes it unique.
562 * If this is the result of an offer the mid will just end up getting replaced.
563 */
564 if (ast_asprintf(&session_media->mid, "%s-%d", ast_codec_media_type2str(type), position) < 0) {
565 ao2_ref(session_media, -1);
566 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't alloc mid\n");
567 }
568 session_media->bundle_group = 0;
569
570 /* Some WebRTC clients can't handle an offer to bundle media streams. Instead they expect them to
571 * already be bundled. Every client handles this scenario though so if WebRTC is enabled just go
572 * ahead and treat the streams as having already been bundled.
573 */
574 session_media->bundled = session->endpoint->media.webrtc;
575 } else {
576 session_media->bundle_group = -1;
577 }
578 }
579
580 ast_free(session_media->stream_name);
581 session_media->stream_name = ast_strdup(ast_stream_get_name(ast_stream_topology_get_stream(media_state->topology, position)));
582
583 if (AST_VECTOR_REPLACE(&media_state->sessions, position, session_media)) {
584 ao2_ref(session_media, -1);
585
586 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't replace media_session\n");
587 }
588
589 ao2_cleanup(current_session_media);
590
591 /* If this stream will be active in some way and it is the first of this type then consider this the default media session to match */
593 ast_trace(1, "Setting media session as default for %s\n", ast_codec_media_type2str(session_media->type));
594
595 media_state->default_session[type] = session_media;
596 }
597
598 SCOPE_EXIT_RTN_VALUE(session_media, "Done\n");
599}
600
601static int is_stream_limitation_reached(enum ast_media_type type, const struct ast_sip_endpoint *endpoint, int *type_streams)
602{
603 switch (type) {
605 return !(type_streams[type] < endpoint->media.max_audio_streams);
607 return !(type_streams[type] < endpoint->media.max_video_streams);
609 /* We don't have an option for image (T.38) streams so cap it to one. */
610 return (type_streams[type] > 0);
613 default:
614 /* We don't want any unknown or "other" streams on our endpoint,
615 * so always just say we've reached the limit
616 */
617 return 1;
618 }
619}
620
621static int get_mid_bundle_group(const pjmedia_sdp_session *sdp, const char *mid)
622{
623 int bundle_group = 0;
624 int index;
625
626 for (index = 0; index < sdp->attr_count; ++index) {
627 pjmedia_sdp_attr *attr = sdp->attr[index];
628 char value[pj_strlen(&attr->value) + 1], *mids = value, *attr_mid;
629
630 if (pj_strcmp2(&attr->name, "group") || pj_strncmp2(&attr->value, "BUNDLE", 6)) {
631 continue;
632 }
633
634 ast_copy_pj_str(value, &attr->value, sizeof(value));
635
636 /* Skip the BUNDLE at the front */
637 mids += 7;
638
639 while ((attr_mid = strsep(&mids, " "))) {
640 if (!strcmp(attr_mid, mid)) {
641 /* The ordering of attributes determines our internal identification of the bundle group based on number,
642 * with -1 being not in a bundle group. Since this is only exposed internally for response purposes it's
643 * actually even fine if things move around.
644 */
645 return bundle_group;
646 }
647 }
648
649 bundle_group++;
650 }
651
652 return -1;
653}
654
656 struct ast_sip_session_media *session_media,
657 const pjmedia_sdp_session *sdp,
658 const struct pjmedia_sdp_media *stream)
659{
660 pjmedia_sdp_attr *attr;
661
662 if (!session->endpoint->media.bundle) {
663 return 0;
664 }
665
666 /* By default on an incoming negotiation we assume no mid and bundle group is present */
667 ast_free(session_media->mid);
668 session_media->mid = NULL;
669 session_media->bundle_group = -1;
670 session_media->bundled = 0;
671
672 /* Grab the media identifier for the stream */
673 attr = pjmedia_sdp_media_find_attr2(stream, "mid", NULL);
674 if (!attr) {
675 return 0;
676 }
677
678 session_media->mid = ast_calloc(1, attr->value.slen + 1);
679 if (!session_media->mid) {
680 return 0;
681 }
682 ast_copy_pj_str(session_media->mid, &attr->value, attr->value.slen + 1);
683
684 /* Determine what bundle group this is part of */
685 session_media->bundle_group = get_mid_bundle_group(sdp, session_media->mid);
686
687 /* If this is actually part of a bundle group then the other side requested or accepted the bundle request */
688 session_media->bundled = session_media->bundle_group != -1;
689
690 return 0;
691}
692
694 struct ast_sip_session_media *session_media,
695 const pjmedia_sdp_session *sdp,
696 const struct pjmedia_sdp_media *stream,
697 struct ast_stream *asterisk_stream)
698{
699 int index;
700
701 ast_free(session_media->remote_mslabel);
702 session_media->remote_mslabel = NULL;
703 ast_free(session_media->remote_label);
704 session_media->remote_label = NULL;
705
706 for (index = 0; index < stream->attr_count; ++index) {
707 pjmedia_sdp_attr *attr = stream->attr[index];
708 char attr_value[pj_strlen(&attr->value) + 1];
709 char *ssrc_attribute_name, *ssrc_attribute_value = NULL;
710 char *msid, *tmp = attr_value;
711 static const pj_str_t STR_msid = { "msid", 4 };
712 static const pj_str_t STR_ssrc = { "ssrc", 4 };
713 static const pj_str_t STR_label = { "label", 5 };
714
715 if (!pj_strcmp(&attr->name, &STR_label)) {
716 ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
717 session_media->remote_label = ast_strdup(attr_value);
718 } else if (!pj_strcmp(&attr->name, &STR_msid)) {
719 ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
720 msid = strsep(&tmp, " ");
721 session_media->remote_mslabel = ast_strdup(msid);
722 break;
723 } else if (!pj_strcmp(&attr->name, &STR_ssrc)) {
724 ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
725
726 if ((ssrc_attribute_name = strchr(attr_value, ' '))) {
727 /* This has an actual attribute */
728 *ssrc_attribute_name++ = '\0';
729 ssrc_attribute_value = strchr(ssrc_attribute_name, ':');
730 if (ssrc_attribute_value) {
731 /* Values are actually optional according to the spec */
732 *ssrc_attribute_value++ = '\0';
733 }
734
735 if (!strcasecmp(ssrc_attribute_name, "mslabel") && !ast_strlen_zero(ssrc_attribute_value)) {
736 session_media->remote_mslabel = ast_strdup(ssrc_attribute_value);
737 break;
738 }
739 }
740 }
741 }
742
743 if (ast_strlen_zero(session_media->remote_mslabel)) {
744 return;
745 }
746
747 /* Iterate through the existing streams looking for a match and if so then group this with it */
748 for (index = 0; index < AST_VECTOR_SIZE(&session->pending_media_state->sessions); ++index) {
749 struct ast_sip_session_media *group_session_media;
750
751 group_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
752
753 if (ast_strlen_zero(group_session_media->remote_mslabel) ||
754 strcmp(group_session_media->remote_mslabel, session_media->remote_mslabel)) {
755 continue;
756 }
757
758 ast_stream_set_group(asterisk_stream, index);
759 break;
760 }
761}
762
763static void remove_stream_from_bundle(struct ast_sip_session_media *session_media,
764 struct ast_stream *stream)
765{
767 ast_free(session_media->mid);
768 session_media->mid = NULL;
769 session_media->bundle_group = -1;
770 session_media->bundled = 0;
771}
772
773static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
774{
775 int i;
776 int handled = 0;
777 int type_streams[AST_MEDIA_TYPE_END] = {0};
778 SCOPE_ENTER(3, "%s: Media count: %d\n", ast_sip_session_get_name(session), sdp->media_count);
779
780 if (session->inv_session && session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
781 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_ERROR, "%s: Failed to handle incoming SDP. Session has been already disconnected\n",
783 }
784
785 /* It is possible for SDP deferral to have already created a pending topology */
786 if (!session->pending_media_state->topology) {
787 session->pending_media_state->topology = ast_stream_topology_alloc();
788 if (!session->pending_media_state->topology) {
789 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_ERROR, "%s: Couldn't alloc pending topology\n",
791 }
792 }
793
794 for (i = 0; i < sdp->media_count; ++i) {
795 /* See if there are registered handlers for this media stream type */
796 char media[20];
798 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
799 struct ast_sip_session_media *session_media = NULL;
800 int res;
801 enum ast_media_type type;
802 struct ast_stream *stream = NULL;
803 pjmedia_sdp_media *remote_stream = sdp->media[i];
804 SCOPE_ENTER(4, "%s: Processing stream %d\n", ast_sip_session_get_name(session), i);
805
806 /* We need a null-terminated version of the media string */
807 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
809
810 /* See if we have an already existing stream, which can occur from SDP deferral checking */
811 if (i < ast_stream_topology_get_count(session->pending_media_state->topology)) {
812 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
813 ast_trace(-1, "%s: Using existing pending stream %s\n", ast_sip_session_get_name(session),
814 ast_str_tmp(128, ast_stream_to_str(stream, &STR_TMP)));
815 }
816 if (!stream) {
817 struct ast_stream *existing_stream = NULL;
818 char *stream_name = NULL, *stream_name_allocated = NULL;
819 const char *stream_label = NULL;
820
821 if (session->active_media_state->topology &&
822 (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
823 existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
824 ast_trace(-1, "%s: Found existing active stream %s\n", ast_sip_session_get_name(session),
825 ast_str_tmp(128, ast_stream_to_str(existing_stream, &STR_TMP)));
826
827 if (ast_stream_get_state(existing_stream) != AST_STREAM_STATE_REMOVED) {
828 stream_name = (char *)ast_stream_get_name(existing_stream);
829 stream_label = ast_stream_get_metadata(existing_stream, "SDP:LABEL");
830 }
831 }
832
833 if (ast_strlen_zero(stream_name)) {
834 if (ast_asprintf(&stream_name_allocated, "%s-%d", ast_codec_media_type2str(type), i) < 0) {
835 handled = 0;
836 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't alloc stream name\n",
838
839 }
840 stream_name = stream_name_allocated;
841 ast_trace(-1, "%s: Using %s for new stream name\n", ast_sip_session_get_name(session),
842 stream_name);
843 }
844
845 stream = ast_stream_alloc(stream_name, type);
846 ast_free(stream_name_allocated);
847 if (!stream) {
848 handled = 0;
849 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't alloc stream\n",
851 }
852
853 if (!ast_strlen_zero(stream_label)) {
854 ast_stream_set_metadata(stream, "SDP:LABEL", stream_label);
855 ast_trace(-1, "%s: Using %s for new stream label\n", ast_sip_session_get_name(session),
856 stream_label);
857
858 }
859
860 if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
861 ast_stream_free(stream);
862 handled = 0;
863 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't set stream in topology\n",
865 }
866
867 /* For backwards compatibility with the core the default audio stream is always sendrecv */
868 if (!ast_sip_session_is_pending_stream_default(session, stream) || strcmp(media, "audio")) {
869 if (pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL)) {
870 /* Stream state reflects our state of a stream, so in the case of
871 * sendonly and recvonly we store the opposite since that is what ours
872 * is.
873 */
875 } else if (pjmedia_sdp_media_find_attr2(remote_stream, "recvonly", NULL)) {
877 } else if (pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
879 } else {
881 }
882 } else {
884 }
885 ast_trace(-1, "%s: Using new stream %s\n", ast_sip_session_get_name(session),
886 ast_str_tmp(128, ast_stream_to_str(stream, &STR_TMP)));
887 }
888
889 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
890 if (!session_media) {
891 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't alloc session media\n",
893 }
894
895 /* If this stream is already declined mark it as such, or mark it as such if we've reached the limit */
896 if (!remote_stream->desc.port || is_stream_limitation_reached(type, session->endpoint, type_streams)) {
897 remove_stream_from_bundle(session_media, stream);
898 SCOPE_EXIT_EXPR(continue, "%s: Declining incoming SDP media stream %s'\n",
900 }
901
902 set_mid_and_bundle_group(session, session_media, sdp, remote_stream);
903 set_remote_mslabel_and_stream_group(session, session_media, sdp, remote_stream, stream);
904
905 if (session_media->handler) {
906 handler = session_media->handler;
907 ast_trace(-1, "%s: Negotiating incoming SDP media stream %s using %s SDP handler\n",
909 session_media->handler->id);
910 res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp, i, stream);
911 if (res < 0) {
912 /* Catastrophic failure. Abort! */
913 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't negotiate stream %s\n",
915 } else if (res == 0) {
916 remove_stream_from_bundle(session_media, stream);
917 SCOPE_EXIT_EXPR(continue, "%s: Declining incoming SDP media stream %s\n",
919 } else if (res > 0) {
920 handled = 1;
921 ++type_streams[type];
922 /* Handled by this handler. Move to the next stream */
923 SCOPE_EXIT_EXPR(continue, "%s: Media stream %s handled by %s\n",
925 session_media->handler->id);
926 }
927 }
928
929 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
930 if (!handler_list) {
931 SCOPE_EXIT_EXPR(continue, "%s: Media stream %s has no registered handlers\n",
933 }
934 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
935 if (handler == session_media->handler) {
936 continue;
937 }
938 ast_trace(-1, "%s: Negotiating incoming SDP media stream %s using %s SDP handler\n",
940 handler->id);
941
942 res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp, i, stream);
943 if (res < 0) {
944 /* Catastrophic failure. Abort! */
945 handled = 0;
946 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Couldn't negotiate stream %s\n",
948 } else if (res == 0) {
949 remove_stream_from_bundle(session_media, stream);
950 ast_trace(-1, "%s: Declining incoming SDP media stream %s\n",
952 continue;
953 } else if (res > 0) {
954 session_media_set_handler(session_media, handler);
955 handled = 1;
956 ++type_streams[type];
957 ast_trace(-1, "%s: Media stream %s handled by %s\n",
959 session_media->handler->id);
960 break;
961 }
962 }
963
964 SCOPE_EXIT("%s: Done with stream %s\n", ast_sip_session_get_name(session),
965 ast_str_tmp(128, ast_stream_to_str(stream, &STR_TMP)));
966 }
967
968end:
969 SCOPE_EXIT_RTN_VALUE(handled ? 0 : -1, "%s: Handled? %s\n", ast_sip_session_get_name(session),
970 handled ? "yes" : "no");
971}
972
974 struct ast_sip_session *session, const pjmedia_sdp_session *local,
975 const pjmedia_sdp_session *remote, int index, struct ast_stream *asterisk_stream)
976{
977 /* See if there are registered handlers for this media stream type */
978 struct pjmedia_sdp_media *local_stream = local->media[index];
979 char media[20];
981 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
982 int res;
983 SCOPE_ENTER(1, "%s\n", session ? ast_sip_session_get_name(session) : "unknown");
984
985 /* We need a null-terminated version of the media string */
986 ast_copy_pj_str(media, &local->media[index]->desc.media, sizeof(media));
987
988 /* For backwards compatibility we only reflect the stream state correctly on
989 * the non-default streams and any non-audio streams. This is because the stream
990 * state of the default audio stream is also used for signaling that someone has
991 * placed us on hold. This situation is not handled currently and can result in
992 * the remote side being sorted of placed on hold too.
993 */
994 if (!ast_sip_session_is_pending_stream_default(session, asterisk_stream) || strcmp(media, "audio")) {
995 /* Determine the state of the stream based on our local SDP */
996 if (pjmedia_sdp_media_find_attr2(local_stream, "sendonly", NULL)) {
998 } else if (pjmedia_sdp_media_find_attr2(local_stream, "recvonly", NULL)) {
1000 } else if (pjmedia_sdp_media_find_attr2(local_stream, "inactive", NULL)) {
1002 } else {
1004 }
1005 } else {
1007 }
1008
1009 set_mid_and_bundle_group(session, session_media, remote, remote->media[index]);
1010 set_remote_mslabel_and_stream_group(session, session_media, remote, remote->media[index], asterisk_stream);
1011
1012 handler = session_media->handler;
1013 if (handler) {
1014 ast_debug(4, "%s: Applying negotiated SDP media stream '%s' using %s SDP handler\n",
1016 handler->id);
1017 res = handler->apply_negotiated_sdp_stream(session, session_media, local, remote, index, asterisk_stream);
1018 if (res >= 0) {
1019 ast_debug(4, "%s: Applied negotiated SDP media stream '%s' using %s SDP handler\n",
1021 handler->id);
1022 SCOPE_EXIT_RTN_VALUE(0, "%s: Applied negotiated SDP media stream '%s' using %s SDP handler\n",
1024 handler->id);
1025 }
1026 SCOPE_EXIT_RTN_VALUE(-1, "%s: Failed to apply negotiated SDP media stream '%s' using %s SDP handler\n",
1028 handler->id);
1029 }
1030
1031 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1032 if (!handler_list) {
1033 ast_debug(4, "%s: No registered SDP handlers for media type '%s'\n", ast_sip_session_get_name(session), media);
1034 return -1;
1035 }
1036 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1037 if (handler == session_media->handler) {
1038 continue;
1039 }
1040 ast_debug(4, "%s: Applying negotiated SDP media stream '%s' using %s SDP handler\n",
1042 handler->id);
1043 res = handler->apply_negotiated_sdp_stream(session, session_media, local, remote, index, asterisk_stream);
1044 if (res < 0) {
1045 /* Catastrophic failure. Abort! */
1046 SCOPE_EXIT_RTN_VALUE(-1, "%s: Handler '%s' returned %d\n",
1048 }
1049 if (res > 0) {
1050 ast_debug(4, "%s: Applied negotiated SDP media stream '%s' using %s SDP handler\n",
1052 handler->id);
1053 /* Handled by this handler. Move to the next stream */
1054 session_media_set_handler(session_media, handler);
1055 SCOPE_EXIT_RTN_VALUE(0, "%s: Handler '%s' handled this sdp stream\n",
1057 }
1058 }
1059
1060 res = 0;
1061 if (session_media->handler && session_media->handler->stream_stop) {
1062 ast_debug(4, "%s: Stopping SDP media stream '%s' as it is not currently negotiated\n",
1064 session_media->handler->stream_stop(session_media);
1065 }
1066
1067 SCOPE_EXIT_RTN_VALUE(0, "%s: Media type '%s' %s\n",
1069 res ? "not negotiated. Stopped" : "handled");
1070}
1071
1072static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
1073{
1074 int i;
1075 struct ast_stream_topology *topology;
1076 unsigned int changed = 0; /* 0 = unchanged, 1 = new source, 2 = new topology */
1078
1079 if (!session->pending_media_state->topology) {
1080 if (session->active_media_state->topology) {
1081 /*
1082 * This happens when we have negotiated media after receiving a 183,
1083 * and we're now receiving a 200 with a new SDP. In this case, there
1084 * is active_media_state, but the pending_media_state has been reset.
1085 */
1086 struct ast_sip_session_media_state *active_media_state_clone;
1087
1088 active_media_state_clone =
1089 ast_sip_session_media_state_clone(session->active_media_state);
1090 if (!active_media_state_clone) {
1091 ast_log(LOG_WARNING, "%s: Unable to clone active media state\n",
1093 return -1;
1094 }
1095
1096 ast_sip_session_media_state_free(session->pending_media_state);
1097 session->pending_media_state = active_media_state_clone;
1098 } else {
1099 ast_log(LOG_WARNING, "%s: No pending or active media state\n",
1101 return -1;
1102 }
1103 }
1104
1105 /* If we're handling negotiated streams, then we should already have set
1106 * up session media instances (and Asterisk streams) that correspond to
1107 * the local SDP, and there should be the same number of session medias
1108 * and streams as there are local SDP streams
1109 */
1110 if (ast_stream_topology_get_count(session->pending_media_state->topology) != local->media_count
1111 || AST_VECTOR_SIZE(&session->pending_media_state->sessions) != local->media_count) {
1112 ast_log(LOG_WARNING, "%s: Local SDP contains %d media streams while we expected it to contain %u\n",
1114 ast_stream_topology_get_count(session->pending_media_state->topology), local->media_count);
1115 SCOPE_EXIT_RTN_VALUE(-1, "Media stream count mismatch\n");
1116 }
1117
1118 AST_VECTOR_RESET(&session->pending_media_state->read_callbacks, AST_VECTOR_ELEM_CLEANUP_NOOP);
1119
1120 for (i = 0; i < local->media_count; ++i) {
1121 struct ast_sip_session_media *session_media;
1122 struct ast_stream *stream;
1123
1124 if (!remote->media[i]) {
1125 continue;
1126 }
1127
1128 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
1129 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
1130
1131 /* Make sure that this stream is in the correct state. If we need to change
1132 * the state to REMOVED, then our work here is done, so go ahead and move on
1133 * to the next stream.
1134 */
1135 if (!remote->media[i]->desc.port) {
1137 continue;
1138 }
1139
1140 /* If the stream state is REMOVED, nothing needs to be done, so move on to the
1141 * next stream. This can occur if an internal thing has requested it to be
1142 * removed, or if we remove it as a result of the stream limit being reached.
1143 */
1145 /*
1146 * Defer removing the handler until we are ready to activate
1147 * the new topology. The channel's thread may still be using
1148 * the stream and we could crash before we are ready.
1149 */
1150 continue;
1151 }
1152
1153 if (handle_negotiated_sdp_session_media(session_media, session, local, remote, i, stream)) {
1154 SCOPE_EXIT_RTN_VALUE(-1, "Unable to handle negotiated session media\n");
1155 }
1156
1157 changed |= session_media->changed;
1158 session_media->changed = 0;
1159 }
1160
1161 /* Apply the pending media state to the channel and make it active */
1162 ast_channel_lock(session->channel);
1163
1164 /* Now update the stream handler for any declined/removed streams */
1165 for (i = 0; i < local->media_count; ++i) {
1166 struct ast_sip_session_media *session_media;
1167 struct ast_stream *stream;
1168
1169 if (!remote->media[i]) {
1170 continue;
1171 }
1172
1173 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
1174 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
1175
1177 && session_media->handler) {
1178 /*
1179 * This stream is no longer being used and the channel's thread
1180 * is held off because we have the channel lock so release any
1181 * resources the handler may have on it.
1182 */
1183 session_media_set_handler(session_media, NULL);
1184 }
1185 }
1186
1187 /* Update the topology on the channel to match the accepted one */
1188 topology = ast_stream_topology_clone(session->pending_media_state->topology);
1189 if (topology) {
1190 ast_channel_set_stream_topology(session->channel, topology);
1191 /* If this is a remotely done renegotiation that has changed the stream topology notify what is
1192 * currently handling this channel. Note that fax uses its own process, so if we are transitioning
1193 * between audio and fax or vice versa we don't notify.
1194 */
1195 if (pjmedia_sdp_neg_was_answer_remote(session->inv_session->neg) == PJ_FALSE &&
1196 session->active_media_state && session->active_media_state->topology &&
1197 !ast_stream_topology_equal(session->active_media_state->topology, topology) &&
1198 !session->active_media_state->default_session[AST_MEDIA_TYPE_IMAGE] &&
1199 !session->pending_media_state->default_session[AST_MEDIA_TYPE_IMAGE]) {
1200 changed = 2;
1201 }
1202 }
1203
1204 /* Remove all current file descriptors from the channel */
1205 for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++i) {
1207 }
1208
1209 /* Add all the file descriptors from the pending media state */
1210 for (i = 0; i < AST_VECTOR_SIZE(&session->pending_media_state->read_callbacks); ++i) {
1211 struct ast_sip_session_media_read_callback_state *callback_state;
1212
1213 callback_state = AST_VECTOR_GET_ADDR(&session->pending_media_state->read_callbacks, i);
1214 ast_channel_internal_fd_set(session->channel, i + AST_EXTENDED_FDS, callback_state->fd);
1215 }
1216
1217 /* Active and pending flip flop as needed */
1218 ast_sip_session_media_stats_save(session, session->active_media_state);
1219 SWAP(session->active_media_state, session->pending_media_state);
1220 ast_sip_session_media_state_reset(session->pending_media_state);
1221
1222 ast_channel_unlock(session->channel);
1223
1224 if (changed == 1) {
1226
1227 ast_queue_frame(session->channel, &f);
1228 } else if (changed == 2) {
1230 } else {
1232 }
1233
1235}
1236
1237#define DATASTORE_BUCKETS 53
1238#define MEDIA_BUCKETS 7
1239
1240static void session_datastore_destroy(void *obj)
1241{
1242 struct ast_datastore *datastore = obj;
1243
1244 /* Using the destroy function (if present) destroy the data */
1245 if (datastore->info->destroy != NULL && datastore->data != NULL) {
1246 datastore->info->destroy(datastore->data);
1247 datastore->data = NULL;
1248 }
1249
1250 ast_free((void *) datastore->uid);
1251 datastore->uid = NULL;
1252}
1253
1255{
1256 RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1257 char uuid_buf[AST_UUID_STR_LEN];
1258 const char *uid_ptr = uid;
1259
1260 if (!info) {
1261 return NULL;
1262 }
1263
1264 datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
1265 if (!datastore) {
1266 return NULL;
1267 }
1268
1269 datastore->info = info;
1270 if (ast_strlen_zero(uid)) {
1271 /* They didn't provide an ID so we'll provide one ourself */
1272 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
1273 }
1274
1275 datastore->uid = ast_strdup(uid_ptr);
1276 if (!datastore->uid) {
1277 return NULL;
1278 }
1279
1280 ao2_ref(datastore, +1);
1281 return datastore;
1282}
1283
1285{
1286 ast_assert(datastore != NULL);
1287 ast_assert(datastore->info != NULL);
1288 ast_assert(ast_strlen_zero(datastore->uid) == 0);
1289
1290 if (!ao2_link(session->datastores, datastore)) {
1291 return -1;
1292 }
1293 return 0;
1294}
1295
1297{
1298 return ao2_find(session->datastores, name, OBJ_KEY);
1299}
1300
1302{
1303 ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
1304}
1305
1310};
1311
1312/*!
1313 * \internal
1314 * \brief Convert delayed method enum value to a string.
1315 * \since 13.3.0
1316 *
1317 * \param method Delayed method enum value to convert to a string.
1318 *
1319 * \return String value of delayed method.
1320 */
1322{
1323 const char *str = "<unknown>";
1324
1325 switch (method) {
1327 str = "INVITE";
1328 break;
1330 str = "UPDATE";
1331 break;
1332 case DELAYED_METHOD_BYE:
1333 str = "BYE";
1334 break;
1335 }
1336
1337 return str;
1338}
1339
1340/*!
1341 * \brief Structure used for sending delayed requests
1342 *
1343 * Requests are typically delayed because the current transaction
1344 * state of an INVITE. Once the pending INVITE transaction terminates,
1345 * the delayed request will be sent
1346 */
1348 /*! Method of the request */
1350 /*! Callback to call when the delayed request is created. */
1352 /*! Callback to call when the delayed request SDP is created */
1354 /*! Callback to call when the delayed request receives a response */
1356 /*! Whether to generate new SDP */
1358 /*! Requested media state for the SDP */
1360 /*! Active media state at the time of the original request */
1362
1364};
1365
1371 int generate_new_sdp,
1374{
1375 struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
1376
1377 if (!delay) {
1378 return NULL;
1379 }
1380 delay->method = method;
1383 delay->on_response = on_response;
1387 return delay;
1388}
1389
1391{
1394 ast_free(delay);
1395}
1396
1397/*!
1398 * \internal
1399 * \brief Send a delayed request
1400 *
1401 * \retval -1 failure
1402 * \retval 0 success
1403 * \retval 1 refresh request not sent as no change would occur
1404 */
1406{
1407 int res;
1408 SCOPE_ENTER(3, "%s: sending delayed %s request\n",
1410 delayed_method2str(delay->method));
1411
1412 switch (delay->method) {
1415 delay->on_sdp_creation, delay->on_response,
1417 delay->active_media_state, 1);
1418 /* Ownership of media state transitions to ast_sip_session_refresh */
1419 delay->pending_media_state = NULL;
1420 delay->active_media_state = NULL;
1424 delay->on_sdp_creation, delay->on_response,
1426 delay->active_media_state, 1);
1427 /* Ownership of media state transitions to ast_sip_session_refresh */
1428 delay->pending_media_state = NULL;
1429 delay->active_media_state = NULL;
1431 case DELAYED_METHOD_BYE:
1433 SCOPE_EXIT_RTN_VALUE(0, "%s: Terminating session on delayed BYE\n", ast_sip_session_get_name(session));
1434 }
1435
1436 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Don't know how to send delayed %s(%d) request.\n",
1438 delayed_method2str(delay->method), delay->method);
1439}
1440
1441/*!
1442 * \internal
1443 * \brief The current INVITE transaction is in the PROCEEDING state.
1444 * \since 13.3.0
1445 *
1446 * \param vsession Session object.
1447 *
1448 * \retval 0 on success.
1449 * \retval -1 on error.
1450 */
1451static int invite_proceeding(void *vsession)
1452{
1453 struct ast_sip_session *session = vsession;
1454 struct ast_sip_session_delayed_request *delay;
1455 int found = 0;
1456 int res = 0;
1458
1459 AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1460 switch (delay->method) {
1462 break;
1465 ast_trace(-1, "%s: Sending delayed %s request\n", ast_sip_session_get_name(session),
1466 delayed_method2str(delay->method));
1467 res = send_delayed_request(session, delay);
1468 delayed_request_free(delay);
1469 if (!res) {
1470 found = 1;
1471 }
1472 break;
1473 case DELAYED_METHOD_BYE:
1474 /* A BYE is pending so don't bother anymore. */
1475 found = 1;
1476 break;
1477 }
1478 if (found) {
1479 break;
1480 }
1481 }
1483
1484 ao2_ref(session, -1);
1486}
1487
1488/*!
1489 * \internal
1490 * \brief The current INVITE transaction is in the TERMINATED state.
1491 * \since 13.3.0
1492 *
1493 * \param vsession Session object.
1494 *
1495 * \retval 0 on success.
1496 * \retval -1 on error.
1497 */
1498static int invite_terminated(void *vsession)
1499{
1500 struct ast_sip_session *session = vsession;
1501 struct ast_sip_session_delayed_request *delay;
1502 int found = 0;
1503 int res = 0;
1504 int timer_running;
1506
1507 /* re-INVITE collision timer running? */
1508 timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
1509
1510 AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1511 switch (delay->method) {
1513 if (!timer_running) {
1514 found = 1;
1515 }
1516 break;
1518 case DELAYED_METHOD_BYE:
1519 found = 1;
1520 break;
1521 }
1522 if (found) {
1524 ast_trace(-1, "%s: Sending delayed %s request\n", ast_sip_session_get_name(session),
1525 delayed_method2str(delay->method));
1526 res = send_delayed_request(session, delay);
1527 delayed_request_free(delay);
1528 if (!res) {
1529 break;
1530 }
1531 }
1532 }
1534
1535 ao2_ref(session, -1);
1537}
1538
1539/*!
1540 * \internal
1541 * \brief INVITE collision timeout.
1542 * \since 13.3.0
1543 *
1544 * \param vsession Session object.
1545 *
1546 * \retval 0 on success.
1547 * \retval -1 on error.
1548 */
1549static int invite_collision_timeout(void *vsession)
1550{
1551 struct ast_sip_session *session = vsession;
1552 int res;
1554
1555 if (session->inv_session->invite_tsx) {
1556 /*
1557 * INVITE transaction still active. Let it send
1558 * the collision re-INVITE when it terminates.
1559 */
1560 ao2_ref(session, -1);
1561 res = 0;
1562 } else {
1564 }
1565
1567}
1568
1569/*!
1570 * \internal
1571 * \brief The current UPDATE transaction is in the COMPLETED state.
1572 * \since 13.3.0
1573 *
1574 * \param vsession Session object.
1575 *
1576 * \retval 0 on success.
1577 * \retval -1 on error.
1578 */
1579static int update_completed(void *vsession)
1580{
1581 struct ast_sip_session *session = vsession;
1582 int res;
1583
1584 if (session->inv_session->invite_tsx) {
1586 } else {
1588 }
1589
1590 return res;
1591}
1592
1594 int (*cb)(void *vsession))
1595{
1596 ao2_ref(session, +1);
1597 if (ast_sip_push_task(session->serializer, cb, session)) {
1598 ao2_ref(session, -1);
1599 }
1600}
1601
1604 ast_sip_session_sdp_creation_cb on_sdp_creation,
1605 ast_sip_session_response_cb on_response,
1606 int generate_new_sdp,
1610 int queue_head)
1611{
1616
1617 if (!delay) {
1620 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_ERROR, "Unable to allocate delay request\n");
1621 }
1622
1623 if (method == DELAYED_METHOD_BYE || queue_head) {
1624 /* Send BYE as early as possible */
1625 AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
1626 } else {
1627 AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
1628 }
1630}
1631
1632static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
1633{
1634 pjsip_inv_session *inv_session = session->inv_session;
1635 const pjmedia_sdp_session *previous_sdp = NULL;
1637
1638 if (inv_session->neg) {
1639 if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
1640 pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
1641 } else {
1642 pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
1643 }
1644 }
1645 SCOPE_EXIT_RTN_VALUE(create_local_sdp(inv_session, session, previous_sdp, 0));
1646}
1647
1649{
1650 struct ast_party_id effective_id;
1651 struct ast_party_id connected_id;
1652 pj_pool_t *dlg_pool;
1653 pjsip_fromto_hdr *dlg_info;
1654 pjsip_contact_hdr *dlg_contact;
1655 pjsip_name_addr *dlg_info_name_addr;
1656 pjsip_sip_uri *dlg_info_uri;
1657 pjsip_sip_uri *dlg_contact_uri;
1658 int restricted;
1659 const char *pjsip_from_domain;
1660
1661 if (!session->channel || session->saved_from_hdr) {
1662 return;
1663 }
1664
1665 /* We need to save off connected_id for RPID/PAI generation */
1666 ast_party_id_init(&connected_id);
1667 ast_channel_lock(session->channel);
1668 effective_id = ast_channel_connected_effective_id(session->channel);
1669 ast_party_id_copy(&connected_id, &effective_id);
1670 ast_channel_unlock(session->channel);
1671
1672 restricted =
1674
1675 /* Now set up dlg->local.info so pjsip can correctly generate From */
1676
1677 dlg_pool = session->inv_session->dlg->pool;
1678 dlg_info = session->inv_session->dlg->local.info;
1679 dlg_contact = session->inv_session->dlg->local.contact;
1680 dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;
1681 dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);
1682 dlg_contact_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(dlg_contact->uri);
1683
1684 if (session->endpoint->id.trust_outbound || !restricted) {
1685 ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);
1686 if (ast_sip_get_use_callerid_contact() && ast_strlen_zero(session->endpoint->contact_user)) {
1687 pj_strdup2(dlg_pool, &dlg_contact_uri->user, S_COR(connected_id.number.valid, connected_id.number.str, ""));
1688 }
1689 }
1690
1691 ast_party_id_free(&connected_id);
1692
1693 if (!ast_strlen_zero(session->endpoint->fromuser)) {
1694 dlg_info_name_addr->display.ptr = NULL;
1695 dlg_info_name_addr->display.slen = 0;
1696 pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);
1697 }
1698
1699 if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1700 pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);
1701 }
1702
1703 /*
1704 * Channel variable for compatibility with chan_sip SIPFROMDOMAIN
1705 */
1706 ast_channel_lock(session->channel);
1707 pjsip_from_domain = pbx_builtin_getvar_helper(session->channel, "SIPFROMDOMAIN");
1708 if (!ast_strlen_zero(pjsip_from_domain)) {
1709 ast_debug(3, "%s: From header domain reset by channel variable SIPFROMDOMAIN (%s)\n",
1710 ast_sip_session_get_name(session), pjsip_from_domain);
1711 pj_strdup2(dlg_pool, &dlg_info_uri->host, pjsip_from_domain);
1712 }
1713 ast_channel_unlock(session->channel);
1714
1715 /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */
1716 session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);
1717 ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);
1718
1719 /* In chan_sip, fromuser and fromdomain trump restricted so we only
1720 * anonymize if they're not set.
1721 */
1722 if (restricted) {
1723 /* fromuser doesn't provide a display name so we always set it */
1724 pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");
1725
1726 if (ast_strlen_zero(session->endpoint->fromuser)) {
1727 pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");
1728 }
1729
1730 if (ast_sip_get_use_callerid_contact() && ast_strlen_zero(session->endpoint->contact_user)) {
1731 pj_strdup2(dlg_pool, &dlg_contact_uri->user, "anonymous");
1732 }
1733
1734 if (ast_strlen_zero(session->endpoint->fromdomain)) {
1735 pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");
1736 }
1737 } else {
1738 ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);
1739 }
1740}
1741
1742/*
1743 * Helper macros for merging and validating media states
1744 */
1745#define STREAM_REMOVED(_stream) (ast_stream_get_state(_stream) == AST_STREAM_STATE_REMOVED)
1746#define STATE_REMOVED(_stream_state) (_stream_state == AST_STREAM_STATE_REMOVED)
1747#define STATE_NONE(_stream_state) (_stream_state == AST_STREAM_STATE_END)
1748#define GET_STREAM_SAFE(_topology, _i) (_i < ast_stream_topology_get_count(_topology) ? ast_stream_topology_get_stream(_topology, _i) : NULL)
1749#define GET_STREAM_STATE_SAFE(_stream) (_stream ? ast_stream_get_state(_stream) : AST_STREAM_STATE_END)
1750#define GET_STREAM_NAME_SAFE(_stream) (_stream ? ast_stream_get_name(_stream) : "")
1751
1752/*!
1753 * \internal
1754 * \brief Validate a media state
1755 *
1756 * \param session_name For log messages
1757 * \param state Media state
1758 *
1759 * \retval 1 The media state is valid
1760 * \retval 0 The media state is NOT valid
1761 *
1762 */
1763static int is_media_state_valid(const char *session_name, struct ast_sip_session_media_state *state)
1764{
1765 int stream_count = ast_stream_topology_get_count(state->topology);
1766 int session_count = AST_VECTOR_SIZE(&state->sessions);
1767 int i;
1768 int res = 0;
1769 SCOPE_ENTER(3, "%s: Topology: %s\n", session_name,
1770 ast_str_tmp(256, ast_stream_topology_to_str(state->topology, &STR_TMP)));
1771
1772 if (session_count != stream_count) {
1773 SCOPE_EXIT_RTN_VALUE(0, "%s: %d media sessions but %d streams\n", session_name,
1774 session_count, stream_count);
1775 }
1776
1777 for (i = 0; i < stream_count; i++) {
1778 struct ast_sip_session_media *media = NULL;
1779 struct ast_stream *stream = ast_stream_topology_get_stream(state->topology, i);
1780 const char *stream_name = NULL;
1781 int j;
1782 SCOPE_ENTER(4, "%s: Checking stream %s\n", session_name, ast_str_tmp(128, ast_stream_to_str(stream, &STR_TMP)));
1783
1784 if (!stream) {
1785 SCOPE_EXIT_EXPR(goto end, "%s: stream %d is null\n", session_name, i);
1786 }
1787 stream_name = ast_stream_get_name(stream);
1788
1789 for (j = 0; j < stream_count; j++) {
1790 struct ast_stream *possible_dup = ast_stream_topology_get_stream(state->topology, j);
1791 if (j == i || !possible_dup) {
1792 continue;
1793 }
1794 if (!STREAM_REMOVED(stream) && ast_strings_equal(stream_name, GET_STREAM_NAME_SAFE(possible_dup))) {
1795 SCOPE_EXIT_EXPR(goto end, "%s: stream %i %s is duplicated to %d\n", session_name,
1796 i, stream_name, j);
1797 }
1798 }
1799
1800 media = AST_VECTOR_GET(&state->sessions, i);
1801 if (!media) {
1802 SCOPE_EXIT_EXPR(continue, "%s: media %d is null\n", session_name, i);
1803 }
1804
1805 for (j = 0; j < session_count; j++) {
1806 struct ast_sip_session_media *possible_dup = AST_VECTOR_GET(&state->sessions, j);
1807 if (j == i || !possible_dup) {
1808 continue;
1809 }
1810 if (!ast_strlen_zero(media->label) && !ast_strlen_zero(possible_dup->label)
1811 && ast_strings_equal(media->label, possible_dup->label)) {
1812 SCOPE_EXIT_EXPR(goto end, "%s: media %d %s is duplicated to %d\n", session_name,
1813 i, media->label, j);
1814 }
1815 }
1816
1817 if (media->stream_num != i) {
1818 SCOPE_EXIT_EXPR(goto end, "%s: media %d has stream_num %d\n", session_name,
1819 i, media->stream_num);
1820 }
1821
1822 if (media->type != ast_stream_get_type(stream)) {
1823 SCOPE_EXIT_EXPR(goto end, "%s: media %d has type %s but stream has type %s\n", stream_name,
1825 }
1826 SCOPE_EXIT("%s: Done with stream %s\n", session_name, ast_str_tmp(128, ast_stream_to_str(stream, &STR_TMP)));
1827 }
1828
1829 res = 1;
1830end:
1831 SCOPE_EXIT_RTN_VALUE(res, "%s: %s\n", session_name, res ? "Valid" : "NOT Valid");
1832}
1833
1834/*!
1835 * \internal
1836 * \brief Merge media states for a delayed session refresh
1837 *
1838 * \param session_name For log messages
1839 * \param delayed_pending_state The pending media state at the time the resuest was queued
1840 * \param delayed_active_state The active media state at the time the resuest was queued
1841 * \param current_active_state The current active media state
1842 * \param run_post_validation Whether to run validation on the resulting media state or not
1843 *
1844 * \returns New merged topology or NULL if there's an error
1845 *
1846 */
1848 const char *session_name,
1849 struct ast_sip_session_media_state *delayed_pending_state,
1850 struct ast_sip_session_media_state *delayed_active_state,
1851 struct ast_sip_session_media_state *current_active_state,
1852 int run_post_validation)
1853{
1855 struct ast_sip_session_media_state *returned_media_state = NULL;
1856 struct ast_stream_topology *delayed_pending = delayed_pending_state->topology;
1857 struct ast_stream_topology *delayed_active = delayed_active_state->topology;
1858 struct ast_stream_topology *current_active = current_active_state->topology;
1859 struct ast_stream_topology *new_pending = NULL;
1860 int i;
1861 int max_stream_count;
1862 int res;
1863 SCOPE_ENTER(2, "%s: DP: %s DA: %s CA: %s\n", session_name,
1864 ast_str_tmp(256, ast_stream_topology_to_str(delayed_pending, &STR_TMP)),
1865 ast_str_tmp(256, ast_stream_topology_to_str(delayed_active, &STR_TMP)),
1866 ast_str_tmp(256, ast_stream_topology_to_str(current_active, &STR_TMP))
1867 );
1868
1869 max_stream_count = MAX(ast_stream_topology_get_count(delayed_pending),
1870 ast_stream_topology_get_count(delayed_active));
1871 max_stream_count = MAX(max_stream_count, ast_stream_topology_get_count(current_active));
1872
1873 /*
1874 * The new_pending_state is always based on the currently negotiated state because
1875 * the stream ordering in its topology must be preserved.
1876 */
1877 new_pending_state = ast_sip_session_media_state_clone(current_active_state);
1878 if (!new_pending_state) {
1879 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_ERROR, "%s: Couldn't clone current_active_state to new_pending_state\n", session_name);
1880 }
1881 new_pending = new_pending_state->topology;
1882
1883 for (i = 0; i < max_stream_count; i++) {
1884 struct ast_stream *dp_stream = GET_STREAM_SAFE(delayed_pending, i);
1885 struct ast_stream *da_stream = GET_STREAM_SAFE(delayed_active, i);
1886 struct ast_stream *ca_stream = GET_STREAM_SAFE(current_active, i);
1887 struct ast_stream *np_stream = GET_STREAM_SAFE(new_pending, i);
1888 struct ast_stream *found_da_stream = NULL;
1889 struct ast_stream *found_np_stream = NULL;
1890 enum ast_stream_state dp_state = GET_STREAM_STATE_SAFE(dp_stream);
1891 enum ast_stream_state da_state = GET_STREAM_STATE_SAFE(da_stream);
1892 enum ast_stream_state ca_state = GET_STREAM_STATE_SAFE(ca_stream);
1893 enum ast_stream_state np_state = GET_STREAM_STATE_SAFE(np_stream);
1894 enum ast_stream_state found_da_state = AST_STREAM_STATE_END;
1895 enum ast_stream_state found_np_state = AST_STREAM_STATE_END;
1896 const char *da_name = GET_STREAM_NAME_SAFE(da_stream);
1897 const char *dp_name = GET_STREAM_NAME_SAFE(dp_stream);
1898 const char *ca_name = GET_STREAM_NAME_SAFE(ca_stream);
1899 const char *np_name = GET_STREAM_NAME_SAFE(np_stream);
1900 const char *found_da_name __attribute__((unused)) = "";
1901 const char *found_np_name __attribute__((unused)) = "";
1902 int found_da_slot __attribute__((unused)) = -1;
1903 int found_np_slot = -1;
1904 int removed_np_slot = -1;
1905 int j;
1906 SCOPE_ENTER(3, "%s: slot: %d DP: %s DA: %s CA: %s\n", session_name, i,
1907 ast_str_tmp(128, ast_stream_to_str(dp_stream, &STR_TMP)),
1908 ast_str_tmp(128, ast_stream_to_str(da_stream, &STR_TMP)),
1909 ast_str_tmp(128, ast_stream_to_str(ca_stream, &STR_TMP)));
1910
1911 if (STATE_NONE(da_state) && STATE_NONE(dp_state) && STATE_NONE(ca_state)) {
1912 SCOPE_EXIT_EXPR(break, "%s: All gone\n", session_name);
1913 }
1914
1915 /*
1916 * Simple cases are handled first to avoid having to search the NP and DA
1917 * topologies for streams with the same name but not in the same position.
1918 */
1919
1920 if (STATE_NONE(dp_state) && !STATE_NONE(da_state)) {
1921 /*
1922 * The slot in the delayed pending topology can't be empty if the delayed
1923 * active topology has a stream there. Streams can't just go away. They
1924 * can be reused or marked "removed" but they can't go away.
1925 */
1926 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_WARNING, "%s: DP slot is empty but DA is not\n", session_name);
1927 }
1928
1929 if (STATE_NONE(dp_state)) {
1930 /*
1931 * The current active topology can certainly have streams that weren't
1932 * in existence when the delayed request was queued. In this case,
1933 * no action is needed since we already copied the current active topology
1934 * to the new pending one.
1935 */
1936 SCOPE_EXIT_EXPR(continue, "%s: No DP stream so use CA stream as is\n", session_name);
1937 }
1938
1939 if (ast_strings_equal(dp_name, da_name) && ast_strings_equal(da_name, ca_name)) {
1940 /*
1941 * The delayed pending stream in this slot matches by name, the streams
1942 * in the same slot in the other two topologies. Easy case.
1943 */
1944 ast_trace(-1, "%s: Same stream in all 3 states\n", session_name);
1945 if (dp_state == da_state && da_state == ca_state) {
1946 /* All the same state, no need to update. */
1947 SCOPE_EXIT_EXPR(continue, "%s: All in the same state so nothing to do\n", session_name);
1948 }
1949 if (da_state != ca_state) {
1950 /*
1951 * Something set the CA state between the time this request was queued
1952 * and now. The CA state wins so we don't do anything.
1953 */
1954 SCOPE_EXIT_EXPR(continue, "%s: Ignoring request to change state from %s to %s\n",
1955 session_name, ast_stream_state2str(ca_state), ast_stream_state2str(dp_state));
1956 }
1957 if (dp_state != da_state) {
1958 /* DP needs to update the state */
1959 ast_stream_set_state(np_stream, dp_state);
1960 SCOPE_EXIT_EXPR(continue, "%s: Changed NP stream state from %s to %s\n",
1961 session_name, ast_stream_state2str(ca_state), ast_stream_state2str(dp_state));
1962 }
1963 }
1964
1965 /*
1966 * We're done with the simple cases. For the rest, we need to identify if the
1967 * DP stream we're trying to take action on is already in the other topologies
1968 * possibly in a different slot. To do that, if the stream in the DA or CA slots
1969 * doesn't match the current DP stream, we need to iterate over the topology
1970 * looking for a stream with the same name.
1971 */
1972
1973 /*
1974 * Since we already copied all of the CA streams to the NP topology, we'll use it
1975 * instead of CA because we'll be updating the NP as we go.
1976 */
1977 if (!ast_strings_equal(dp_name, np_name)) {
1978 /*
1979 * The NP stream in this slot doesn't have the same name as the DP stream
1980 * so we need to see if it's in another NP slot. We're not going to stop
1981 * when we find a matching stream because we also want to find the first
1982 * removed removed slot, if any, so we can re-use this slot. We'll break
1983 * early if we find both before we reach the end.
1984 */
1985 ast_trace(-1, "%s: Checking if DP is already in NP somewhere\n", session_name);
1986 for (j = 0; j < ast_stream_topology_get_count(new_pending); j++) {
1987 struct ast_stream *possible_existing = ast_stream_topology_get_stream(new_pending, j);
1988 const char *possible_existing_name = GET_STREAM_NAME_SAFE(possible_existing);
1989
1990 ast_trace(-1, "%s: Checking %s against %s\n", session_name, dp_name, possible_existing_name);
1991 if (found_np_slot == -1 && ast_strings_equal(dp_name, possible_existing_name)) {
1992 ast_trace(-1, "%s: Pending stream %s slot %d is in NP slot %d\n", session_name,
1993 dp_name, i, j);
1994 found_np_slot = j;
1995 found_np_stream = possible_existing;
1996 found_np_state = ast_stream_get_state(possible_existing);
1997 found_np_name = ast_stream_get_name(possible_existing);
1998 }
1999 if (STREAM_REMOVED(possible_existing) && removed_np_slot == -1) {
2000 removed_np_slot = j;
2001 }
2002 if (removed_np_slot >= 0 && found_np_slot >= 0) {
2003 break;
2004 }
2005 }
2006 } else {
2007 /* Makes the subsequent code easier */
2008 found_np_slot = i;
2009 found_np_stream = np_stream;
2010 found_np_state = np_state;
2011 found_np_name = np_name;
2012 }
2013
2014 if (!ast_strings_equal(dp_name, da_name)) {
2015 /*
2016 * The DA stream in this slot doesn't have the same name as the DP stream
2017 * so we need to see if it's in another DA slot. In real life, the DA stream
2018 * in this slot could have a different name but there shouldn't be a case
2019 * where the DP stream is another slot in the DA topology. Just in case though.
2020 * We don't care about removed slots in the DA topology.
2021 */
2022 ast_trace(-1, "%s: Checking if DP is already in DA somewhere\n", session_name);
2023 for (j = 0; j < ast_stream_topology_get_count(delayed_active); j++) {
2024 struct ast_stream *possible_existing = ast_stream_topology_get_stream(delayed_active, j);
2025 const char *possible_existing_name = GET_STREAM_NAME_SAFE(possible_existing);
2026
2027 ast_trace(-1, "%s: Checking %s against %s\n", session_name, dp_name, possible_existing_name);
2028 if (ast_strings_equal(dp_name, possible_existing_name)) {
2029 ast_trace(-1, "%s: Pending stream %s slot %d is already in delayed active slot %d\n",
2030 session_name, dp_name, i, j);
2031 found_da_slot = j;
2032 found_da_stream = possible_existing;
2033 found_da_state = ast_stream_get_state(possible_existing);
2034 found_da_name = ast_stream_get_name(possible_existing);
2035 break;
2036 }
2037 }
2038 } else {
2039 /* Makes the subsequent code easier */
2040 found_da_slot = i;
2041 found_da_stream = da_stream;
2042 found_da_state = da_state;
2043 found_da_name = da_name;
2044 }
2045
2046 ast_trace(-1, "%s: Found NP slot: %d Found removed NP slot: %d Found DA slot: %d\n",
2047 session_name, found_np_slot, removed_np_slot, found_da_slot);
2048
2049 /*
2050 * Now we know whether the DP stream is new or changing state and we know if the DP
2051 * stream exists in the other topologies and if so, where in those topologies it exists.
2052 */
2053
2054 if (!found_da_stream) {
2055 /*
2056 * The DP stream isn't in the DA topology which would imply that the intention of the
2057 * request was to add the stream, not change its state. It's possible though that
2058 * the stream was added by another request between the time this request was queued
2059 * and now so we need to check the CA topology as well.
2060 */
2061 ast_trace(-1, "%s: There was no corresponding DA stream so the request was to add a stream\n", session_name);
2062
2063 if (found_np_stream) {
2064 /*
2065 * We found it in the CA topology. Since the intention was to add it
2066 * and it's already there, there's nothing to do.
2067 */
2068 SCOPE_EXIT_EXPR(continue, "%s: New stream requested but it's already in CA\n", session_name);
2069 } else {
2070 /* OK, it's not in either which would again imply that the intention of the
2071 * request was to add the stream.
2072 */
2073 ast_trace(-1, "%s: There was no corresponding NP stream\n", session_name);
2074 if (STATE_REMOVED(dp_state)) {
2075 /*
2076 * How can DP request to remove a stream that doesn't seem to exist anythere?
2077 * It's not. It's possible that the stream was already removed and the slot
2078 * reused in the CA topology, but it would still have to exist in the DA
2079 * topology. Bail.
2080 */
2082 "%s: Attempting to remove stream %d:%s but it doesn't exist anywhere.\n", session_name, i, dp_name);
2083 } else {
2084 /*
2085 * We're now sure we want to add the the stream. Since we can re-use
2086 * slots in the CA topology that have streams marked as "removed", we
2087 * use the slot we saved in removed_np_slot if it exists.
2088 */
2089 ast_trace(-1, "%s: Checking for open slot\n", session_name);
2090 if (removed_np_slot >= 0) {
2091 struct ast_sip_session_media *old_media = AST_VECTOR_GET(&new_pending_state->sessions, removed_np_slot);
2092 res = ast_stream_topology_set_stream(new_pending, removed_np_slot, ast_stream_clone(dp_stream, NULL));
2093 if (res != 0) {
2094 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_WARNING, "%s: Couldn't set stream in new topology\n", session_name);
2095 }
2096 /*
2097 * Since we're reusing the removed_np_slot slot for something else, we need
2098 * to free and remove any session media already in it.
2099 * ast_stream_topology_set_stream() took care of freeing the old stream.
2100 */
2101 res = AST_VECTOR_REPLACE(&new_pending_state->sessions, removed_np_slot, NULL);
2102 if (res != 0) {
2103 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_WARNING, "%s: Couldn't replace media session\n", session_name);
2104 }
2105
2106 ao2_cleanup(old_media);
2107 SCOPE_EXIT_EXPR(continue, "%s: Replaced removed stream in slot %d\n",
2108 session_name, removed_np_slot);
2109 } else {
2110 int new_slot = ast_stream_topology_append_stream(new_pending, ast_stream_clone(dp_stream, NULL));
2111 if (new_slot < 0) {
2112 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_WARNING, "%s: Couldn't append stream in new topology\n", session_name);
2113 }
2114
2115 res = AST_VECTOR_REPLACE(&new_pending_state->sessions, new_slot, NULL);
2116 if (res != 0) {
2117 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_WARNING, "%s: Couldn't replace media session\n", session_name);
2118 }
2119 SCOPE_EXIT_EXPR(continue, "%s: Appended new stream to slot %d\n",
2120 session_name, new_slot);
2121 }
2122 }
2123 }
2124 } else {
2125 /*
2126 * The DP stream exists in the DA topology so it's a change of some sort.
2127 */
2128 ast_trace(-1, "%s: There was a corresponding DA stream so the request was to change/remove a stream\n", session_name);
2129 if (dp_state == found_da_state) {
2130 /* No change? Let's see if it's in CA */
2131 if (!found_np_stream) {
2132 /*
2133 * The DP and DA state are the same which would imply that the stream
2134 * already exists but it's not in the CA topology. It's possible that
2135 * between the time this request was queued and now the stream was removed
2136 * from the CA topology and the slot used for something else. Nothing
2137 * we can do here.
2138 */
2139 SCOPE_EXIT_EXPR(continue, "%s: Stream doesn't exist in CA so nothing to do\n", session_name);
2140 } else if (dp_state == found_np_state) {
2141 SCOPE_EXIT_EXPR(continue, "%s: States are the same all around so nothing to do\n", session_name);
2142 } else {
2143 SCOPE_EXIT_EXPR(continue, "%s: Something changed the CA state so we're going to leave it as is\n", session_name);
2144 }
2145 } else {
2146 /* We have a state change. */
2147 ast_trace(-1, "%s: Requesting state change to %s\n", session_name, ast_stream_state2str(dp_state));
2148 if (!found_np_stream) {
2149 SCOPE_EXIT_EXPR(continue, "%s: Stream doesn't exist in CA so nothing to do\n", session_name);
2150 } else if (da_state == found_np_state) {
2151 ast_stream_set_state(found_np_stream, dp_state);
2152 SCOPE_EXIT_EXPR(continue, "%s: Changed NP stream state from %s to %s\n",
2153 session_name, ast_stream_state2str(found_np_state), ast_stream_state2str(dp_state));
2154 } else {
2155 SCOPE_EXIT_EXPR(continue, "%s: Something changed the CA state so we're going to leave it as is\n",
2156 session_name);
2157 }
2158 }
2159 }
2160
2161 SCOPE_EXIT("%s: Done with slot %d\n", session_name, i);
2162 }
2163
2164 ast_trace(-1, "%s: Resetting default media states\n", session_name);
2165 for (i = 0; i < AST_MEDIA_TYPE_END; i++) {
2166 int j;
2167 new_pending_state->default_session[i] = NULL;
2168 for (j = 0; j < AST_VECTOR_SIZE(&new_pending_state->sessions); j++) {
2169 struct ast_sip_session_media *media = AST_VECTOR_GET(&new_pending_state->sessions, j);
2170 struct ast_stream *stream = ast_stream_topology_get_stream(new_pending_state->topology, j);
2171
2172 if (media && media->type == i && !STREAM_REMOVED(stream)) {
2173 new_pending_state->default_session[i] = media;
2174 break;
2175 }
2176 }
2177 }
2178
2179 if (run_post_validation) {
2180 ast_trace(-1, "%s: Running post-validation\n", session_name);
2181 if (!is_media_state_valid(session_name, new_pending_state)) {
2182 SCOPE_EXIT_LOG_RTN_VALUE(NULL, LOG_ERROR, "State not consistent\n");
2183 }
2184 }
2185
2186 /*
2187 * We need to move the new pending state to another variable and set new_pending_state to NULL
2188 * so RAII_VAR doesn't free it.
2189 */
2190 returned_media_state = new_pending_state;
2191 new_pending_state = NULL;
2192 SCOPE_EXIT_RTN_VALUE(returned_media_state, "%s: NP: %s\n", session_name,
2193 ast_str_tmp(256, ast_stream_topology_to_str(new_pending, &STR_TMP)));
2194}
2195
2197 ast_sip_session_request_creation_cb on_request_creation,
2198 ast_sip_session_sdp_creation_cb on_sdp_creation,
2199 ast_sip_session_response_cb on_response,
2200 enum ast_sip_session_refresh_method method, int generate_new_sdp,
2201 struct ast_sip_session_media_state *pending_media_state,
2202 struct ast_sip_session_media_state *active_media_state,
2203 int queued)
2204{
2205 pjsip_inv_session *inv_session = session->inv_session;
2206 pjmedia_sdp_session *new_sdp = NULL;
2207 pjsip_tx_data *tdata;
2208 int res = -1;
2209 SCOPE_ENTER(3, "%s: New SDP? %s Queued? %s DP: %s DA: %s\n", ast_sip_session_get_name(session),
2210 generate_new_sdp ? "yes" : "no", queued ? "yes" : "no",
2211 pending_media_state ? ast_str_tmp(256, ast_stream_topology_to_str(pending_media_state->topology, &STR_TMP)) : "none",
2212 active_media_state ? ast_str_tmp(256, ast_stream_topology_to_str(active_media_state->topology, &STR_TMP)) : "none");
2213
2214 if (pending_media_state && (!pending_media_state->topology || !generate_new_sdp)) {
2215
2216 ast_sip_session_media_state_free(pending_media_state);
2217 ast_sip_session_media_state_free(active_media_state);
2218 SCOPE_EXIT_RTN_VALUE(-1, "%s: Not sending reinvite because %s%s\n", ast_sip_session_get_name(session),
2219 pending_media_state->topology == NULL ? "pending topology is null " : "",
2220 !generate_new_sdp ? "generate_new_sdp is false" : "");
2221 }
2222
2223 if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2224 /* Don't try to do anything with a hung-up call */
2225 ast_sip_session_media_state_free(pending_media_state);
2226 ast_sip_session_media_state_free(active_media_state);
2227 SCOPE_EXIT_RTN_VALUE(0, "%s: Not sending reinvite because of disconnected state\n",
2229 }
2230
2231 /* If the dialog has not yet been established we have to defer until it has */
2232 if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
2233 res = delay_request(session, on_request_creation, on_sdp_creation, on_response,
2234 generate_new_sdp,
2237 pending_media_state, active_media_state ? active_media_state : ast_sip_session_media_state_clone(session->active_media_state), queued);
2238 SCOPE_EXIT_RTN_VALUE(res, "%s: Delay sending reinvite because dialog has not been established\n",
2240 }
2241
2243 if (inv_session->invite_tsx) {
2244 /* We can't send a reinvite yet, so delay it */
2245 res = delay_request(session, on_request_creation, on_sdp_creation,
2246 on_response, generate_new_sdp, DELAYED_METHOD_INVITE, pending_media_state,
2247 active_media_state ? active_media_state : ast_sip_session_media_state_clone(session->active_media_state), queued);
2248 SCOPE_EXIT_RTN_VALUE(res, "%s: Delay sending reinvite because of outstanding transaction\n",
2250 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
2251 /* Initial INVITE transaction failed to progress us to a confirmed state
2252 * which means re-invites are not possible
2253 */
2254 ast_sip_session_media_state_free(pending_media_state);
2255 ast_sip_session_media_state_free(active_media_state);
2256 SCOPE_EXIT_RTN_VALUE(0, "%s: Not sending reinvite because not in confirmed state\n",
2258 }
2259 }
2260
2261 if (generate_new_sdp) {
2262 /* SDP can only be generated if current negotiation has already completed */
2263 if (inv_session->neg
2264 && pjmedia_sdp_neg_get_state(inv_session->neg)
2265 != PJMEDIA_SDP_NEG_STATE_DONE) {
2266 res = delay_request(session, on_request_creation, on_sdp_creation,
2267 on_response, generate_new_sdp,
2269 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE, pending_media_state,
2270 active_media_state ? active_media_state : ast_sip_session_media_state_clone(session->active_media_state), queued);
2271 SCOPE_EXIT_RTN_VALUE(res, "%s: Delay session refresh with new SDP because SDP negotiation is not yet done\n",
2273 }
2274
2275 /* If an explicitly requested media state has been provided use it instead of any pending one */
2276 if (pending_media_state) {
2277 int index;
2278 int type_streams[AST_MEDIA_TYPE_END] = {0};
2279
2280 ast_trace(-1, "%s: Pending media state exists\n", ast_sip_session_get_name(session));
2281
2282 /* Media state conveys a desired media state, so if there are outstanding
2283 * delayed requests we need to ensure we go into the queue and not jump
2284 * ahead. If we sent this media state now then updates could go out of
2285 * order.
2286 */
2287 if (!queued && !AST_LIST_EMPTY(&session->delayed_requests)) {
2288 res = delay_request(session, on_request_creation, on_sdp_creation,
2289 on_response, generate_new_sdp,
2291 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE, pending_media_state,
2292 active_media_state ? active_media_state : ast_sip_session_media_state_clone(session->active_media_state), queued);
2293 SCOPE_EXIT_RTN_VALUE(res, "%s: Delay sending reinvite because of outstanding requests\n",
2295 }
2296
2297 /*
2298 * Attempt to resolve only if objects are available, and it's not
2299 * switching to or from an image type.
2300 */
2301 if (active_media_state && active_media_state->topology &&
2302 (!active_media_state->default_session[AST_MEDIA_TYPE_IMAGE] ==
2303 !pending_media_state->default_session[AST_MEDIA_TYPE_IMAGE])) {
2304
2305 struct ast_sip_session_media_state *new_pending_state;
2306
2307 ast_trace(-1, "%s: Active media state exists and is%s equal to pending\n", ast_sip_session_get_name(session),
2308 !ast_stream_topology_equal(active_media_state->topology,pending_media_state->topology) ? " not" : "");
2309 ast_trace(-1, "%s: DP: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(pending_media_state->topology, &STR_TMP)));
2310 ast_trace(-1, "%s: DA: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(active_media_state->topology, &STR_TMP)));
2311 ast_trace(-1, "%s: CP: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(session->pending_media_state->topology, &STR_TMP)));
2312 ast_trace(-1, "%s: CA: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(session->active_media_state->topology, &STR_TMP)));
2313
2315 pending_media_state, active_media_state, session->active_media_state, 1);
2316 if (new_pending_state) {
2317 ast_trace(-1, "%s: NP: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(new_pending_state->topology, &STR_TMP)));
2318 ast_sip_session_media_state_free(pending_media_state);
2319 pending_media_state = new_pending_state;
2320 } else {
2321 ast_sip_session_media_state_reset(pending_media_state);
2322 ast_sip_session_media_state_free(active_media_state);
2323 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Unable to merge media states\n", ast_sip_session_get_name(session));
2324 }
2325 }
2326
2327 /* Prune the media state so the number of streams fit within the configured limits - we do it here
2328 * so that the index of the resulting streams in the SDP match. If we simply left the streams out
2329 * of the SDP when producing it we'd be in trouble. We also enforce formats here for media types that
2330 * are configurable on the endpoint.
2331 */
2332 ast_trace(-1, "%s: Pruning and checking formats of streams\n", ast_sip_session_get_name(session));
2333
2334 for (index = 0; index < ast_stream_topology_get_count(pending_media_state->topology); ++index) {
2335 struct ast_stream *existing_stream = NULL;
2336 struct ast_stream *stream = ast_stream_topology_get_stream(pending_media_state->topology, index);
2337 SCOPE_ENTER(4, "%s: Checking stream %s\n", ast_sip_session_get_name(session),
2338 ast_stream_get_name(stream));
2339
2340 if (session->active_media_state->topology &&
2341 index < ast_stream_topology_get_count(session->active_media_state->topology)) {
2342 existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
2343 ast_trace(-1, "%s: Found existing stream %s\n", ast_sip_session_get_name(session),
2344 ast_stream_get_name(existing_stream));
2345 }
2346
2347 if (is_stream_limitation_reached(ast_stream_get_type(stream), session->endpoint, type_streams)) {
2348 if (index < AST_VECTOR_SIZE(&pending_media_state->sessions)) {
2349 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&pending_media_state->sessions, index);
2350
2351 ao2_cleanup(session_media);
2352 AST_VECTOR_REMOVE(&pending_media_state->sessions, index, 1);
2353 }
2354
2355 ast_stream_topology_del_stream(pending_media_state->topology, index);
2356 ast_trace(-1, "%s: Dropped overlimit stream %s\n", ast_sip_session_get_name(session),
2357 ast_stream_get_name(stream));
2358
2359 /* A stream has potentially moved into our spot so we need to jump back so we process it */
2360 index -= 1;
2361 SCOPE_EXIT_EXPR(continue);
2362 }
2363
2364 /* No need to do anything with stream if it's media state is removed */
2366 /* If there is no existing stream we can just not have this stream in the topology at all. */
2367 if (!existing_stream) {
2368 ast_trace(-1, "%s: Dropped removed stream %s\n", ast_sip_session_get_name(session),
2369 ast_stream_get_name(stream));
2370 ast_stream_topology_del_stream(pending_media_state->topology, index);
2371 /* TODO: Do we need to remove the corresponding media state? */
2372 index -= 1;
2373 }
2374 SCOPE_EXIT_EXPR(continue);
2375 }
2376
2377 /* Enforce the configured allowed codecs on audio and video streams */
2379 !ast_stream_get_metadata(stream, "pjsip_session_refresh")) {
2380 struct ast_format_cap *joint_cap;
2381
2383 if (!joint_cap) {
2384 ast_sip_session_media_state_free(pending_media_state);
2385 ast_sip_session_media_state_free(active_media_state);
2386 res = -1;
2387 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Unable to alloc format caps\n", ast_sip_session_get_name(session));
2388 }
2389 ast_format_cap_get_compatible(ast_stream_get_formats(stream), session->endpoint->media.codecs, joint_cap);
2390 if (!ast_format_cap_count(joint_cap)) {
2391 ao2_ref(joint_cap, -1);
2392
2393 if (!existing_stream) {
2394 /* If there is no existing stream we can just not have this stream in the topology
2395 * at all.
2396 */
2397 ast_stream_topology_del_stream(pending_media_state->topology, index);
2398 index -= 1;
2399 SCOPE_EXIT_EXPR(continue, "%s: Dropped incompatible stream %s\n",
2401 } else if (ast_stream_get_state(stream) != ast_stream_get_state(existing_stream) ||
2402 strcmp(ast_stream_get_name(stream), ast_stream_get_name(existing_stream))) {
2403 /* If the underlying stream is a different type or different name then we have to
2404 * mark it as removed, as it is replacing an existing stream. We do this so order
2405 * is preserved.
2406 */
2408 SCOPE_EXIT_EXPR(continue, "%s: Dropped incompatible stream %s\n",
2410 } else {
2411 /* However if the stream is otherwise remaining the same we can keep the formats
2412 * that exist on it already which allows media to continue to flow. We don't modify
2413 * the format capabilities but do need to cast it so that ao2_bump can raise the
2414 * reference count.
2415 */
2416 joint_cap = ao2_bump((struct ast_format_cap *)ast_stream_get_formats(existing_stream));
2417 }
2418 }
2419 ast_stream_set_formats(stream, joint_cap);
2420 ao2_cleanup(joint_cap);
2421 }
2422
2423 ++type_streams[ast_stream_get_type(stream)];
2424
2425 SCOPE_EXIT();
2426 }
2427
2428 if (session->active_media_state->topology) {
2429 /* SDP is a fun thing. Take for example the fact that streams are never removed. They just become
2430 * declined. To better handle this in the case where something requests a topology change for fewer
2431 * streams than are currently present we fill in the topology to match the current number of streams
2432 * that are active.
2433 */
2434
2435 for (index = ast_stream_topology_get_count(pending_media_state->topology);
2436 index < ast_stream_topology_get_count(session->active_media_state->topology); ++index) {
2437 struct ast_stream *stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
2438 struct ast_stream *cloned;
2439 int position;
2440 SCOPE_ENTER(4, "%s: Stream %s not in pending\n", ast_sip_session_get_name(session),
2441 ast_stream_get_name(stream));
2442
2443 cloned = ast_stream_clone(stream, NULL);
2444 if (!cloned) {
2445 ast_sip_session_media_state_free(pending_media_state);
2446 ast_sip_session_media_state_free(active_media_state);
2447 res = -1;
2448 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Unable to clone stream %s\n",
2450 }
2451
2453 position = ast_stream_topology_append_stream(pending_media_state->topology, cloned);
2454 if (position < 0) {
2455 ast_stream_free(cloned);
2456 ast_sip_session_media_state_free(pending_media_state);
2457 ast_sip_session_media_state_free(active_media_state);
2458 res = -1;
2459 SCOPE_EXIT_LOG_EXPR(goto end, LOG_ERROR, "%s: Unable to append cloned stream\n",
2461 }
2462 SCOPE_EXIT("%s: Appended empty stream in position %d to make counts match\n",
2464 }
2465
2466 /*
2467 * We can suppress this re-invite if the pending topology is equal to the currently
2468 * active topology.
2469 */
2470 if (ast_stream_topology_equal(session->active_media_state->topology, pending_media_state->topology)) {
2471 ast_trace(-1, "%s: CA: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(session->active_media_state->topology, &STR_TMP)));
2472 ast_trace(-1, "%s: NP: %s\n", ast_sip_session_get_name(session), ast_str_tmp(256, ast_stream_topology_to_str(pending_media_state->topology, &STR_TMP)));
2473 ast_sip_session_media_state_free(pending_media_state);
2474 ast_sip_session_media_state_free(active_media_state);
2475 /* For external consumers we return 0 to say success, but internally for
2476 * send_delayed_request we return a separate value to indicate that this
2477 * session refresh would be redundant so we didn't send it
2478 */
2479 SCOPE_EXIT_RTN_VALUE(queued ? 1 : 0, "%s: Topologies are equal. Not sending re-invite\n",
2481 }
2482 }
2483
2484 ast_sip_session_media_state_free(session->pending_media_state);
2485 session->pending_media_state = pending_media_state;
2486 }
2487
2489 if (!new_sdp) {
2490 ast_sip_session_media_state_reset(session->pending_media_state);
2491 ast_sip_session_media_state_free(active_media_state);
2492 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Failed to generate session refresh SDP. Not sending session refresh\n",
2494 }
2495 if (on_sdp_creation) {
2496 if (on_sdp_creation(session, new_sdp)) {
2497 ast_sip_session_media_state_reset(session->pending_media_state);
2498 ast_sip_session_media_state_free(active_media_state);
2499 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: on_sdp_creation failed\n", ast_sip_session_get_name(session));
2500 }
2501 }
2502 }
2503
2505 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
2506 if (generate_new_sdp) {
2507 ast_sip_session_media_state_reset(session->pending_media_state);
2508 }
2509 ast_sip_session_media_state_free(active_media_state);
2510 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Failed to create reinvite properly\n", ast_sip_session_get_name(session));
2511 }
2512 } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
2513 if (generate_new_sdp) {
2514 ast_sip_session_media_state_reset(session->pending_media_state);
2515 }
2516 ast_sip_session_media_state_free(active_media_state);
2517 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: Failed to create UPDATE properly\n", ast_sip_session_get_name(session));
2518 }
2519 if (on_request_creation) {
2520 if (on_request_creation(session, tdata)) {
2521 if (generate_new_sdp) {
2522 ast_sip_session_media_state_reset(session->pending_media_state);
2523 }
2524 ast_sip_session_media_state_free(active_media_state);
2525 SCOPE_EXIT_LOG_RTN_VALUE(-1, LOG_WARNING, "%s: on_request_creation failed.\n", ast_sip_session_get_name(session));
2526 }
2527 }
2528 ast_sip_session_send_request_with_cb(session, tdata, on_response);
2529 ast_sip_session_media_state_free(active_media_state);
2530
2531end:
2532 SCOPE_EXIT_RTN_VALUE(res, "%s: Sending session refresh SDP via %s\n", ast_sip_session_get_name(session),
2533 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE");
2534}
2535
2537 ast_sip_session_request_creation_cb on_request_creation,
2538 ast_sip_session_sdp_creation_cb on_sdp_creation,
2539 ast_sip_session_response_cb on_response,
2540 enum ast_sip_session_refresh_method method, int generate_new_sdp,
2541 struct ast_sip_session_media_state *media_state)
2542{
2543 return sip_session_refresh(session, on_request_creation, on_sdp_creation,
2544 on_response, method, generate_new_sdp, media_state, NULL, 0);
2545}
2546
2548 ast_sip_session_sdp_creation_cb on_sdp_creation)
2549{
2550 pjsip_inv_session *inv_session = session->inv_session;
2551 pjmedia_sdp_session *new_answer = NULL;
2552 const pjmedia_sdp_session *previous_offer = NULL;
2554
2555 /* The SDP answer can only be regenerated if it is still pending to be sent */
2556 if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
2557 pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {
2558 ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",
2559 ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));
2560 SCOPE_EXIT_RTN_VALUE(-1, "Bad negotiation state\n");
2561 }
2562
2563 pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);
2564 if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {
2565 /* Transition the SDP negotiator back to when it received the remote offer */
2566 pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);
2567 pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);
2568 }
2569
2570 new_answer = create_local_sdp(inv_session, session, previous_offer, 0);
2571 if (!new_answer) {
2572 ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",
2573 ast_channel_name(session->channel));
2574 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create new SDP\n");
2575 }
2576
2577 if (on_sdp_creation) {
2578 if (on_sdp_creation(session, new_answer)) {
2579 SCOPE_EXIT_RTN_VALUE(-1, "Callback failed\n");
2580 }
2581 }
2582
2583 pjsip_inv_set_sdp_answer(inv_session, new_answer);
2584
2586}
2587
2588void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
2589{
2590 pjsip_dialog *dlg = pjsip_tdata_get_dlg(tdata);
2591 RAII_VAR(struct ast_sip_session *, dlg_session, dlg ? ast_sip_dialog_get_session(dlg) : NULL, ao2_cleanup);
2592 if (!dlg_session) {
2593 /* If the dialog has a session, handle_outgoing_response will be called
2594 from session_on_tx_response. If it does not, call it from here. */
2596 }
2597 pjsip_inv_send_msg(session->inv_session, tdata);
2598 return;
2599}
2600
2601static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
2602static pj_bool_t session_on_rx_response(pjsip_rx_data *rdata);
2603static pj_status_t session_on_tx_response(pjsip_tx_data *tdata);
2604static void session_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e);
2605
2606static pjsip_module session_module = {
2607 .name = {"Session Module", 14},
2608 .priority = PJSIP_MOD_PRIORITY_APPLICATION,
2609 .on_rx_request = session_on_rx_request,
2610 .on_rx_response = session_on_rx_response,
2611 .on_tsx_state = session_on_tsx_state,
2612 .on_tx_response = session_on_tx_response,
2613};
2614
2615/*! \brief Determine whether the SDP provided requires deferral of negotiating or not
2616 *
2617 * \retval 1 re-invite should be deferred and resumed later
2618 * \retval 0 re-invite should not be deferred
2619 */
2620static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
2621{
2622 int i;
2623
2624 if (!session->pending_media_state->topology) {
2625 session->pending_media_state->topology = ast_stream_topology_alloc();
2626 if (!session->pending_media_state->topology) {
2627 return -1;
2628 }
2629 }
2630
2631 for (i = 0; i < sdp->media_count; ++i) {
2632 /* See if there are registered handlers for this media stream type */
2633 char media[20];
2635 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2636 struct ast_stream *existing_stream = NULL;
2637 struct ast_stream *stream;
2638 enum ast_media_type type;
2639 struct ast_sip_session_media *session_media = NULL;
2641 pjmedia_sdp_media *remote_stream = sdp->media[i];
2642
2643 /* We need a null-terminated version of the media string */
2644 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
2645
2646 if (session->active_media_state->topology &&
2647 (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
2648 existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
2649 }
2650
2652 stream = ast_stream_alloc(existing_stream ? ast_stream_get_name(existing_stream) : ast_codec_media_type2str(type), type);
2653 if (!stream) {
2654 return -1;
2655 }
2656
2657 /* As this is only called on an incoming SDP offer before processing it is not possible
2658 * for streams and their media sessions to exist.
2659 */
2660 if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
2661 ast_stream_free(stream);
2662 return -1;
2663 }
2664
2665 if (existing_stream) {
2666 const char *stream_label = ast_stream_get_metadata(existing_stream, "SDP:LABEL");
2667
2668 if (!ast_strlen_zero(stream_label)) {
2669 ast_stream_set_metadata(stream, "SDP:LABEL", stream_label);
2670 }
2671 }
2672
2673 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
2674 if (!session_media) {
2675 return -1;
2676 }
2677
2678 /* For backwards compatibility with the core the default audio stream is always sendrecv */
2679 if (!ast_sip_session_is_pending_stream_default(session, stream) || strcmp(media, "audio")) {
2680 if (pjmedia_sdp_media_find_attr2(remote_stream, "sendonly", NULL)) {
2681 /* Stream state reflects our state of a stream, so in the case of
2682 * sendonly and recvonly we store the opposite since that is what ours
2683 * is.
2684 */
2686 } else if (pjmedia_sdp_media_find_attr2(remote_stream, "recvonly", NULL)) {
2688 } else if (pjmedia_sdp_media_find_attr2(remote_stream, "inactive", NULL)) {
2690 } else {
2692 }
2693 } else {
2695 }
2696
2697 if (session_media->handler) {
2698 handler = session_media->handler;
2699 if (handler->defer_incoming_sdp_stream) {
2700 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
2701 sdp->media[i]);
2702 switch (res) {
2704 break;
2706 return 0;
2708 break;
2710 return 1;
2711 }
2712 }
2713 /* Handled by this handler. Move to the next stream */
2714 continue;
2715 }
2716
2717 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2718 if (!handler_list) {
2719 ast_debug(3, "%s: No registered SDP handlers for media type '%s'\n", ast_sip_session_get_name(session), media);
2720 continue;
2721 }
2722 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2723 if (handler == session_media->handler) {
2724 continue;
2725 }
2726 if (!handler->defer_incoming_sdp_stream) {
2727 continue;
2728 }
2729 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
2730 sdp->media[i]);
2731 switch (res) {
2733 continue;
2735 session_media_set_handler(session_media, handler);
2736 return 0;
2738 /* Handled by this handler. */
2739 session_media_set_handler(session_media, handler);
2740 break;
2742 /* Handled by this handler. */
2743 session_media_set_handler(session_media, handler);
2744 return 1;
2745 }
2746 /* Move to the next stream */
2747 break;
2748 }
2749 }
2750 return 0;
2751}
2752
2753static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
2754{
2755 pjsip_dialog *dlg;
2757 pjsip_rdata_sdp_info *sdp_info;
2758 int deferred;
2759
2760 if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
2761 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
2763 !session->channel) {
2764 return PJ_FALSE;
2765 }
2766
2767 if (session->inv_session->invite_tsx) {
2768 /* There's a transaction in progress so bail now and let pjproject send 491 */
2769 return PJ_FALSE;
2770 }
2771
2772 if (session->deferred_reinvite) {
2773 pj_str_t key, deferred_key;
2774 pjsip_tx_data *tdata;
2775
2776 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
2777 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
2778 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
2779 session->deferred_reinvite);
2780
2781 /* If this is a retransmission ignore it */
2782 if (!pj_strcmp(&key, &deferred_key)) {
2783 return PJ_TRUE;
2784 }
2785
2786 /* Otherwise this is a new re-invite, so reject it */
2787 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
2788 if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
2789 pjsip_tx_data_dec_ref(tdata);
2790 }
2791 }
2792
2793 return PJ_TRUE;
2794 }
2795
2796 if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
2797 (sdp_info->sdp_err != PJ_SUCCESS)) {
2798 return PJ_FALSE;
2799 }
2800
2801 if (!sdp_info->sdp) {
2802 return PJ_FALSE;
2803 }
2804
2805 deferred = sdp_requires_deferral(session, sdp_info->sdp);
2806 if (deferred == -1) {
2807 ast_sip_session_media_state_reset(session->pending_media_state);
2808 return PJ_FALSE;
2809 } else if (!deferred) {
2810 return PJ_FALSE;
2811 }
2812
2813 pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
2814
2815 return PJ_TRUE;
2816}
2817
2819{
2820 if (!session->deferred_reinvite) {
2821 return;
2822 }
2823
2824 if (session->channel) {
2825 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
2826 session->deferred_reinvite, NULL, NULL);
2827 }
2828 pjsip_rx_data_free_cloned(session->deferred_reinvite);
2829 session->deferred_reinvite = NULL;
2830}
2831
2832static pjsip_module session_reinvite_module = {
2833 .name = { "Session Re-Invite Module", 24 },
2834 .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
2835 .on_rx_request = session_reinvite_on_rx_request,
2836};
2837
2839 ast_sip_session_response_cb on_response)
2840{
2841 pjsip_inv_session *inv_session = session->inv_session;
2842
2843 /* For every request except BYE we disallow sending of the message when
2844 * the session has been disconnected. A BYE request is special though
2845 * because it can be sent again after the session is disconnected except
2846 * with credentials.
2847 */
2848 if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&
2849 tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {
2850 return;
2851 }
2852
2853 ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
2854 MOD_DATA_ON_RESPONSE, on_response);
2855
2857 pjsip_inv_send_msg(session->inv_session, tdata);
2858
2859 return;
2860}
2861
2862void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2863{
2865}
2866
2867int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
2868{
2869 pjmedia_sdp_session *offer;
2871
2872 if (!(offer = create_local_sdp(session->inv_session, session, NULL, 0))) {
2873 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
2874 SCOPE_EXIT_RTN_VALUE(-1, "Couldn't create offer\n");
2875 }
2876
2877 pjsip_inv_set_local_sdp(session->inv_session, offer);
2878 pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
2879#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2880 if (!session->endpoint->preferred_codec_only) {
2881 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
2882 }
2883#endif
2884
2885 /*
2886 * We MUST call set_from_header() before pjsip_inv_invite. If we don't, the
2887 * From in the initial INVITE will be wrong but the rest of the messages will be OK.
2888 */
2890
2891 if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
2892 SCOPE_EXIT_RTN_VALUE(-1, "pjsip_inv_invite failed\n");
2893 }
2894
2896}
2897
2898static int datastore_hash(const void *obj, int flags)
2899{
2900 const struct ast_datastore *datastore = obj;
2901 const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
2902
2903 ast_assert(uid != NULL);
2904
2905 return ast_str_hash(uid);
2906}
2907
2908static int datastore_cmp(void *obj, void *arg, int flags)
2909{
2910 const struct ast_datastore *datastore1 = obj;
2911 const struct ast_datastore *datastore2 = arg;
2912 const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
2913
2914 ast_assert(datastore1->uid != NULL);
2915 ast_assert(uid2 != NULL);
2916
2917 return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
2918}
2919
2920static void session_destructor(void *obj)
2921{
2922 struct ast_sip_session *session = obj;
2923 struct ast_sip_session_delayed_request *delay;
2924
2925#ifdef TEST_FRAMEWORK
2926 /* We dup the endpoint ID in case the endpoint gets freed out from under us */
2927 const char *endpoint_name = session->endpoint ?
2928 ast_strdupa(ast_sorcery_object_get_id(session->endpoint)) : "<none>";
2929#endif
2930
2931 ast_debug(3, "%s: Destroying SIP session\n", ast_sip_session_get_name(session));
2932
2933 ast_test_suite_event_notify("SESSION_DESTROYING",
2934 "Endpoint: %s\r\n"
2935 "AOR: %s\r\n"
2936 "Contact: %s"
2937 , endpoint_name
2938 , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"
2939 , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"
2940 );
2941
2942 /* fire session destroy handler */
2944
2945 /* remove all registered supplements */
2947 AST_LIST_HEAD_DESTROY(&session->supplements);
2948
2949 /* remove all saved media stats */
2950 AST_VECTOR_RESET(&session->media_stats, ast_free);
2951 AST_VECTOR_FREE(&session->media_stats);
2952
2954 ao2_cleanup(session->datastores);
2955 ast_sip_session_media_state_free(session->active_media_state);
2956 ast_sip_session_media_state_free(session->pending_media_state);
2957
2958 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2959 delayed_request_free(delay);
2960 }
2962 ao2_cleanup(session->endpoint);
2963 ao2_cleanup(session->aor);
2964 ao2_cleanup(session->contact);
2965 ao2_cleanup(session->direct_media_cap);
2966
2967 ast_dsp_free(session->dsp);
2968
2969 if (session->inv_session) {
2970 struct pjsip_dialog *dlg = session->inv_session->dlg;
2971
2972 /* The INVITE session uses the dialog pool for memory, so we need to
2973 * decrement its reference first before that of the dialog.
2974 */
2975
2976#ifdef HAVE_PJSIP_INV_SESSION_REF
2977 pjsip_inv_dec_ref(session->inv_session);
2978#endif
2979 pjsip_dlg_dec_session(dlg, &session_module);
2980 }
2981
2982 ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);
2983}
2984
2985/*! \brief Destructor for SIP channel */
2986static void sip_channel_destroy(void *obj)
2987{
2988 struct ast_sip_channel_pvt *channel = obj;
2989
2990 ao2_cleanup(channel->pvt);
2991 ao2_cleanup(channel->session);
2992}
2993
2995{
2996 struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
2997
2998 if (!channel) {
2999 return NULL;
3000 }
3001
3002 ao2_ref(pvt, +1);
3003 channel->pvt = pvt;
3004 ao2_ref(session, +1);
3005 channel->session = session;
3006
3007 return channel;
3008}
3009
3011 struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
3012{
3014 struct ast_sip_session *ret_session;
3015 int dsp_features = 0;
3016
3018 if (!session) {
3019 return NULL;
3020 }
3021
3022 AST_LIST_HEAD_INIT(&session->supplements);
3023 AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
3025
3027 if (!session->direct_media_cap) {
3028 return NULL;
3029 }
3032 if (!session->datastores) {
3033 return NULL;
3034 }
3035 session->active_media_state = ast_sip_session_media_state_alloc();
3036 if (!session->active_media_state) {
3037 return NULL;
3038 }
3039 session->pending_media_state = ast_sip_session_media_state_alloc();
3040 if (!session->pending_media_state) {
3041 return NULL;
3042 }
3043 if (AST_VECTOR_INIT(&session->media_stats, 1) < 0) {
3044 return NULL;
3045 }
3046
3048 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
3049 }
3050 if (endpoint->faxdetect) {
3051 dsp_features |= DSP_FEATURE_FAX_DETECT;
3052 }
3053 if (dsp_features) {
3054 session->dsp = ast_dsp_new();
3055 if (!session->dsp) {
3056 return NULL;
3057 }
3058
3059 ast_dsp_set_features(session->dsp, dsp_features);
3060 }
3061
3062 session->endpoint = ao2_bump(endpoint);
3063
3064 if (rdata) {
3065 /*
3066 * We must continue using the serializer that the original
3067 * INVITE came in on for the dialog. There may be
3068 * retransmissions already enqueued in the original
3069 * serializer that can result in reentrancy and message
3070 * sequencing problems.
3071 */
3072 session->serializer = ast_sip_get_distributor_serializer(rdata);
3073 } else {
3074 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
3075
3076 /* Create name with seq number appended. */
3077 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
3079
3080 session->serializer = ast_sip_create_serializer(tps_name);
3081 }
3082 if (!session->serializer) {
3083 return NULL;
3084 }
3087
3088 /* When a PJSIP INVITE session is created it is created with a reference
3089 * count of 1, with that reference being managed by the underlying state
3090 * of the INVITE session itself. When the INVITE session transitions to
3091 * a DISCONNECTED state that reference is released. This means we can not
3092 * rely on that reference to ensure the INVITE session remains for the
3093 * lifetime of our session. To ensure it does we add our own reference
3094 * and release it when our own session goes away, ensuring that the INVITE
3095 * session remains for the lifetime of session.
3096 */
3097
3098#ifdef HAVE_PJSIP_INV_SESSION_REF
3099 if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {
3100 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
3101 return NULL;
3102 }
3103#endif
3104
3105 pjsip_dlg_inc_session(inv_session->dlg, &session_module);
3106 inv_session->mod_data[session_module.id] = ao2_bump(session);
3107 session->contact = ao2_bump(contact);
3108 session->inv_session = inv_session;
3109
3110 session->dtmf = endpoint->dtmf;
3111 session->moh_passthrough = endpoint->moh_passthrough;
3112
3114 /* Release the ref held by session->inv_session */
3115 ao2_ref(session, -1);
3116 return NULL;
3117 }
3118
3119 session->authentication_challenge_count = 0;
3120
3121 /* Fire session begin handlers */
3123
3124 /* Avoid unnecessary ref manipulation to return a session */
3125 ret_session = session;
3126 session = NULL;
3127 return ret_session;
3128}
3129
3130/*! \brief struct controlling the suspension of the session's serializer. */
3136};
3137
3138static void sip_session_suspender_dtor(void *vdoomed)
3139{
3140 struct ast_sip_session_suspender *doomed = vdoomed;
3141
3144}
3145
3146/*!
3147 * \internal
3148 * \brief Block the session serializer thread task.
3149 *
3150 * \param data Pushed serializer task data for suspension.
3151 *
3152 * \retval 0
3153 */
3154static int sip_session_suspend_task(void *data)
3155{
3156 struct ast_sip_session_suspender *suspender = data;
3157
3158 ao2_lock(suspender);
3159
3160 /* Signal that the serializer task is now suspended. */
3161 suspender->suspended = 1;
3162 ast_cond_signal(&suspender->cond_suspended);
3163
3164 /* Wait for the serializer suspension to be completed. */
3165 while (!suspender->complete) {
3166 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
3167 }
3168
3169 ao2_unlock(suspender);
3170 ao2_ref(suspender, -1);
3171
3172 return 0;
3173}
3174
3176{
3177 struct ast_sip_session_suspender *suspender;
3178 int res;
3179
3180 ast_assert(session->suspended == NULL);
3181
3182 if (ast_taskprocessor_is_task(session->serializer)) {
3183 /* I am the session's serializer thread so I cannot suspend. */
3184 return;
3185 }
3186
3187 if (ast_taskprocessor_is_suspended(session->serializer)) {
3188 /* The serializer already suspended. */
3189 return;
3190 }
3191
3192 suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
3193 if (!suspender) {
3194 /* We will just have to hope that the system does not deadlock */
3195 return;
3196 }
3197 ast_cond_init(&suspender->cond_suspended, NULL);
3198 ast_cond_init(&suspender->cond_complete, NULL);
3199
3200 ao2_ref(suspender, +1);
3201 res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
3202 if (res) {
3203 /* We will just have to hope that the system does not deadlock */
3204 ao2_ref(suspender, -2);
3205 return;
3206 }
3207
3208 session->suspended = suspender;
3209
3210 /* Wait for the serializer to get suspended. */
3211 ao2_lock(suspender);
3212 while (!suspender->suspended) {
3213 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
3214 }
3215 ao2_unlock(suspender);
3216
3218}
3219
3221{
3222 struct ast_sip_session_suspender *suspender = session->suspended;
3223
3224 if (!suspender) {
3225 /* Nothing to do */
3226 return;
3227 }
3228 session->suspended = NULL;
3229
3230 /* Signal that the serializer task suspension is now complete. */
3231 ao2_lock(suspender);
3232 suspender->complete = 1;
3233 ast_cond_signal(&suspender->cond_complete);
3234 ao2_unlock(suspender);
3235
3236 ao2_ref(suspender, -1);
3237
3239}
3240
3241/*!
3242 * \internal
3243 * \brief Handle initial INVITE challenge response message.
3244 * \since 13.5.0
3245 *
3246 * \param rdata PJSIP receive response message data.
3247 *
3248 * \retval PJ_FALSE Did not handle message.
3249 * \retval PJ_TRUE Handled message.
3250 */
3251static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
3252{
3253 pjsip_transaction *tsx;
3254 pjsip_dialog *dlg;
3255 pjsip_inv_session *inv;
3256 pjsip_tx_data *tdata;
3257 struct ast_sip_session *session;
3258
3259 if (rdata->msg_info.msg->line.status.code != 401
3260 && rdata->msg_info.msg->line.status.code != 407) {
3261 /* Doesn't pertain to us. Move on */
3262 return PJ_FALSE;
3263 }
3264
3265 tsx = pjsip_rdata_get_tsx(rdata);
3266 dlg = pjsip_rdata_get_dlg(rdata);
3267 if (!dlg || !tsx) {
3268 return PJ_FALSE;
3269 }
3270
3271 if (tsx->method.id != PJSIP_INVITE_METHOD) {
3272 /* Not an INVITE that needs authentication */
3273 return PJ_FALSE;
3274 }
3275
3276 inv = pjsip_dlg_get_inv_session(dlg);
3277 session = inv->mod_data[session_module.id];
3278
3279 if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
3280 /*
3281 * We cannot handle reINVITE authentication at this
3282 * time because the reINVITE transaction is still in
3283 * progress.
3284 */
3285 ast_debug(3, "%s: A reINVITE is being challenged\n", ast_sip_session_get_name(session));
3286 return PJ_FALSE;
3287 }
3288 ast_debug(3, "%s: Initial INVITE is being challenged.\n", ast_sip_session_get_name(session));
3289
3290 if (++session->authentication_challenge_count > MAX_RX_CHALLENGES) {
3291 ast_debug(3, "%s: Initial INVITE reached maximum number of auth attempts.\n", ast_sip_session_get_name(session));
3292 return PJ_FALSE;
3293 }
3294
3295 if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
3296 tsx->last_tx, &tdata)) {
3297 return PJ_FALSE;
3298 }
3299
3300 /*
3301 * Restart the outgoing initial INVITE transaction to deal
3302 * with authentication.
3303 */
3304 pjsip_inv_uac_restart(inv, PJ_FALSE);
3305
3307 return PJ_TRUE;
3308}
3309
3310static pjsip_module outbound_invite_auth_module = {
3311 .name = {"Outbound INVITE Auth", 20},
3312 .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
3313 .on_rx_response = outbound_invite_auth,
3314};
3315
3316/*!
3317 * \internal
3318 * \brief Setup outbound initial INVITE authentication.
3319 * \since 13.5.0
3320 *
3321 * \param dlg PJSIP dialog to attach outbound authentication.
3322 *
3323 * \retval 0 on success.
3324 * \retval -1 on error.
3325 */
3326static int setup_outbound_invite_auth(pjsip_dialog *dlg)
3327{
3328 pj_status_t status;
3329
3330 ++dlg->sess_count;
3331 status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
3332 --dlg->sess_count;
3333
3334 return status != PJ_SUCCESS ? -1 : 0;
3335}
3336
3338 struct ast_sip_contact *contact, const char *location, const char *request_user,
3339 struct ast_stream_topology *req_topology)
3340{
3341 const char *uri = NULL;
3342 RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
3343 RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
3344 pjsip_timer_setting timer;
3345 pjsip_dialog *dlg;
3346 struct pjsip_inv_session *inv_session;
3348 struct ast_sip_session *ret_session;
3349 SCOPE_ENTER(1, "%s %s Topology: %s\n", ast_sorcery_object_get_id(endpoint), request_user,
3350 ast_str_tmp(256, ast_stream_topology_to_str(req_topology, &STR_TMP)));
3351
3352 /* If no location has been provided use the AOR list from the endpoint itself */
3353 if (location || !contact) {
3354 location = S_OR(location, endpoint->aors);
3355
3357 &found_aor, &found_contact);
3358 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
3359 uri = location;
3360 } else {
3361 uri = found_contact->uri;
3362 }
3363 } else {
3364 uri = contact->uri;
3365 }
3366
3367 /* If we still have no URI to dial fail to create the session */
3368 if (ast_strlen_zero(uri)) {
3369 ast_log(LOG_ERROR, "Endpoint '%s': No URI available. Is endpoint registered?\n",
3371 SCOPE_EXIT_RTN_VALUE(NULL, "No URI\n");
3372 }
3373
3374 if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
3375 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create dialog\n");
3376 }
3377
3378 if (setup_outbound_invite_auth(dlg)) {
3379 pjsip_dlg_terminate(dlg);
3380 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't setup auth\n");
3381 }
3382
3383 if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
3384 pjsip_dlg_terminate(dlg);
3385 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create uac\n");
3386 }
3387#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
3388 inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
3389#endif
3390
3391 pjsip_timer_setting_default(&timer);
3393 timer.sess_expires = endpoint->extensions.timer.sess_expires;
3394 pjsip_timer_init_session(inv_session, &timer);
3395
3396 session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
3397 inv_session, NULL);
3398 if (!session) {
3399 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3400 return NULL;
3401 }
3402 session->aor = ao2_bump(found_aor);
3403 session->call_direction = AST_SIP_SESSION_OUTGOING_CALL;
3404
3406
3407 if (ast_stream_topology_get_count(req_topology) > 0) {
3408 /* get joint caps between req_topology and endpoint topology */
3409 int i;
3410
3411 for (i = 0; i < ast_stream_topology_get_count(req_topology); ++i) {
3412 struct ast_stream *req_stream;
3413 struct ast_stream *clone_stream;
3414
3415 req_stream = ast_stream_topology_get_stream(req_topology, i);
3416
3418 continue;
3419 }
3420
3421 clone_stream = ast_sip_session_create_joint_call_stream(session, req_stream);
3422 if (!clone_stream || ast_stream_get_format_count(clone_stream) == 0) {
3423 ast_stream_free(clone_stream);
3424 continue;
3425 }
3426
3427 if (!session->pending_media_state->topology) {
3428 session->pending_media_state->topology = ast_stream_topology_alloc();
3429 if (!session->pending_media_state->topology) {
3430 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3431 ao2_ref(session, -1);
3432 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't create topology\n");
3433 }
3434 }
3435
3436 if (ast_stream_topology_append_stream(session->pending_media_state->topology, clone_stream) < 0) {
3437 ast_stream_free(clone_stream);
3438 continue;
3439 }
3440 }
3441 }
3442
3443 if (!session->pending_media_state->topology) {
3444 /* Use the configured topology on the endpoint as the pending one */
3445 session->pending_media_state->topology = ast_stream_topology_clone(endpoint->media.topology);
3446 if (!session->pending_media_state->topology) {
3447 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3448 ao2_ref(session, -1);
3449 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't clone topology\n");
3450 }
3451 }
3452
3453 if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
3454 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3455 /* Since we are not notifying ourselves that the INVITE session is being terminated
3456 * we need to manually drop its reference to session
3457 */
3458 ao2_ref(session, -1);
3459 SCOPE_EXIT_RTN_VALUE(NULL, "Couldn't add usage\n");
3460 }
3461
3462 /* Avoid unnecessary ref manipulation to return a session */
3463 ret_session = session;
3464 session = NULL;
3465 SCOPE_EXIT_RTN_VALUE(ret_session);
3466}
3467
3468static int session_end(void *vsession);
3469static int session_end_completion(void *vsession);
3470
3472{
3473 pj_status_t status;
3474 pjsip_tx_data *packet = NULL;
3475 SCOPE_ENTER(1, "%s Response %d\n", ast_sip_session_get_name(session), response);
3476
3477 if (session->defer_terminate) {
3478 session->terminate_while_deferred = 1;
3479 SCOPE_EXIT_RTN("Deferred\n");
3480 }
3481
3482 if (!response) {
3483 response = 603;
3484 }
3485
3486 /* The media sessions need to exist for the lifetime of the underlying channel
3487 * to ensure that anything (such as bridge_native_rtp) has access to them as
3488 * appropriate. Since ast_sip_session_terminate is called by chan_pjsip and other
3489 * places when the session is to be terminated we terminate any existing
3490 * media sessions here.
3491 */
3492 ast_sip_session_media_stats_save(session, session->active_media_state);
3493 SWAP(session->active_media_state, session->pending_media_state);
3494 ast_sip_session_media_state_reset(session->pending_media_state);
3495
3496 switch (session->inv_session->state) {
3497 case PJSIP_INV_STATE_NULL:
3498 if (!session->inv_session->invite_tsx) {
3499 /*
3500 * Normally, it's pjproject's transaction cleanup that ultimately causes the
3501 * final session reference to be released but if both STATE and invite_tsx are NULL,
3502 * we never created a transaction in the first place. In this case, we need to
3503 * do the cleanup ourselves.
3504 */
3505 /* Transfer the inv_session session reference to the session_end_task */
3506 session->inv_session->mod_data[session_module.id] = NULL;
3507 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
3509 /*
3510 * session_end_completion will cleanup the final session reference unless
3511 * ast_sip_session_terminate's caller is holding one.
3512 */
3514 } else {
3515 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
3516 }
3517 break;
3518 case PJSIP_INV_STATE_CONFIRMED:
3519 if (session->inv_session->invite_tsx) {
3520 ast_debug(3, "%s: Delay sending BYE because of outstanding transaction...\n",
3522 /* If this is delayed the only thing that will happen is a BYE request so we don't
3523 * actually need to store the response code for when it happens.
3524 */
3526 break;
3527 }
3528 /* Fall through */
3529 default:
3530 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
3531 if (status == PJ_SUCCESS && packet) {
3532 struct ast_sip_session_delayed_request *delay;
3533
3534 /* Flush any delayed requests so they cannot overlap this transaction. */
3535 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
3536 delayed_request_free(delay);
3537 }
3538
3539 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
3541 } else {
3543 }
3544 }
3545 break;
3546 }
3548}
3549
3550static int session_termination_task(void *data)
3551{
3552 struct ast_sip_session *session = data;
3553
3554 if (session->defer_terminate) {
3555 session->defer_terminate = 0;
3556 if (session->inv_session) {
3558 }
3559 }
3560
3561 ao2_ref(session, -1);
3562 return 0;
3563}
3564
3565static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
3566{
3567 struct ast_sip_session *session = entry->user_data;
3568
3571 }
3572}
3573
3575{
3576 pj_time_val delay = { .sec = 60, };
3577 int res;
3578
3579 /* The session should not have an active deferred termination request. */
3580 ast_assert(!session->defer_terminate);
3581
3582 session->defer_terminate = 1;
3583
3584 session->defer_end = 1;
3585 session->ended_while_deferred = 0;
3586
3587 ao2_ref(session, +1);
3588 pj_timer_entry_init(&session->scheduled_termination, 0, session, session_termination_cb);
3589
3590 res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
3591 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
3592 if (res) {
3593 session->defer_terminate = 0;
3594 ao2_ref(session, -1);
3595 }
3596 return res;
3597}
3598
3599/*!
3600 * \internal
3601 * \brief Stop the defer termination timer if it is still running.
3602 * \since 13.5.0
3603 *
3604 * \param session Which session to stop the timer.
3605 */
3607{
3608 if (pj_timer_heap_cancel_if_active(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
3609 &session->scheduled_termination, session->scheduled_termination.id)) {
3610 ao2_ref(session, -1);
3611 }
3612}
3613
3615{
3616 if (!session->defer_terminate) {
3617 /* Already canceled or timer fired. */
3618 return;
3619 }
3620
3621 session->defer_terminate = 0;
3622
3623 if (session->terminate_while_deferred) {
3624 /* Complete the termination started by the upper layer. */
3626 }
3627
3628 /* Stop the termination timer if it is still running. */
3630}
3631
3633{
3634 if (!session->defer_end) {
3635 return;
3636 }
3637
3638 session->defer_end = 0;
3639
3640 if (session->ended_while_deferred) {
3641 /* Complete the session end started by the remote hangup. */
3642 ast_debug(3, "%s: Ending session after being deferred\n", ast_sip_session_get_name(session));
3643 session->ended_while_deferred = 0;
3645 }
3646}
3647
3649{
3650 pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
3651 struct ast_sip_session *session;
3652
3653 if (!inv_session ||
3654 !(session = inv_session->mod_data[session_module.id])) {
3655 return NULL;
3656 }
3657
3658 ao2_ref(session, +1);
3659
3660 return session;
3661}
3662
3664{
3665 pjsip_inv_session *inv_session = session->inv_session;
3666
3667 if (!inv_session) {
3668 return NULL;
3669 }
3670
3671 return inv_session->dlg;
3672}
3673
3675{
3676 pjsip_inv_session *inv_session = session->inv_session;
3677
3678 if (!inv_session) {
3679 return PJSIP_INV_STATE_NULL;
3680 }
3681
3682 return inv_session->state;
3683}
3684
3685/*! \brief Fetch just the Caller ID number in order of PAI, RPID, From */
3686static int fetch_callerid_num(struct ast_sip_session *session, pjsip_rx_data *rdata, char *buf, size_t len)
3687{
3688 int res = -1;
3689 struct ast_party_id id;
3690
3691 ast_party_id_init(&id);
3692 if (!ast_sip_set_id_from_invite(rdata, &id, &session->endpoint->id.self, session->endpoint->id.trust_inbound)) {
3693 ast_copy_string(buf, id.number.str, len);
3694 res = 0;
3695 }
3696 ast_party_id_free(&id);
3697 return res;
3698}
3699
3701 /*! The extension was successfully found */
3703 /*! The extension specified in the RURI was not found */
3705 /*! The extension specified in the RURI was a partial match */
3707 /*! The RURI is of an unsupported scheme */
3709};
3710
3711/*!
3712 * \brief Determine where in the dialplan a call should go
3713 *
3714 * This uses the username in the request URI to try to match
3715 * an extension in the endpoint's configured context in order
3716 * to route the call.
3717 *
3718 * \param session The inbound SIP session
3719 * \param rdata The SIP INVITE
3720 */
3721static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
3722{
3723 char cid_num[AST_CHANNEL_NAME];
3724 pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
3725 struct ast_features_pickup_config *pickup_cfg;
3726 const char *pickupexten;
3727
3728 if (!ast_sip_is_allowed_uri(ruri)) {
3730 }
3731
3732 ast_copy_pj_str(session->exten, ast_sip_pjsip_uri_get_username(ruri), sizeof(session->exten));
3733 if (ast_strlen_zero(session->exten)) {
3734 /* Some SIP devices send an empty extension for PLAR: this should map to s */
3735 ast_debug(1, "RURI contains no user portion: defaulting to extension 's'\n");
3736 ast_copy_string(session->exten, "s", sizeof(session->exten));
3737 }
3738
3739 /*
3740 * We may want to match in the dialplan without any user
3741 * options getting in the way.
3742 */
3744
3745 pickup_cfg = ast_get_chan_features_pickup_config(NULL); /* session->channel doesn't exist yet, using NULL */
3746 if (!pickup_cfg) {
3747 ast_log(LOG_ERROR, "%s: Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n",
3749 pickupexten = "";
3750 } else {
3751 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
3752 ao2_ref(pickup_cfg, -1);
3753 }
3754
3755 fetch_callerid_num(session, rdata, cid_num, sizeof(cid_num));
3756
3757 /* If there's an overlap_context override specified, use that; otherwise, just use the endpoint's context */
3758
3759 if (!strcmp(session->exten, pickupexten) ||
3760 ast_exists_extension(NULL, S_OR(session->endpoint->overlap_context, session->endpoint->context), session->exten, 1, S_OR(cid_num, NULL))) {
3761 /*
3762 * Save off the INVITE Request-URI in case it is
3763 * needed: CHANNEL(pjsip,request_uri)
3764 */
3765 session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);
3766
3768 }
3769
3770 /*
3771 * Check for partial match via overlap dialling (if enabled)
3772 */
3773 if (session->endpoint->allow_overlap && (
3774 !strncmp(session->exten, pickupexten, strlen(session->exten)) ||
3775 ast_canmatch_extension(NULL, S_OR(session->endpoint->overlap_context, session->endpoint->context), session->exten, 1, S_OR(cid_num, NULL)))) {
3776 /* Overlap partial match */
3778 }
3779
3781}
3782
3783/*!
3784 * \internal
3785 * \brief Process initial answer for an incoming invite
3786 *
3787 * This function should only be called during the setup, and handling of a
3788 * new incoming invite. Most, if not all of the time, this will be called
3789 * when an error occurs and we need to respond as such.
3790 *
3791 * When a SIP session termination code is given for the answer it's assumed
3792 * this call then will be the final bit of processing before ending session
3793 * setup. As such, we've been holding a lock, and a reference on the invite
3794 * session's dialog. So before returning this function removes that reference,
3795 * and unlocks the dialog.
3796 *
3797 * \param inv_session The session on which to answer
3798 * \param rdata The original request
3799 * \param answer_code The answer's numeric code
3800 * \param terminate_code The termination code if the answer fails
3801 * \param notify Whether or not to call on_state_changed
3802 *
3803 * \retval 0 if invite successfully answered, -1 if an error occurred
3804 */
3805static int new_invite_initial_answer(pjsip_inv_session *inv_session, pjsip_rx_data *rdata,
3806 int answer_code, int terminate_code, pj_bool_t notify)
3807{
3808 pjsip_tx_data *tdata = NULL;
3809 int res = 0;
3810
3811 if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {
3812 if (pjsip_inv_initial_answer(
3813 inv_session, rdata, answer_code, NULL, NULL, &tdata) != PJ_SUCCESS) {
3814
3815 pjsip_inv_terminate(inv_session, terminate_code ? terminate_code : answer_code, notify);
3816 res = -1;
3817 } else {
3818 pjsip_inv_send_msg(inv_session, tdata);
3819 }
3820 }
3821
3822 if (answer_code >= 300) {
3823 /*
3824 * A session is ending. The dialog has a reference that needs to be
3825 * removed and holds a lock that needs to be unlocked before returning.
3826 */
3827 pjsip_dlg_dec_lock(inv_session->dlg);
3828 }
3829
3830 return res;
3831}
3832
3833/*!
3834 * \internal
3835 * \brief Create and initialize a pjsip invite session
3836 *
3837 * pjsip_inv_session adds, and maintains a reference to the dialog upon a successful
3838 * invite session creation until the session is destroyed. However, we'll wait to
3839 * remove the reference that was added for the dialog when it gets created since we're
3840 * not ready to unlock the dialog in this function.
3841 *
3842 * So, if this function successfully returns that means it returns with its newly
3843 * created, and associated dialog locked and with two references (i.e. dialog's
3844 * reference count should be 2).
3845 *
3846 * \param rdata The request that is starting the dialog
3847 * \param endpoint A pointer to the endpoint
3848 *
3849 * \return A pjsip invite session object
3850 * \retval NULL on error
3851 */
3852static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
3853{
3854 pjsip_tx_data *tdata;
3855 pjsip_dialog *dlg;
3856 pjsip_inv_session *inv_session;
3857 unsigned int options = endpoint->extensions.flags;
3858 const pj_str_t STR_100REL = { "100rel", 6};
3859 unsigned int i;
3860 pj_status_t dlg_status = PJ_EUNKNOWN;
3861
3862 /*
3863 * If 100rel is set to "peer_supported" on the endpoint and the peer indicated support for 100rel
3864 * in the Supported header, send 1xx responses reliably by adding PJSIP_INV_REQUIRE_100REL to pjsip_inv_options flags.
3865 */
3866 if (endpoint->rel100 == AST_SIP_100REL_PEER_SUPPORTED && rdata->msg_info.supported != NULL) {
3867 for (i = 0; i < rdata->msg_info.supported->count; ++i) {
3868 if (pj_stricmp(&rdata->msg_info.supported->values[i], &STR_100REL) == 0) {
3869 options |= PJSIP_INV_REQUIRE_100REL;
3870 break;
3871 }
3872 }
3873 }
3874
3875 if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
3876 if (tdata) {
3877 if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
3878 pjsip_tx_data_dec_ref(tdata);
3879 }
3880 } else {
3881 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
3882 }
3883 return NULL;
3884 }
3885
3886 dlg = ast_sip_create_dialog_uas_locked(endpoint, rdata, &dlg_status);
3887 if (!dlg) {
3888 if (dlg_status != PJ_EEXISTS) {
3889 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
3890 }
3891 return NULL;
3892 }
3893
3894 /*
3895 * The returned dialog holds a lock and has a reference added. Any paths where the
3896 * dialog invite session is not returned must unlock the dialog and remove its reference.
3897 */
3898
3899 if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
3900 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
3901 /*
3902 * The acquired dialog holds a lock, and a reference. Since the dialog is not
3903 * going to be returned here it must first be unlocked and de-referenced. This
3904 * must be done prior to calling dialog termination.
3905 */
3906 pjsip_dlg_dec_lock(dlg);
3907 pjsip_dlg_terminate(dlg);
3908 return NULL;
3909 }
3910
3911#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
3912 inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
3913#endif
3914 if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
3915 /* Dialog's lock and a reference are removed in new_invite_initial_answer */
3916 new_invite_initial_answer(inv_session, rdata, 500, 500, PJ_FALSE);
3917 /* Remove 2nd reference added at inv_session creation */
3918 pjsip_dlg_dec_session(inv_session->dlg, &session_module);
3919 return NULL;
3920 }
3921
3922 return inv_session;
3923}
3924
3926 /*! \brief Session created for the new INVITE */
3928
3929 /*! \brief INVITE request itself */
3930 pjsip_rx_data *rdata;
3931};
3932
3933static int check_sdp_content_type_supported(pjsip_media_type *content_type)
3934{
3935 pjsip_media_type app_sdp;
3936 pjsip_media_type_init2(&app_sdp, "application", "sdp");
3937
3938 if (!pjsip_media_type_cmp(content_type, &app_sdp, 0)) {
3939 return 1;
3940 }
3941
3942 return 0;
3943}
3944
3945static int check_content_disposition_in_multipart(pjsip_multipart_part *part)
3946{
3947 pjsip_hdr *hdr = part->hdr.next;
3948 static const pj_str_t str_handling_required = {"handling=required", 16};
3949
3950 while (hdr != &part->hdr) {
3951 if (hdr->type == PJSIP_H_OTHER) {
3952 pjsip_generic_string_hdr *generic_hdr = (pjsip_generic_string_hdr*)hdr;
3953
3954 if (!pj_stricmp2(&hdr->name, "Content-Disposition") &&
3955 pj_stristr(&generic_hdr->hvalue, &str_handling_required) &&
3956 !check_sdp_content_type_supported(&part->body->content_type)) {
3957 return 1;
3958 }
3959 }
3960 hdr = hdr->next;
3961 }
3962
3963 return 0;
3964}
3965
3966/**
3967 * if there is required media we don't understand, return 1
3968 */
3969static int check_content_disposition(pjsip_rx_data *rdata)
3970{
3971 pjsip_msg_body *body = rdata->msg_info.msg->body;
3972 pjsip_ctype_hdr *ctype_hdr = rdata->msg_info.ctype;
3973
3974 if (body && ctype_hdr &&
3977 pjsip_multipart_part *part = pjsip_multipart_get_first_part(body);
3978 while (part != NULL) {
3980 return 1;
3981 }
3982 part = pjsip_multipart_get_next_part(body, part);
3983 }
3984 }
3985 return 0;
3986}
3987
3988static int new_invite(struct new_invite *invite)
3989{
3990 pjsip_tx_data *tdata = NULL;
3991 pjsip_timer_setting timer;
3992 pjsip_rdata_sdp_info *sdp_info;
3993 pjmedia_sdp_session *local = NULL;
3994 char buffer[AST_SOCKADDR_BUFLEN];
3995 SCOPE_ENTER(3, "%s\n", ast_sip_session_get_name(invite->session));
3996
3997
3998 /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
3999 * so that we will be notified so we can destroy the session properly
4000 */
4001
4002 if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
4003 ast_trace_log(-1, LOG_ERROR, "%s: Session already DISCONNECTED [reason=%d (%s)]\n",
4005 invite->session->inv_session->cause,
4006 pjsip_get_status_text(invite->session->inv_session->cause)->ptr);
4008 }
4009
4010 switch (get_destination(invite->session, invite->rdata)) {
4012 /* Things worked. Keep going */
4013 break;
4015 ast_trace(-1, "%s: Call (%s:%s) to extension '%s' - unsupported uri\n",
4017 invite->rdata->tp_info.transport->type_name,
4018 pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
4019 invite->session->exten);
4020 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
4021 ast_sip_session_send_response(invite->session, tdata);
4022 } else {
4023 pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
4024 }
4025 goto end;
4027 ast_trace(-1, "%s: Call (%s:%s) to extension '%s' - partial match\n",
4029 invite->rdata->tp_info.transport->type_name,
4030 pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
4031 invite->session->exten);
4032
4033 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {
4034 ast_sip_session_send_response(invite->session, tdata);
4035 } else {
4036 pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);
4037 }
4038 goto end;
4040 default:
4041 ast_trace_log(-1, LOG_NOTICE, "%s: Call (%s:%s) to extension '%s' rejected because extension not found in context '%s'.\n",
4043 invite->rdata->tp_info.transport->type_name,
4044 pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
4045 invite->session->exten,
4046 invite->session->endpoint->context);
4047
4048 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
4049 ast_sip_session_send_response(invite->session, tdata);
4050 } else {
4051 pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
4052 }
4053 goto end;
4054 };
4055
4056 if (check_content_disposition(invite->rdata)) {
4057 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 415, NULL, NULL, &tdata) == PJ_SUCCESS) {
4058 ast_sip_session_send_response(invite->session, tdata);
4059 } else {
4060 pjsip_inv_terminate(invite->session->inv_session, 415, PJ_TRUE);
4061 }
4062 goto end;
4063 }
4064
4065 pjsip_timer_setting_default(&timer);
4066 timer.min_se = invite->session->endpoint->extensions.timer.min_se;
4067 timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
4068 pjsip_timer_init_session(invite->session->inv_session, &timer);
4069
4070 /*
4071 * At this point, we've verified what we can that won't take awhile,
4072 * so let's go ahead and send a 100 Trying out to stop any
4073 * retransmissions.
4074 */
4075 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
4076 if (tdata) {
4077 pjsip_inv_send_msg(invite->session->inv_session, tdata);
4078 } else {
4079 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
4080 }
4081 goto end;
4082 }
4083
4084 ast_trace(-1, "%s: Call (%s:%s) to extension '%s' sending 100 Trying\n",
4086 invite->rdata->tp_info.transport->type_name,
4087 pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
4088 invite->session->exten);
4089 ast_sip_session_send_response(invite->session, tdata);
4090
4091 sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);
4092 if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
4093 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
4094 tdata = NULL;
4095 if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS
4096 && tdata) {
4097 ast_sip_session_send_response(invite->session, tdata);
4098 }
4099 goto end;
4100 }
4101 /* We are creating a local SDP which is an answer to their offer */
4102 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp, 0);
4103 } else {
4104 /* We are creating a local SDP which is an offer */
4105 local = create_local_sdp(invite->session->inv_session, invite->session, NULL, 0);
4106 }
4107
4108 /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
4109 if (!local) {
4110 tdata = NULL;
4111 if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS
4112 && tdata) {
4113 ast_sip_session_send_response(invite->session, tdata);
4114 }
4115 goto end;
4116 }
4117
4118 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
4119 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
4120#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
4121 if (!invite->session->endpoint->preferred_codec_only) {
4122 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
4123 }
4124#endif
4125
4126 handle_incoming_request(invite->session, invite->rdata);
4127
4128end:
4130}
4131
4132static void handle_new_invite_request(pjsip_rx_data *rdata)
4133{
4136 pjsip_inv_session *inv_session = NULL;
4137 struct ast_sip_session *session;
4138 struct new_invite invite;
4139 char *req_uri = TRACE_ATLEAST(1) ? ast_alloca(256) : "";
4140 int res = TRACE_ATLEAST(1) ? pjsip_uri_print(PJSIP_URI_IN_REQ_URI, rdata->msg_info.msg->line.req.uri, req_uri, 256) : 0;
4141 SCOPE_ENTER(1, "Request: %s\n", res ? req_uri : "");
4142
4143 ast_assert(endpoint != NULL);
4144
4145 inv_session = pre_session_setup(rdata, endpoint);
4146 if (!inv_session) {
4147 /* pre_session_setup() returns a response on failure */
4148 SCOPE_EXIT_RTN("Failure in pre session setup\n");
4149 }
4150
4151 /*
4152 * Upon a successful pre_session_setup the associated dialog is returned locked
4153 * and with an added reference. Well actually two references. One added when the
4154 * dialog itself was created, and another added when the pjsip invite session was
4155 * created and the dialog was added to it.
4156 *
4157 * In order to ensure the dialog's, and any of its internal attributes, lifetimes
4158 * we'll hold the lock and maintain the reference throughout the entire new invite
4159 * handling process. See ast_sip_create_dialog_uas_locked for more details but,
4160 * basically we do this to make sure a transport failure does not destroy the dialog
4161 * and/or transaction out from underneath us between pjsip calls. Alternatively, we
4162 * could probably release the lock if we needed to, but then we'd have to re-lock and
4163 * check the dialog and transaction prior to every pjsip call.
4164 *
4165 * That means any off nominal/failure paths in this function must remove the associated
4166 * dialog reference added at dialog creation, and remove the lock. As well the
4167 * referenced pjsip invite session must be "cleaned up", which should also then
4168 * remove its reference to the dialog at that time.
4169 *
4170 * Nominally we'll unlock the dialog, and release the reference when all new invite
4171 * process handling has successfully completed.
4172 */
4173
4174 session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);
4175 if (!session) {
4176 /* Dialog's lock and reference are removed in new_invite_initial_answer */
4177 if (!new_invite_initial_answer(inv_session, rdata, 500, 500, PJ_FALSE)) {
4178 /* Terminate the session if it wasn't done in the answer */
4179 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
4180 }
4181 SCOPE_EXIT_RTN("Couldn't create session\n");
4182 }
4183 session->call_direction = AST_SIP_SESSION_INCOMING_CALL;
4184
4185 /*
4186 * The current thread is supposed be the session serializer to prevent
4187 * any initial INVITE retransmissions from trying to setup the same
4188 * call again.
4189 */
4191
4192 invite.session = session;
4193 invite.rdata = rdata;
4194 new_invite(&invite);
4195
4196 /*
4197 * The dialog lock and reference added at dialog creation time must be
4198 * maintained throughout the new invite process. Since we're pretty much
4199 * done at this point with things it's safe to go ahead and remove the lock
4200 * and the reference here. See ast_sip_create_dialog_uas_locked for more info.
4201 *
4202 * Note, any future functionality added that does work using the dialog must
4203 * be done before this.
4204 */
4205 pjsip_dlg_dec_lock(inv_session->dlg);
4206
4207 SCOPE_EXIT("Request: %s Session: %s\n", req_uri, ast_sip_session_get_name(session));
4208 ao2_ref(session, -1);
4209}
4210
4211static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
4212{
4213 pj_str_t method;
4214
4215 if (ast_strlen_zero(supplement_method)) {
4216 return PJ_TRUE;
4217 }
4218
4219 pj_cstr(&method, supplement_method);
4220
4221 return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
4222}
4223
4224static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
4225{
4226 struct ast_sip_session_supplement *supplement;
4227 struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
4228
4229 if (!session) {
4230 return PJ_FALSE;
4231 }
4232
4233 AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
4234 if (does_method_match(&method->name, supplement->method)) {
4235 return PJ_TRUE;
4236 }
4237 }
4238 return PJ_FALSE;
4239}
4240
4241/*!
4242 * \internal
4243 * Added for debugging purposes
4244 */
4245static void session_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e)
4246{
4247
4248 pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4249 pjsip_inv_session *inv_session = (dlg ? pjsip_dlg_get_inv_session(dlg) : NULL);
4250 struct ast_sip_session *session = (inv_session ? inv_session->mod_data[session_module.id] : NULL);
4251 SCOPE_ENTER(1, "%s TSX State: %s Inv State: %s\n", ast_sip_session_get_name(session),
4252 pjsip_tsx_state_str(tsx->state), inv_session ? pjsip_inv_state_name(inv_session->state) : "unknown");
4253
4254 if (session) {
4255 ast_trace(2, "Topology: Pending: %s Active: %s\n",
4256 ast_str_tmp(256, ast_stream_topology_to_str(session->pending_media_state->topology, &STR_TMP)),
4257 ast_str_tmp(256, ast_stream_topology_to_str(session->active_media_state->topology, &STR_TMP)));
4258 }
4259
4261}
4262
4263/*!
4264 * \internal
4265 * Added for debugging purposes
4266 */
4267static pj_bool_t session_on_rx_response(pjsip_rx_data *rdata)
4268{
4269
4270 struct pjsip_status_line status = rdata->msg_info.msg->line.status;
4271 pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
4272 pjsip_inv_session *inv_session = dlg ? pjsip_dlg_get_inv_session(dlg) : NULL;
4273 struct ast_sip_session *session = (inv_session ? inv_session->mod_data[session_module.id] : NULL);
4274 SCOPE_ENTER(1, "%s Method: %.*s Status: %d\n", ast_sip_session_get_name(session),
4275 (int)rdata->msg_info.cseq->method.name.slen, rdata->msg_info.cseq->method.name.ptr, status.code);
4276
4277 SCOPE_EXIT_RTN_VALUE(PJ_FALSE);
4278}
4279
4280/*!
4281 * \brief Called when a new SIP request comes into PJSIP
4282 *
4283 * This function is called under two circumstances
4284 * 1) An out-of-dialog request is received by PJSIP
4285 * 2) An in-dialog request that the inv_session layer does not
4286 * handle is received (such as an in-dialog INFO)
4287 *
4288 * Except for INVITEs, there is very little we actually do in this function
4289 * 1) For requests we don't handle, we return PJ_FALSE
4290 * 2) For new INVITEs, handle them now to prevent retransmissions from
4291 * trying to setup the same call again.
4292 * 3) For in-dialog requests we handle, we process them in the
4293 * .on_state_changed = session_inv_on_state_changed or
4294 * .on_tsx_state_changed = session_inv_on_tsx_state_changed
4295 * callbacks instead.
4296 */
4297static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
4298{
4299 pj_status_t handled = PJ_FALSE;
4300 struct pjsip_request_line req = rdata->msg_info.msg->line.req;
4301 pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
4302 pjsip_inv_session *inv_session = (dlg ? pjsip_dlg_get_inv_session(dlg) : NULL);
4303 struct ast_sip_session *session = (inv_session ? inv_session->mod_data[session_module.id] : NULL);
4304 char *req_uri = TRACE_ATLEAST(1) ? ast_alloca(256) : "";
4305 int res = TRACE_ATLEAST(1) ? pjsip_uri_print(PJSIP_URI_IN_REQ_URI, rdata->msg_info.msg->line.req.uri, req_uri, 256) : 0;
4306 SCOPE_ENTER(1, "%s Request: %.*s %s\n", ast_sip_session_get_name(session),
4307 (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name), res ? req_uri : "");
4308
4309 switch (req.method.id) {
4310 case PJSIP_INVITE_METHOD:
4311 if (dlg) {
4312 ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
4313 break;
4314 }
4315 handled = PJ_TRUE;
4317 break;
4318 default:
4319 /* Handle other in-dialog methods if their supplements have been registered */
4320 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
4321 has_supplement(inv_session->mod_data[session_module.id], rdata);
4322 break;
4323 }
4324
4325 SCOPE_EXIT_RTN_VALUE(handled, "%s Handled request %.*s %s ? %s\n", ast_sip_session_get_name(session),
4326 (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name), req_uri,
4327 handled == PJ_TRUE ? "yes" : "no");
4328}
4329
4330
4331static pj_bool_t session_on_tx_response(pjsip_tx_data *tdata)
4332{
4333 pjsip_dialog *dlg = pjsip_tdata_get_dlg(tdata);
4335 if (session) {
4337 }
4338
4339 return PJ_SUCCESS;
4340}
4341
4342static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
4343{
4344 struct ast_sip_session *session = entry->user_data;
4345
4346 ast_debug(3, "%s: re-INVITE collision timer expired.\n",
4348
4349 if (AST_LIST_EMPTY(&session->delayed_requests)) {
4350 /* No delayed request pending, so just return */
4351 ao2_ref(session, -1);
4352 return;
4353 }
4355 /*
4356 * Uh oh. We now have nothing in the foreseeable future
4357 * to trigger sending the delayed requests.
4358 */
4359 ao2_ref(session, -1);
4360 }
4361}
4362
4364{
4365 pjsip_inv_session *inv = session->inv_session;
4366 pj_time_val tv;
4367 struct ast_sip_session_media_state *pending_media_state = NULL;
4368 struct ast_sip_session_media_state *active_media_state = NULL;
4369 const char *session_name = ast_sip_session_get_name(session);
4370 int use_pending = 0;
4371 int use_active = 0;
4372
4373 SCOPE_ENTER(3, "%s\n", session_name);
4374
4375 /*
4376 * If the two media state topologies are the same this means that the session refresh request
4377 * did not specify a desired topology, so it does not care. If that is the case we don't even
4378 * pass one in here resulting in the current topology being used. It's possible though that
4379 * either one of the topologies could be NULL so we have to test for that before we check for
4380 * equality.
4381 */
4382
4383 /* We only want to clone a media state if its topology is not null */
4384 use_pending = session->pending_media_state->topology != NULL;
4385 use_active = session->active_media_state->topology != NULL;
4386
4387 /*
4388 * If both media states have topologies, we can test for equality. If they're equal we're not going to
4389 * clone either states.
4390 */
4391 if (use_pending && use_active && ast_stream_topology_equal(session->active_media_state->topology, session->pending_media_state->topology)) {
4392 use_pending = 0;
4393 use_active = 0;
4394 }
4395
4396 if (use_pending) {
4397 pending_media_state = ast_sip_session_media_state_clone(session->pending_media_state);
4398 if (!pending_media_state) {
4399 SCOPE_EXIT_LOG_RTN(LOG_ERROR, "%s: Failed to clone pending media state\n", session_name);
4400 }
<