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