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