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