res_pjsip_session: Prevent crash during shutdown.
[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         /* This situation can legitimately happen when an SDP is received in a
880          * 183 Session Progress message.  In that case, everything's been done
881          * by the time this function is called and there are no more pending
882          * streams.
883          */
884         if (!session->pending_media_state->topology) {
885                 ast_debug(1, "Pending topology was NULL for channel '%s'\n",
886                         session->channel ? ast_channel_name(session->channel) : "unknown");
887                 return 0;
888         }
889
890         /* If we're handling negotiated streams, then we should already have set
891          * up session media instances (and Asterisk streams) that correspond to
892          * the local SDP, and there should be the same number of session medias
893          * and streams as there are local SDP streams
894          */
895         if (ast_stream_topology_get_count(session->pending_media_state->topology) != local->media_count
896                 || AST_VECTOR_SIZE(&session->pending_media_state->sessions) != local->media_count) {
897                 ast_log(LOG_WARNING, "Local SDP for channel '%s' contains %d media streams while we expected it to contain %u\n",
898                         session->channel ? ast_channel_name(session->channel) : "unknown",
899                         ast_stream_topology_get_count(session->pending_media_state->topology), local->media_count);
900                 return -1;
901         }
902
903         for (i = 0; i < local->media_count; ++i) {
904                 struct ast_sip_session_media *session_media;
905                 struct ast_stream *stream;
906
907                 if (!remote->media[i]) {
908                         continue;
909                 }
910
911                 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
912                 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
913
914                 /* The stream state will have already been set to removed when either we
915                  * negotiate the incoming SDP stream or when we produce our own local SDP.
916                  * This can occur if an internal thing has requested it to be removed, or if
917                  * we remove it as a result of the stream limit being reached.
918                  */
919                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
920                         /*
921                          * Defer removing the handler until we are ready to activate
922                          * the new topology.  The channel's thread may still be using
923                          * the stream and we could crash before we are ready.
924                          */
925                         continue;
926                 }
927
928                 if (handle_negotiated_sdp_session_media(session_media, session, local, remote, i, stream)) {
929                         return -1;
930                 }
931
932                 changed |= session_media->changed;
933                 session_media->changed = 0;
934         }
935
936         /* Apply the pending media state to the channel and make it active */
937         ast_channel_lock(session->channel);
938
939         /* Now update the stream handler for any declined/removed streams */
940         for (i = 0; i < local->media_count; ++i) {
941                 struct ast_sip_session_media *session_media;
942                 struct ast_stream *stream;
943
944                 if (!remote->media[i]) {
945                         continue;
946                 }
947
948                 session_media = AST_VECTOR_GET(&session->pending_media_state->sessions, i);
949                 stream = ast_stream_topology_get_stream(session->pending_media_state->topology, i);
950
951                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED
952                         && session_media->handler) {
953                         /*
954                          * This stream is no longer being used and the channel's thread
955                          * is held off because we have the channel lock so release any
956                          * resources the handler may have on it.
957                          */
958                         session_media_set_handler(session_media, NULL);
959                 }
960         }
961
962         /* Update the topology on the channel to match the accepted one */
963         topology = ast_stream_topology_clone(session->pending_media_state->topology);
964         if (topology) {
965                 ast_channel_set_stream_topology(session->channel, topology);
966         }
967
968         /* Remove all current file descriptors from the channel */
969         for (i = 0; i < AST_VECTOR_SIZE(&session->active_media_state->read_callbacks); ++i) {
970                 ast_channel_internal_fd_clear(session->channel, i + AST_EXTENDED_FDS);
971         }
972
973         /* Add all the file descriptors from the pending media state */
974         for (i = 0; i < AST_VECTOR_SIZE(&session->pending_media_state->read_callbacks); ++i) {
975                 struct ast_sip_session_media_read_callback_state *callback_state;
976
977                 callback_state = AST_VECTOR_GET_ADDR(&session->pending_media_state->read_callbacks, i);
978                 ast_channel_internal_fd_set(session->channel, i + AST_EXTENDED_FDS, callback_state->fd);
979         }
980
981         /* Active and pending flip flop as needed */
982         SWAP(session->active_media_state, session->pending_media_state);
983         ast_sip_session_media_state_reset(session->pending_media_state);
984
985         ast_channel_unlock(session->channel);
986
987         if (changed) {
988                 struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_STREAM_TOPOLOGY_SOURCE_CHANGED };
989
990                 ast_queue_frame(session->channel, &f);
991         } else {
992                 ast_queue_frame(session->channel, &ast_null_frame);
993         }
994
995         return 0;
996 }
997
998 #define DATASTORE_BUCKETS 53
999 #define MEDIA_BUCKETS 7
1000
1001 static void session_datastore_destroy(void *obj)
1002 {
1003         struct ast_datastore *datastore = obj;
1004
1005         /* Using the destroy function (if present) destroy the data */
1006         if (datastore->info->destroy != NULL && datastore->data != NULL) {
1007                 datastore->info->destroy(datastore->data);
1008                 datastore->data = NULL;
1009         }
1010
1011         ast_free((void *) datastore->uid);
1012         datastore->uid = NULL;
1013 }
1014
1015 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
1016 {
1017         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
1018         char uuid_buf[AST_UUID_STR_LEN];
1019         const char *uid_ptr = uid;
1020
1021         if (!info) {
1022                 return NULL;
1023         }
1024
1025         datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
1026         if (!datastore) {
1027                 return NULL;
1028         }
1029
1030         datastore->info = info;
1031         if (ast_strlen_zero(uid)) {
1032                 /* They didn't provide an ID so we'll provide one ourself */
1033                 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
1034         }
1035
1036         datastore->uid = ast_strdup(uid_ptr);
1037         if (!datastore->uid) {
1038                 return NULL;
1039         }
1040
1041         ao2_ref(datastore, +1);
1042         return datastore;
1043 }
1044
1045 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
1046 {
1047         ast_assert(datastore != NULL);
1048         ast_assert(datastore->info != NULL);
1049         ast_assert(ast_strlen_zero(datastore->uid) == 0);
1050
1051         if (!ao2_link(session->datastores, datastore)) {
1052                 return -1;
1053         }
1054         return 0;
1055 }
1056
1057 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
1058 {
1059         return ao2_find(session->datastores, name, OBJ_KEY);
1060 }
1061
1062 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
1063 {
1064         ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
1065 }
1066
1067 enum delayed_method {
1068         DELAYED_METHOD_INVITE,
1069         DELAYED_METHOD_UPDATE,
1070         DELAYED_METHOD_BYE,
1071 };
1072
1073 /*!
1074  * \internal
1075  * \brief Convert delayed method enum value to a string.
1076  * \since 13.3.0
1077  *
1078  * \param method Delayed method enum value to convert to a string.
1079  *
1080  * \return String value of delayed method.
1081  */
1082 static const char *delayed_method2str(enum delayed_method method)
1083 {
1084         const char *str = "<unknown>";
1085
1086         switch (method) {
1087         case DELAYED_METHOD_INVITE:
1088                 str = "INVITE";
1089                 break;
1090         case DELAYED_METHOD_UPDATE:
1091                 str = "UPDATE";
1092                 break;
1093         case DELAYED_METHOD_BYE:
1094                 str = "BYE";
1095                 break;
1096         }
1097
1098         return str;
1099 }
1100
1101 /*!
1102  * \brief Structure used for sending delayed requests
1103  *
1104  * Requests are typically delayed because the current transaction
1105  * state of an INVITE. Once the pending INVITE transaction terminates,
1106  * the delayed request will be sent
1107  */
1108 struct ast_sip_session_delayed_request {
1109         /*! Method of the request */
1110         enum delayed_method method;
1111         /*! Callback to call when the delayed request is created. */
1112         ast_sip_session_request_creation_cb on_request_creation;
1113         /*! Callback to call when the delayed request SDP is created */
1114         ast_sip_session_sdp_creation_cb on_sdp_creation;
1115         /*! Callback to call when the delayed request receives a response */
1116         ast_sip_session_response_cb on_response;
1117         /*! Whether to generate new SDP */
1118         int generate_new_sdp;
1119         /*! Requested media state for the SDP */
1120         struct ast_sip_session_media_state *media_state;
1121         AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
1122 };
1123
1124 static struct ast_sip_session_delayed_request *delayed_request_alloc(
1125         enum delayed_method method,
1126         ast_sip_session_request_creation_cb on_request_creation,
1127         ast_sip_session_sdp_creation_cb on_sdp_creation,
1128         ast_sip_session_response_cb on_response,
1129         int generate_new_sdp,
1130         struct ast_sip_session_media_state *media_state)
1131 {
1132         struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
1133
1134         if (!delay) {
1135                 return NULL;
1136         }
1137         delay->method = method;
1138         delay->on_request_creation = on_request_creation;
1139         delay->on_sdp_creation = on_sdp_creation;
1140         delay->on_response = on_response;
1141         delay->generate_new_sdp = generate_new_sdp;
1142         delay->media_state = media_state;
1143         return delay;
1144 }
1145
1146 static void delayed_request_free(struct ast_sip_session_delayed_request *delay)
1147 {
1148         ast_sip_session_media_state_free(delay->media_state);
1149         ast_free(delay);
1150 }
1151
1152 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
1153 {
1154         ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",
1155                 ast_sorcery_object_get_id(session->endpoint),
1156                 session->channel ? ast_channel_name(session->channel) : "",
1157                 delayed_method2str(delay->method));
1158
1159         switch (delay->method) {
1160         case DELAYED_METHOD_INVITE:
1161                 ast_sip_session_refresh(session, delay->on_request_creation,
1162                         delay->on_sdp_creation, delay->on_response,
1163                         AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp, delay->media_state);
1164                 /* Ownership of media state transitions to ast_sip_session_refresh */
1165                 delay->media_state = NULL;
1166                 return 0;
1167         case DELAYED_METHOD_UPDATE:
1168                 ast_sip_session_refresh(session, delay->on_request_creation,
1169                         delay->on_sdp_creation, delay->on_response,
1170                         AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp, delay->media_state);
1171                 /* Ownership of media state transitions to ast_sip_session_refresh */
1172                 delay->media_state = NULL;
1173                 return 0;
1174         case DELAYED_METHOD_BYE:
1175                 ast_sip_session_terminate(session, 0);
1176                 return 0;
1177         }
1178         ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",
1179                 delayed_method2str(delay->method), delay->method);
1180         return -1;
1181 }
1182
1183 /*!
1184  * \internal
1185  * \brief The current INVITE transaction is in the PROCEEDING state.
1186  * \since 13.3.0
1187  *
1188  * \param vsession Session object.
1189  *
1190  * \retval 0 on success.
1191  * \retval -1 on error.
1192  */
1193 static int invite_proceeding(void *vsession)
1194 {
1195         struct ast_sip_session *session = vsession;
1196         struct ast_sip_session_delayed_request *delay;
1197         int found = 0;
1198         int res = 0;
1199
1200         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1201                 switch (delay->method) {
1202                 case DELAYED_METHOD_INVITE:
1203                         break;
1204                 case DELAYED_METHOD_UPDATE:
1205                         AST_LIST_REMOVE_CURRENT(next);
1206                         res = send_delayed_request(session, delay);
1207                         delayed_request_free(delay);
1208                         found = 1;
1209                         break;
1210                 case DELAYED_METHOD_BYE:
1211                         /* A BYE is pending so don't bother anymore. */
1212                         found = 1;
1213                         break;
1214                 }
1215                 if (found) {
1216                         break;
1217                 }
1218         }
1219         AST_LIST_TRAVERSE_SAFE_END;
1220
1221         ao2_ref(session, -1);
1222         return res;
1223 }
1224
1225 /*!
1226  * \internal
1227  * \brief The current INVITE transaction is in the TERMINATED state.
1228  * \since 13.3.0
1229  *
1230  * \param vsession Session object.
1231  *
1232  * \retval 0 on success.
1233  * \retval -1 on error.
1234  */
1235 static int invite_terminated(void *vsession)
1236 {
1237         struct ast_sip_session *session = vsession;
1238         struct ast_sip_session_delayed_request *delay;
1239         int found = 0;
1240         int res = 0;
1241         int timer_running;
1242
1243         /* re-INVITE collision timer running? */
1244         timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
1245
1246         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
1247                 switch (delay->method) {
1248                 case DELAYED_METHOD_INVITE:
1249                         if (!timer_running) {
1250                                 found = 1;
1251                         }
1252                         break;
1253                 case DELAYED_METHOD_UPDATE:
1254                 case DELAYED_METHOD_BYE:
1255                         found = 1;
1256                         break;
1257                 }
1258                 if (found) {
1259                         AST_LIST_REMOVE_CURRENT(next);
1260                         res = send_delayed_request(session, delay);
1261                         delayed_request_free(delay);
1262                         break;
1263                 }
1264         }
1265         AST_LIST_TRAVERSE_SAFE_END;
1266
1267         ao2_ref(session, -1);
1268         return res;
1269 }
1270
1271 /*!
1272  * \internal
1273  * \brief INVITE collision timeout.
1274  * \since 13.3.0
1275  *
1276  * \param vsession Session object.
1277  *
1278  * \retval 0 on success.
1279  * \retval -1 on error.
1280  */
1281 static int invite_collision_timeout(void *vsession)
1282 {
1283         struct ast_sip_session *session = vsession;
1284         int res;
1285
1286         if (session->inv_session->invite_tsx) {
1287                 /*
1288                  * INVITE transaction still active.  Let it send
1289                  * the collision re-INVITE when it terminates.
1290                  */
1291                 ao2_ref(session, -1);
1292                 res = 0;
1293         } else {
1294                 res = invite_terminated(session);
1295         }
1296
1297         return res;
1298 }
1299
1300 /*!
1301  * \internal
1302  * \brief The current UPDATE transaction is in the COMPLETED state.
1303  * \since 13.3.0
1304  *
1305  * \param vsession Session object.
1306  *
1307  * \retval 0 on success.
1308  * \retval -1 on error.
1309  */
1310 static int update_completed(void *vsession)
1311 {
1312         struct ast_sip_session *session = vsession;
1313         int res;
1314
1315         if (session->inv_session->invite_tsx) {
1316                 res = invite_proceeding(session);
1317         } else {
1318                 res = invite_terminated(session);
1319         }
1320
1321         return res;
1322 }
1323
1324 static void check_delayed_requests(struct ast_sip_session *session,
1325         int (*cb)(void *vsession))
1326 {
1327         ao2_ref(session, +1);
1328         if (ast_sip_push_task(session->serializer, cb, session)) {
1329                 ao2_ref(session, -1);
1330         }
1331 }
1332
1333 static int delay_request(struct ast_sip_session *session,
1334         ast_sip_session_request_creation_cb on_request,
1335         ast_sip_session_sdp_creation_cb on_sdp_creation,
1336         ast_sip_session_response_cb on_response,
1337         int generate_new_sdp,
1338         enum delayed_method method,
1339         struct ast_sip_session_media_state *media_state)
1340 {
1341         struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
1342                         on_request, on_sdp_creation, on_response, generate_new_sdp, media_state);
1343
1344         if (!delay) {
1345                 ast_sip_session_media_state_free(media_state);
1346                 return -1;
1347         }
1348
1349         if (method == DELAYED_METHOD_BYE) {
1350                 /* Send BYE as early as possible */
1351                 AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
1352         } else {
1353                 AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
1354         }
1355         return 0;
1356 }
1357
1358 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
1359 {
1360         pjsip_inv_session *inv_session = session->inv_session;
1361         const pjmedia_sdp_session *previous_sdp = NULL;
1362
1363         if (inv_session->neg) {
1364                 if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
1365                         pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
1366                 } else {
1367                         pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
1368                 }
1369         }
1370         return create_local_sdp(inv_session, session, previous_sdp);
1371 }
1372
1373 static void set_from_header(struct ast_sip_session *session)
1374 {
1375         struct ast_party_id effective_id;
1376         struct ast_party_id connected_id;
1377         pj_pool_t *dlg_pool;
1378         pjsip_fromto_hdr *dlg_info;
1379         pjsip_name_addr *dlg_info_name_addr;
1380         pjsip_sip_uri *dlg_info_uri;
1381         int restricted;
1382
1383         if (!session->channel || session->saved_from_hdr) {
1384                 return;
1385         }
1386
1387         /* We need to save off connected_id for RPID/PAI generation */
1388         ast_party_id_init(&connected_id);
1389         ast_channel_lock(session->channel);
1390         effective_id = ast_channel_connected_effective_id(session->channel);
1391         ast_party_id_copy(&connected_id, &effective_id);
1392         ast_channel_unlock(session->channel);
1393
1394         restricted =
1395                 ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);
1396
1397         /* Now set up dlg->local.info so pjsip can correctly generate From */
1398
1399         dlg_pool = session->inv_session->dlg->pool;
1400         dlg_info = session->inv_session->dlg->local.info;
1401         dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;
1402         dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);
1403
1404         if (session->endpoint->id.trust_outbound || !restricted) {
1405                 ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);
1406         }
1407
1408         ast_party_id_free(&connected_id);
1409
1410         if (!ast_strlen_zero(session->endpoint->fromuser)) {
1411                 dlg_info_name_addr->display.ptr = NULL;
1412                 dlg_info_name_addr->display.slen = 0;
1413                 pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);
1414         }
1415
1416         if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1417                 pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);
1418         }
1419
1420         /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */
1421         session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);
1422         ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);
1423
1424         /* In chan_sip, fromuser and fromdomain trump restricted so we only
1425          * anonymize if they're not set.
1426          */
1427         if (restricted) {
1428                 /* fromuser doesn't provide a display name so we always set it */
1429                 pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");
1430
1431                 if (ast_strlen_zero(session->endpoint->fromuser)) {
1432                         pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");
1433                 }
1434
1435                 if (ast_strlen_zero(session->endpoint->fromdomain)) {
1436                         pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");
1437                 }
1438         } else {
1439                 ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);
1440     }
1441 }
1442
1443 int ast_sip_session_refresh(struct ast_sip_session *session,
1444                 ast_sip_session_request_creation_cb on_request_creation,
1445                 ast_sip_session_sdp_creation_cb on_sdp_creation,
1446                 ast_sip_session_response_cb on_response,
1447                 enum ast_sip_session_refresh_method method, int generate_new_sdp,
1448                 struct ast_sip_session_media_state *media_state)
1449 {
1450         pjsip_inv_session *inv_session = session->inv_session;
1451         pjmedia_sdp_session *new_sdp = NULL;
1452         pjsip_tx_data *tdata;
1453
1454         if (media_state && (!media_state->topology || !generate_new_sdp)) {
1455                 ast_sip_session_media_state_free(media_state);
1456                 return -1;
1457         }
1458
1459         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1460                 /* Don't try to do anything with a hung-up call */
1461                 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
1462                                 ast_sorcery_object_get_id(session->endpoint));
1463                 ast_sip_session_media_state_free(media_state);
1464                 return 0;
1465         }
1466
1467         /* If the dialog has not yet been established we have to defer until it has */
1468         if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1469                 ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
1470                         ast_sorcery_object_get_id(session->endpoint));
1471                 return delay_request(session, on_request_creation, on_sdp_creation, on_response,
1472                         generate_new_sdp,
1473                         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1474                                 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE,
1475                         media_state);
1476         }
1477
1478         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1479                 if (inv_session->invite_tsx) {
1480                         /* We can't send a reinvite yet, so delay it */
1481                         ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
1482                                         ast_sorcery_object_get_id(session->endpoint));
1483                         return delay_request(session, on_request_creation, on_sdp_creation,
1484                                 on_response, generate_new_sdp, DELAYED_METHOD_INVITE, media_state);
1485                 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
1486                         /* Initial INVITE transaction failed to progress us to a confirmed state
1487                          * which means re-invites are not possible
1488                          */
1489                         ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
1490                                         ast_sorcery_object_get_id(session->endpoint));
1491                         ast_sip_session_media_state_free(media_state);
1492                         return 0;
1493                 }
1494         }
1495
1496         if (generate_new_sdp) {
1497                 /* SDP can only be generated if current negotiation has already completed */
1498                 if (inv_session->neg
1499                         && pjmedia_sdp_neg_get_state(inv_session->neg)
1500                                 != PJMEDIA_SDP_NEG_STATE_DONE) {
1501                         ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
1502                                 ast_sorcery_object_get_id(session->endpoint));
1503                         return delay_request(session, on_request_creation, on_sdp_creation,
1504                                 on_response, generate_new_sdp,
1505                                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1506                                         ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE, media_state);
1507                 }
1508
1509                 /* If an explicitly requested media state has been provided use it instead of any pending one */
1510                 if (media_state) {
1511                         int index;
1512                         int type_streams[AST_MEDIA_TYPE_END] = {0};
1513                         struct ast_stream *stream;
1514
1515                         /* Prune the media state so the number of streams fit within the configured limits - we do it here
1516                          * so that the index of the resulting streams in the SDP match. If we simply left the streams out
1517                          * of the SDP when producing it we'd be in trouble. We also enforce formats here for media types that
1518                          * are configurable on the endpoint.
1519                          */
1520                         for (index = 0; index < ast_stream_topology_get_count(media_state->topology); ++index) {
1521                                 struct ast_stream *existing_stream = NULL;
1522
1523                                 stream = ast_stream_topology_get_stream(media_state->topology, index);
1524
1525                                 if (session->active_media_state->topology &&
1526                                         index < ast_stream_topology_get_count(session->active_media_state->topology)) {
1527                                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1528                                 }
1529
1530                                 if (is_stream_limitation_reached(ast_stream_get_type(stream), session->endpoint, type_streams)) {
1531                                         if (index < AST_VECTOR_SIZE(&media_state->sessions)) {
1532                                                 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&media_state->sessions, index);
1533
1534                                                 ao2_cleanup(session_media);
1535                                                 AST_VECTOR_REMOVE(&media_state->sessions, index, 1);
1536                                         }
1537
1538                                         ast_stream_topology_del_stream(media_state->topology, index);
1539
1540                                         /* A stream has potentially moved into our spot so we need to jump back so we process it */
1541                                         index -= 1;
1542                                         continue;
1543                                 }
1544
1545                                 /* No need to do anything with stream if it's media state is removed */
1546                                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
1547                                         continue;
1548                                 }
1549
1550                                 /* Enforce the configured allowed codecs on audio and video streams */
1551                                 if (ast_stream_get_type(stream) == AST_MEDIA_TYPE_AUDIO || ast_stream_get_type(stream) == AST_MEDIA_TYPE_VIDEO) {
1552                                         struct ast_format_cap *joint_cap;
1553
1554                                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1555                                         if (!joint_cap) {
1556                                                 ast_sip_session_media_state_free(media_state);
1557                                                 return 0;
1558                                         }
1559                                         ast_format_cap_get_compatible(ast_stream_get_formats(stream), session->endpoint->media.codecs, joint_cap);
1560                                         if (!ast_format_cap_count(joint_cap)) {
1561                                                 ao2_ref(joint_cap, -1);
1562
1563                                                 if (!existing_stream) {
1564                                                         /* If there is no existing stream we can just not have this stream in the topology
1565                                                          * at all.
1566                                                          */
1567                                                         ast_stream_topology_del_stream(media_state->topology, index);
1568                                                         index -= 1;
1569                                                         continue;
1570                                                 } else if (ast_stream_get_state(stream) != ast_stream_get_state(existing_stream) ||
1571                                                                 strcmp(ast_stream_get_name(stream), ast_stream_get_name(existing_stream))) {
1572                                                         /* If the underlying stream is a different type or different name then we have to
1573                                                          * mark it as removed, as it is replacing an existing stream. We do this so order
1574                                                          * is preserved.
1575                                                          */
1576                                                         ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
1577                                                         continue;
1578                                                 } else {
1579                                                         /* However if the stream is otherwise remaining the same we can keep the formats
1580                                                          * that exist on it already which allows media to continue to flow.
1581                                                          */
1582                                                         joint_cap = ao2_bump(ast_stream_get_formats(existing_stream));
1583                                                 }
1584                                         }
1585                                         ast_stream_set_formats(stream, joint_cap);
1586                                         ao2_cleanup(joint_cap);
1587                                 }
1588
1589                                 ++type_streams[ast_stream_get_type(stream)];
1590                         }
1591
1592                         if (session->active_media_state->topology) {
1593                                 /* SDP is a fun thing. Take for example the fact that streams are never removed. They just become
1594                                  * declined. To better handle this in the case where something requests a topology change for fewer
1595                                  * streams than are currently present we fill in the topology to match the current number of streams
1596                                  * that are active.
1597                                  */
1598                                 for (index = ast_stream_topology_get_count(media_state->topology);
1599                                         index < ast_stream_topology_get_count(session->active_media_state->topology); ++index) {
1600                                         struct ast_stream *cloned;
1601
1602                                         stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1603                                         ast_assert(stream != NULL);
1604
1605                                         cloned = ast_stream_clone(stream, NULL);
1606                                         if (!cloned) {
1607                                                 ast_sip_session_media_state_free(media_state);
1608                                                 return -1;
1609                                         }
1610
1611                                         ast_stream_set_state(cloned, AST_STREAM_STATE_REMOVED);
1612                                         if (ast_stream_topology_append_stream(media_state->topology, cloned) < 0) {
1613                                                 ast_stream_free(cloned);
1614                                                 ast_sip_session_media_state_free(media_state);
1615                                                 return -1;
1616                                         }
1617                                 }
1618
1619                                 /* If the resulting media state matches the existing active state don't bother doing a session refresh */
1620                                 if (ast_stream_topology_equal(session->active_media_state->topology, media_state->topology)) {
1621                                         ast_sip_session_media_state_free(media_state);
1622                                         return 0;
1623                                 }
1624                         }
1625
1626                         ast_sip_session_media_state_free(session->pending_media_state);
1627                         session->pending_media_state = media_state;
1628                 }
1629
1630                 new_sdp = generate_session_refresh_sdp(session);
1631                 if (!new_sdp) {
1632                         ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
1633                         ast_sip_session_media_state_reset(session->pending_media_state);
1634                         return -1;
1635                 }
1636                 if (on_sdp_creation) {
1637                         if (on_sdp_creation(session, new_sdp)) {
1638                                 ast_sip_session_media_state_reset(session->pending_media_state);
1639                                 return -1;
1640                         }
1641                 }
1642         }
1643
1644         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1645                 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
1646                         ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
1647                         if (generate_new_sdp) {
1648                                 ast_sip_session_media_state_reset(session->pending_media_state);
1649                         }
1650                         return -1;
1651                 }
1652         } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
1653                 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
1654                 if (generate_new_sdp) {
1655                         ast_sip_session_media_state_reset(session->pending_media_state);
1656                 }
1657                 return -1;
1658         }
1659         if (on_request_creation) {
1660                 if (on_request_creation(session, tdata)) {
1661                         if (generate_new_sdp) {
1662                                 ast_sip_session_media_state_reset(session->pending_media_state);
1663                         }
1664                         return -1;
1665                 }
1666         }
1667         ast_debug(3, "Sending session refresh SDP via %s to %s\n",
1668                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
1669                 ast_sorcery_object_get_id(session->endpoint));
1670         ast_sip_session_send_request_with_cb(session, tdata, on_response);
1671         return 0;
1672 }
1673
1674 int ast_sip_session_regenerate_answer(struct ast_sip_session *session,
1675                 ast_sip_session_sdp_creation_cb on_sdp_creation)
1676 {
1677         pjsip_inv_session *inv_session = session->inv_session;
1678         pjmedia_sdp_session *new_answer = NULL;
1679         const pjmedia_sdp_session *previous_offer = NULL;
1680
1681         /* The SDP answer can only be regenerated if it is still pending to be sent */
1682         if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
1683                 pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {
1684                 ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",
1685                         ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));
1686                 return -1;
1687         }
1688
1689         pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);
1690         if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {
1691                 /* Transition the SDP negotiator back to when it received the remote offer */
1692                 pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);
1693                 pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);
1694         }
1695
1696         new_answer = create_local_sdp(inv_session, session, previous_offer);
1697         if (!new_answer) {
1698                 ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",
1699                         ast_channel_name(session->channel));
1700                 return -1;
1701         }
1702
1703         if (on_sdp_creation) {
1704                 if (on_sdp_creation(session, new_answer)) {
1705                         return -1;
1706                 }
1707         }
1708
1709         pjsip_inv_set_sdp_answer(inv_session, new_answer);
1710
1711         return 0;
1712 }
1713
1714 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1715 {
1716         handle_outgoing_response(session, tdata);
1717         pjsip_inv_send_msg(session->inv_session, tdata);
1718         return;
1719 }
1720
1721 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
1722
1723 static pjsip_module session_module = {
1724         .name = {"Session Module", 14},
1725         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1726         .on_rx_request = session_on_rx_request,
1727 };
1728
1729 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
1730  *
1731  * \retval 1 re-invite should be deferred and resumed later
1732  * \retval 0 re-invite should not be deferred
1733  */
1734 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
1735 {
1736         int i;
1737
1738         if (!session->pending_media_state->topology) {
1739                 session->pending_media_state->topology = ast_stream_topology_alloc();
1740                 if (!session->pending_media_state->topology) {
1741                         return -1;
1742                 }
1743         }
1744
1745         for (i = 0; i < sdp->media_count; ++i) {
1746                 /* See if there are registered handlers for this media stream type */
1747                 char media[20];
1748                 struct ast_sip_session_sdp_handler *handler;
1749                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1750                 struct ast_stream *existing_stream = NULL;
1751                 struct ast_stream *stream;
1752                 enum ast_media_type type;
1753                 struct ast_sip_session_media *session_media = NULL;
1754                 enum ast_sip_session_sdp_stream_defer res;
1755
1756                 /* We need a null-terminated version of the media string */
1757                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
1758
1759                 if (session->active_media_state->topology &&
1760                         (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
1761                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
1762                 }
1763
1764                 type = ast_media_type_from_str(media);
1765                 stream = ast_stream_alloc(existing_stream ? ast_stream_get_name(existing_stream) : ast_codec_media_type2str(type), type);
1766                 if (!stream) {
1767                         return -1;
1768                 }
1769
1770                 /* As this is only called on an incoming SDP offer before processing it is not possible
1771                  * for streams and their media sessions to exist.
1772                  */
1773                 if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
1774                         ast_stream_free(stream);
1775                         return -1;
1776                 }
1777
1778                 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
1779                 if (!session_media) {
1780                         return -1;
1781                 }
1782
1783                 if (session_media->handler) {
1784                         handler = session_media->handler;
1785                         if (handler->defer_incoming_sdp_stream) {
1786                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1787                                         sdp->media[i]);
1788                                 switch (res) {
1789                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1790                                         break;
1791                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
1792                                         return 0;
1793                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1794                                         break;
1795                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1796                                         return 1;
1797                                 }
1798                         }
1799                         /* Handled by this handler. Move to the next stream */
1800                         continue;
1801                 }
1802
1803                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1804                 if (!handler_list) {
1805                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
1806                         continue;
1807                 }
1808                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1809                         if (handler == session_media->handler) {
1810                                 continue;
1811                         }
1812                         if (!handler->defer_incoming_sdp_stream) {
1813                                 continue;
1814                         }
1815                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1816                                 sdp->media[i]);
1817                         switch (res) {
1818                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1819                                 continue;
1820                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
1821                                 session_media_set_handler(session_media, handler);
1822                                 return 0;
1823                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1824                                 /* Handled by this handler. */
1825                                 session_media_set_handler(session_media, handler);
1826                                 break;
1827                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1828                                 /* Handled by this handler. */
1829                                 session_media_set_handler(session_media, handler);
1830                                 return 1;
1831                         }
1832                         /* Move to the next stream */
1833                         break;
1834                 }
1835         }
1836         return 0;
1837 }
1838
1839 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
1840 {
1841         pjsip_dialog *dlg;
1842         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1843         pjsip_rdata_sdp_info *sdp_info;
1844
1845         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
1846                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
1847                 !(session = ast_sip_dialog_get_session(dlg)) ||
1848                 !session->channel) {
1849                 return PJ_FALSE;
1850         }
1851
1852         if (session->deferred_reinvite) {
1853                 pj_str_t key, deferred_key;
1854                 pjsip_tx_data *tdata;
1855
1856                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1857                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1858                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1859                         session->deferred_reinvite);
1860
1861                 /* If this is a retransmission ignore it */
1862                 if (!pj_strcmp(&key, &deferred_key)) {
1863                         return PJ_TRUE;
1864                 }
1865
1866                 /* Otherwise this is a new re-invite, so reject it */
1867                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1868                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1869                 }
1870
1871                 return PJ_TRUE;
1872         }
1873
1874         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1875                 (sdp_info->sdp_err != PJ_SUCCESS)) {
1876                 return PJ_FALSE;
1877         }
1878
1879         if (!sdp_info->sdp) {
1880                 const pjmedia_sdp_session *local;
1881                 int i;
1882
1883                 ast_queue_unhold(session->channel);
1884
1885                 pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);
1886                 if (!local) {
1887                         return PJ_FALSE;
1888                 }
1889
1890                 /*
1891                  * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).
1892                  * When hold is initially indicated, we
1893                  * - Receive an INVITE with no SDP
1894                  * - Send a 200 OK with SDP, indicating sendrecv in the media streams
1895                  * - Receive an ACK with SDP, indicating sendonly in the media streams
1896                  *
1897                  * At this point, the pjmedia negotiator saves the state of the media direction so that
1898                  * if we are to send any offers, we'll offer recvonly in the media streams. This is
1899                  * problematic if the device is attempting to unhold, though. If the device unholds
1900                  * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.
1901                  * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond
1902                  * with sendonly or inactive. The result of this is that the stream is not off hold.
1903                  *
1904                  * Therefore, in this case, when we receive a reinvite while the stream is on hold, we
1905                  * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv
1906                  * in order to get the stream off hold. If this is actually a different purpose reinvite
1907                  * (like a session timer refresh), then the answerer can respond to our sendrecv with
1908                  * sendonly, keeping the stream on hold.
1909                  */
1910                 for (i = 0; i < local->media_count; ++i) {
1911                         pjmedia_sdp_media *m = local->media[i];
1912                         pjmedia_sdp_attr *recvonly;
1913                         pjmedia_sdp_attr *inactive;
1914
1915                         recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);
1916                         inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);
1917                         if (recvonly || inactive) {
1918                                 pjmedia_sdp_attr *to_remove = recvonly ?: inactive;
1919                                 pjmedia_sdp_attr *sendrecv;
1920
1921                                 pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);
1922
1923                                 sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);
1924                                 pjmedia_sdp_media_add_attr(m, sendrecv);
1925                         }
1926                 }
1927
1928                 return PJ_FALSE;
1929         }
1930
1931         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1932                 return PJ_FALSE;
1933         }
1934
1935         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1936
1937         return PJ_TRUE;
1938 }
1939
1940 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1941 {
1942         if (!session->deferred_reinvite) {
1943                 return;
1944         }
1945
1946         if (session->channel) {
1947                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1948                         session->deferred_reinvite, NULL, NULL);
1949         }
1950         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1951         session->deferred_reinvite = NULL;
1952 }
1953
1954 static pjsip_module session_reinvite_module = {
1955         .name = { "Session Re-Invite Module", 24 },
1956         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1957         .on_rx_request = session_reinvite_on_rx_request,
1958 };
1959
1960
1961 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1962                 ast_sip_session_response_cb on_response)
1963 {
1964         pjsip_inv_session *inv_session = session->inv_session;
1965
1966         /* For every request except BYE we disallow sending of the message when
1967          * the session has been disconnected. A BYE request is special though
1968          * because it can be sent again after the session is disconnected except
1969          * with credentials.
1970          */
1971         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&
1972                 tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {
1973                 return;
1974         }
1975
1976         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
1977                              MOD_DATA_ON_RESPONSE, on_response);
1978
1979         handle_outgoing_request(session, tdata);
1980         pjsip_inv_send_msg(session->inv_session, tdata);
1981
1982         return;
1983 }
1984
1985 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1986 {
1987         ast_sip_session_send_request_with_cb(session, tdata, NULL);
1988 }
1989
1990 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
1991 {
1992         pjmedia_sdp_session *offer;
1993
1994         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1995                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1996                 return -1;
1997         }
1998
1999         pjsip_inv_set_local_sdp(session->inv_session, offer);
2000         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
2001 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2002         if (!session->endpoint->preferred_codec_only) {
2003                 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
2004         }
2005 #endif
2006
2007         /*
2008          * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the
2009          * From in the initial INVITE will be wrong but the rest of the messages will be OK.
2010          */
2011         set_from_header(session);
2012
2013         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
2014                 return -1;
2015         }
2016
2017         return 0;
2018 }
2019
2020 static int datastore_hash(const void *obj, int flags)
2021 {
2022         const struct ast_datastore *datastore = obj;
2023         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
2024
2025         ast_assert(uid != NULL);
2026
2027         return ast_str_hash(uid);
2028 }
2029
2030 static int datastore_cmp(void *obj, void *arg, int flags)
2031 {
2032         const struct ast_datastore *datastore1 = obj;
2033         const struct ast_datastore *datastore2 = arg;
2034         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
2035
2036         ast_assert(datastore1->uid != NULL);
2037         ast_assert(uid2 != NULL);
2038
2039         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
2040 }
2041
2042 static void session_destructor(void *obj)
2043 {
2044         struct ast_sip_session *session = obj;
2045         struct ast_sip_session_supplement *supplement;
2046         struct ast_sip_session_delayed_request *delay;
2047         const char *endpoint_name = session->endpoint ?
2048                 ast_sorcery_object_get_id(session->endpoint) : "<none>";
2049
2050         ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);
2051
2052         ast_test_suite_event_notify("SESSION_DESTROYING",
2053                 "Endpoint: %s\r\n"
2054                 "AOR: %s\r\n"
2055                 "Contact: %s"
2056                 , endpoint_name
2057                 , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"
2058                 , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"
2059                 );
2060
2061         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
2062                 if (supplement->session_destroy) {
2063                         supplement->session_destroy(session);
2064                 }
2065                 ast_free(supplement);
2066         }
2067
2068         ast_taskprocessor_unreference(session->serializer);
2069         ao2_cleanup(session->datastores);
2070         ast_sip_session_media_state_free(session->active_media_state);
2071         ast_sip_session_media_state_free(session->pending_media_state);
2072
2073         AST_LIST_HEAD_DESTROY(&session->supplements);
2074         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2075                 delayed_request_free(delay);
2076         }
2077         ast_party_id_free(&session->id);
2078         ao2_cleanup(session->endpoint);
2079         ao2_cleanup(session->aor);
2080         ao2_cleanup(session->contact);
2081         ao2_cleanup(session->direct_media_cap);
2082
2083         ast_dsp_free(session->dsp);
2084
2085         if (session->inv_session) {
2086                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
2087         }
2088
2089         ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);
2090 }
2091
2092 /*! \brief Destructor for SIP channel */
2093 static void sip_channel_destroy(void *obj)
2094 {
2095         struct ast_sip_channel_pvt *channel = obj;
2096
2097         ao2_cleanup(channel->pvt);
2098         ao2_cleanup(channel->session);
2099 }
2100
2101 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
2102 {
2103         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
2104
2105         if (!channel) {
2106                 return NULL;
2107         }
2108
2109         ao2_ref(pvt, +1);
2110         channel->pvt = pvt;
2111         ao2_ref(session, +1);
2112         channel->session = session;
2113
2114         return channel;
2115 }
2116
2117 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
2118         struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
2119 {
2120         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2121         struct ast_sip_session *ret_session;
2122         struct ast_sip_session_supplement *iter;
2123         int dsp_features = 0;
2124
2125         session = ao2_alloc(sizeof(*session), session_destructor);
2126         if (!session) {
2127                 return NULL;
2128         }
2129
2130         AST_LIST_HEAD_INIT(&session->supplements);
2131         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
2132         ast_party_id_init(&session->id);
2133
2134         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2135         if (!session->direct_media_cap) {
2136                 return NULL;
2137         }
2138         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
2139         if (!session->datastores) {
2140                 return NULL;
2141         }
2142         session->active_media_state = ast_sip_session_media_state_alloc();
2143         if (!session->active_media_state) {
2144                 return NULL;
2145         }
2146         session->pending_media_state = ast_sip_session_media_state_alloc();
2147         if (!session->pending_media_state) {
2148                 return NULL;
2149         }
2150
2151         if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {
2152                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
2153         }
2154         if (endpoint->faxdetect) {
2155                 dsp_features |= DSP_FEATURE_FAX_DETECT;
2156         }
2157         if (dsp_features) {
2158                 session->dsp = ast_dsp_new();
2159                 if (!session->dsp) {
2160                         return NULL;
2161                 }
2162
2163                 ast_dsp_set_features(session->dsp, dsp_features);
2164         }
2165
2166         session->endpoint = ao2_bump(endpoint);
2167
2168         if (rdata) {
2169                 /*
2170                  * We must continue using the serializer that the original
2171                  * INVITE came in on for the dialog.  There may be
2172                  * retransmissions already enqueued in the original
2173                  * serializer that can result in reentrancy and message
2174                  * sequencing problems.
2175                  */
2176                 session->serializer = ast_sip_get_distributor_serializer(rdata);
2177         } else {
2178                 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
2179
2180                 /* Create name with seq number appended. */
2181                 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
2182                         ast_sorcery_object_get_id(endpoint));
2183
2184                 session->serializer = ast_sip_create_serializer(tps_name);
2185         }
2186         if (!session->serializer) {
2187                 return NULL;
2188         }
2189         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
2190         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
2191         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
2192         inv_session->mod_data[session_module.id] = ao2_bump(session);
2193         session->contact = ao2_bump(contact);
2194         session->inv_session = inv_session;
2195
2196         session->dtmf = endpoint->dtmf;
2197
2198         if (ast_sip_session_add_supplements(session)) {
2199                 /* Release the ref held by session->inv_session */
2200                 ao2_ref(session, -1);
2201                 return NULL;
2202         }
2203         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2204                 if (iter->session_begin) {
2205                         iter->session_begin(session);
2206                 }
2207         }
2208
2209         /* Avoid unnecessary ref manipulation to return a session */
2210         ret_session = session;
2211         session = NULL;
2212         return ret_session;
2213 }
2214
2215 /*! \brief struct controlling the suspension of the session's serializer. */
2216 struct ast_sip_session_suspender {
2217         ast_cond_t cond_suspended;
2218         ast_cond_t cond_complete;
2219         int suspended;
2220         int complete;
2221 };
2222
2223 static void sip_session_suspender_dtor(void *vdoomed)
2224 {
2225         struct ast_sip_session_suspender *doomed = vdoomed;
2226
2227         ast_cond_destroy(&doomed->cond_suspended);
2228         ast_cond_destroy(&doomed->cond_complete);
2229 }
2230
2231 /*!
2232  * \internal
2233  * \brief Block the session serializer thread task.
2234  *
2235  * \param data Pushed serializer task data for suspension.
2236  *
2237  * \retval 0
2238  */
2239 static int sip_session_suspend_task(void *data)
2240 {
2241         struct ast_sip_session_suspender *suspender = data;
2242
2243         ao2_lock(suspender);
2244
2245         /* Signal that the serializer task is now suspended. */
2246         suspender->suspended = 1;
2247         ast_cond_signal(&suspender->cond_suspended);
2248
2249         /* Wait for the serializer suspension to be completed. */
2250         while (!suspender->complete) {
2251                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
2252         }
2253
2254         ao2_unlock(suspender);
2255         ao2_ref(suspender, -1);
2256
2257         return 0;
2258 }
2259
2260 void ast_sip_session_suspend(struct ast_sip_session *session)
2261 {
2262         struct ast_sip_session_suspender *suspender;
2263         int res;
2264
2265         ast_assert(session->suspended == NULL);
2266
2267         if (ast_taskprocessor_is_task(session->serializer)) {
2268                 /* I am the session's serializer thread so I cannot suspend. */
2269                 return;
2270         }
2271
2272         if (ast_taskprocessor_is_suspended(session->serializer)) {
2273                 /* The serializer already suspended. */
2274                 return;
2275         }
2276
2277         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
2278         if (!suspender) {
2279                 /* We will just have to hope that the system does not deadlock */
2280                 return;
2281         }
2282         ast_cond_init(&suspender->cond_suspended, NULL);
2283         ast_cond_init(&suspender->cond_complete, NULL);
2284
2285         ao2_ref(suspender, +1);
2286         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
2287         if (res) {
2288                 /* We will just have to hope that the system does not deadlock */
2289                 ao2_ref(suspender, -2);
2290                 return;
2291         }
2292
2293         session->suspended = suspender;
2294
2295         /* Wait for the serializer to get suspended. */
2296         ao2_lock(suspender);
2297         while (!suspender->suspended) {
2298                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
2299         }
2300         ao2_unlock(suspender);
2301
2302         ast_taskprocessor_suspend(session->serializer);
2303 }
2304
2305 void ast_sip_session_unsuspend(struct ast_sip_session *session)
2306 {
2307         struct ast_sip_session_suspender *suspender = session->suspended;
2308
2309         if (!suspender) {
2310                 /* Nothing to do */
2311                 return;
2312         }
2313         session->suspended = NULL;
2314
2315         /* Signal that the serializer task suspension is now complete. */
2316         ao2_lock(suspender);
2317         suspender->complete = 1;
2318         ast_cond_signal(&suspender->cond_complete);
2319         ao2_unlock(suspender);
2320
2321         ao2_ref(suspender, -1);
2322
2323         ast_taskprocessor_unsuspend(session->serializer);
2324 }
2325
2326 /*!
2327  * \internal
2328  * \brief Handle initial INVITE challenge response message.
2329  * \since 13.5.0
2330  *
2331  * \param rdata PJSIP receive response message data.
2332  *
2333  * \retval PJ_FALSE Did not handle message.
2334  * \retval PJ_TRUE Handled message.
2335  */
2336 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
2337 {
2338         pjsip_transaction *tsx;
2339         pjsip_dialog *dlg;
2340         pjsip_inv_session *inv;
2341         pjsip_tx_data *tdata;
2342         struct ast_sip_session *session;
2343
2344         if (rdata->msg_info.msg->line.status.code != 401
2345                 && rdata->msg_info.msg->line.status.code != 407) {
2346                 /* Doesn't pertain to us. Move on */
2347                 return PJ_FALSE;
2348         }
2349
2350         tsx = pjsip_rdata_get_tsx(rdata);
2351         dlg = pjsip_rdata_get_dlg(rdata);
2352         if (!dlg || !tsx) {
2353                 return PJ_FALSE;
2354         }
2355
2356         if (tsx->method.id != PJSIP_INVITE_METHOD) {
2357                 /* Not an INVITE that needs authentication */
2358                 return PJ_FALSE;
2359         }
2360
2361         inv = pjsip_dlg_get_inv_session(dlg);
2362         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
2363                 /*
2364                  * We cannot handle reINVITE authentication at this
2365                  * time because the reINVITE transaction is still in
2366                  * progress.
2367                  */
2368                 ast_debug(1, "A reINVITE is being challenged.\n");
2369                 return PJ_FALSE;
2370         }
2371         ast_debug(1, "Initial INVITE is being challenged.\n");
2372
2373         session = inv->mod_data[session_module.id];
2374
2375         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
2376                 tsx->last_tx, &tdata)) {
2377                 return PJ_FALSE;
2378         }
2379
2380         /*
2381          * Restart the outgoing initial INVITE transaction to deal
2382          * with authentication.
2383          */
2384         pjsip_inv_uac_restart(inv, PJ_FALSE);
2385
2386         ast_sip_session_send_request(session, tdata);
2387         return PJ_TRUE;
2388 }
2389
2390 static pjsip_module outbound_invite_auth_module = {
2391         .name = {"Outbound INVITE Auth", 20},
2392         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
2393         .on_rx_response = outbound_invite_auth,
2394 };
2395
2396 /*!
2397  * \internal
2398  * \brief Setup outbound initial INVITE authentication.
2399  * \since 13.5.0
2400  *
2401  * \param dlg PJSIP dialog to attach outbound authentication.
2402  *
2403  * \retval 0 on success.
2404  * \retval -1 on error.
2405  */
2406 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
2407 {
2408         pj_status_t status;
2409
2410         ++dlg->sess_count;
2411         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
2412         --dlg->sess_count;
2413
2414         return status != PJ_SUCCESS ? -1 : 0;
2415 }
2416
2417 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
2418         struct ast_sip_contact *contact, const char *location, const char *request_user,
2419         struct ast_stream_topology *req_topology)
2420 {
2421         const char *uri = NULL;
2422         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
2423         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
2424         pjsip_timer_setting timer;
2425         pjsip_dialog *dlg;
2426         struct pjsip_inv_session *inv_session;
2427         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2428         struct ast_sip_session *ret_session;
2429
2430         /* If no location has been provided use the AOR list from the endpoint itself */
2431         if (location || !contact) {
2432                 location = S_OR(location, endpoint->aors);
2433
2434                 ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,
2435                         &found_aor, &found_contact);
2436                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
2437                         uri = location;
2438                 } else {
2439                         uri = found_contact->uri;
2440                 }
2441         } else {
2442                 uri = contact->uri;
2443         }
2444
2445         /* If we still have no URI to dial fail to create the session */
2446         if (ast_strlen_zero(uri)) {
2447                 ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",
2448                         ast_sorcery_object_get_id(endpoint));
2449                 return NULL;
2450         }
2451
2452         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
2453                 return NULL;
2454         }
2455
2456         if (setup_outbound_invite_auth(dlg)) {
2457                 pjsip_dlg_terminate(dlg);
2458                 return NULL;
2459         }
2460
2461         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
2462                 pjsip_dlg_terminate(dlg);
2463                 return NULL;
2464         }
2465 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2466         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2467 #endif
2468
2469         pjsip_timer_setting_default(&timer);
2470         timer.min_se = endpoint->extensions.timer.min_se;
2471         timer.sess_expires = endpoint->extensions.timer.sess_expires;
2472         pjsip_timer_init_session(inv_session, &timer);
2473
2474         session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
2475                 inv_session, NULL);
2476         if (!session) {
2477                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2478                 return NULL;
2479         }
2480         session->aor = ao2_bump(found_aor);
2481         ast_party_id_copy(&session->id, &endpoint->id.self);
2482
2483         if (ast_stream_topology_get_count(req_topology) > 0) {
2484                 /* get joint caps between req_topology and endpoint topology */
2485                 int i;
2486
2487                 for (i = 0; i < ast_stream_topology_get_count(req_topology); ++i) {
2488                         struct ast_stream *req_stream;
2489                         struct ast_format_cap *req_cap;
2490                         struct ast_format_cap *joint_cap;
2491                         struct ast_stream *clone_stream;
2492
2493                         req_stream = ast_stream_topology_get_stream(req_topology, i);
2494
2495                         if (ast_stream_get_state(req_stream) == AST_STREAM_STATE_REMOVED) {
2496                                 continue;
2497                         }
2498
2499                         req_cap = ast_stream_get_formats(req_stream);
2500
2501                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2502                         if (!joint_cap) {
2503                                 continue;
2504                         }
2505
2506                         ast_format_cap_get_compatible(req_cap, endpoint->media.codecs, joint_cap);
2507                         if (!ast_format_cap_count(joint_cap)) {
2508                                 ao2_ref(joint_cap, -1);
2509                                 continue;
2510                         }
2511
2512                         clone_stream = ast_stream_clone(req_stream, NULL);
2513                         if (!clone_stream) {
2514                                 ao2_ref(joint_cap, -1);
2515                                 continue;
2516                         }
2517
2518                         if (ast_stream_get_type(req_stream) == AST_MEDIA_TYPE_AUDIO) {
2519                                 /*
2520                                  * By appending codecs from the endpoint after compatible ones this
2521                                  * guarantees that priority is given to those while also allowing
2522                                  * translation to occur for non-compatible.
2523                                  */
2524                                 ast_format_cap_append_from_cap(joint_cap,
2525                                         endpoint->media.codecs, AST_MEDIA_TYPE_AUDIO);
2526                         }
2527
2528                         ast_stream_set_formats(clone_stream, joint_cap);
2529                         ao2_ref(joint_cap, -1);
2530
2531                         if (!session->pending_media_state->topology) {
2532                                 session->pending_media_state->topology = ast_stream_topology_alloc();
2533                                 if (!session->pending_media_state->topology) {
2534                                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2535                                         ao2_ref(session, -1);
2536                                         return NULL;
2537                                 }
2538                         }
2539
2540                         if (ast_stream_topology_append_stream(session->pending_media_state->topology, clone_stream) < 0) {
2541                                 ast_stream_free(clone_stream);
2542                                 continue;
2543                         }
2544                 }
2545         }
2546
2547         if (!session->pending_media_state->topology) {
2548                 /* Use the configured topology on the endpoint as the pending one */
2549                 session->pending_media_state->topology = ast_stream_topology_clone(endpoint->media.topology);
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 (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2558                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2559                 /* Since we are not notifying ourselves that the INVITE session is being terminated
2560                  * we need to manually drop its reference to session
2561                  */
2562                 ao2_ref(session, -1);
2563                 return NULL;
2564         }
2565
2566         /* Avoid unnecessary ref manipulation to return a session */
2567         ret_session = session;
2568         session = NULL;
2569         return ret_session;
2570 }
2571
2572 static int session_end(void *vsession);
2573 static int session_end_completion(void *vsession);
2574
2575 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
2576 {
2577         pj_status_t status;
2578         pjsip_tx_data *packet = NULL;
2579
2580         if (session->defer_terminate) {
2581                 session->terminate_while_deferred = 1;
2582                 return;
2583         }
2584
2585         if (!response) {
2586                 response = 603;
2587         }
2588
2589         /* The media sessions need to exist for the lifetime of the underlying channel
2590          * to ensure that anything (such as bridge_native_rtp) has access to them as
2591          * appropriate. Since ast_sip_session_terminate is called by chan_pjsip and other
2592          * places when the session is to be terminated we terminate any existing
2593          * media sessions here.
2594          */
2595         SWAP(session->active_media_state, session->pending_media_state);
2596         ast_sip_session_media_state_reset(session->pending_media_state);
2597
2598         switch (session->inv_session->state) {
2599         case PJSIP_INV_STATE_NULL:
2600                 if (!session->inv_session->invite_tsx) {
2601                         /*
2602                          * Normally, it's pjproject's transaction cleanup that ultimately causes the
2603                          * final session reference to be released but if both STATE and invite_tsx are NULL,
2604                          * we never created a transaction in the first place.  In this case, we need to
2605                          * do the cleanup ourselves.
2606                          */
2607                         /* Transfer the inv_session session reference to the session_end_task */
2608                         session->inv_session->mod_data[session_module.id] = NULL;
2609                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2610                         session_end(session);
2611                         /*
2612                          * session_end_completion will cleanup the final session reference unless
2613                          * ast_sip_session_terminate's caller is holding one.
2614                          */
2615                         session_end_completion(session);
2616                 } else {
2617                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2618                 }
2619                 break;
2620         case PJSIP_INV_STATE_CONFIRMED:
2621                 if (session->inv_session->invite_tsx) {
2622                         ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
2623                                         ast_sorcery_object_get_id(session->endpoint));
2624                         /* If this is delayed the only thing that will happen is a BYE request so we don't
2625                          * actually need to store the response code for when it happens.
2626                          */
2627                         delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE, NULL);
2628                         break;
2629                 }
2630                 /* Fall through */
2631         default:
2632                 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
2633                 if (status == PJ_SUCCESS && packet) {
2634                         struct ast_sip_session_delayed_request *delay;
2635
2636                         /* Flush any delayed requests so they cannot overlap this transaction. */
2637                         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2638                                 delayed_request_free(delay);
2639                         }
2640
2641                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
2642                                 ast_sip_session_send_response(session, packet);
2643                         } else {
2644                                 ast_sip_session_send_request(session, packet);
2645                         }
2646                 }
2647                 break;
2648         }
2649 }
2650
2651 static int session_termination_task(void *data)
2652 {
2653         struct ast_sip_session *session = data;
2654
2655         if (session->defer_terminate) {
2656                 session->defer_terminate = 0;
2657                 if (session->inv_session) {
2658                         ast_sip_session_terminate(session, 0);
2659                 }
2660         }
2661
2662         ao2_ref(session, -1);
2663         return 0;
2664 }
2665
2666 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
2667 {
2668         struct ast_sip_session *session = entry->user_data;
2669
2670         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
2671                 ao2_cleanup(session);
2672         }
2673 }
2674
2675 int ast_sip_session_defer_termination(struct ast_sip_session *session)
2676 {
2677         pj_time_val delay = { .sec = 60, };
2678         int res;
2679
2680         /* The session should not have an active deferred termination request. */
2681         ast_assert(!session->defer_terminate);
2682
2683         session->defer_terminate = 1;
2684
2685         session->defer_end = 1;
2686         session->ended_while_deferred = 0;
2687
2688         session->scheduled_termination.id = 0;
2689         ao2_ref(session, +1);
2690         session->scheduled_termination.user_data = session;
2691         session->scheduled_termination.cb = session_termination_cb;
2692
2693         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2694                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
2695         if (res) {
2696                 session->defer_terminate = 0;
2697                 ao2_ref(session, -1);
2698         }
2699         return res;
2700 }
2701
2702 /*!
2703  * \internal
2704  * \brief Stop the defer termination timer if it is still running.
2705  * \since 13.5.0
2706  *
2707  * \param session Which session to stop the timer.
2708  *
2709  * \return Nothing
2710  */
2711 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
2712 {
2713         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
2714                 &session->scheduled_termination)) {
2715                 ao2_ref(session, -1);
2716         }
2717 }
2718
2719 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
2720 {
2721         if (!session->defer_terminate) {
2722                 /* Already canceled or timer fired. */
2723                 return;
2724         }
2725
2726         session->defer_terminate = 0;
2727
2728         if (session->terminate_while_deferred) {
2729                 /* Complete the termination started by the upper layer. */
2730                 ast_sip_session_terminate(session, 0);
2731         }
2732
2733         /* Stop the termination timer if it is still running. */
2734         sip_session_defer_termination_stop_timer(session);
2735 }
2736
2737 void ast_sip_session_end_if_deferred(struct ast_sip_session *session)
2738 {
2739         if (!session->defer_end) {
2740                 return;
2741         }
2742
2743         session->defer_end = 0;
2744
2745         if (session->ended_while_deferred) {
2746                 /* Complete the session end started by the remote hangup. */
2747                 ast_debug(3, "Ending session (%p) after being deferred\n", session);
2748                 session->ended_while_deferred = 0;
2749                 session_end(session);
2750         }
2751 }
2752
2753 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
2754 {
2755         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
2756         struct ast_sip_session *session;
2757
2758         if (!inv_session ||
2759                 !(session = inv_session->mod_data[session_module.id])) {
2760                 return NULL;
2761         }
2762
2763         ao2_ref(session, +1);
2764
2765         return session;
2766 }
2767
2768 enum sip_get_destination_result {
2769         /*! The extension was successfully found */
2770         SIP_GET_DEST_EXTEN_FOUND,
2771         /*! The extension specified in the RURI was not found */
2772         SIP_GET_DEST_EXTEN_NOT_FOUND,
2773         /*! The extension specified in the RURI was a partial match */
2774         SIP_GET_DEST_EXTEN_PARTIAL,
2775         /*! The RURI is of an unsupported scheme */
2776         SIP_GET_DEST_UNSUPPORTED_URI,
2777 };
2778
2779 /*!
2780  * \brief Determine where in the dialplan a call should go
2781  *
2782  * This uses the username in the request URI to try to match
2783  * an extension in the endpoint's configured context in order
2784  * to route the call.
2785  *
2786  * \param session The inbound SIP session
2787  * \param rdata The SIP INVITE
2788  */
2789 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
2790 {
2791         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
2792         pjsip_sip_uri *sip_ruri;
2793         struct ast_features_pickup_config *pickup_cfg;
2794         const char *pickupexten;
2795
2796         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
2797                 return SIP_GET_DEST_UNSUPPORTED_URI;
2798         }
2799
2800         sip_ruri = pjsip_uri_get_uri(ruri);
2801         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
2802
2803         /*
2804          * We may want to match in the dialplan without any user
2805          * options getting in the way.
2806          */
2807         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);
2808
2809         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2810         if (!pickup_cfg) {
2811                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
2812                 pickupexten = "";
2813         } else {
2814                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
2815                 ao2_ref(pickup_cfg, -1);
2816         }
2817
2818         if (!strcmp(session->exten, pickupexten) ||
2819                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
2820                 size_t size = pj_strlen(&sip_ruri->host) + 1;
2821                 char *domain = ast_alloca(size);
2822
2823                 ast_copy_pj_str(domain, &sip_ruri->host, size);
2824                 pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);
2825
2826                 /*
2827                  * Save off the INVITE Request-URI in case it is
2828                  * needed: CHANNEL(pjsip,request_uri)
2829                  */
2830                 session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);
2831
2832                 return SIP_GET_DEST_EXTEN_FOUND;
2833         }
2834
2835         /*
2836          * Check for partial match via overlap dialling (if enabled)
2837          */
2838         if (session->endpoint->allow_overlap && (
2839                 !strncmp(session->exten, pickupexten, strlen(session->exten)) ||
2840                 ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {
2841                 /* Overlap partial match */
2842                 return SIP_GET_DEST_EXTEN_PARTIAL;
2843         }
2844
2845         return SIP_GET_DEST_EXTEN_NOT_FOUND;
2846 }
2847
2848 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
2849 {
2850         pjsip_tx_data *tdata;
2851         pjsip_dialog *dlg;
2852         pjsip_inv_session *inv_session;
2853         unsigned int options = endpoint->extensions.flags;
2854         pj_status_t dlg_status;
2855
2856         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
2857                 if (tdata) {
2858                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
2859                 } else {
2860                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2861                 }
2862                 return NULL;
2863         }
2864         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
2865         if (!dlg) {
2866                 if (dlg_status != PJ_EEXISTS) {
2867                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2868                 }
2869                 return NULL;
2870         }
2871         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
2872                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2873                 pjsip_dlg_terminate(dlg);
2874                 return NULL;
2875         }
2876
2877 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2878         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2879 #endif
2880         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2881                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
2882                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2883                 }
2884                 pjsip_inv_send_msg(inv_session, tdata);
2885                 return NULL;
2886         }
2887         return inv_session;
2888 }
2889
2890 struct new_invite {
2891         /*! \brief Session created for the new INVITE */
2892         struct ast_sip_session *session;
2893
2894         /*! \brief INVITE request itself */
2895         pjsip_rx_data *rdata;
2896 };
2897
2898 static int new_invite(struct new_invite *invite)
2899 {
2900         pjsip_tx_data *tdata = NULL;
2901         pjsip_timer_setting timer;
2902         pjsip_rdata_sdp_info *sdp_info;
2903         pjmedia_sdp_session *local = NULL;
2904
2905         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
2906          * so that we will be notified so we can destroy the session properly
2907          */
2908
2909         if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2910                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2911                         invite->session->inv_session->cause,
2912                         pjsip_get_status_text(invite->session->inv_session->cause)->ptr);
2913 #ifdef HAVE_PJSIP_INV_SESSION_REF
2914                 pjsip_inv_dec_ref(invite->session->inv_session);
2915 #endif
2916                 return -1;
2917         }
2918
2919         switch (get_destination(invite->session, invite->rdata)) {
2920         case SIP_GET_DEST_EXTEN_FOUND:
2921                 /* Things worked. Keep going */
2922                 break;
2923         case SIP_GET_DEST_UNSUPPORTED_URI:
2924                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
2925                         ast_sip_session_send_response(invite->session, tdata);
2926                 } else  {
2927                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
2928                 }
2929                 goto end;
2930         case SIP_GET_DEST_EXTEN_PARTIAL:
2931                 ast_debug(1, "Call from '%s' (%s:%s:%d) to extension '%s' - partial match\n", ast_sorcery_object_get_id(invite->session->endpoint),
2932                         invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name, invite->rdata->pkt_info.src_port, invite->session->exten);
2933
2934                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {
2935                         ast_sip_session_send_response(invite->session, tdata);
2936                 } else  {
2937                         pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);
2938                 }
2939                 goto end;
2940         case SIP_GET_DEST_EXTEN_NOT_FOUND:
2941         default:
2942                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
2943                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
2944                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
2945
2946                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
2947                         ast_sip_session_send_response(invite->session, tdata);
2948                 } else  {
2949                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
2950                 }
2951                 goto end;
2952         };
2953
2954         pjsip_timer_setting_default(&timer);
2955         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
2956         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
2957         pjsip_timer_init_session(invite->session->inv_session, &timer);
2958
2959         /*
2960          * At this point, we've verified what we can that won't take awhile,
2961          * so let's go ahead and send a 100 Trying out to stop any
2962          * retransmissions.
2963          */
2964         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
2965                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
2966                 goto end;
2967         }
2968         ast_sip_session_send_response(invite->session, tdata);
2969
2970         sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);
2971         if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
2972                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
2973                         tdata = NULL;
2974                         if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS
2975                                 && tdata) {
2976                                 ast_sip_session_send_response(invite->session, tdata);
2977                         }
2978                         goto end;
2979                 }
2980                 /* We are creating a local SDP which is an answer to their offer */
2981                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
2982         } else {
2983                 /* We are creating a local SDP which is an offer */
2984                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
2985         }
2986
2987         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
2988         if (!local) {
2989                 tdata = NULL;
2990                 if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS
2991                         && tdata) {
2992                         ast_sip_session_send_response(invite->session, tdata);
2993                 }
2994                 goto end;
2995         }
2996
2997         pjsip_inv_set_local_sdp(invite->session->inv_session, local);
2998         pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
2999 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
3000         if (!invite->session->endpoint->preferred_codec_only) {
3001                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
3002         }
3003 #endif
3004
3005         handle_incoming_request(invite->session, invite->rdata);
3006
3007 end:
3008 #ifdef HAVE_PJSIP_INV_SESSION_REF
3009         pjsip_inv_dec_ref(invite->session->inv_session);
3010 #endif
3011         return 0;
3012 }
3013
3014 static void handle_new_invite_request(pjsip_rx_data *rdata)
3015 {
3016         RAII_VAR(struct ast_sip_endpoint *, endpoint,
3017                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
3018         pjsip_tx_data *tdata = NULL;
3019         pjsip_inv_session *inv_session = NULL;
3020         struct ast_sip_session *session;
3021         struct new_invite invite;
3022
3023         ast_assert(endpoint != NULL);
3024
3025         inv_session = pre_session_setup(rdata, endpoint);
3026         if (!inv_session) {
3027                 /* pre_session_setup() returns a response on failure */
3028                 return;
3029         }
3030
3031 #ifdef HAVE_PJSIP_INV_SESSION_REF
3032         if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {
3033                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
3034                 if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {
3035                         if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
3036                                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3037                         } else {
3038                                 pjsip_inv_send_msg(inv_session, tdata);
3039                         }
3040                 }
3041                 return;
3042         }
3043 #endif
3044
3045         session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);
3046         if (!session) {
3047                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
3048                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3049                 } else {
3050                         pjsip_inv_send_msg(inv_session, tdata);
3051                 }
3052 #ifdef HAVE_PJSIP_INV_SESSION_REF
3053                 pjsip_inv_dec_ref(inv_session);
3054 #endif
3055                 return;
3056         }
3057
3058         /*
3059          * The current thread is supposed be the session serializer to prevent
3060          * any initial INVITE retransmissions from trying to setup the same
3061          * call again.
3062          */
3063         ast_assert(ast_taskprocessor_is_task(session->serializer));
3064
3065         invite.session = session;
3066         invite.rdata = rdata;
3067         new_invite(&invite);
3068
3069         ao2_ref(session, -1);
3070 }
3071
3072 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
3073 {
3074         pj_str_t method;
3075
3076         if (ast_strlen_zero(supplement_method)) {
3077                 return PJ_TRUE;
3078         }
3079
3080         pj_cstr(&method, supplement_method);
3081
3082         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
3083 }
3084
3085 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
3086 {
3087         struct ast_sip_session_supplement *supplement;
3088         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
3089
3090         if (!session) {
3091                 return PJ_FALSE;
3092         }
3093
3094         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3095                 if (does_method_match(&method->name, supplement->method)) {
3096                         return PJ_TRUE;
3097                 }
3098         }
3099         return PJ_FALSE;
3100 }
3101 /*!
3102  * \brief Called when a new SIP request comes into PJSIP
3103  *
3104  * This function is called under two circumstances
3105  * 1) An out-of-dialog request is received by PJSIP