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