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