244b8cc5bcfda42b2e444fda706ee8e7e5da25c6
[asterisk/asterisk.git] / res / res_pjsip_session.c
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
31 #include "asterisk/res_pjsip.h"
32 #include "asterisk/res_pjsip_session.h"
33 #include "asterisk/callerid.h"
34 #include "asterisk/datastore.h"
35 #include "asterisk/module.h"
36 #include "asterisk/logger.h"
37 #include "asterisk/res_pjsip.h"
38 #include "asterisk/astobj2.h"
39 #include "asterisk/lock.h"
40 #include "asterisk/uuid.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/taskprocessor.h"
43 #include "asterisk/causes.h"
44 #include "asterisk/sdp_srtp.h"
45 #include "asterisk/dsp.h"
46 #include "asterisk/acl.h"
47 #include "asterisk/features_config.h"
48 #include "asterisk/pickup.h"
49 #include "asterisk/test.h"
50 #include "asterisk/stream.h"
51
52 #define SDP_HANDLER_BUCKETS 11
53
54 #define MOD_DATA_ON_RESPONSE "on_response"
55 #define MOD_DATA_NAT_HOOK "nat_hook"
56
57 /* Most common case is one audio and one video stream */
58 #define DEFAULT_NUM_SESSION_MEDIA 2
59
60 /* Some forward declarations */
61 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata);
62 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
63                 enum ast_sip_session_response_priority response_priority);
64 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,
65                 enum ast_sip_session_response_priority response_priority);
66 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);
67 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);
68
69 /*! \brief NAT hook for modifying outgoing messages with SDP */
70 static struct ast_sip_nat_hook *nat_hook;
71
72 /*!
73  * \brief Registered SDP stream handlers
74  *
75  * This container is keyed on stream types. Each
76  * object in the container is a linked list of
77  * handlers for the stream type.
78  */
79 static struct ao2_container *sdp_handlers;
80
81 /*!
82  * These are the objects in the sdp_handlers container
83  */
84 struct sdp_handler_list {
85         /* The list of handlers to visit */
86         AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;
87         /* The handlers in this list handle streams of this type */
88         char stream_type[1];
89 };
90
91 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);
92
93 static int sdp_handler_list_hash(const void *obj, int flags)
94 {
95         const struct sdp_handler_list *handler_list = obj;
96         const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
97
98         return ast_str_hash(stream_type);
99 }
100
101 static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
102 {
103         struct sdp_handler_list *handler_list1 = obj;
104         struct sdp_handler_list *handler_list2 = arg;
105         const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;
106
107         return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
108 }
109
110 int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
111 {
112         RAII_VAR(struct sdp_handler_list *, handler_list,
113                         ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);
114         SCOPED_AO2LOCK(lock, sdp_handlers);
115
116         if (handler_list) {
117                 struct ast_sip_session_sdp_handler *iter;
118                 /* Check if this handler is already registered for this stream type */
119                 AST_LIST_TRAVERSE(&handler_list->list, iter, next) {
120                         if (!strcmp(iter->id, handler->id)) {
121                                 ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);
122                                 return -1;
123                         }
124                 }
125                 AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
126                 ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
127
128                 return 0;
129         }
130
131         /* No stream of this type has been registered yet, so we need to create a new list */
132         handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);
133         if (!handler_list) {
134                 return -1;
135         }
136         /* Safe use of strcpy */
137         strcpy(handler_list->stream_type, stream_type);
138         AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);
139         AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
140         if (!ao2_link(sdp_handlers, handler_list)) {
141                 return -1;
142         }
143         ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
144
145         return 0;
146 }
147
148 static int remove_handler(void *obj, void *arg, void *data, int flags)
149 {
150         struct sdp_handler_list *handler_list = obj;
151         struct ast_sip_session_sdp_handler *handler = data;
152         struct ast_sip_session_sdp_handler *iter;
153         const char *stream_type = arg;
154
155         AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {
156                 if (!strcmp(iter->id, handler->id)) {
157                         AST_LIST_REMOVE_CURRENT(next);
158                         ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
159                 }
160         }
161         AST_LIST_TRAVERSE_SAFE_END;
162
163         if (AST_LIST_EMPTY(&handler_list->list)) {
164                 ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
165                 return CMP_MATCH;
166         } else {
167                 return CMP_STOP;
168         }
169 }
170
171 void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
172 {
173         ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);
174 }
175
176 static struct ast_sip_session_media_state *internal_sip_session_media_state_alloc(
177         size_t sessions, size_t read_callbacks)
178 {
179         struct ast_sip_session_media_state *media_state;
180
181         media_state = ast_calloc(1, sizeof(*media_state));
182         if (!media_state) {
183                 return NULL;
184         }
185
186         if (AST_VECTOR_INIT(&media_state->sessions, sessions) < 0) {
187                 ast_free(media_state);
188                 return NULL;
189         }
190
191         if (AST_VECTOR_INIT(&media_state->read_callbacks, read_callbacks) < 0) {
192                 AST_VECTOR_FREE(&media_state->sessions);
193                 ast_free(media_state);
194                 return NULL;
195         }
196
197         return media_state;
198 }
199
200 struct ast_sip_session_media_state *ast_sip_session_media_state_alloc(void)
201 {
202         return internal_sip_session_media_state_alloc(
203                 DEFAULT_NUM_SESSION_MEDIA, DEFAULT_NUM_SESSION_MEDIA);
204 }
205
206 void ast_sip_session_media_state_reset(struct ast_sip_session_media_state *media_state)
207 {
208         int index;
209
210         if (!media_state) {
211                 return;
212         }
213
214         AST_VECTOR_RESET(&media_state->sessions, ao2_cleanup);
215         AST_VECTOR_RESET(&media_state->read_callbacks, AST_VECTOR_ELEM_CLEANUP_NOOP);
216
217         for (index = 0; index < AST_MEDIA_TYPE_END; ++index) {
218                 media_state->default_session[index] = NULL;
219         }
220
221         ast_stream_topology_free(media_state->topology);
222         media_state->topology = NULL;
223 }
224
225 struct ast_sip_session_media_state *ast_sip_session_media_state_clone(const struct ast_sip_session_media_state *media_state)
226 {
227         struct ast_sip_session_media_state *cloned;
228         int index;
229
230         if (!media_state) {
231                 return NULL;
232         }
233
234         cloned = internal_sip_session_media_state_alloc(
235                 AST_VECTOR_SIZE(&media_state->sessions),
236                 AST_VECTOR_SIZE(&media_state->read_callbacks));
237         if (!cloned) {
238                 return NULL;
239         }
240
241         if (media_state->topology) {
242                 cloned->topology = ast_stream_topology_clone(media_state->topology);
243                 if (!cloned->topology) {
244                         ast_sip_session_media_state_free(cloned);
245                         return NULL;
246                 }
247         }
248
249         for (index = 0; index < AST_VECTOR_SIZE(&media_state->sessions); ++index) {
250                 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&media_state->sessions, index);
251                 enum ast_media_type type = ast_stream_get_type(ast_stream_topology_get_stream(cloned->topology, index));
252
253                 ao2_bump(session_media);
254                 if (AST_VECTOR_REPLACE(&cloned->sessions, index, session_media)) {
255                         ao2_cleanup(session_media);
256                 }
257                 if (ast_stream_get_state(ast_stream_topology_get_stream(cloned->topology, index)) != AST_STREAM_STATE_REMOVED &&
258                         !cloned->default_session[type]) {
259                         cloned->default_session[type] = session_media;
260                 }
261         }
262
263         for (index = 0; index < AST_VECTOR_SIZE(&media_state->read_callbacks); ++index) {
264                 struct ast_sip_session_media_read_callback_state *read_callback = AST_VECTOR_GET_ADDR(&media_state->read_callbacks, index);
265
266                 AST_VECTOR_REPLACE(&cloned->read_callbacks, index, *read_callback);
267         }
268
269         return cloned;
270 }
271
272 void ast_sip_session_media_state_free(struct ast_sip_session_media_state *media_state)
273 {
274         if (!media_state) {
275                 return;
276         }
277
278         /* This will reset the internal state so we only have to free persistent things */
279         ast_sip_session_media_state_reset(media_state);
280
281         AST_VECTOR_FREE(&media_state->sessions);
282         AST_VECTOR_FREE(&media_state->read_callbacks);
283
284         ast_free(media_state);
285 }
286
287 int ast_sip_session_is_pending_stream_default(const struct ast_sip_session *session, const struct ast_stream *stream)
288 {
289         int index;
290
291         if (!session->pending_media_state->topology) {
292                 ast_log(LOG_WARNING, "Pending topology was NULL for channel '%s'\n",
293                         session->channel ? ast_channel_name(session->channel) : "unknown");
294                 return 0;
295         }
296
297         if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
298                 return 0;
299         }
300
301         for (index = 0; index < ast_stream_topology_get_count(session->pending_media_state->topology); ++index) {
302                 if (ast_stream_get_type(ast_stream_topology_get_stream(session->pending_media_state->topology, index)) !=
303                         ast_stream_get_type(stream)) {
304                         continue;
305                 }
306
307                 return ast_stream_topology_get_stream(session->pending_media_state->topology, index) == stream ? 1 : 0;
308         }
309
310         return 0;
311 }
312
313 int ast_sip_session_media_add_read_callback(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
314         int fd, ast_sip_session_media_read_cb callback)
315 {
316         struct ast_sip_session_media_read_callback_state callback_state = {
317                 .fd = fd,
318                 .read_callback = callback,
319                 .session = session_media,
320         };
321
322         /* The contents of the vector are whole structs and not pointers */
323         return AST_VECTOR_APPEND(&session->pending_media_state->read_callbacks, callback_state);
324 }
325
326 int ast_sip_session_media_set_write_callback(struct ast_sip_session *session, struct ast_sip_session_media *session_media,
327         ast_sip_session_media_write_cb callback)
328 {
329         if (session_media->write_callback) {
330                 if (session_media->write_callback == callback) {
331                         return 0;
332                 }
333
334                 return -1;
335         }
336
337         session_media->write_callback = callback;
338
339         return 0;
340 }
341
342 struct ast_sip_session_media *ast_sip_session_media_get_transport(struct ast_sip_session *session, struct ast_sip_session_media *session_media)
343 {
344         int index;
345
346         if (!session->endpoint->media.bundle || ast_strlen_zero(session_media->mid)) {
347                 return session_media;
348         }
349
350         for (index = 0; index < AST_VECTOR_SIZE(&session->pending_media_state->sessions); ++index) {
351                 struct ast_sip_session_media *bundle_group_session_media;
352
353                 bundle_group_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
354
355                 /* The first session which is in the bundle group is considered the authoritative session for transport */
356                 if (bundle_group_session_media->bundle_group == session_media->bundle_group) {
357                         return bundle_group_session_media;
358                 }
359         }
360
361         return session_media;
362 }
363
364 /*!
365  * \brief Set an SDP stream handler for a corresponding session media.
366  *
367  * \note Always use this function to set the SDP handler for a session media.
368  *
369  * This function will properly free resources on the SDP handler currently being
370  * used by the session media, then set the session media to use the new SDP
371  * handler.
372  */
373 static void session_media_set_handler(struct ast_sip_session_media *session_media,
374                 struct ast_sip_session_sdp_handler *handler)
375 {
376         ast_assert(session_media->handler != handler);
377
378         if (session_media->handler) {
379                 session_media->handler->stream_destroy(session_media);
380         }
381         session_media->handler = handler;
382 }
383
384 static int stream_destroy(void *obj, void *arg, int flags)
385 {
386         struct sdp_handler_list *handler_list = obj;
387         struct ast_sip_session_media *session_media = arg;
388         struct ast_sip_session_sdp_handler *handler;
389
390         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
391                 handler->stream_destroy(session_media);
392         }
393
394         return 0;
395 }
396
397 static void session_media_dtor(void *obj)
398 {
399         struct ast_sip_session_media *session_media = obj;
400
401         /* It is possible for multiple handlers to have allocated memory on the
402          * session media (usually through a stream changing types). Therefore, we
403          * traverse all the SDP handlers and let them all call stream_destroy on
404          * the session_media
405          */
406         ao2_callback(sdp_handlers, 0, stream_destroy, session_media);
407
408         if (session_media->srtp) {
409                 ast_sdp_srtp_destroy(session_media->srtp);
410         }
411
412         ast_free(session_media->mid);
413         ast_free(session_media->remote_mslabel);
414 }
415
416 struct ast_sip_session_media *ast_sip_session_media_state_add(struct ast_sip_session *session,
417         struct ast_sip_session_media_state *media_state, enum ast_media_type type, int position)
418 {
419         struct ast_sip_session_media *session_media = NULL;
420
421         /* It is possible for this media state to already contain a session for the stream. If this
422          * is the case we simply return it.
423          */
424         if (position < AST_VECTOR_SIZE(&media_state->sessions)) {
425                 return AST_VECTOR_GET(&media_state->sessions, position);
426         }
427
428         /* Determine if we can reuse the session media from the active media state if present */
429         if (position < AST_VECTOR_SIZE(&session->active_media_state->sessions)) {
430                 session_media = AST_VECTOR_GET(&session->active_media_state->sessions, position);
431                 /* A stream can never exist without an accompanying media session */
432                 if (session_media->type == type) {
433                         ao2_ref(session_media, +1);
434                 } else {
435                         session_media = NULL;
436                 }
437         }
438
439         if (!session_media) {
440                 /* No existing media session we can use so create a new one */
441                 session_media = ao2_alloc_options(sizeof(*session_media), session_media_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
442                 if (!session_media) {
443                         return NULL;
444                 }
445
446                 session_media->encryption = session->endpoint->media.rtp.encryption;
447                 session_media->remote_ice = session->endpoint->media.rtp.ice_support;
448                 session_media->remote_rtcp_mux = session->endpoint->media.rtcp_mux;
449                 session_media->keepalive_sched_id = -1;
450                 session_media->timeout_sched_id = -1;
451                 session_media->type = type;
452                 session_media->stream_num = position;
453
454                 if (session->endpoint->media.bundle) {
455                         /* This is a new stream so create a new mid based on media type and position, which makes it unique.
456                          * If this is the result of an offer the mid will just end up getting replaced.
457                          */
458                         if (ast_asprintf(&session_media->mid, "%s-%d", ast_codec_media_type2str(type), position) < 0) {
459                                 ao2_ref(session_media, -1);
460                                 return NULL;
461                         }
462                         session_media->bundle_group = 0;
463
464                         /* Some WebRTC clients can't handle an offer to bundle media streams. Instead they expect them to
465                          * already be bundled. Every client handles this scenario though so if WebRTC is enabled just go
466                          * ahead and treat the streams as having already been bundled.
467                          */
468                         session_media->bundled = session->endpoint->media.webrtc;
469                 } else {
470                         session_media->bundle_group = -1;
471                 }
472         }
473
474         if (AST_VECTOR_REPLACE(&media_state->sessions, position, session_media)) {
475                 ao2_ref(session_media, -1);
476
477                 return NULL;
478         }
479
480         /* 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 */
481         if (!media_state->default_session[type] && ast_stream_get_state(ast_stream_topology_get_stream(media_state->topology, position)) != AST_STREAM_STATE_REMOVED) {
482                 media_state->default_session[type] = session_media;
483         }
484
485         return session_media;
486 }
487
488 static int is_stream_limitation_reached(enum ast_media_type type, const struct ast_sip_endpoint *endpoint, int *type_streams)
489 {
490         switch (type) {
491         case AST_MEDIA_TYPE_AUDIO:
492                 return !(type_streams[type] < endpoint->media.max_audio_streams);
493         case AST_MEDIA_TYPE_VIDEO:
494                 return !(type_streams[type] < endpoint->media.max_video_streams);
495         case AST_MEDIA_TYPE_IMAGE:
496                 /* We don't have an option for image (T.38) streams so cap it to one. */
497                 return (type_streams[type] > 0);
498         case AST_MEDIA_TYPE_UNKNOWN:
499         case AST_MEDIA_TYPE_TEXT:
500         default:
501                 /* We don't want any unknown or "other" streams on our endpoint,
502                  * so always just say we've reached the limit
503                  */
504                 return 1;
505         }
506 }
507
508 static int get_mid_bundle_group(const pjmedia_sdp_session *sdp, const char *mid)
509 {
510         int bundle_group = 0;
511         int index;
512
513         for (index = 0; index < sdp->attr_count; ++index) {
514                 pjmedia_sdp_attr *attr = sdp->attr[index];
515                 char value[pj_strlen(&attr->value) + 1], *mids = value, *attr_mid;
516
517                 if (pj_strcmp2(&attr->name, "group") || pj_strncmp2(&attr->value, "BUNDLE", 6)) {
518                         continue;
519                 }
520
521                 ast_copy_pj_str(value, &attr->value, sizeof(value));
522
523                 /* Skip the BUNDLE at the front */
524                 mids += 7;
525
526                 while ((attr_mid = strsep(&mids, " "))) {
527                         if (!strcmp(attr_mid, mid)) {
528                                 /* The ordering of attributes determines our internal identification of the bundle group based on number,
529                                  * with -1 being not in a bundle group. Since this is only exposed internally for response purposes it's
530                                  * actually even fine if things move around.
531                                  */
532                                 return bundle_group;
533                         }
534                 }
535
536                 bundle_group++;
537         }
538
539         return -1;
540 }
541
542 static int set_mid_and_bundle_group(struct ast_sip_session *session,
543         struct ast_sip_session_media *session_media,
544         const pjmedia_sdp_session *sdp,
545         const struct pjmedia_sdp_media *stream)
546 {
547         pjmedia_sdp_attr *attr;
548
549         if (!session->endpoint->media.bundle) {
550                 return 0;
551         }
552
553         /* By default on an incoming negotiation we assume no mid and bundle group is present */
554         ast_free(session_media->mid);
555         session_media->mid = NULL;
556         session_media->bundle_group = -1;
557         session_media->bundled = 0;
558
559         /* Grab the media identifier for the stream */
560         attr = pjmedia_sdp_media_find_attr2(stream, "mid", NULL);
561         if (!attr) {
562                 return 0;
563         }
564
565         session_media->mid = ast_calloc(1, attr->value.slen + 1);
566         if (!session_media->mid) {
567                 return 0;
568         }
569         ast_copy_pj_str(session_media->mid, &attr->value, attr->value.slen + 1);
570
571         /* Determine what bundle group this is part of */
572         session_media->bundle_group = get_mid_bundle_group(sdp, session_media->mid);
573
574         /* If this is actually part of a bundle group then the other side requested or accepted the bundle request */
575         session_media->bundled = session_media->bundle_group != -1;
576
577         return 0;
578 }
579
580 static void set_remote_mslabel_and_stream_group(struct ast_sip_session *session,
581         struct ast_sip_session_media *session_media,
582         const pjmedia_sdp_session *sdp,
583         const struct pjmedia_sdp_media *stream,
584         struct ast_stream *asterisk_stream)
585 {
586         int index;
587
588         ast_free(session_media->remote_mslabel);
589         session_media->remote_mslabel = NULL;
590
591         for (index = 0; index < stream->attr_count; ++index) {
592                 pjmedia_sdp_attr *attr = stream->attr[index];
593                 char attr_value[pj_strlen(&attr->value) + 1];
594                 char *ssrc_attribute_name, *ssrc_attribute_value = NULL;
595                 char *msid, *tmp = attr_value;
596                 static const pj_str_t STR_msid = { "msid", 4 };
597                 static const pj_str_t STR_ssrc = { "ssrc", 4 };
598
599                 if (!pj_strcmp(&attr->name, &STR_msid)) {
600                         ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
601                         msid = strsep(&tmp, " ");
602                         session_media->remote_mslabel = ast_strdup(msid);
603                         break;
604                 } else if (!pj_strcmp(&attr->name, &STR_ssrc)) {
605                         ast_copy_pj_str(attr_value, &attr->value, sizeof(attr_value));
606
607                         if ((ssrc_attribute_name = strchr(attr_value, ' '))) {
608                                 /* This has an actual attribute */
609                                 *ssrc_attribute_name++ = '\0';
610                                 ssrc_attribute_value = strchr(ssrc_attribute_name, ':');
611                                 if (ssrc_attribute_value) {
612                                         /* Values are actually optional according to the spec */
613                                         *ssrc_attribute_value++ = '\0';
614                                 }
615
616                                 if (!strcasecmp(ssrc_attribute_name, "mslabel") && !ast_strlen_zero(ssrc_attribute_value)) {
617                                         session_media->remote_mslabel = ast_strdup(ssrc_attribute_value);
618                                         break;
619                                 }
620                         }
621                 }
622         }
623
624         if (ast_strlen_zero(session_media->remote_mslabel)) {
625                 return;
626         }
627
628         /* Iterate through the existing streams looking for a match and if so then group this with it */
629         for (index = 0; index < AST_VECTOR_SIZE(&session->pending_media_state->sessions); ++index) {
630                 struct ast_sip_session_media *group_session_media;
631
632                 group_session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, index);
633
634                 if (ast_strlen_zero(group_session_media->remote_mslabel) ||
635                         strcmp(group_session_media->remote_mslabel, session_media->remote_mslabel)) {
636                         continue;
637                 }
638
639                 ast_stream_set_group(asterisk_stream, index);
640                 break;
641         }
642 }
643
644 static void remove_stream_from_bundle(struct ast_sip_session_media *session_media,
645         struct ast_stream *stream)
646 {
647         ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
648         ast_free(session_media->mid);
649         session_media->mid = NULL;
650         session_media->bundle_group = -1;
651         session_media->bundled = 0;
652 }
653
654 static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
655 {
656         int i;
657         int handled = 0;
658         int type_streams[AST_MEDIA_TYPE_END] = {0};
659
660         if (session->inv_session && session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
661                 ast_log(LOG_ERROR, "Failed to handle incoming SDP. Session has been already disconnected\n");
662                 return -1;
663         }
664
665         /* It is possible for SDP deferral to have already created a pending topology */
666         if (!session->pending_media_state->topology) {
667                 session->pending_media_state->topology = ast_stream_topology_alloc();
668                 if (!session->pending_media_state->topology) {
669                         return -1;
670                 }
671         }
672
673         for (i = 0; i < sdp->media_count; ++i) {
674                 /* See if there are registered handlers for this media stream type */
675                 char media[20];
676                 struct ast_sip_session_sdp_handler *handler;
677                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
678                 struct ast_sip_session_media *session_media = NULL;
679                 int res;
680                 enum ast_media_type type;
681                 struct ast_stream *stream = NULL;
682                 pjmedia_sdp_media *remote_stream = sdp->media[i];
683
684                 /* We need a null-terminated version of the media string */
685                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
686                 type = ast_media_type_from_str(media);
687
688                 /* See if we have an already existing stream, which can occur from SDP deferral checking */
689                 if (i < ast_stream_topology_get_count(session->pending_media_state->topology)) {
690                         stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
691                 }
692                 if (!stream) {
693                         struct ast_stream *existing_stream = NULL;
694
695                         if (session->active_media_state->topology &&
696                                 (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
697                                 existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
698                         }
699
700                         stream = ast_stream_alloc(existing_stream ? ast_stream_get_name(existing_stream) : ast_codec_media_type2str(type), type);
701                         if (!stream) {
702                                 return -1;
703                         }
704                         if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
705                                 ast_stream_free(stream);
706                                 return -1;
707                         }
708                 }
709
710                 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
711                 if (!session_media) {
712                         return -1;
713                 }
714
715                 /* If this stream is already declined mark it as such, or mark it as such if we've reached the limit */
716                 if (!remote_stream->desc.port || is_stream_limitation_reached(type, session->endpoint, type_streams)) {
717                         ast_debug(1, "Declining incoming SDP media stream '%s' at position '%d'\n",
718                                 ast_codec_media_type2str(type), i);
719                         remove_stream_from_bundle(session_media, stream);
720                         continue;
721                 }
722
723                 set_mid_and_bundle_group(session, session_media, sdp, remote_stream);
724                 set_remote_mslabel_and_stream_group(session, session_media, sdp, remote_stream, stream);
725
726                 if (session_media->handler) {
727                         handler = session_media->handler;
728                         ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
729                                 ast_codec_media_type2str(session_media->type),
730                                 session_media->handler->id);
731                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp, i, stream);
732                         if (res < 0) {
733                                 /* Catastrophic failure. Abort! */
734                                 return -1;
735                         } else if (res == 0) {
736                                 ast_debug(1, "Declining incoming SDP media stream '%s' at position '%d'\n",
737                                         ast_codec_media_type2str(type), i);
738                                 remove_stream_from_bundle(session_media, stream);
739                                 continue;
740                         } else if (res > 0) {
741                                 ast_debug(1, "Media stream '%s' handled by %s\n",
742                                         ast_codec_media_type2str(session_media->type),
743                                         session_media->handler->id);
744                                 /* Handled by this handler. Move to the next stream */
745                                 handled = 1;
746                                 ++type_streams[type];
747                                 continue;
748                         }
749                 }
750
751                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
752                 if (!handler_list) {
753                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
754                         continue;
755                 }
756                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
757                         if (handler == session_media->handler) {
758                                 continue;
759                         }
760                         ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
761                                 ast_codec_media_type2str(session_media->type),
762                                 handler->id);
763                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp, i, stream);
764                         if (res < 0) {
765                                 /* Catastrophic failure. Abort! */
766                                 return -1;
767                         } else if (res == 0) {
768                                 ast_debug(1, "Declining incoming SDP media stream '%s' at position '%d'\n",
769                                         ast_codec_media_type2str(type), i);
770                                 remove_stream_from_bundle(session_media, stream);
771                                 continue;
772                         } else if (res > 0) {
773                                 ast_debug(1, "Media stream '%s' handled by %s\n",
774                                         ast_codec_media_type2str(session_media->type),
775                                         handler->id);
776                                 /* Handled by this handler. Move to the next stream */
777                                 session_media_set_handler(session_media, handler);
778                                 handled = 1;
779                                 ++type_streams[type];
780                                 break;
781                         }
782                 }
783         }
784         if (!handled) {
785                 return -1;
786         }
787         return 0;
788 }
789
790 static int handle_negotiated_sdp_session_media(struct ast_sip_session_media *session_media,
791                 struct ast_sip_session *session, const pjmedia_sdp_session *local,
792                 const pjmedia_sdp_session *remote, int index, struct ast_stream *asterisk_stream)
793 {
794         /* See if there are registered handlers for this media stream type */
795         struct pjmedia_sdp_media *local_stream = local->media[index];
796         char media[20];
797         struct ast_sip_session_sdp_handler *handler;
798         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
799         int res;
800
801         /* For backwards compatibility we only reflect the stream state correctly on
802          * the non-default streams. This is because the stream state is also used for
803          * signaling that someone has placed us on hold. This situation is not handled
804          * currently and can result in the remote side being sort of placed on hold too.
805          */
806         if (!ast_sip_session_is_pending_stream_default(session, asterisk_stream)) {
807                 /* Determine the state of the stream based on our local SDP */
808                 if (pjmedia_sdp_media_find_attr2(local_stream, "sendonly", NULL)) {
809                         ast_stream_set_state(asterisk_stream, AST_STREAM_STATE_SENDONLY);
810                 } else if (pjmedia_sdp_media_find_attr2(local_stream, "recvonly", NULL)) {
811                         ast_stream_set_state(asterisk_stream, AST_STREAM_STATE_RECVONLY);
812                 } else if (pjmedia_sdp_media_find_attr2(local_stream, "inactive", NULL)) {
813                         ast_stream_set_state(asterisk_stream, AST_STREAM_STATE_INACTIVE);
814                 } else {
815                         ast_stream_set_state(asterisk_stream, AST_STREAM_STATE_SENDRECV);
816                 }
817         } else {
818                 ast_stream_set_state(asterisk_stream, AST_STREAM_STATE_SENDRECV);
819         }
820
821         /* We need a null-terminated version of the media string */
822         ast_copy_pj_str(media, &local->media[index]->desc.media, sizeof(media));
823
824         set_mid_and_bundle_group(session, session_media, remote, remote->media[index]);
825         set_remote_mslabel_and_stream_group(session, session_media, remote, remote->media[index], asterisk_stream);
826
827         handler = session_media->handler;
828         if (handler) {
829                 ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
830                         ast_codec_media_type2str(session_media->type),
831                         handler->id);
832                 res = handler->apply_negotiated_sdp_stream(session, session_media, local, remote, index, asterisk_stream);
833                 if (res >= 0) {
834                         ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
835                                 ast_codec_media_type2str(session_media->type),
836                                 handler->id);
837                         return 0;
838                 }
839                 return -1;
840         }
841
842         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
843         if (!handler_list) {
844                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
845                 return -1;
846         }
847         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
848                 if (handler == session_media->handler) {
849                         continue;
850                 }
851                 ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
852                         ast_codec_media_type2str(session_media->type),
853                         handler->id);
854                 res = handler->apply_negotiated_sdp_stream(session, session_media, local, remote, index, asterisk_stream);
855                 if (res < 0) {
856                         /* Catastrophic failure. Abort! */
857                         return -1;
858                 }
859                 if (res > 0) {
860                         ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
861                                 ast_codec_media_type2str(session_media->type),
862                                 handler->id);
863                         /* Handled by this handler. Move to the next stream */
864                         session_media_set_handler(session_media, handler);
865                         return 0;
866                 }
867         }
868
869         if (session_media->handler && session_media->handler->stream_stop) {
870                 ast_debug(1, "Stopping SDP media stream '%s' as it is not currently negotiated\n",
871                         ast_codec_media_type2str(session_media->type));
872                 session_media->handler->stream_stop(session_media);
873         }
874
875         return 0;
876 }
877
878 static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
879 {
880         int i;
881         struct ast_stream_topology *topology;
882         unsigned int changed = 0;
883
884         if (!session->pending_media_state->topology) {
885                 if (session->active_media_state->topology) {
886                         /*
887                          * This happens when we have negotiated media after receiving a 183,
888                          * and we're now receiving a 200 with a new SDP.  In this case, there
889                          * is active_media_state, but the pending_media_state has been reset.
890                          */
891                         struct ast_sip_session_media_state *active_media_state_clone;
892
893                         active_media_state_clone =
894                                 ast_sip_session_media_state_clone(session->active_media_state);
895                         if (!active_media_state_clone) {
896                                 ast_log(LOG_WARNING, "Unable to clone active media state for channel '%s'\n",
897                                         session->channel ? ast_channel_name(session->channel) : "unknown");
898                                 return -1;
899                         }
900
901                         ast_sip_session_media_state_free(session->pending_media_state);
902                         session->pending_media_state = active_media_state_clone;
903                 } else {
904                         ast_log(LOG_WARNING, "No pending or active media state for channel '%s'\n",
905                                 session->channel ? ast_channel_name(session->channel) : "unknown");
906                         return -1;
907                 }
908         }
909
910         /* If we're handling negotiated streams, then we should already have set
911          * up session media instances (and Asterisk streams) that correspond to
912          * the local SDP, and there should be the same number of session medias
913          * and streams as there are local SDP streams
914          */
915         if (ast_stream_topology_get_count(session->pending_media_state->topology) != local->media_count
916                 || AST_VECTOR_SIZE(&session->pending_media_state->sessions) != local->media_count) {
917                 ast_log(LOG_WARNING, "Local SDP for channel '%s' contains %d media streams while we expected it to contain %u\n",
918                         session->channel ? ast_channel_name(session->channel) : "unknown",
919                         ast_stream_topology_get_count(session->pending_media_state->topology), local->media_count);
920                 return -1;
921         }
922
923         for (i = 0; i < local->media_count; ++i) {
924                 struct ast_sip_session_media *session_media;
925                 struct ast_stream *stream;
926
927                 if (!remote->media[i]) {
928                         continue;
929                 }
930
931                 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
932                 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
933
934                 /* Make sure that this stream is in the correct state. If we need to change
935                  * the state to REMOVED, then our work here is done, so go ahead and move on
936                  * to the next stream.
937                  */
938                 if (!remote->media[i]->desc.port) {
939                         ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
940                         continue;
941                 }
942
943                 /* If the stream state is REMOVED, nothing needs to be done, so move on to the
944                  * next stream. This can occur if an internal thing has requested it to be
945                  * removed, or if we remove it as a result of the stream limit being reached.
946                  */
947                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
948                         /*
949                          * Defer removing the handler until we are ready to activate
950                          * the new topology.  The channel's thread may still be using
951                          * the stream and we could crash before we are ready.
952                          */
953                         continue;
954                 }
955
956                 if (handle_negotiated_sdp_session_media(session_media, session, local, remote, i, stream)) {
957                         return -1;
958                 }
959
960                 changed |= session_media->changed;
961                 session_media->changed = 0;
962         }
963
964         /* Apply the pending media state to the channel and make it active */
965         ast_channel_lock(session->channel);
966
967         /* Now update the stream handler for any declined/removed streams */
968         for (i = 0; i < local->media_count; ++i) {
969                 struct ast_sip_session_media *session_media;
970                 struct ast_stream *stream;
971
972                 if (!remote->media[i]) {
973                         continue;
974                 }
975
976                 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
977                 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
978
979                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED
980                         && session_media->handler) {
981                         /*
982                          * This stream is no longer being used and the channel's thread
983                          * is held off because we have the channel lock so release any
984                          * resources the handler may have on it.
985                          */
986                         session_media_set_handler(session_media, NULL);
987                 }
988         }
989
990         /* Update the topology on the channel to match the accepted one */
991         topology = ast_stream_topology_clone(session->pending_media_state->topology);
992         if (topology) {
993                 ast_channel_set_stream_topology(session->channel, topology);
994         }
995
996         /* Remove all current file descriptors from the channel */
997         for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++i) {
998                 ast_channel_internal_fd_clear(session->channel, i + AST_EXTENDED_FDS);
999         }
1000
1001         /* Add all the file descriptors from the pending media state */
1002         for (i = 0; i < AST_VECTOR_SIZE(&session->pending_media_state->read_callbacks); ++i) {
1003                 struct ast_sip_session_media_read_callback_state *callback_state;
1004
1005                 callback_state = AST_VECTOR_GET_ADDR(&session->pending_media_state->read_callbacks, i);
1006                 ast_channel_internal_fd_set(session->channel, i + AST_EXTENDED_FDS, callback_state->fd);
1007         }
1008
1009         /* Active and pending flip flop as needed */
1010         SWAP(session->active_media_state, session->pending_media_state);
1011         ast_sip_session_media_state_reset(session->pending_media_state);
1012
1013         ast_channel_unlock(session->channel);
1014
1015         if (changed) {
1016                 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED };
1017
1018                 ast_queue_frame(session->channel, &f);
1019         } else {
1020                 ast_queue_frame(session->channel, &ast_null_frame);
1021         }
1022
1023         return 0;
1024 }
1025
1026 #define DATASTORE_BUCKETS 53
1027 #define MEDIA_BUCKETS 7
1028
1029 static void session_datastore_destroy(void *obj)
1030 {
1031         struct ast_datastore *datastore = obj;
1032
1033         /* Using the destroy function (if present) destroy the data */
1034         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1035                 datastore->info->destroy(datastore->data);
1036                 datastore->data = NULL;
1037         }
1038
1039         ast_free((void *) datastore->uid);
1040         datastore->uid = NULL;
1041 }
1042
1043 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
1044 {
1045         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1046         char uuid_buf[AST_UUID_STR_LEN];
1047         const char *uid_ptr = uid;
1048
1049         if (!info) {
1050                 return NULL;
1051         }
1052
1053         datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
1054         if (!datastore) {
1055                 return NULL;
1056         }
1057
1058         datastore->info = info;
1059         if (ast_strlen_zero(uid)) {
1060                 /* They didn't provide an ID so we'll provide one ourself */
1061                 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
1062         }
1063
1064         datastore->uid = ast_strdup(uid_ptr);
1065         if (!datastore->uid) {
1066                 return NULL;
1067         }
1068
1069         ao2_ref(datastore, +1);
1070         return datastore;
1071 }
1072
1073 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
1074 {
1075         ast_assert(datastore != NULL);
1076         ast_assert(datastore->info != NULL);
1077         ast_assert(ast_strlen_zero(datastore->uid) == 0);
1078
1079         if (!ao2_link(session->datastores, datastore)) {
1080                 return -1;
1081         }
1082         return 0;
1083 }
1084
1085 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
1086 {
1087         return ao2_find(session->datastores, name, OBJ_KEY);
1088 }
1089
1090 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
1091 {
1092         ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
1093 }
1094
1095 enum delayed_method {
1096         DELAYED_METHOD_INVITE,
1097         DELAYED_METHOD_UPDATE,
1098         DELAYED_METHOD_BYE,
1099 };
1100
1101 /*!
1102  * \internal
1103  * \brief Convert delayed method enum value to a string.
1104  * \since 13.3.0
1105  *
1106  * \param method Delayed method enum value to convert to a string.
1107  *
1108  * \return String value of delayed method.
1109  */
1110 static const char *delayed_method2str(enum delayed_method method)
1111 {
1112         const char *str = "<unknown>";
1113
1114         switch (method) {
1115         case DELAYED_METHOD_INVITE:
1116                 str = "INVITE";
1117                 break;
1118         case DELAYED_METHOD_UPDATE:
1119                 str = "UPDATE";
1120                 break;
1121         case DELAYED_METHOD_BYE:
1122                 str = "BYE";
1123                 break;
1124         }
1125
1126         return str;
1127 }
1128
1129 /*!
1130  * \brief Structure used for sending delayed requests
1131  *
1132  * Requests are typically delayed because the current transaction
1133  * state of an INVITE. Once the pending INVITE transaction terminates,
1134  * the delayed request will be sent
1135  */
1136 struct ast_sip_session_delayed_request {
1137         /*! Method of the request */
1138         enum delayed_method method;
1139         /*! Callback to call when the delayed request is created. */
1140         ast_sip_session_request_creation_cb on_request_creation;
1141         /*! Callback to call when the delayed request SDP is created */
1142         ast_sip_session_sdp_creation_cb on_sdp_creation;
1143         /*! Callback to call when the delayed request receives a response */
1144         ast_sip_session_response_cb on_response;
1145         /*! Whether to generate new SDP */
1146         int generate_new_sdp;
1147         /*! Requested media state for the SDP */
1148         struct ast_sip_session_media_state *media_state;
1149         AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
1150 };
1151
1152 static struct ast_sip_session_delayed_request *delayed_request_alloc(
1153         enum delayed_method method,
1154         ast_sip_session_request_creation_cb on_request_creation,
1155         ast_sip_session_sdp_creation_cb on_sdp_creation,
1156         ast_sip_session_response_cb on_response,
1157         int generate_new_sdp,
1158         struct ast_sip_session_media_state *media_state)
1159 {
1160         struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
1161
1162         if (!delay) {
1163                 return NULL;
1164         }
1165         delay->method = method;
1166         delay->on_request_creation = on_request_creation;
1167         delay->on_sdp_creation = on_sdp_creation;
1168         delay->on_response = on_response;
1169         delay->generate_new_sdp = generate_new_sdp;
1170         delay->media_state = media_state;
1171         return delay;
1172 }
1173
1174 static void delayed_request_free(struct ast_sip_session_delayed_request *delay)
1175 {
1176         ast_sip_session_media_state_free(delay->media_state);
1177         ast_free(delay);
1178 }
1179
1180 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
1181 {
1182         ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",
1183                 ast_sorcery_object_get_id(session->endpoint),
1184                 session->channel ? ast_channel_name(session->channel) : "",
1185                 delayed_method2str(delay->method));
1186
1187         switch (delay->method) {
1188         case DELAYED_METHOD_INVITE:
1189                 ast_sip_session_refresh(session, delay->on_request_creation,
1190                         delay->on_sdp_creation, delay->on_response,
1191                         AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp, delay->media_state);
1192                 /* Ownership of media state transitions to ast_sip_session_refresh */
1193                 delay->media_state = NULL;
1194                 return 0;
1195         case DELAYED_METHOD_UPDATE:
1196                 ast_sip_session_refresh(session, delay->on_request_creation,
1197                         delay->on_sdp_creation, delay->on_response,
1198                         AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp, delay->media_state);
1199                 /* Ownership of media state transitions to ast_sip_session_refresh */
1200                 delay->media_state = NULL;
1201                 return 0;
1202         case DELAYED_METHOD_BYE:
1203                 ast_sip_session_terminate(session, 0);
1204                 return 0;
1205         }
1206         ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",
1207                 delayed_method2str(delay->method), delay->method);
1208         return -1;
1209 }
1210
1211 /*!
1212  * \internal
1213  * \brief The current INVITE transaction is in the PROCEEDING state.
1214  * \since 13.3.0
1215  *
1216  * \param vsession Session object.
1217  *
1218  * \retval 0 on success.
1219  * \retval -1 on error.
1220  */
1221 static int invite_proceeding(void *vsession)
1222 {
1223         struct ast_sip_session *session = vsession;
1224         struct ast_sip_session_delayed_request *delay;
1225         int found = 0;
1226         int res = 0;
1227
1228         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1229                 switch (delay->method) {
1230                 case DELAYED_METHOD_INVITE:
1231                         break;
1232                 case DELAYED_METHOD_UPDATE:
1233                         AST_LIST_REMOVE_CURRENT(next);
1234                         res = send_delayed_request(session, delay);
1235                         delayed_request_free(delay);
1236                         found = 1;
1237                         break;
1238                 case DELAYED_METHOD_BYE:
1239                         /* A BYE is pending so don't bother anymore. */
1240                         found = 1;
1241                         break;
1242                 }
1243                 if (found) {
1244                         break;
1245                 }
1246         }
1247         AST_LIST_TRAVERSE_SAFE_END;
1248
1249         ao2_ref(session, -1);
1250         return res;
1251 }
1252
1253 /*!
1254  * \internal
1255  * \brief The current INVITE transaction is in the TERMINATED state.
1256  * \since 13.3.0
1257  *
1258  * \param vsession Session object.
1259  *
1260  * \retval 0 on success.
1261  * \retval -1 on error.
1262  */
1263 static int invite_terminated(void *vsession)
1264 {
1265         struct ast_sip_session *session = vsession;
1266         struct ast_sip_session_delayed_request *delay;
1267         int found = 0;
1268         int res = 0;
1269         int timer_running;
1270
1271         /* re-INVITE collision timer running? */
1272         timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
1273
1274         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1275                 switch (delay->method) {
1276                 case DELAYED_METHOD_INVITE:
1277                         if (!timer_running) {
1278                                 found = 1;
1279                         }
1280                         break;
1281                 case DELAYED_METHOD_UPDATE:
1282                 case DELAYED_METHOD_BYE:
1283                         found = 1;
1284                         break;
1285                 }
1286                 if (found) {
1287                         AST_LIST_REMOVE_CURRENT(next);
1288                         res = send_delayed_request(session, delay);
1289                         delayed_request_free(delay);
1290                         break;
1291                 }
1292         }
1293         AST_LIST_TRAVERSE_SAFE_END;
1294
1295         ao2_ref(session, -1);
1296         return res;
1297 }
1298
1299 /*!
1300  * \internal
1301  * \brief INVITE collision timeout.
1302  * \since 13.3.0
1303  *
1304  * \param vsession Session object.
1305  *
1306  * \retval 0 on success.
1307  * \retval -1 on error.
1308  */
1309 static int invite_collision_timeout(void *vsession)
1310 {
1311         struct ast_sip_session *session = vsession;
1312         int res;
1313
1314         if (session->inv_session->invite_tsx) {
1315                 /*
1316                  * INVITE transaction still active.  Let it send
1317                  * the collision re-INVITE when it terminates.
1318                  */
1319                 ao2_ref(session, -1);
1320                 res = 0;
1321         } else {
1322                 res = invite_terminated(session);
1323         }
1324
1325         return res;
1326 }
1327
1328 /*!
1329  * \internal
1330  * \brief The current UPDATE transaction is in the COMPLETED state.
1331  * \since 13.3.0
1332  *
1333  * \param vsession Session object.
1334  *
1335  * \retval 0 on success.
1336  * \retval -1 on error.
1337  */
1338 static int update_completed(void *vsession)
1339 {
1340         struct ast_sip_session *session = vsession;
1341         int res;
1342
1343         if (session->inv_session->invite_tsx) {
1344                 res = invite_proceeding(session);
1345         } else {
1346                 res = invite_terminated(session);
1347         }
1348
1349         return res;
1350 }
1351
1352 static void check_delayed_requests(struct ast_sip_session *session,
1353         int (*cb)(void *vsession))
1354 {
1355         ao2_ref(session, +1);
1356         if (ast_sip_push_task(session->serializer, cb, session)) {
1357                 ao2_ref(session, -1);
1358         }
1359 }
1360
1361 static int delay_request(struct ast_sip_session *session,
1362         ast_sip_session_request_creation_cb on_request,
1363         ast_sip_session_sdp_creation_cb on_sdp_creation,
1364         ast_sip_session_response_cb on_response,
1365         int generate_new_sdp,
1366         enum delayed_method method,
1367         struct ast_sip_session_media_state *media_state)
1368 {
1369         struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
1370                         on_request, on_sdp_creation, on_response, generate_new_sdp, media_state);
1371
1372         if (!delay) {
1373                 ast_sip_session_media_state_free(media_state);
1374                 return -1;
1375         }
1376
1377         if (method == DELAYED_METHOD_BYE) {
1378                 /* Send BYE as early as possible */
1379                 AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
1380         } else {
1381                 AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
1382         }
1383         return 0;
1384 }
1385
1386 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
1387 {
1388         pjsip_inv_session *inv_session = session->inv_session;
1389         const pjmedia_sdp_session *previous_sdp = NULL;
1390
1391         if (inv_session->neg) {
1392                 if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
1393                         pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
1394                 } else {
1395                         pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
1396                 }
1397         }
1398         return create_local_sdp(inv_session, session, previous_sdp);
1399 }
1400
1401 static void set_from_header(struct ast_sip_session *session)
1402 {
1403         struct ast_party_id effective_id;
1404         struct ast_party_id connected_id;
1405         pj_pool_t *dlg_pool;
1406         pjsip_fromto_hdr *dlg_info;
1407         pjsip_name_addr *dlg_info_name_addr;
1408         pjsip_sip_uri *dlg_info_uri;
1409         int restricted;
1410
1411         if (!session->channel || session->saved_from_hdr) {
1412                 return;
1413         }
1414
1415         /* We need to save off connected_id for RPID/PAI generation */
1416         ast_party_id_init(&connected_id);
1417         ast_channel_lock(session->channel);
1418         effective_id = ast_channel_connected_effective_id(session->channel);
1419         ast_party_id_copy(&connected_id, &effective_id);
1420         ast_channel_unlock(session->channel);
1421
1422         restricted =
1423                 ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);
1424
1425         /* Now set up dlg->local.info so pjsip can correctly generate From */
1426
1427         dlg_pool = session->inv_session->dlg->pool;
1428         dlg_info = session->inv_session->dlg->local.info;
1429         dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;
1430         dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);
1431
1432         if (session->endpoint->id.trust_outbound || !restricted) {
1433                 ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);
1434         }
1435
1436         ast_party_id_free(&connected_id);
1437
1438         if (!ast_strlen_zero(session->endpoint->fromuser)) {
1439                 dlg_info_name_addr->display.ptr = NULL;
1440                 dlg_info_name_addr->display.slen = 0;
1441                 pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);
1442         }
1443
1444         if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1445                 pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);
1446         }
1447
1448         /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */
1449         session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);
1450         ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);
1451
1452         /* In chan_sip, fromuser and fromdomain trump restricted so we only
1453          * anonymize if they're not set.
1454          */
1455         if (restricted) {
1456                 /* fromuser doesn't provide a display name so we always set it */
1457                 pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");
1458
1459                 if (ast_strlen_zero(session->endpoint->fromuser)) {
1460                         pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");
1461                 }
1462
1463                 if (ast_strlen_zero(session->endpoint->fromdomain)) {
1464                         pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");
1465                 }
1466         } else {
1467                 ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);
1468     }
1469 }
1470
1471 int ast_sip_session_refresh(struct ast_sip_session *session,
1472                 ast_sip_session_request_creation_cb on_request_creation,
1473                 ast_sip_session_sdp_creation_cb on_sdp_creation,
1474                 ast_sip_session_response_cb on_response,
1475                 enum ast_sip_session_refresh_method method, int generate_new_sdp,
1476                 struct ast_sip_session_media_state *media_state)
1477 {
1478         pjsip_inv_session *inv_session = session->inv_session;
1479         pjmedia_sdp_session *new_sdp = NULL;
1480         pjsip_tx_data *tdata;
1481
1482         if (media_state && (!media_state->topology || !generate_new_sdp)) {
1483                 ast_sip_session_media_state_free(media_state);
1484                 return -1;
1485         }
1486
1487         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1488                 /* Don't try to do anything with a hung-up call */
1489                 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
1490                                 ast_sorcery_object_get_id(session->endpoint));
1491                 ast_sip_session_media_state_free(media_state);
1492                 return 0;
1493         }
1494
1495         /* If the dialog has not yet been established we have to defer until it has */
1496         if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1497                 ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
1498                         ast_sorcery_object_get_id(session->endpoint));
1499                 return delay_request(session, on_request_creation, on_sdp_creation, on_response,
1500                         generate_new_sdp,
1501                         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1502                                 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE,
1503                         media_state);
1504         }
1505
1506         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1507                 if (inv_session->invite_tsx) {
1508                         /* We can't send a reinvite yet, so delay it */
1509                         ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
1510                                         ast_sorcery_object_get_id(session->endpoint));
1511                         return delay_request(session, on_request_creation, on_sdp_creation,
1512                                 on_response, generate_new_sdp, DELAYED_METHOD_INVITE, media_state);
1513                 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
1514                         /* Initial INVITE transaction failed to progress us to a confirmed state
1515                          * which means re-invites are not possible
1516                          */
1517                         ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
1518                                         ast_sorcery_object_get_id(session->endpoint));
1519                         ast_sip_session_media_state_free(media_state);
1520                         return 0;
1521                 }
1522         }
1523
1524         if (generate_new_sdp) {
1525                 /* SDP can only be generated if current negotiation has already completed */
1526                 if (inv_session->neg
1527                         && pjmedia_sdp_neg_get_state(inv_session->neg)
1528                                 != PJMEDIA_SDP_NEG_STATE_DONE) {
1529                         ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
1530                                 ast_sorcery_object_get_id(session->endpoint));
1531                         return delay_request(session, on_request_creation, on_sdp_creation,
1532                                 on_response, generate_new_sdp,
1533                                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1534                                         ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE, media_state);
1535                 }
1536
1537                 /* If an explicitly requested media state has been provided use it instead of any pending one */
1538                 if (media_state) {
1539                         int index;
1540                         int type_streams[AST_MEDIA_TYPE_END] = {0};
1541                         struct ast_stream *stream;
1542
1543                         /* Prune the media state so the number of streams fit within the configured limits - we do it here
1544                          * so that the index of the resulting streams in the SDP match. If we simply left the streams out
1545                          * of the SDP when producing it we'd be in trouble. We also enforce formats here for media types that
1546                          * are configurable on the endpoint.
1547                          */
1548                         for (index = 0; index < ast_stream_topology_get_count(media_state->topology); ++index) {
1549                                 struct ast_stream *existing_stream = NULL;
1550
1551                                 stream = ast_stream_topology_get_stream(media_state->topology, index);
1552
1553                                 if (session->active_media_state->topology &&
1554                                         index < ast_stream_topology_get_count(session->active_media_state->topology)) {
1555                                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1556                                 }
1557
1558                                 if (is_stream_limitation_reached(ast_stream_get_type(stream), session->endpoint, type_streams)) {
1559                                         if (index < AST_VECTOR_SIZE(&media_state->sessions)) {
1560                                                 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&media_state->sessions, index);
1561
1562                                                 ao2_cleanup(session_media);
1563                                                 AST_VECTOR_REMOVE(&media_state->sessions, index, 1);
1564                                         }
1565
1566                                         ast_stream_topology_del_stream(media_state->topology, index);
1567
1568                                         /* A stream has potentially moved into our spot so we need to jump back so we process it */
1569                                         index -= 1;
1570                                         continue;
1571                                 }
1572
1573                                 /* No need to do anything with stream if it's media state is removed */
1574                                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
1575                                         continue;
1576                                 }
1577
1578                                 /* Enforce the configured allowed codecs on audio and video streams */
1579                                 if (ast_stream_get_type(stream) == AST_MEDIA_TYPE_AUDIO || ast_stream_get_type(stream) == AST_MEDIA_TYPE_VIDEO) {
1580                                         struct ast_format_cap *joint_cap;
1581
1582                                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1583                                         if (!joint_cap) {
1584                                                 ast_sip_session_media_state_free(media_state);
1585                                                 return 0;
1586                                         }
1587                                         ast_format_cap_get_compatible(ast_stream_get_formats(stream), session->endpoint->media.codecs, joint_cap);
1588                                         if (!ast_format_cap_count(joint_cap)) {
1589                                                 ao2_ref(joint_cap, -1);
1590
1591                                                 if (!existing_stream) {
1592                                                         /* If there is no existing stream we can just not have this stream in the topology
1593                                                          * at all.
1594                                                          */
1595                                                         ast_stream_topology_del_stream(media_state->topology, index);
1596                                                         index -= 1;
1597                                                         continue;
1598                                                 } else if (ast_stream_get_state(stream) != ast_stream_get_state(existing_stream) ||
1599                                                                 strcmp(ast_stream_get_name(stream), ast_stream_get_name(existing_stream))) {
1600                                                         /* If the underlying stream is a different type or different name then we have to
1601                                                          * mark it as removed, as it is replacing an existing stream. We do this so order
1602                                                          * is preserved.
1603                                                          */
1604                                                         ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
1605                                                         continue;
1606                                                 } else {
1607                                                         /* However if the stream is otherwise remaining the same we can keep the formats
1608                                                          * that exist on it already which allows media to continue to flow.
1609                                                          */
1610                                                         joint_cap = ao2_bump(ast_stream_get_formats(existing_stream));
1611                                                 }
1612                                         }
1613                                         ast_stream_set_formats(stream, joint_cap);
1614                                         ao2_cleanup(joint_cap);
1615                                 }
1616
1617                                 ++type_streams[ast_stream_get_type(stream)];
1618                         }
1619
1620                         if (session->active_media_state->topology) {
1621                                 /* SDP is a fun thing. Take for example the fact that streams are never removed. They just become
1622                                  * declined. To better handle this in the case where something requests a topology change for fewer
1623                                  * streams than are currently present we fill in the topology to match the current number of streams
1624                                  * that are active.
1625                                  */
1626                                 for (index = ast_stream_topology_get_count(media_state->topology);
1627                                         index < ast_stream_topology_get_count(session->active_media_state->topology); ++index) {
1628                                         struct ast_stream *cloned;
1629
1630                                         stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1631                                         ast_assert(stream != NULL);
1632
1633                                         cloned = ast_stream_clone(stream, NULL);
1634                                         if (!cloned) {
1635                                                 ast_sip_session_media_state_free(media_state);
1636                                                 return -1;
1637                                         }
1638
1639                                         ast_stream_set_state(cloned, AST_STREAM_STATE_REMOVED);
1640                                         if (ast_stream_topology_append_stream(media_state->topology, cloned) < 0) {
1641                                                 ast_stream_free(cloned);
1642                                                 ast_sip_session_media_state_free(media_state);
1643                                                 return -1;
1644                                         }
1645                                 }
1646
1647                                 /* If the resulting media state matches the existing active state don't bother doing a session refresh */
1648                                 if (ast_stream_topology_equal(session->active_media_state->topology, media_state->topology)) {
1649                                         ast_sip_session_media_state_free(media_state);
1650                                         return 0;
1651                                 }
1652                         }
1653
1654                         ast_sip_session_media_state_free(session->pending_media_state);
1655                         session->pending_media_state = media_state;
1656                 }
1657
1658                 new_sdp = generate_session_refresh_sdp(session);
1659                 if (!new_sdp) {
1660                         ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
1661                         ast_sip_session_media_state_reset(session->pending_media_state);
1662                         return -1;
1663                 }
1664                 if (on_sdp_creation) {
1665                         if (on_sdp_creation(session, new_sdp)) {
1666                                 ast_sip_session_media_state_reset(session->pending_media_state);
1667                                 return -1;
1668                         }
1669                 }
1670         }
1671
1672         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1673                 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
1674                         ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
1675                         if (generate_new_sdp) {
1676                                 ast_sip_session_media_state_reset(session->pending_media_state);
1677                         }
1678                         return -1;
1679                 }
1680         } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
1681                 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
1682                 if (generate_new_sdp) {
1683                         ast_sip_session_media_state_reset(session->pending_media_state);
1684                 }
1685                 return -1;
1686         }
1687         if (on_request_creation) {
1688                 if (on_request_creation(session, tdata)) {
1689                         if (generate_new_sdp) {
1690                                 ast_sip_session_media_state_reset(session->pending_media_state);
1691                         }
1692                         return -1;
1693                 }
1694         }
1695         ast_debug(3, "Sending session refresh SDP via %s to %s\n",
1696                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
1697                 ast_sorcery_object_get_id(session->endpoint));
1698         ast_sip_session_send_request_with_cb(session, tdata, on_response);
1699         return 0;
1700 }
1701
1702 int ast_sip_session_regenerate_answer(struct ast_sip_session *session,
1703                 ast_sip_session_sdp_creation_cb on_sdp_creation)
1704 {
1705         pjsip_inv_session *inv_session = session->inv_session;
1706         pjmedia_sdp_session *new_answer = NULL;
1707         const pjmedia_sdp_session *previous_offer = NULL;
1708
1709         /* The SDP answer can only be regenerated if it is still pending to be sent */
1710         if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
1711                 pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {
1712                 ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",
1713                         ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));
1714                 return -1;
1715         }
1716
1717         pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);
1718         if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {
1719                 /* Transition the SDP negotiator back to when it received the remote offer */
1720                 pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);
1721                 pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);
1722         }
1723
1724         new_answer = create_local_sdp(inv_session, session, previous_offer);
1725         if (!new_answer) {
1726                 ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",
1727                         ast_channel_name(session->channel));
1728                 return -1;
1729         }
1730
1731         if (on_sdp_creation) {
1732                 if (on_sdp_creation(session, new_answer)) {
1733                         return -1;
1734                 }
1735         }
1736
1737         pjsip_inv_set_sdp_answer(inv_session, new_answer);
1738
1739         return 0;
1740 }
1741
1742 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1743 {
1744         handle_outgoing_response(session, tdata);
1745         pjsip_inv_send_msg(session->inv_session, tdata);
1746         return;
1747 }
1748
1749 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
1750
1751 static pjsip_module session_module = {
1752         .name = {"Session Module", 14},
1753         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1754         .on_rx_request = session_on_rx_request,
1755 };
1756
1757 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
1758  *
1759  * \retval 1 re-invite should be deferred and resumed later
1760  * \retval 0 re-invite should not be deferred
1761  */
1762 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
1763 {
1764         int i;
1765
1766         if (!session->pending_media_state->topology) {
1767                 session->pending_media_state->topology = ast_stream_topology_alloc();
1768                 if (!session->pending_media_state->topology) {
1769                         return -1;
1770                 }
1771         }
1772
1773         for (i = 0; i < sdp->media_count; ++i) {
1774                 /* See if there are registered handlers for this media stream type */
1775                 char media[20];
1776                 struct ast_sip_session_sdp_handler *handler;
1777                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1778                 struct ast_stream *existing_stream = NULL;
1779                 struct ast_stream *stream;
1780                 enum ast_media_type type;
1781                 struct ast_sip_session_media *session_media = NULL;
1782                 enum ast_sip_session_sdp_stream_defer res;
1783
1784                 /* We need a null-terminated version of the media string */
1785                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
1786
1787                 if (session->active_media_state->topology &&
1788                         (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
1789                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
1790                 }
1791
1792                 type = ast_media_type_from_str(media);
1793                 stream = ast_stream_alloc(existing_stream ? ast_stream_get_name(existing_stream) : ast_codec_media_type2str(type), type);
1794                 if (!stream) {
1795                         return -1;
1796                 }
1797
1798                 /* As this is only called on an incoming SDP offer before processing it is not possible
1799                  * for streams and their media sessions to exist.
1800                  */
1801                 if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
1802                         ast_stream_free(stream);
1803                         return -1;
1804                 }
1805
1806                 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
1807                 if (!session_media) {
1808                         return -1;
1809                 }
1810
1811                 if (session_media->handler) {
1812                         handler = session_media->handler;
1813                         if (handler->defer_incoming_sdp_stream) {
1814                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1815                                         sdp->media[i]);
1816                                 switch (res) {
1817                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1818                                         break;
1819                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
1820                                         return 0;
1821                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1822                                         break;
1823                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1824                                         return 1;
1825                                 }
1826                         }
1827                         /* Handled by this handler. Move to the next stream */
1828                         continue;
1829                 }
1830
1831                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1832                 if (!handler_list) {
1833                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
1834                         continue;
1835                 }
1836                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1837                         if (handler == session_media->handler) {
1838                                 continue;
1839                         }
1840                         if (!handler->defer_incoming_sdp_stream) {
1841                                 continue;
1842                         }
1843                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1844                                 sdp->media[i]);
1845                         switch (res) {
1846                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1847                                 continue;
1848                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
1849                                 session_media_set_handler(session_media, handler);
1850                                 return 0;
1851                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1852                                 /* Handled by this handler. */
1853                                 session_media_set_handler(session_media, handler);
1854                                 break;
1855                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1856                                 /* Handled by this handler. */
1857                                 session_media_set_handler(session_media, handler);
1858                                 return 1;
1859                         }
1860                         /* Move to the next stream */
1861                         break;
1862                 }
1863         }
1864         return 0;
1865 }
1866
1867 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
1868 {
1869         pjsip_dialog *dlg;
1870         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1871         pjsip_rdata_sdp_info *sdp_info;
1872
1873         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
1874                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
1875                 !(session = ast_sip_dialog_get_session(dlg)) ||
1876                 !session->channel) {
1877                 return PJ_FALSE;
1878         }
1879
1880         if (session->deferred_reinvite) {
1881                 pj_str_t key, deferred_key;
1882                 pjsip_tx_data *tdata;
1883
1884                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1885                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1886                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1887                         session->deferred_reinvite);
1888
1889                 /* If this is a retransmission ignore it */
1890                 if (!pj_strcmp(&key, &deferred_key)) {
1891                         return PJ_TRUE;
1892                 }
1893
1894                 /* Otherwise this is a new re-invite, so reject it */
1895                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1896                         if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
1897                                 pjsip_tx_data_dec_ref(tdata);
1898                         }
1899                 }
1900
1901                 return PJ_TRUE;
1902         }
1903
1904         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1905                 (sdp_info->sdp_err != PJ_SUCCESS)) {
1906                 return PJ_FALSE;
1907         }
1908
1909         if (!sdp_info->sdp) {
1910                 const pjmedia_sdp_session *local;
1911                 int i;
1912
1913                 ast_queue_unhold(session->channel);
1914
1915                 pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);
1916                 if (!local) {
1917                         return PJ_FALSE;
1918                 }
1919
1920                 /*
1921                  * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).
1922                  * When hold is initially indicated, we
1923                  * - Receive an INVITE with no SDP
1924                  * - Send a 200 OK with SDP, indicating sendrecv in the media streams
1925                  * - Receive an ACK with SDP, indicating sendonly in the media streams
1926                  *
1927                  * At this point, the pjmedia negotiator saves the state of the media direction so that
1928                  * if we are to send any offers, we'll offer recvonly in the media streams. This is
1929                  * problematic if the device is attempting to unhold, though. If the device unholds
1930                  * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.
1931                  * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond
1932                  * with sendonly or inactive. The result of this is that the stream is not off hold.
1933                  *
1934                  * Therefore, in this case, when we receive a reinvite while the stream is on hold, we
1935                  * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv
1936                  * in order to get the stream off hold. If this is actually a different purpose reinvite
1937                  * (like a session timer refresh), then the answerer can respond to our sendrecv with
1938                  * sendonly, keeping the stream on hold.
1939                  */
1940                 for (i = 0; i < local->media_count; ++i) {
1941                         pjmedia_sdp_media *m = local->media[i];
1942                         pjmedia_sdp_attr *recvonly;
1943                         pjmedia_sdp_attr *inactive;
1944
1945                         recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);
1946                         inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);
1947                         if (recvonly || inactive) {
1948                                 pjmedia_sdp_attr *to_remove = recvonly ?: inactive;
1949                                 pjmedia_sdp_attr *sendrecv;
1950
1951                                 pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);
1952
1953                                 sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);
1954                                 pjmedia_sdp_media_add_attr(m, sendrecv);
1955                         }
1956                 }
1957
1958                 return PJ_FALSE;
1959         }
1960
1961         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1962                 return PJ_FALSE;
1963         }
1964
1965         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1966
1967         return PJ_TRUE;
1968 }
1969
1970 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1971 {
1972         if (!session->deferred_reinvite) {
1973                 return;
1974         }
1975
1976         if (session->channel) {
1977                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1978                         session->deferred_reinvite, NULL, NULL);
1979         }
1980         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1981         session->deferred_reinvite = NULL;
1982 }
1983
1984 static pjsip_module session_reinvite_module = {
1985         .name = { "Session Re-Invite Module", 24 },
1986         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1987         .on_rx_request = session_reinvite_on_rx_request,
1988 };
1989
1990
1991 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1992                 ast_sip_session_response_cb on_response)
1993 {
1994         pjsip_inv_session *inv_session = session->inv_session;
1995
1996         /* For every request except BYE we disallow sending of the message when
1997          * the session has been disconnected. A BYE request is special though
1998          * because it can be sent again after the session is disconnected except
1999          * with credentials.
2000          */
2001         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&
2002                 tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {
2003                 return;
2004         }
2005
2006         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
2007                              MOD_DATA_ON_RESPONSE, on_response);
2008
2009         handle_outgoing_request(session, tdata);
2010         pjsip_inv_send_msg(session->inv_session, tdata);
2011
2012         return;
2013 }
2014
2015 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2016 {
2017         ast_sip_session_send_request_with_cb(session, tdata, NULL);
2018 }
2019
2020 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
2021 {
2022         pjmedia_sdp_session *offer;
2023
2024         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
2025                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
2026                 return -1;
2027         }
2028
2029         pjsip_inv_set_local_sdp(session->inv_session, offer);
2030         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
2031 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2032         if (!session->endpoint->preferred_codec_only) {
2033                 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
2034         }
2035 #endif
2036
2037         /*
2038          * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the
2039          * From in the initial INVITE will be wrong but the rest of the messages will be OK.
2040          */
2041         set_from_header(session);
2042
2043         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
2044                 return -1;
2045         }
2046
2047         return 0;
2048 }
2049
2050 static int datastore_hash(const void *obj, int flags)
2051 {
2052         const struct ast_datastore *datastore = obj;
2053         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
2054
2055         ast_assert(uid != NULL);
2056
2057         return ast_str_hash(uid);
2058 }
2059
2060 static int datastore_cmp(void *obj, void *arg, int flags)
2061 {
2062         const struct ast_datastore *datastore1 = obj;
2063         const struct ast_datastore *datastore2 = arg;
2064         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
2065
2066         ast_assert(datastore1->uid != NULL);
2067         ast_assert(uid2 != NULL);
2068
2069         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
2070 }
2071
2072 static void session_destructor(void *obj)
2073 {
2074         struct ast_sip_session *session = obj;
2075         struct ast_sip_session_supplement *supplement;
2076         struct ast_sip_session_delayed_request *delay;
2077         const char *endpoint_name = session->endpoint ?
2078                 ast_sorcery_object_get_id(session->endpoint) : "<none>";
2079
2080         ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);
2081
2082         ast_test_suite_event_notify("SESSION_DESTROYING",
2083                 "Endpoint: %s\r\n"
2084                 "AOR: %s\r\n"
2085                 "Contact: %s"
2086                 , endpoint_name
2087                 , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"
2088                 , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"
2089                 );
2090
2091         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
2092                 if (supplement->session_destroy) {
2093                         supplement->session_destroy(session);
2094                 }
2095                 ast_free(supplement);
2096         }
2097
2098         ast_taskprocessor_unreference(session->serializer);
2099         ao2_cleanup(session->datastores);
2100         ast_sip_session_media_state_free(session->active_media_state);
2101         ast_sip_session_media_state_free(session->pending_media_state);
2102
2103         AST_LIST_HEAD_DESTROY(&session->supplements);
2104         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2105                 delayed_request_free(delay);
2106         }
2107         ast_party_id_free(&session->id);
2108         ao2_cleanup(session->endpoint);
2109         ao2_cleanup(session->aor);
2110         ao2_cleanup(session->contact);
2111         ao2_cleanup(session->direct_media_cap);
2112
2113         ast_dsp_free(session->dsp);
2114
2115         if (session->inv_session) {
2116                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
2117         }
2118
2119         ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);
2120 }
2121
2122 /*! \brief Destructor for SIP channel */
2123 static void sip_channel_destroy(void *obj)
2124 {
2125         struct ast_sip_channel_pvt *channel = obj;
2126
2127         ao2_cleanup(channel->pvt);
2128         ao2_cleanup(channel->session);
2129 }
2130
2131 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
2132 {
2133         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
2134
2135         if (!channel) {
2136                 return NULL;
2137         }
2138
2139         ao2_ref(pvt, +1);
2140         channel->pvt = pvt;
2141         ao2_ref(session, +1);
2142         channel->session = session;
2143
2144         return channel;
2145 }
2146
2147 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
2148         struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
2149 {
2150         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2151         struct ast_sip_session *ret_session;
2152         struct ast_sip_session_supplement *iter;
2153         int dsp_features = 0;
2154
2155         session = ao2_alloc(sizeof(*session), session_destructor);
2156         if (!session) {
2157                 return NULL;
2158         }
2159
2160         AST_LIST_HEAD_INIT(&session->supplements);
2161         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
2162         ast_party_id_init(&session->id);
2163
2164         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2165         if (!session->direct_media_cap) {
2166                 return NULL;
2167         }
2168         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
2169         if (!session->datastores) {
2170                 return NULL;
2171         }
2172         session->active_media_state = ast_sip_session_media_state_alloc();
2173         if (!session->active_media_state) {
2174                 return NULL;
2175         }
2176         session->pending_media_state = ast_sip_session_media_state_alloc();
2177         if (!session->pending_media_state) {
2178                 return NULL;
2179         }
2180
2181         if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {
2182                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
2183         }
2184         if (endpoint->faxdetect) {
2185                 dsp_features |= DSP_FEATURE_FAX_DETECT;
2186         }
2187         if (dsp_features) {
2188                 session->dsp = ast_dsp_new();
2189                 if (!session->dsp) {
2190                         return NULL;
2191                 }
2192
2193                 ast_dsp_set_features(session->dsp, dsp_features);
2194         }
2195
2196         session->endpoint = ao2_bump(endpoint);
2197
2198         if (rdata) {
2199                 /*
2200                  * We must continue using the serializer that the original
2201                  * INVITE came in on for the dialog.  There may be
2202                  * retransmissions already enqueued in the original
2203                  * serializer that can result in reentrancy and message
2204                  * sequencing problems.
2205                  */
2206                 session->serializer = ast_sip_get_distributor_serializer(rdata);
2207         } else {
2208                 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
2209
2210                 /* Create name with seq number appended. */
2211                 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
2212                         ast_sorcery_object_get_id(endpoint));
2213
2214                 session->serializer = ast_sip_create_serializer(tps_name);
2215         }
2216         if (!session->serializer) {
2217                 return NULL;
2218         }
2219         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
2220         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
2221         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
2222         inv_session->mod_data[session_module.id] = ao2_bump(session);
2223         session->contact = ao2_bump(contact);
2224         session->inv_session = inv_session;
2225
2226         session->dtmf = endpoint->dtmf;
2227
2228         if (ast_sip_session_add_supplements(session)) {
2229                 /* Release the ref held by session->inv_session */
2230                 ao2_ref(session, -1);
2231                 return NULL;
2232         }
2233         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2234                 if (iter->session_begin) {
2235                         iter->session_begin(session);
2236                 }
2237         }
2238
2239         /* Avoid unnecessary ref manipulation to return a session */
2240         ret_session = session;
2241         session = NULL;
2242         return ret_session;
2243 }
2244
2245 /*! \brief struct controlling the suspension of the session's serializer. */
2246 struct ast_sip_session_suspender {
2247         ast_cond_t cond_suspended;
2248         ast_cond_t cond_complete;
2249         int suspended;
2250         int complete;
2251 };
2252
2253 static void sip_session_suspender_dtor(void *vdoomed)
2254 {
2255         struct ast_sip_session_suspender *doomed = vdoomed;
2256
2257         ast_cond_destroy(&doomed->cond_suspended);
2258         ast_cond_destroy(&doomed->cond_complete);
2259 }
2260
2261 /*!
2262  * \internal
2263  * \brief Block the session serializer thread task.
2264  *
2265  * \param data Pushed serializer task data for suspension.
2266  *
2267  * \retval 0
2268  */
2269 static int sip_session_suspend_task(void *data)
2270 {
2271         struct ast_sip_session_suspender *suspender = data;
2272
2273         ao2_lock(suspender);
2274
2275         /* Signal that the serializer task is now suspended. */
2276         suspender->suspended = 1;
2277         ast_cond_signal(&suspender->cond_suspended);
2278
2279         /* Wait for the serializer suspension to be completed. */
2280         while (!suspender->complete) {
2281                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
2282         }
2283
2284         ao2_unlock(suspender);
2285         ao2_ref(suspender, -1);
2286
2287         return 0;
2288 }
2289
2290 void ast_sip_session_suspend(struct ast_sip_session *session)
2291 {
2292         struct ast_sip_session_suspender *suspender;
2293         int res;
2294
2295         ast_assert(session->suspended == NULL);
2296
2297         if (ast_taskprocessor_is_task(session->serializer)) {
2298                 /* I am the session's serializer thread so I cannot suspend. */
2299                 return;
2300         }
2301
2302         if (ast_taskprocessor_is_suspended(session->serializer)) {
2303                 /* The serializer already suspended. */
2304                 return;
2305         }
2306
2307         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
2308         if (!suspender) {
2309                 /* We will just have to hope that the system does not deadlock */
2310                 return;
2311         }
2312         ast_cond_init(&suspender->cond_suspended, NULL);
2313         ast_cond_init(&suspender->cond_complete, NULL);
2314
2315         ao2_ref(suspender, +1);
2316         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
2317         if (res) {
2318                 /* We will just have to hope that the system does not deadlock */
2319                 ao2_ref(suspender, -2);
2320                 return;
2321         }
2322
2323         session->suspended = suspender;
2324
2325         /* Wait for the serializer to get suspended. */
2326         ao2_lock(suspender);
2327         while (!suspender->suspended) {
2328                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
2329         }
2330         ao2_unlock(suspender);
2331
2332         ast_taskprocessor_suspend(session->serializer);
2333 }
2334
2335 void ast_sip_session_unsuspend(struct ast_sip_session *session)
2336 {
2337         struct ast_sip_session_suspender *suspender = session->suspended;
2338
2339         if (!suspender) {
2340                 /* Nothing to do */
2341                 return;
2342         }
2343         session->suspended = NULL;
2344
2345         /* Signal that the serializer task suspension is now complete. */
2346         ao2_lock(suspender);
2347         suspender->complete = 1;
2348         ast_cond_signal(&suspender->cond_complete);
2349         ao2_unlock(suspender);
2350
2351         ao2_ref(suspender, -1);
2352
2353         ast_taskprocessor_unsuspend(session->serializer);
2354 }
2355
2356 /*!
2357  * \internal
2358  * \brief Handle initial INVITE challenge response message.
2359  * \since 13.5.0
2360  *
2361  * \param rdata PJSIP receive response message data.
2362  *
2363  * \retval PJ_FALSE Did not handle message.
2364  * \retval PJ_TRUE Handled message.
2365  */
2366 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
2367 {
2368         pjsip_transaction *tsx;
2369         pjsip_dialog *dlg;
2370         pjsip_inv_session *inv;
2371         pjsip_tx_data *tdata;
2372         struct ast_sip_session *session;
2373
2374         if (rdata->msg_info.msg->line.status.code != 401
2375                 && rdata->msg_info.msg->line.status.code != 407) {
2376                 /* Doesn't pertain to us. Move on */
2377                 return PJ_FALSE;
2378         }
2379
2380         tsx = pjsip_rdata_get_tsx(rdata);
2381         dlg = pjsip_rdata_get_dlg(rdata);
2382         if (!dlg || !tsx) {
2383                 return PJ_FALSE;
2384         }
2385
2386         if (tsx->method.id != PJSIP_INVITE_METHOD) {
2387                 /* Not an INVITE that needs authentication */
2388                 return PJ_FALSE;
2389         }
2390
2391         inv = pjsip_dlg_get_inv_session(dlg);
2392         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
2393                 /*
2394                  * We cannot handle reINVITE authentication at this
2395                  * time because the reINVITE transaction is still in
2396                  * progress.
2397                  */
2398                 ast_debug(1, "A reINVITE is being challenged.\n");
2399                 return PJ_FALSE;
2400         }
2401         ast_debug(1, "Initial INVITE is being challenged.\n");
2402
2403         session = inv->mod_data[session_module.id];
2404
2405         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
2406                 tsx->last_tx, &tdata)) {
2407                 return PJ_FALSE;
2408         }
2409
2410         /*
2411          * Restart the outgoing initial INVITE transaction to deal
2412          * with authentication.
2413          */
2414         pjsip_inv_uac_restart(inv, PJ_FALSE);
2415
2416         ast_sip_session_send_request(session, tdata);
2417         return PJ_TRUE;
2418 }
2419
2420 static pjsip_module outbound_invite_auth_module = {
2421         .name = {"Outbound INVITE Auth", 20},
2422         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
2423         .on_rx_response = outbound_invite_auth,
2424 };
2425
2426 /*!
2427  * \internal
2428  * \brief Setup outbound initial INVITE authentication.
2429  * \since 13.5.0
2430  *
2431  * \param dlg PJSIP dialog to attach outbound authentication.
2432  *
2433  * \retval 0 on success.
2434  * \retval -1 on error.
2435  */
2436 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
2437 {
2438         pj_status_t status;
2439
2440         ++dlg->sess_count;
2441         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
2442         --dlg->sess_count;
2443
2444         return status != PJ_SUCCESS ? -1 : 0;
2445 }
2446
2447 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
2448         struct ast_sip_contact *contact, const char *location, const char *request_user,
2449         struct ast_stream_topology *req_topology)
2450 {
2451         const char *uri = NULL;
2452         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
2453         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
2454         pjsip_timer_setting timer;
2455         pjsip_dialog *dlg;
2456         struct pjsip_inv_session *inv_session;
2457         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2458         struct ast_sip_session *ret_session;
2459
2460         /* If no location has been provided use the AOR list from the endpoint itself */
2461         if (location || !contact) {
2462                 location = S_OR(location, endpoint->aors);
2463
2464                 ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,
2465                         &found_aor, &found_contact);
2466                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
2467                         uri = location;
2468                 } else {
2469                         uri = found_contact->uri;
2470                 }
2471         } else {
2472                 uri = contact->uri;
2473         }
2474
2475         /* If we still have no URI to dial fail to create the session */
2476         if (ast_strlen_zero(uri)) {
2477                 ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",
2478                         ast_sorcery_object_get_id(endpoint));
2479                 return NULL;
2480         }
2481
2482         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
2483                 return NULL;
2484         }
2485
2486         if (setup_outbound_invite_auth(dlg)) {
2487                 pjsip_dlg_terminate(dlg);
2488                 return NULL;
2489         }
2490
2491         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
2492                 pjsip_dlg_terminate(dlg);
2493                 return NULL;
2494         }
2495 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2496         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2497 #endif
2498
2499         pjsip_timer_setting_default(&timer);
2500         timer.min_se = endpoint->extensions.timer.min_se;
2501         timer.sess_expires = endpoint->extensions.timer.sess_expires;
2502         pjsip_timer_init_session(inv_session, &timer);
2503
2504         session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
2505                 inv_session, NULL);
2506         if (!session) {
2507                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2508                 return NULL;
2509         }
2510         session->aor = ao2_bump(found_aor);
2511         ast_party_id_copy(&session->id, &endpoint->id.self);
2512
2513         if (ast_stream_topology_get_count(req_topology) > 0) {
2514                 /* get joint caps between req_topology and endpoint topology */
2515                 int i;
2516
2517                 for (i = 0; i < ast_stream_topology_get_count(req_topology); ++i) {
2518                         struct ast_stream *req_stream;
2519                         struct ast_format_cap *req_cap;
2520                         struct ast_format_cap *joint_cap;
2521                         struct ast_stream *clone_stream;
2522
2523                         req_stream = ast_stream_topology_get_stream(req_topology, i);
2524
2525                         if (ast_stream_get_state(req_stream) == AST_STREAM_STATE_REMOVED) {
2526                                 continue;
2527                         }
2528
2529                         req_cap = ast_stream_get_formats(req_stream);
2530
2531                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2532                         if (!joint_cap) {
2533                                 continue;
2534                         }
2535
2536                         ast_format_cap_get_compatible(req_cap, endpoint->media.codecs, joint_cap);
2537                         if (!ast_format_cap_count(joint_cap)) {
2538                                 ao2_ref(joint_cap, -1);
2539                                 continue;
2540                         }
2541
2542                         clone_stream = ast_stream_clone(req_stream, NULL);
2543                         if (!clone_stream) {
2544                                 ao2_ref(joint_cap, -1);
2545                                 continue;
2546                         }
2547
2548                         if (ast_stream_get_type(req_stream) == AST_MEDIA_TYPE_AUDIO) {
2549                                 /*
2550                                  * By appending codecs from the endpoint after compatible ones this
2551                                  * guarantees that priority is given to those while also allowing
2552                                  * translation to occur for non-compatible.
2553                                  */
2554                                 ast_format_cap_append_from_cap(joint_cap,
2555                                         endpoint->media.codecs, AST_MEDIA_TYPE_AUDIO);
2556                         }
2557
2558                         ast_stream_set_formats(clone_stream, joint_cap);
2559                         ao2_ref(joint_cap, -1);
2560
2561                         if (!session->pending_media_state->topology) {
2562                                 session->pending_media_state->topology = ast_stream_topology_alloc();
2563                                 if (!session->pending_media_state->topology) {
2564                                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2565                                         ao2_ref(session, -1);
2566                                         return NULL;
2567                                 }
2568                         }
2569
2570                         if (ast_stream_topology_append_stream(session->pending_media_state->topology, clone_stream) < 0) {
2571                                 ast_stream_free(clone_stream);
2572                                 continue;
2573                         }
2574                 }
2575         }
2576
2577         if (!session->pending_media_state->topology) {
2578                 /* Use the configured topology on the endpoint as the pending one */
2579                 session->pending_media_state->topology = ast_stream_topology_clone(endpoint->media.topology);
2580                 if (!session->pending_media_state->topology) {
2581                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2582                         ao2_ref(session, -1);
2583                         return NULL;
2584                 }
2585         }
2586
2587         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2588                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2589                 /* Since we are not notifying ourselves that the INVITE session is being terminated
2590                  * we need to manually drop its reference to session
2591                  */
2592                 ao2_ref(session, -1);
2593                 return NULL;
2594         }
2595
2596         /* Avoid unnecessary ref manipulation to return a session */
2597         ret_session = session;
2598         session = NULL;
2599         return ret_session;
2600 }
2601
2602 static int session_end(void *vsession);
2603 static int session_end_completion(void *vsession);
2604
2605 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
2606 {
2607         pj_status_t status;
2608         pjsip_tx_data *packet = NULL;
2609
2610         if (session->defer_terminate) {
2611                 session->terminate_while_deferred = 1;
2612                 return;
2613         }
2614
2615         if (!response) {
2616                 response = 603;
2617         }
2618
2619         /* The media sessions need to exist for the lifetime of the underlying channel
2620          * to ensure that anything (such as bridge_native_rtp) has access to them as
2621          * appropriate. Since ast_sip_session_terminate is called by chan_pjsip and other
2622          * places when the session is to be terminated we terminate any existing
2623          * media sessions here.
2624          */
2625         SWAP(session->active_media_state, session->pending_media_state);
2626         ast_sip_session_media_state_reset(session->pending_media_state);
2627
2628         switch (session->inv_session->state) {
2629         case PJSIP_INV_STATE_NULL:
2630                 if (!session->inv_session->invite_tsx) {
2631                         /*
2632                          * Normally, it's pjproject's transaction cleanup that ultimately causes the
2633                          * final session reference to be released but if both STATE and invite_tsx are NULL,
2634                          * we never created a transaction in the first place.  In this case, we need to
2635                          * do the cleanup ourselves.
2636                          */
2637                         /* Transfer the inv_session session reference to the session_end_task */
2638                         session->inv_session->mod_data[session_module.id] = NULL;
2639                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2640                         session_end(session);
2641                         /*
2642                          * session_end_completion will cleanup the final session reference unless
2643                          * ast_sip_session_terminate's caller is holding one.
2644                          */
2645                         session_end_completion(session);
2646                 } else {
2647                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2648                 }
2649                 break;
2650         case PJSIP_INV_STATE_CONFIRMED:
2651                 if (session->inv_session->invite_tsx) {
2652                         ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
2653                                         ast_sorcery_object_get_id(session->endpoint));
2654                         /* If this is delayed the only thing that will happen is a BYE request so we don't
2655                          * actually need to store the response code for when it happens.
2656                          */
2657                         delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE, NULL);
2658                         break;
2659                 }
2660                 /* Fall through */
2661         default:
2662                 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
2663                 if (status == PJ_SUCCESS && packet) {
2664                         struct ast_sip_session_delayed_request *delay;
2665
2666                         /* Flush any delayed requests so they cannot overlap this transaction. */
2667                         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2668                                 delayed_request_free(delay);
2669                         }
2670
2671                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
2672                                 ast_sip_session_send_response(session, packet);
2673                         } else {
2674                                 ast_sip_session_send_request(session, packet);
2675                         }
2676                 }
2677                 break;
2678         }
2679 }
2680
2681 static int session_termination_task(void *data)
2682 {
2683         struct ast_sip_session *session = data;
2684
2685         if (session->defer_terminate) {
2686                 session->defer_terminate = 0;
2687                 if (session->inv_session) {
2688                         ast_sip_session_terminate(session, 0);
2689                 }
2690         }
2691
2692         ao2_ref(session, -1);
2693         return 0;
2694 }
2695
2696 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
2697 {
2698         struct ast_sip_session *session = entry->user_data;
2699
2700         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
2701                 ao2_cleanup(session);
2702         }
2703 }
2704
2705 int ast_sip_session_defer_termination(struct ast_sip_session *session)
2706 {
2707         pj_time_val delay = { .sec = 60, };
2708         int res;
2709
2710         /* The session should not have an active deferred termination request. */
2711         ast_assert(!session->defer_terminate);
2712
2713         session->defer_terminate = 1;
2714
2715         session->defer_end = 1;
2716         session->ended_while_deferred = 0;
2717
2718         ao2_ref(session, +1);
2719         pj_timer_entry_init(&session->scheduled_termination, 0, session, session_termination_cb);
2720
2721         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2722                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
2723         if (res) {
2724                 session->defer_terminate = 0;
2725                 ao2_ref(session, -1);
2726         }
2727         return res;
2728 }
2729
2730 /*!
2731  * \internal
2732  * \brief Stop the defer termination timer if it is still running.
2733  * \since 13.5.0
2734  *
2735  * \param session Which session to stop the timer.
2736  *
2737  * \return Nothing
2738  */
2739 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
2740 {
2741         if (pj_timer_heap_cancel_if_active(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
2742                 &session->scheduled_termination, session->scheduled_termination.id)) {
2743                 ao2_ref(session, -1);
2744         }
2745 }
2746
2747 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
2748 {
2749         if (!session->defer_terminate) {
2750                 /* Already canceled or timer fired. */
2751                 return;
2752         }
2753
2754         session->defer_terminate = 0;
2755
2756         if (session->terminate_while_deferred) {
2757                 /* Complete the termination started by the upper layer. */
2758                 ast_sip_session_terminate(session, 0);
2759         }
2760
2761         /* Stop the termination timer if it is still running. */
2762         sip_session_defer_termination_stop_timer(session);
2763 }
2764
2765 void ast_sip_session_end_if_deferred(struct ast_sip_session *session)
2766 {
2767         if (!session->defer_end) {
2768                 return;
2769         }
2770
2771         session->defer_end = 0;
2772
2773         if (session->ended_while_deferred) {
2774                 /* Complete the session end started by the remote hangup. */
2775                 ast_debug(3, "Ending session (%p) after being deferred\n", session);
2776                 session->ended_while_deferred = 0;
2777                 session_end(session);
2778         }
2779 }
2780
2781 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
2782 {
2783         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
2784         struct ast_sip_session *session;
2785
2786         if (!inv_session ||
2787                 !(session = inv_session->mod_data[session_module.id])) {
2788                 return NULL;
2789         }
2790
2791         ao2_ref(session, +1);
2792
2793         return session;
2794 }
2795
2796 enum sip_get_destination_result {
2797         /*! The extension was successfully found */
2798         SIP_GET_DEST_EXTEN_FOUND,
2799         /*! The extension specified in the RURI was not found */
2800         SIP_GET_DEST_EXTEN_NOT_FOUND,
2801         /*! The extension specified in the RURI was a partial match */
2802         SIP_GET_DEST_EXTEN_PARTIAL,
2803         /*! The RURI is of an unsupported scheme */
2804         SIP_GET_DEST_UNSUPPORTED_URI,
2805 };
2806
2807 /*!
2808  * \brief Determine where in the dialplan a call should go
2809  *
2810  * This uses the username in the request URI to try to match
2811  * an extension in the endpoint's configured context in order
2812  * to route the call.
2813  *
2814  * \param session The inbound SIP session
2815  * \param rdata The SIP INVITE
2816  */
2817 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
2818 {
2819         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
2820         pjsip_sip_uri *sip_ruri;
2821         struct ast_features_pickup_config *pickup_cfg;
2822         const char *pickupexten;
2823
2824         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
2825                 return SIP_GET_DEST_UNSUPPORTED_URI;
2826         }
2827
2828         sip_ruri = pjsip_uri_get_uri(ruri);
2829         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
2830
2831         /*
2832          * We may want to match in the dialplan without any user
2833          * options getting in the way.
2834          */
2835         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);
2836
2837         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2838         if (!pickup_cfg) {
2839                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
2840                 pickupexten = "";
2841         } else {
2842                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
2843                 ao2_ref(pickup_cfg, -1);
2844         }
2845
2846         if (!strcmp(session->exten, pickupexten) ||
2847                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
2848                 size_t size = pj_strlen(&sip_ruri->host) + 1;
2849                 char *domain = ast_alloca(size);
2850
2851                 ast_copy_pj_str(domain, &sip_ruri->host, size);
2852                 pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);
2853
2854                 /*
2855                  * Save off the INVITE Request-URI in case it is
2856                  * needed: CHANNEL(pjsip,request_uri)
2857                  */
2858                 session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);
2859
2860                 return SIP_GET_DEST_EXTEN_FOUND;
2861         }
2862
2863         /*
2864          * Check for partial match via overlap dialling (if enabled)
2865          */
2866         if (session->endpoint->allow_overlap && (
2867                 !strncmp(session->exten, pickupexten, strlen(session->exten)) ||
2868                 ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {
2869                 /* Overlap partial match */
2870                 return SIP_GET_DEST_EXTEN_PARTIAL;
2871         }
2872
2873         return SIP_GET_DEST_EXTEN_NOT_FOUND;
2874 }
2875
2876 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
2877 {
2878         pjsip_tx_data *tdata;
2879         pjsip_dialog *dlg;
2880         pjsip_inv_session *inv_session;
2881         unsigned int options = endpoint->extensions.flags;
2882         pj_status_t dlg_status;
2883
2884         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
2885                 if (tdata) {
2886                         if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
2887                                 pjsip_tx_data_dec_ref(tdata);
2888                         }
2889                 } else {
2890                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2891                 }
2892                 return NULL;
2893         }
2894         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
2895         if (!dlg) {
2896                 if (dlg_status != PJ_EEXISTS) {
2897                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2898                 }
2899                 return NULL;
2900         }
2901         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
2902                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2903                 pjsip_dlg_terminate(dlg);
2904                 return NULL;
2905         }
2906
2907 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2908         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2909 #endif
2910         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2911                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
2912                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2913                 }
2914                 pjsip_inv_send_msg(inv_session, tdata);
2915                 return NULL;
2916         }
2917         return inv_session;
2918 }
2919
2920 struct new_invite {
2921         /*! \brief Session created for the new INVITE */
2922         struct ast_sip_session *session;
2923
2924         /*! \brief INVITE request itself */
2925         pjsip_rx_data *rdata;
2926 };
2927
2928 static int new_invite(struct new_invite *invite)
2929 {
2930         pjsip_tx_data *tdata = NULL;
2931         pjsip_timer_setting timer;
2932         pjsip_rdata_sdp_info *sdp_info;
2933         pjmedia_sdp_session *local = NULL;
2934
2935         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
2936          * so that we will be notified so we can destroy the session properly
2937          */
2938
2939         if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2940                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2941                         invite->session->inv_session->cause,
2942                         pjsip_get_status_text(invite->session->inv_session->cause)->ptr);
2943 #ifdef HAVE_PJSIP_INV_SESSION_REF
2944                 pjsip_inv_dec_ref(invite->session->inv_session);
2945 #endif
2946                 return -1;
2947         }
2948
2949         switch (get_destination(invite->session, invite->rdata)) {
2950         case SIP_GET_DEST_EXTEN_FOUND:
2951                 /* Things worked. Keep going */
2952                 break;
2953         case SIP_GET_DEST_UNSUPPORTED_URI:
2954                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
2955                         ast_sip_session_send_response(invite->session, tdata);
2956                 } else  {
2957                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
2958                 }
2959                 goto end;
2960         case SIP_GET_DEST_EXTEN_PARTIAL:
2961                 ast_debug(1, "Call from '%s' (%s:%s:%d) to extension '%s' - partial match\n", ast_sorcery_object_get_id(invite->session->endpoint),
2962                         invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name, invite->rdata->pkt_info.src_port, invite->session->exten);
2963
2964                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {
2965                         ast_sip_session_send_response(invite->session, tdata);
2966                 } else  {
2967                         pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);
2968                 }
2969                 goto end;
2970         case SIP_GET_DEST_EXTEN_NOT_FOUND:
2971         default:
2972                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
2973                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
2974                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
2975
2976                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
2977                         ast_sip_session_send_response(invite->session, tdata);
2978                 } else  {
2979                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
2980                 }
2981                 goto end;
2982         };
2983
2984         pjsip_timer_setting_default(&timer);
2985         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
2986         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
2987         pjsip_timer_init_session(invite->session->inv_session, &timer);
2988
2989         /*
2990          * At this point, we've verified what we can that won't take awhile,
2991          * so let's go ahead and send a 100 Trying out to stop any
2992          * retransmissions.
2993          */
2994         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
2995                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
2996                 goto end;
2997         }
2998         ast_sip_session_send_response(invite->session, tdata);
2999
3000         sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);
3001         if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
3002                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
3003                         tdata = NULL;
3004                         if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS
3005                                 && tdata) {
3006                                 ast_sip_session_send_response(invite->session, tdata);
3007                         }
3008                         goto end;
3009                 }
3010                 /* We are creating a local SDP which is an answer to their offer */
3011                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
3012         } else {
3013                 /* We are creating a local SDP which is an offer */
3014                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
3015         }
3016
3017         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
3018         if (!local) {
3019                 tdata = NULL;
3020                 if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS
3021                         && tdata) {
3022                         ast_sip_session_send_response(invite->session, tdata);
3023                 }
3024                 goto end;
3025         }
3026
3027         pjsip_inv_set_local_sdp(invite->session->inv_session, local);
3028         pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
3029 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
3030         if (!invite->session->endpoint->preferred_codec_only) {
3031                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
3032         }
3033 #endif
3034
3035         handle_incoming_request(invite->session, invite->rdata);
3036
3037 end:
3038 #ifdef HAVE_PJSIP_INV_SESSION_REF
3039         pjsip_inv_dec_ref(invite->session->inv_session);
3040 #endif
3041         return 0;
3042 }
3043
3044 static void handle_new_invite_request(pjsip_rx_data *rdata)
3045 {
3046         RAII_VAR(struct ast_sip_endpoint *, endpoint,
3047                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
3048         pjsip_tx_data *tdata = NULL;
3049         pjsip_inv_session *inv_session = NULL;
3050         struct ast_sip_session *session;
3051         struct new_invite invite;
3052
3053         ast_assert(endpoint != NULL);
3054
3055         inv_session = pre_session_setup(rdata, endpoint);
3056         if (!inv_session) {
3057                 /* pre_session_setup() returns a response on failure */
3058                 return;
3059         }
3060
3061 #ifdef HAVE_PJSIP_INV_SESSION_REF
3062         if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {
3063                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
3064                 if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {
3065                         if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
3066                                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3067                         } else {
3068                                 pjsip_inv_send_msg(inv_session, tdata);
3069                         }
3070                 }
3071                 return;
3072         }
3073 #endif
3074
3075         session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);
3076         if (!session) {
3077                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
3078                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3079                 } else {
3080                         pjsip_inv_send_msg(inv_session, tdata);
3081                 }
3082 #ifdef HAVE_PJSIP_INV_SESSION_REF
3083                 pjsip_inv_dec_ref(inv_session);
3084 #endif
3085                 return;
3086         }
3087
3088         /*
3089          * The current thread is supposed be the session serializer to prevent
3090          * any initial INVITE retransmissions from trying to setup the same
3091          * call again.
3092          */
3093         ast_assert(ast_taskprocessor_is_task(session->serializer));
3094
3095         invite.session = session;
3096         invite.rdata = rdata;
3097         new_invite(&invite);
3098
3099         ao2_ref(session, -1);
3100 }
3101
3102 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
3103 {
3104         pj_str_t method;
3105
3106         if (ast_strlen_zero(supplement_method)) {
3107                 return PJ_TRUE;
3108         }
3109
3110         pj_cstr(&method, supplement_method);
3111
3112         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
3113 }
3114
3115 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
3116 {
3117         struct ast_sip_session_supplement *supplement;
3118         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
3119
3120         if (!session) {
3121                 return PJ_FALSE;
3122         }
3123
3124         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3125                 if (does_method_match(&method->name, supplement->method)) {
3126                         return PJ_TRUE;
3127                 }
3128         }
3129         return PJ_FALSE;
3130 }
3131 /*!
3132  * \brief Called when a new SIP request comes into PJSIP
3133  *
3134  * This function is called under two circumstances
3135  * 1) An out-of-dialog request is received by PJSIP
3136  * 2) An in-dialog request that the inv_session layer does not
3137  *    handle is received (such as an in-dialog INFO)
3138  *
3139  * Except for INVITEs, there is very little we actually do in this function
3140  * 1) For requests we don't handle, we return PJ_FALSE
3141  * 2) For new INVITEs, handle them now to prevent retransmissions from
3142  *    trying to setup the same call again.
3143  * 3) For in-dialog requests we handle, we process them in the
3144  *    .on_state_changed = session_inv_on_state_changed or
3145  *    .on_tsx_state_changed = session_inv_on_tsx_state_changed
3146  *    callbacks instead.
3147  */
3148 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
3149 {
3150         pj_status_t handled = PJ_FALSE;
3151         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
3152         pjsip_inv_session *inv_session;
3153
3154         switch (rdata->msg_info.msg->line.req.method.id) {
3155         case PJSIP_INVITE_METHOD:
3156                 if (dlg) {
3157                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
3158                         break;
3159                 }
3160                 handled = PJ_TRUE;
3161                 handle_new_invite_request(rdata);
3162                 break;
3163         default:
3164                 /* Handle other in-dialog methods if their supplements have been registered */
3165                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
3166                         has_supplement(inv_session->mod_data[session_module.id], rdata);
3167                 break;
3168         }
3169
3170         return handled;
3171 }
3172
3173 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
3174 {
3175         struct ast_sip_session *session = entry->user_data;
3176
3177         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
3178                 ast_sorcery_object_get_id(session->endpoint),
3179                 session->channel ? ast_channel_name(session->channel) : "");
3180
3181         if (AST_LIST_EMPTY(&session->delayed_requests)) {
3182                 /* No delayed request pending, so just return */
3183                 ao2_ref(session, -1);
3184                 return;
3185         }
3186         if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
3187                 /*
3188                  * Uh oh.  We now have nothing in the foreseeable future
3189                  * to trigger sending the delayed requests.
3190                  */
3191                 ao2_ref(session, -1);
3192         }
3193 }
3194
3195 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
3196 {
3197         pjsip_inv_session *inv = session->inv_session;
3198         pj_time_val tv;
3199
3200         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
3201                 ast_sorcery_object_get_id(session->endpoint),
3202                 session->channel ? ast_channel_name(session->channel) : "");
3203         if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE, NULL)) {
3204                 return;
3205         }
3206         if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
3207                 /* Timer already running.  Something weird is going on. */
3208                 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
3209                         ast_sorcery_object_get_id(session->endpoint),
3210                         session->channel ? ast_channel_name(session->channel) : "");
3211                 return;
3212         }
3213
3214         tv.sec = 0;
3215         if (inv->role == PJSIP_ROLE_UAC) {
3216                 tv.msec = 2100 + ast_random() % 2000;
3217         } else {
3218                 tv.msec = ast_random() % 2000;
3219         }
3220         pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
3221
3222         ao2_ref(session, +1);
3223         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
3224                 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
3225                 ao2_ref(session, -1);
3226         }
3227 }
3228
3229 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
3230 {
3231         int id = session_module.id;
3232         struct ast_sip_session *session = NULL;
3233
3234         if (!DEBUG_ATLEAST(5)) {
3235                 /* Debug not spamy enough */
3236                 return;
3237         }
3238
3239         ast_log(LOG_DEBUG, "Function %s called on event %s\n",
3240                 function, pjsip_event_str(e->type));
3241         if (!inv) {
3242                 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
3243                 ast_log(LOG_DEBUG, "The transaction state is %s\n",
3244                         pjsip_tsx_state_str(tsx->state));
3245                 return;
3246         }
3247         if (id > -1) {
3248                 session = inv->mod_data[session_module.id];
3249         }
3250         if (!session) {
3251                 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
3252         } else {
3253                 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
3254                         ast_sorcery_object_get_id(session->endpoint),
3255                         session->channel ? ast_channel_name(session->channel) : "");
3256         }
3257         if (inv->invite_tsx) {
3258                 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
3259                         inv->invite_tsx);
3260         } else {
3261                 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
3262         }
3263         if (tsx) {
3264                 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
3265                         pjsip_role_name(tsx->role),
3266                         (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
3267                         tsx);
3268                 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
3269                         pjsip_tsx_state_str(tsx->state));
3270                 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
3271                         pjsip_event_str(e->body.tsx_state.type));
3272         } else {
3273                 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
3274         }
3275         ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
3276 }
3277
3278 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
3279
3280 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
3281 {
3282         struct ast_sip_session_supplement *supplement;
3283         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
3284
3285         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
3286         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3287                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
3288                         if (supplement->incoming_request(session, rdata)) {
3289                                 break;
3290                         }
3291                 }
3292         }
3293 }
3294
3295 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
3296                 enum ast_sip_session_response_priority response_priority)
3297 {
3298         struct ast_sip_session_supplement *supplement;
3299         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
3300
3301         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
3302                         pj_strbuf(&status.reason));
3303
3304         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3305                 if (!(supplement->response_priority & response_priority)) {
3306                         continue;
3307                 }
3308                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
3309                         supplement->incoming_response(session, rdata);
3310                 }
3311         }
3312 }
3313
3314 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,
3315                 enum ast_sip_session_response_priority response_priority)
3316 {
3317         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
3318                         "request" : "response");
3319
3320         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
3321                 handle_incoming_request(session, rdata);
3322         } else {
3323                 handle_incoming_response(session, rdata, response_priority);
3324         }
3325
3326         return 0;
3327 }
3328
3329 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
3330 {
3331         struct ast_sip_session_supplement *supplement;
3332         struct pjsip_request_line req = tdata->msg->line.req;
3333
3334         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
3335         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3336                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
3337                         supplement->outgoing_request(session, tdata);
3338                 }
3339         }
3340 }
3341
3342 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
3343 {
3344         struct ast_sip_session_supplement *supplement;
3345         struct pjsip_status_line status = tdata->msg->line.status;
3346         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
3347
3348         if (!cseq) {
3349                 ast_log(LOG_ERROR, "Cannot send response due to missing sequence header");
3350                 return;
3351         }
3352
3353         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
3354                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
3355                 pj_strbuf(&status.reason));
3356
3357         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3358                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
3359                         supplement->outgoing_response(session, tdata);
3360                 }
3361         }
3362 }
3363
3364 static int session_end(void *vsession)
3365 {
3366         struct ast_sip_session *session = vsession;
3367         struct ast_sip_session_supplement *iter;
3368
3369         /* Stop the scheduled termination */
3370         sip_session_defer_termination_stop_timer(session);
3371
3372         /* Session is dead.  Notify the supplements. */
3373         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
3374                 if (iter->session_end) {
3375                         iter->session_end(session);
3376                 }
3377         }
3378         return 0;
3379 }
3380
3381 /*!
3382  * \internal
3383  * \brief Complete ending session activities.
3384  * \since 13.5.0
3385  *
3386  * \param vsession Which session to complete stopping.
3387  *
3388  * \retval 0 on success.
3389  * \retval -1 on error.
3390  */
3391 static int session_end_completion(void *vsession)
3392 {
3393         struct ast_sip_session *session = vsession;
3394
3395         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
3396         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
3397
3398         /* Now we can release the ref that was held by session->inv_session */
3399         ao2_cleanup(session);
3400         return 0;
3401 }
3402
3403 static int check_request_status(pjsip_inv_session *inv, pjsip_event *e)
3404 {
3405         struct ast_sip_session *session = inv->mod_data[session_module.id];
3406         pjsip_transaction *tsx = e->body.tsx_state.tsx;
3407
3408         if (tsx->status_code != 503 && tsx->status_code != 408) {
3409                 return 0;
3410         }
3411
3412         if (!ast_sip_failover_request(tsx->last_tx)) {
3413                 return 0;
3414         }
3415
3416         pjsip_inv_uac_restart(inv, PJ_FALSE);
3417         /*
3418          * Bump the ref since it will be on a new transaction and
3419          * we don't want it to go away along with the old transaction.
3420          */
3421         pjsip_tx_data_add_ref(tsx->last_tx);
3422         ast_sip_session_send_request(session, tsx->last_tx);
3423         return 1;
3424 }
3425
3426 static void handle_incoming_before_media(pjsip_inv_session *inv,
3427         struct ast_sip_session *session, pjsip_rx_data *rdata)
3428 {
3429         pjsip_msg *msg;
3430
3431         handle_incoming(session, rdata, AST_SIP_SESSION_BEFORE_MEDIA);
3432         msg = rdata->msg_info.msg;
3433         if (msg->type == PJSIP_REQUEST_MSG
3434                 && msg->line.req.method.id == PJSIP_ACK_METHOD
3435                 && pjmedia_sdp_neg_get_state(inv->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
3436                 pjsip_tx_data *tdata;
3437
3438                 /*
3439                  * SDP negotiation failed on an incoming call that delayed
3440                  * negotiation and then gave us an invalid SDP answer.  We
3441                  * need to send a BYE to end the call because of the invalid
3442                  * SDP answer.
3443                  */
3444                 ast_debug(1,
3445                         "Endpoint '%s(%s)': Ending session due to incomplete SDP negotiation.  %s\n",
3446                         ast_sorcery_object_get_id(session->endpoint),
3447                         session->channel ? ast_channel_name(session->channel) : "",
3448                         pjsip_rx_data_get_info(rdata));
3449                 if (pjsip_inv_end_session(inv, 400, NULL, &tdata) == PJ_SUCCESS
3450                         && tdata) {
3451                         ast_sip_session_send_request(session, tdata);
3452                 }
3453         }
3454 }
3455
3456 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
3457 {
3458         struct ast_sip_session *session;
3459         pjsip_event_id_e type;
3460
3461         if (ast_shutdown_final()) {
3462                 return;
3463         }
3464
3465         if (e) {
3466                 print_debug_details(inv, NULL, e);
3467                 type = e->type;
3468         } else {
3469                 type = PJSIP_EVENT_UNKNOWN;
3470         }
3471
3472         session = inv->mod_data[session_module.id];
3473         if (!session) {
3474                 return;
3475         }
3476
3477         switch(type) {
3478         case PJSIP_EVENT_TX_MSG:
3479                 break;
3480         case PJSIP_EVENT_RX_MSG:
3481                 handle_incoming_before_media(inv, session, e->body.rx_msg.rdata);
3482                 break;
3483         case PJSIP_EVENT_TSX_STATE:
3484                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
3485                 /* Transaction state changes are prompted by some other underlying event. */
3486                 switch(e->body.tsx_state.type) {
3487                 case PJSIP_EVENT_TX_MSG:
3488                         break;
3489                 case PJSIP_EVENT_RX_MSG:
3490                         if (!check_request_status(inv, e)) {
3491                                 handle_incoming_before_media(inv, session, e->body.tsx_state.src.rdata);
3492                         }
3493                         break;
3494                 case PJSIP_EVENT_TRANSPORT_ERROR:
3495                 case PJSIP_EVENT_TIMER:
3496                         /*
3497                          * Check the request status on transport error or timeout. A transport
3498                          * error can occur when a TCP socket closes and that can be the result
3499                          * of a 503. Also we may need to failover on a timeout (408).
3500                          */
3501                         check_request_status(inv, e);
3502                         break;
3503                 case PJSIP_EVENT_USER:
3504                 case PJSIP_EVENT_UNKNOWN:
3505                 case PJSIP_EVENT_TSX_STATE:
3506                         /* Inception? */
3507                         break;
3508                 }
3509                 break;
3510         case PJSIP_EVENT_TRANSPORT_ERROR:
3511         case PJSIP_EVENT_TIMER:
3512         case PJSIP_EVENT_UNKNOWN:
3513         case PJSIP_EVENT_USER:
3514         default:
3515                 break;
3516         }
3517
3518         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
3519                 if (session->defer_end) {
3520                         ast_debug(3, "Deferring session (%p) end\n", session);
3521                         session->ended_while_deferred = 1;
3522                         return;
3523                 }
3524
3525                 if (ast_sip_push_task(session->serializer, session_end, session)) {
3526                         /* Do it anyway even though this is not the right thread. */
3527                         session_end(session);
3528                 }
3529         }
3530 }
3531
3532 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
3533 {
3534         /* XXX STUB */
3535 }
3536
3537 static int session_end_if_disconnected(int id, pjsip_inv_session *inv)
3538 {
3539         struct ast_sip_session *session;
3540
3541         if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
3542                 return 0;
3543         }
3544
3545         /*
3546          * We are locking because ast_sip_dialog_get_session() needs
3547          * the dialog locked to get the session by other threads.
3548          */
3549         pjsip_dlg_inc_lock(inv->dlg);
3550         session = inv->mod_data[id];
3551         inv->mod_data[id] = NULL;
3552         pjsip_dlg_dec_lock(inv->dlg);
3553
3554         /*
3555          * Pass the session ref held by session->inv_session to
3556          * session_end_completion().
3557          */
3558         if (session
3559                 && ast_sip_push_task(session->serializer, session_end_completion, session)) {
3560                 /* Do it anyway even though this is not the right thread. */
3561                 session_end_completion(session);
3562         }
3563
3564         return 1;
3565 }
3566
3567 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
3568 {
3569         ast_sip_session_response_cb cb;
3570         int id = session_module.id;
3571         struct ast_sip_session *session;
3572         pjsip_tx_data *tdata;
3573
3574         if (ast_shutdown_final()) {
3575                 return;
3576         }
3577
3578         session = inv->mod_data[id];
3579
3580         print_debug_details(inv, tsx, e);
3581         if (!session) {
3582                 /* The session has ended.  Ignore the transaction change. */
3583              &nbs