res_pjsip_notify: improve realtime performance on CLI completion on the endpoint
[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_name_addr *dlg_info_name_addr;
1408         pjsip_sip_uri *dlg_info_uri;
1409         int restricted;
1410
1411         if (!session->channel || session->saved_from_hdr) {
1412                 return;
1413         }
1414
1415         /* We need to save off connected_id for RPID/PAI generation */
1416         ast_party_id_init(&connected_id);
1417         ast_channel_lock(session->channel);
1418         effective_id = ast_channel_connected_effective_id(session->channel);
1419         ast_party_id_copy(&connected_id, &effective_id);
1420         ast_channel_unlock(session->channel);
1421
1422         restricted =
1423                 ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);
1424
1425         /* Now set up dlg->local.info so pjsip can correctly generate From */
1426
1427         dlg_pool = session->inv_session->dlg->pool;
1428         dlg_info = session->inv_session->dlg->local.info;
1429         dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;
1430         dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);
1431
1432         if (session->endpoint->id.trust_outbound || !restricted) {
1433                 ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);
1434         }
1435
1436         ast_party_id_free(&connected_id);
1437
1438         if (!ast_strlen_zero(session->endpoint->fromuser)) {
1439                 dlg_info_name_addr->display.ptr = NULL;
1440                 dlg_info_name_addr->display.slen = 0;
1441                 pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);
1442         }
1443
1444         if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1445                 pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);
1446         }
1447
1448         /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */
1449         session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);
1450         ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);
1451
1452         /* In chan_sip, fromuser and fromdomain trump restricted so we only
1453          * anonymize if they're not set.
1454          */
1455         if (restricted) {
1456                 /* fromuser doesn't provide a display name so we always set it */
1457                 pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");
1458
1459                 if (ast_strlen_zero(session->endpoint->fromuser)) {
1460                         pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");
1461                 }
1462
1463                 if (ast_strlen_zero(session->endpoint->fromdomain)) {
1464                         pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");
1465                 }
1466         } else {
1467                 ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);
1468     }
1469 }
1470
1471 int ast_sip_session_refresh(struct ast_sip_session *session,
1472                 ast_sip_session_request_creation_cb on_request_creation,
1473                 ast_sip_session_sdp_creation_cb on_sdp_creation,
1474                 ast_sip_session_response_cb on_response,
1475                 enum ast_sip_session_refresh_method method, int generate_new_sdp,
1476                 struct ast_sip_session_media_state *media_state)
1477 {
1478         pjsip_inv_session *inv_session = session->inv_session;
1479         pjmedia_sdp_session *new_sdp = NULL;
1480         pjsip_tx_data *tdata;
1481
1482         if (media_state && (!media_state->topology || !generate_new_sdp)) {
1483                 ast_sip_session_media_state_free(media_state);
1484                 return -1;
1485         }
1486
1487         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1488                 /* Don't try to do anything with a hung-up call */
1489                 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
1490                                 ast_sorcery_object_get_id(session->endpoint));
1491                 ast_sip_session_media_state_free(media_state);
1492                 return 0;
1493         }
1494
1495         /* If the dialog has not yet been established we have to defer until it has */
1496         if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1497                 ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
1498                         ast_sorcery_object_get_id(session->endpoint));
1499                 return delay_request(session, on_request_creation, on_sdp_creation, on_response,
1500                         generate_new_sdp,
1501                         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1502                                 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE,
1503                         media_state);
1504         }
1505
1506         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1507                 if (inv_session->invite_tsx) {
1508                         /* We can't send a reinvite yet, so delay it */
1509                         ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
1510                                         ast_sorcery_object_get_id(session->endpoint));
1511                         return delay_request(session, on_request_creation, on_sdp_creation,
1512                                 on_response, generate_new_sdp, DELAYED_METHOD_INVITE, media_state);
1513                 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
1514                         /* Initial INVITE transaction failed to progress us to a confirmed state
1515                          * which means re-invites are not possible
1516                          */
1517                         ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
1518                                         ast_sorcery_object_get_id(session->endpoint));
1519                         ast_sip_session_media_state_free(media_state);
1520                         return 0;
1521                 }
1522         }
1523
1524         if (generate_new_sdp) {
1525                 /* SDP can only be generated if current negotiation has already completed */
1526                 if (inv_session->neg
1527                         && pjmedia_sdp_neg_get_state(inv_session->neg)
1528                                 != PJMEDIA_SDP_NEG_STATE_DONE) {
1529                         ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
1530                                 ast_sorcery_object_get_id(session->endpoint));
1531                         return delay_request(session, on_request_creation, on_sdp_creation,
1532                                 on_response, generate_new_sdp,
1533                                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
1534                                         ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE, media_state);
1535                 }
1536
1537                 /* If an explicitly requested media state has been provided use it instead of any pending one */
1538                 if (media_state) {
1539                         int index;
1540                         int type_streams[AST_MEDIA_TYPE_END] = {0};
1541                         struct ast_stream *stream;
1542
1543                         /* Prune the media state so the number of streams fit within the configured limits - we do it here
1544                          * so that the index of the resulting streams in the SDP match. If we simply left the streams out
1545                          * of the SDP when producing it we'd be in trouble. We also enforce formats here for media types that
1546                          * are configurable on the endpoint.
1547                          */
1548                         for (index = 0; index < ast_stream_topology_get_count(media_state->topology); ++index) {
1549                                 struct ast_stream *existing_stream = NULL;
1550
1551                                 stream = ast_stream_topology_get_stream(media_state->topology, index);
1552
1553                                 if (session->active_media_state->topology &&
1554                                         index < ast_stream_topology_get_count(session->active_media_state->topology)) {
1555                                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1556                                 }
1557
1558                                 if (is_stream_limitation_reached(ast_stream_get_type(stream), session->endpoint, type_streams)) {
1559                                         if (index < AST_VECTOR_SIZE(&media_state->sessions)) {
1560                                                 struct ast_sip_session_media *session_media = AST_VECTOR_GET(&media_state->sessions, index);
1561
1562                                                 ao2_cleanup(session_media);
1563                                                 AST_VECTOR_REMOVE(&media_state->sessions, index, 1);
1564                                         }
1565
1566                                         ast_stream_topology_del_stream(media_state->topology, index);
1567
1568                                         /* A stream has potentially moved into our spot so we need to jump back so we process it */
1569                                         index -= 1;
1570                                         continue;
1571                                 }
1572
1573                                 /* No need to do anything with stream if it's media state is removed */
1574                                 if (ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
1575                                         /* If there is no existing stream we can just not have this stream in the topology at all. */
1576                                         if (!existing_stream) {
1577                                                 ast_stream_topology_del_stream(media_state->topology, index);
1578                                                 index -= 1;
1579                                         }
1580                                         continue;
1581                                 }
1582
1583                                 /* Enforce the configured allowed codecs on audio and video streams */
1584                                 if (ast_stream_get_type(stream) == AST_MEDIA_TYPE_AUDIO || ast_stream_get_type(stream) == AST_MEDIA_TYPE_VIDEO) {
1585                                         struct ast_format_cap *joint_cap;
1586
1587                                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1588                                         if (!joint_cap) {
1589                                                 ast_sip_session_media_state_free(media_state);
1590                                                 return 0;
1591                                         }
1592                                         ast_format_cap_get_compatible(ast_stream_get_formats(stream), session->endpoint->media.codecs, joint_cap);
1593                                         if (!ast_format_cap_count(joint_cap)) {
1594                                                 ao2_ref(joint_cap, -1);
1595
1596                                                 if (!existing_stream) {
1597                                                         /* If there is no existing stream we can just not have this stream in the topology
1598                                                          * at all.
1599                                                          */
1600                                                         ast_stream_topology_del_stream(media_state->topology, index);
1601                                                         index -= 1;
1602                                                         continue;
1603                                                 } else if (ast_stream_get_state(stream) != ast_stream_get_state(existing_stream) ||
1604                                                                 strcmp(ast_stream_get_name(stream), ast_stream_get_name(existing_stream))) {
1605                                                         /* If the underlying stream is a different type or different name then we have to
1606                                                          * mark it as removed, as it is replacing an existing stream. We do this so order
1607                                                          * is preserved.
1608                                                          */
1609                                                         ast_stream_set_state(stream, AST_STREAM_STATE_REMOVED);
1610                                                         continue;
1611                                                 } else {
1612                                                         /* However if the stream is otherwise remaining the same we can keep the formats
1613                                                          * that exist on it already which allows media to continue to flow.
1614                                                          */
1615                                                         joint_cap = ao2_bump(ast_stream_get_formats(existing_stream));
1616                                                 }
1617                                         }
1618                                         ast_stream_set_formats(stream, joint_cap);
1619                                         ao2_cleanup(joint_cap);
1620                                 }
1621
1622                                 ++type_streams[ast_stream_get_type(stream)];
1623                         }
1624
1625                         if (session->active_media_state->topology) {
1626                                 /* SDP is a fun thing. Take for example the fact that streams are never removed. They just become
1627                                  * declined. To better handle this in the case where something requests a topology change for fewer
1628                                  * streams than are currently present we fill in the topology to match the current number of streams
1629                                  * that are active.
1630                                  */
1631                                 for (index = ast_stream_topology_get_count(media_state->topology);
1632                                         index < ast_stream_topology_get_count(session->active_media_state->topology); ++index) {
1633                                         struct ast_stream *cloned;
1634
1635                                         stream = ast_stream_topology_get_stream(session->active_media_state->topology, index);
1636                                         ast_assert(stream != NULL);
1637
1638                                         cloned = ast_stream_clone(stream, NULL);
1639                                         if (!cloned) {
1640                                                 ast_sip_session_media_state_free(media_state);
1641                                                 return -1;
1642                                         }
1643
1644                                         ast_stream_set_state(cloned, AST_STREAM_STATE_REMOVED);
1645                                         if (ast_stream_topology_append_stream(media_state->topology, cloned) < 0) {
1646                                                 ast_stream_free(cloned);
1647                                                 ast_sip_session_media_state_free(media_state);
1648                                                 return -1;
1649                                         }
1650                                 }
1651
1652                                 /* If the resulting media state matches the existing active state don't bother doing a session refresh */
1653                                 if (ast_stream_topology_equal(session->active_media_state->topology, media_state->topology)) {
1654                                         ast_sip_session_media_state_free(media_state);
1655                                         return 0;
1656                                 }
1657                         }
1658
1659                         ast_sip_session_media_state_free(session->pending_media_state);
1660                         session->pending_media_state = media_state;
1661                 }
1662
1663                 new_sdp = generate_session_refresh_sdp(session);
1664                 if (!new_sdp) {
1665                         ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
1666                         ast_sip_session_media_state_reset(session->pending_media_state);
1667                         return -1;
1668                 }
1669                 if (on_sdp_creation) {
1670                         if (on_sdp_creation(session, new_sdp)) {
1671                                 ast_sip_session_media_state_reset(session->pending_media_state);
1672                                 return -1;
1673                         }
1674                 }
1675         }
1676
1677         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
1678                 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
1679                         ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
1680                         if (generate_new_sdp) {
1681                                 ast_sip_session_media_state_reset(session->pending_media_state);
1682                         }
1683                         return -1;
1684                 }
1685         } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
1686                 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
1687                 if (generate_new_sdp) {
1688                         ast_sip_session_media_state_reset(session->pending_media_state);
1689                 }
1690                 return -1;
1691         }
1692         if (on_request_creation) {
1693                 if (on_request_creation(session, tdata)) {
1694                         if (generate_new_sdp) {
1695                                 ast_sip_session_media_state_reset(session->pending_media_state);
1696                         }
1697                         return -1;
1698                 }
1699         }
1700         ast_debug(3, "Sending session refresh SDP via %s to %s\n",
1701                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
1702                 ast_sorcery_object_get_id(session->endpoint));
1703         ast_sip_session_send_request_with_cb(session, tdata, on_response);
1704         return 0;
1705 }
1706
1707 int ast_sip_session_regenerate_answer(struct ast_sip_session *session,
1708                 ast_sip_session_sdp_creation_cb on_sdp_creation)
1709 {
1710         pjsip_inv_session *inv_session = session->inv_session;
1711         pjmedia_sdp_session *new_answer = NULL;
1712         const pjmedia_sdp_session *previous_offer = NULL;
1713
1714         /* The SDP answer can only be regenerated if it is still pending to be sent */
1715         if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
1716                 pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {
1717                 ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",
1718                         ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));
1719                 return -1;
1720         }
1721
1722         pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);
1723         if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {
1724                 /* Transition the SDP negotiator back to when it received the remote offer */
1725                 pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);
1726                 pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);
1727         }
1728
1729         new_answer = create_local_sdp(inv_session, session, previous_offer);
1730         if (!new_answer) {
1731                 ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",
1732                         ast_channel_name(session->channel));
1733                 return -1;
1734         }
1735
1736         if (on_sdp_creation) {
1737                 if (on_sdp_creation(session, new_answer)) {
1738                         return -1;
1739                 }
1740         }
1741
1742         pjsip_inv_set_sdp_answer(inv_session, new_answer);
1743
1744         return 0;
1745 }
1746
1747 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1748 {
1749         handle_outgoing_response(session, tdata);
1750         pjsip_inv_send_msg(session->inv_session, tdata);
1751         return;
1752 }
1753
1754 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
1755
1756 static pjsip_module session_module = {
1757         .name = {"Session Module", 14},
1758         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1759         .on_rx_request = session_on_rx_request,
1760 };
1761
1762 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
1763  *
1764  * \retval 1 re-invite should be deferred and resumed later
1765  * \retval 0 re-invite should not be deferred
1766  */
1767 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
1768 {
1769         int i;
1770
1771         if (!session->pending_media_state->topology) {
1772                 session->pending_media_state->topology = ast_stream_topology_alloc();
1773                 if (!session->pending_media_state->topology) {
1774                         return -1;
1775                 }
1776         }
1777
1778         for (i = 0; i < sdp->media_count; ++i) {
1779                 /* See if there are registered handlers for this media stream type */
1780                 char media[20];
1781                 struct ast_sip_session_sdp_handler *handler;
1782                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1783                 struct ast_stream *existing_stream = NULL;
1784                 struct ast_stream *stream;
1785                 enum ast_media_type type;
1786                 struct ast_sip_session_media *session_media = NULL;
1787                 enum ast_sip_session_sdp_stream_defer res;
1788
1789                 /* We need a null-terminated version of the media string */
1790                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
1791
1792                 if (session->active_media_state->topology &&
1793                         (i < ast_stream_topology_get_count(session->active_media_state->topology))) {
1794                         existing_stream = ast_stream_topology_get_stream(session->active_media_state->topology, i);
1795                 }
1796
1797                 type = ast_media_type_from_str(media);
1798                 stream = ast_stream_alloc(existing_stream ? ast_stream_get_name(existing_stream) : ast_codec_media_type2str(type), type);
1799                 if (!stream) {
1800                         return -1;
1801                 }
1802
1803                 /* As this is only called on an incoming SDP offer before processing it is not possible
1804                  * for streams and their media sessions to exist.
1805                  */
1806                 if (ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream)) {
1807                         ast_stream_free(stream);
1808                         return -1;
1809                 }
1810
1811                 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
1812                 if (!session_media) {
1813                         return -1;
1814                 }
1815
1816                 if (session_media->handler) {
1817                         handler = session_media->handler;
1818                         if (handler->defer_incoming_sdp_stream) {
1819                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1820                                         sdp->media[i]);
1821                                 switch (res) {
1822                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1823                                         break;
1824                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
1825                                         return 0;
1826                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1827                                         break;
1828                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1829                                         return 1;
1830                                 }
1831                         }
1832                         /* Handled by this handler. Move to the next stream */
1833                         continue;
1834                 }
1835
1836                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1837                 if (!handler_list) {
1838                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
1839                         continue;
1840                 }
1841                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1842                         if (handler == session_media->handler) {
1843                                 continue;
1844                         }
1845                         if (!handler->defer_incoming_sdp_stream) {
1846                                 continue;
1847                         }
1848                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1849                                 sdp->media[i]);
1850                         switch (res) {
1851                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1852                                 continue;
1853                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
1854                                 session_media_set_handler(session_media, handler);
1855                                 return 0;
1856                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1857                                 /* Handled by this handler. */
1858                                 session_media_set_handler(session_media, handler);
1859                                 break;
1860                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1861                                 /* Handled by this handler. */
1862                                 session_media_set_handler(session_media, handler);
1863                                 return 1;
1864                         }
1865                         /* Move to the next stream */
1866                         break;
1867                 }
1868         }
1869         return 0;
1870 }
1871
1872 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
1873 {
1874         pjsip_dialog *dlg;
1875         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1876         pjsip_rdata_sdp_info *sdp_info;
1877
1878         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
1879                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
1880                 !(session = ast_sip_dialog_get_session(dlg)) ||
1881                 !session->channel) {
1882                 return PJ_FALSE;
1883         }
1884
1885         if (session->deferred_reinvite) {
1886                 pj_str_t key, deferred_key;
1887                 pjsip_tx_data *tdata;
1888
1889                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1890                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1891                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1892                         session->deferred_reinvite);
1893
1894                 /* If this is a retransmission ignore it */
1895                 if (!pj_strcmp(&key, &deferred_key)) {
1896                         return PJ_TRUE;
1897                 }
1898
1899                 /* Otherwise this is a new re-invite, so reject it */
1900                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1901                         if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
1902                                 pjsip_tx_data_dec_ref(tdata);
1903                         }
1904                 }
1905
1906                 return PJ_TRUE;
1907         }
1908
1909         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1910                 (sdp_info->sdp_err != PJ_SUCCESS)) {
1911                 return PJ_FALSE;
1912         }
1913
1914         if (!sdp_info->sdp) {
1915                 const pjmedia_sdp_session *local;
1916                 int i;
1917
1918                 ast_queue_unhold(session->channel);
1919
1920                 pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);
1921                 if (!local) {
1922                         return PJ_FALSE;
1923                 }
1924
1925                 /*
1926                  * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).
1927                  * When hold is initially indicated, we
1928                  * - Receive an INVITE with no SDP
1929                  * - Send a 200 OK with SDP, indicating sendrecv in the media streams
1930                  * - Receive an ACK with SDP, indicating sendonly in the media streams
1931                  *
1932                  * At this point, the pjmedia negotiator saves the state of the media direction so that
1933                  * if we are to send any offers, we'll offer recvonly in the media streams. This is
1934                  * problematic if the device is attempting to unhold, though. If the device unholds
1935                  * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.
1936                  * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond
1937                  * with sendonly or inactive. The result of this is that the stream is not off hold.
1938                  *
1939                  * Therefore, in this case, when we receive a reinvite while the stream is on hold, we
1940                  * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv
1941                  * in order to get the stream off hold. If this is actually a different purpose reinvite
1942                  * (like a session timer refresh), then the answerer can respond to our sendrecv with
1943                  * sendonly, keeping the stream on hold.
1944                  */
1945                 for (i = 0; i < local->media_count; ++i) {
1946                         pjmedia_sdp_media *m = local->media[i];
1947                         pjmedia_sdp_attr *recvonly;
1948                         pjmedia_sdp_attr *inactive;
1949
1950                         recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);
1951                         inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);
1952                         if (recvonly || inactive) {
1953                                 pjmedia_sdp_attr *to_remove = recvonly ?: inactive;
1954                                 pjmedia_sdp_attr *sendrecv;
1955
1956                                 pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);
1957
1958                                 sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);
1959                                 pjmedia_sdp_media_add_attr(m, sendrecv);
1960                         }
1961                 }
1962
1963                 return PJ_FALSE;
1964         }
1965
1966         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1967                 return PJ_FALSE;
1968         }
1969
1970         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1971
1972         return PJ_TRUE;
1973 }
1974
1975 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1976 {
1977         if (!session->deferred_reinvite) {
1978                 return;
1979         }
1980
1981         if (session->channel) {
1982                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1983                         session->deferred_reinvite, NULL, NULL);
1984         }
1985         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1986         session->deferred_reinvite = NULL;
1987 }
1988
1989 static pjsip_module session_reinvite_module = {
1990         .name = { "Session Re-Invite Module", 24 },
1991         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1992         .on_rx_request = session_reinvite_on_rx_request,
1993 };
1994
1995
1996 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1997                 ast_sip_session_response_cb on_response)
1998 {
1999         pjsip_inv_session *inv_session = session->inv_session;
2000
2001         /* For every request except BYE we disallow sending of the message when
2002          * the session has been disconnected. A BYE request is special though
2003          * because it can be sent again after the session is disconnected except
2004          * with credentials.
2005          */
2006         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&
2007                 tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {
2008                 return;
2009         }
2010
2011         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
2012                              MOD_DATA_ON_RESPONSE, on_response);
2013
2014         handle_outgoing_request(session, tdata);
2015         pjsip_inv_send_msg(session->inv_session, tdata);
2016
2017         return;
2018 }
2019
2020 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2021 {
2022         ast_sip_session_send_request_with_cb(session, tdata, NULL);
2023 }
2024
2025 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
2026 {
2027         pjmedia_sdp_session *offer;
2028
2029         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
2030                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
2031                 return -1;
2032         }
2033
2034         pjsip_inv_set_local_sdp(session->inv_session, offer);
2035         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
2036 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2037         if (!session->endpoint->preferred_codec_only) {
2038                 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
2039         }
2040 #endif
2041
2042         /*
2043          * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the
2044          * From in the initial INVITE will be wrong but the rest of the messages will be OK.
2045          */
2046         set_from_header(session);
2047
2048         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
2049                 return -1;
2050         }
2051
2052         return 0;
2053 }
2054
2055 static int datastore_hash(const void *obj, int flags)
2056 {
2057         const struct ast_datastore *datastore = obj;
2058         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
2059
2060         ast_assert(uid != NULL);
2061
2062         return ast_str_hash(uid);
2063 }
2064
2065 static int datastore_cmp(void *obj, void *arg, int flags)
2066 {
2067         const struct ast_datastore *datastore1 = obj;
2068         const struct ast_datastore *datastore2 = arg;
2069         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
2070
2071         ast_assert(datastore1->uid != NULL);
2072         ast_assert(uid2 != NULL);
2073
2074         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
2075 }
2076
2077 static void session_destructor(void *obj)
2078 {
2079         struct ast_sip_session *session = obj;
2080         struct ast_sip_session_supplement *supplement;
2081         struct ast_sip_session_delayed_request *delay;
2082         const char *endpoint_name = session->endpoint ?
2083                 ast_sorcery_object_get_id(session->endpoint) : "<none>";
2084
2085         ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);
2086
2087         ast_test_suite_event_notify("SESSION_DESTROYING",
2088                 "Endpoint: %s\r\n"
2089                 "AOR: %s\r\n"
2090                 "Contact: %s"
2091                 , endpoint_name
2092                 , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"
2093                 , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"
2094                 );
2095
2096         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
2097                 if (supplement->session_destroy) {
2098                         supplement->session_destroy(session);
2099                 }
2100                 ast_free(supplement);
2101         }
2102
2103         ast_taskprocessor_unreference(session->serializer);
2104         ao2_cleanup(session->datastores);
2105         ast_sip_session_media_state_free(session->active_media_state);
2106         ast_sip_session_media_state_free(session->pending_media_state);
2107
2108         AST_LIST_HEAD_DESTROY(&session->supplements);
2109         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2110                 delayed_request_free(delay);
2111         }
2112         ast_party_id_free(&session->id);
2113         ao2_cleanup(session->endpoint);
2114         ao2_cleanup(session->aor);
2115         ao2_cleanup(session->contact);
2116         ao2_cleanup(session->direct_media_cap);
2117
2118         ast_dsp_free(session->dsp);
2119
2120         if (session->inv_session) {
2121                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
2122         }
2123
2124         ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);
2125 }
2126
2127 /*! \brief Destructor for SIP channel */
2128 static void sip_channel_destroy(void *obj)
2129 {
2130         struct ast_sip_channel_pvt *channel = obj;
2131
2132         ao2_cleanup(channel->pvt);
2133         ao2_cleanup(channel->session);
2134 }
2135
2136 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
2137 {
2138         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
2139
2140         if (!channel) {
2141                 return NULL;
2142         }
2143
2144         ao2_ref(pvt, +1);
2145         channel->pvt = pvt;
2146         ao2_ref(session, +1);
2147         channel->session = session;
2148
2149         return channel;
2150 }
2151
2152 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
2153         struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
2154 {
2155         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2156         struct ast_sip_session *ret_session;
2157         struct ast_sip_session_supplement *iter;
2158         int dsp_features = 0;
2159
2160         session = ao2_alloc(sizeof(*session), session_destructor);
2161         if (!session) {
2162                 return NULL;
2163         }
2164
2165         AST_LIST_HEAD_INIT(&session->supplements);
2166         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
2167         ast_party_id_init(&session->id);
2168
2169         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2170         if (!session->direct_media_cap) {
2171                 return NULL;
2172         }
2173         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
2174         if (!session->datastores) {
2175                 return NULL;
2176         }
2177         session->active_media_state = ast_sip_session_media_state_alloc();
2178         if (!session->active_media_state) {
2179                 return NULL;
2180         }
2181         session->pending_media_state = ast_sip_session_media_state_alloc();
2182         if (!session->pending_media_state) {
2183                 return NULL;
2184         }
2185
2186         if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {
2187                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
2188         }
2189         if (endpoint->faxdetect) {
2190                 dsp_features |= DSP_FEATURE_FAX_DETECT;
2191         }
2192         if (dsp_features) {
2193                 session->dsp = ast_dsp_new();
2194                 if (!session->dsp) {
2195                         return NULL;
2196                 }
2197
2198                 ast_dsp_set_features(session->dsp, dsp_features);
2199         }
2200
2201         session->endpoint = ao2_bump(endpoint);
2202
2203         if (rdata) {
2204                 /*
2205                  * We must continue using the serializer that the original
2206                  * INVITE came in on for the dialog.  There may be
2207                  * retransmissions already enqueued in the original
2208                  * serializer that can result in reentrancy and message
2209                  * sequencing problems.
2210                  */
2211                 session->serializer = ast_sip_get_distributor_serializer(rdata);
2212         } else {
2213                 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
2214
2215                 /* Create name with seq number appended. */
2216                 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
2217                         ast_sorcery_object_get_id(endpoint));
2218
2219                 session->serializer = ast_sip_create_serializer(tps_name);
2220         }
2221         if (!session->serializer) {
2222                 return NULL;
2223         }
2224         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
2225         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
2226         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
2227         inv_session->mod_data[session_module.id] = ao2_bump(session);
2228         session->contact = ao2_bump(contact);
2229         session->inv_session = inv_session;
2230
2231         session->dtmf = endpoint->dtmf;
2232
2233         if (ast_sip_session_add_supplements(session)) {
2234                 /* Release the ref held by session->inv_session */
2235                 ao2_ref(session, -1);
2236                 return NULL;
2237         }
2238         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2239                 if (iter->session_begin) {
2240                         iter->session_begin(session);
2241                 }
2242         }
2243
2244         /* Avoid unnecessary ref manipulation to return a session */
2245         ret_session = session;
2246         session = NULL;
2247         return ret_session;
2248 }
2249
2250 /*! \brief struct controlling the suspension of the session's serializer. */
2251 struct ast_sip_session_suspender {
2252         ast_cond_t cond_suspended;
2253         ast_cond_t cond_complete;
2254         int suspended;
2255         int complete;
2256 };
2257
2258 static void sip_session_suspender_dtor(void *vdoomed)
2259 {
2260         struct ast_sip_session_suspender *doomed = vdoomed;
2261
2262         ast_cond_destroy(&doomed->cond_suspended);
2263         ast_cond_destroy(&doomed->cond_complete);
2264 }
2265
2266 /*!
2267  * \internal
2268  * \brief Block the session serializer thread task.
2269  *
2270  * \param data Pushed serializer task data for suspension.
2271  *
2272  * \retval 0
2273  */
2274 static int sip_session_suspend_task(void *data)
2275 {
2276         struct ast_sip_session_suspender *suspender = data;
2277
2278         ao2_lock(suspender);
2279
2280         /* Signal that the serializer task is now suspended. */
2281         suspender->suspended = 1;
2282         ast_cond_signal(&suspender->cond_suspended);
2283
2284         /* Wait for the serializer suspension to be completed. */
2285         while (!suspender->complete) {
2286                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
2287         }
2288
2289         ao2_unlock(suspender);
2290         ao2_ref(suspender, -1);
2291
2292         return 0;
2293 }
2294
2295 void ast_sip_session_suspend(struct ast_sip_session *session)
2296 {
2297         struct ast_sip_session_suspender *suspender;
2298         int res;
2299
2300         ast_assert(session->suspended == NULL);
2301
2302         if (ast_taskprocessor_is_task(session->serializer)) {
2303                 /* I am the session's serializer thread so I cannot suspend. */
2304                 return;
2305         }
2306
2307         if (ast_taskprocessor_is_suspended(session->serializer)) {
2308                 /* The serializer already suspended. */
2309                 return;
2310         }
2311
2312         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
2313         if (!suspender) {
2314                 /* We will just have to hope that the system does not deadlock */
2315                 return;
2316         }
2317         ast_cond_init(&suspender->cond_suspended, NULL);
2318         ast_cond_init(&suspender->cond_complete, NULL);
2319
2320         ao2_ref(suspender, +1);
2321         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
2322         if (res) {
2323                 /* We will just have to hope that the system does not deadlock */
2324                 ao2_ref(suspender, -2);
2325                 return;
2326         }
2327
2328         session->suspended = suspender;
2329
2330         /* Wait for the serializer to get suspended. */
2331         ao2_lock(suspender);
2332         while (!suspender->suspended) {
2333                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
2334         }
2335         ao2_unlock(suspender);
2336
2337         ast_taskprocessor_suspend(session->serializer);
2338 }
2339
2340 void ast_sip_session_unsuspend(struct ast_sip_session *session)
2341 {
2342         struct ast_sip_session_suspender *suspender = session->suspended;
2343
2344         if (!suspender) {
2345                 /* Nothing to do */
2346                 return;
2347         }
2348         session->suspended = NULL;
2349
2350         /* Signal that the serializer task suspension is now complete. */
2351         ao2_lock(suspender);
2352         suspender->complete = 1;
2353         ast_cond_signal(&suspender->cond_complete);
2354         ao2_unlock(suspender);
2355
2356         ao2_ref(suspender, -1);
2357
2358         ast_taskprocessor_unsuspend(session->serializer);
2359 }
2360
2361 /*!
2362  * \internal
2363  * \brief Handle initial INVITE challenge response message.
2364  * \since 13.5.0
2365  *
2366  * \param rdata PJSIP receive response message data.
2367  *
2368  * \retval PJ_FALSE Did not handle message.
2369  * \retval PJ_TRUE Handled message.
2370  */
2371 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
2372 {
2373         pjsip_transaction *tsx;
2374         pjsip_dialog *dlg;
2375         pjsip_inv_session *inv;
2376         pjsip_tx_data *tdata;
2377         struct ast_sip_session *session;
2378
2379         if (rdata->msg_info.msg->line.status.code != 401
2380                 && rdata->msg_info.msg->line.status.code != 407) {
2381                 /* Doesn't pertain to us. Move on */
2382                 return PJ_FALSE;
2383         }
2384
2385         tsx = pjsip_rdata_get_tsx(rdata);
2386         dlg = pjsip_rdata_get_dlg(rdata);
2387         if (!dlg || !tsx) {
2388                 return PJ_FALSE;
2389         }
2390
2391         if (tsx->method.id != PJSIP_INVITE_METHOD) {
2392                 /* Not an INVITE that needs authentication */
2393                 return PJ_FALSE;
2394         }
2395
2396         inv = pjsip_dlg_get_inv_session(dlg);
2397         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
2398                 /*
2399                  * We cannot handle reINVITE authentication at this
2400                  * time because the reINVITE transaction is still in
2401                  * progress.
2402                  */
2403                 ast_debug(1, "A reINVITE is being challenged.\n");
2404                 return PJ_FALSE;
2405         }
2406         ast_debug(1, "Initial INVITE is being challenged.\n");
2407
2408         session = inv->mod_data[session_module.id];
2409
2410         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
2411                 tsx->last_tx, &tdata)) {
2412                 return PJ_FALSE;
2413         }
2414
2415         /*
2416          * Restart the outgoing initial INVITE transaction to deal
2417          * with authentication.
2418          */
2419         pjsip_inv_uac_restart(inv, PJ_FALSE);
2420
2421         ast_sip_session_send_request(session, tdata);
2422         return PJ_TRUE;
2423 }
2424
2425 static pjsip_module outbound_invite_auth_module = {
2426         .name = {"Outbound INVITE Auth", 20},
2427         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
2428         .on_rx_response = outbound_invite_auth,
2429 };
2430
2431 /*!
2432  * \internal
2433  * \brief Setup outbound initial INVITE authentication.
2434  * \since 13.5.0
2435  *
2436  * \param dlg PJSIP dialog to attach outbound authentication.
2437  *
2438  * \retval 0 on success.
2439  * \retval -1 on error.
2440  */
2441 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
2442 {
2443         pj_status_t status;
2444
2445         ++dlg->sess_count;
2446         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
2447         --dlg->sess_count;
2448
2449         return status != PJ_SUCCESS ? -1 : 0;
2450 }
2451
2452 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
2453         struct ast_sip_contact *contact, const char *location, const char *request_user,
2454         struct ast_stream_topology *req_topology)
2455 {
2456         const char *uri = NULL;
2457         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
2458         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
2459         pjsip_timer_setting timer;
2460         pjsip_dialog *dlg;
2461         struct pjsip_inv_session *inv_session;
2462         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2463         struct ast_sip_session *ret_session;
2464
2465         /* If no location has been provided use the AOR list from the endpoint itself */
2466         if (location || !contact) {
2467                 location = S_OR(location, endpoint->aors);
2468
2469                 ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,
2470                         &found_aor, &found_contact);
2471                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
2472                         uri = location;
2473                 } else {
2474                         uri = found_contact->uri;
2475                 }
2476         } else {
2477                 uri = contact->uri;
2478         }
2479
2480         /* If we still have no URI to dial fail to create the session */
2481         if (ast_strlen_zero(uri)) {
2482                 ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",
2483                         ast_sorcery_object_get_id(endpoint));
2484                 return NULL;
2485         }
2486
2487         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
2488                 return NULL;
2489         }
2490
2491         if (setup_outbound_invite_auth(dlg)) {
2492                 pjsip_dlg_terminate(dlg);
2493                 return NULL;
2494         }
2495
2496         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
2497                 pjsip_dlg_terminate(dlg);
2498                 return NULL;
2499         }
2500 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2501         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2502 #endif
2503
2504         pjsip_timer_setting_default(&timer);
2505         timer.min_se = endpoint->extensions.timer.min_se;
2506         timer.sess_expires = endpoint->extensions.timer.sess_expires;
2507         pjsip_timer_init_session(inv_session, &timer);
2508
2509         session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
2510                 inv_session, NULL);
2511         if (!session) {
2512                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2513                 return NULL;
2514         }
2515         session->aor = ao2_bump(found_aor);
2516         ast_party_id_copy(&session->id, &endpoint->id.self);
2517
2518         if (ast_stream_topology_get_count(req_topology) > 0) {
2519                 /* get joint caps between req_topology and endpoint topology */
2520                 int i;
2521
2522                 for (i = 0; i < ast_stream_topology_get_count(req_topology); ++i) {
2523                         struct ast_stream *req_stream;
2524                         struct ast_format_cap *req_cap;
2525                         struct ast_format_cap *joint_cap;
2526                         struct ast_stream *clone_stream;
2527
2528                         req_stream = ast_stream_topology_get_stream(req_topology, i);
2529
2530                         if (ast_stream_get_state(req_stream) == AST_STREAM_STATE_REMOVED) {
2531                                 continue;
2532                         }
2533
2534                         req_cap = ast_stream_get_formats(req_stream);
2535
2536                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2537                         if (!joint_cap) {
2538                                 continue;
2539                         }
2540
2541                         ast_format_cap_get_compatible(req_cap, endpoint->media.codecs, joint_cap);
2542                         if (!ast_format_cap_count(joint_cap)) {
2543                                 ao2_ref(joint_cap, -1);
2544                                 continue;
2545                         }
2546
2547                         clone_stream = ast_stream_clone(req_stream, NULL);
2548                         if (!clone_stream) {
2549                                 ao2_ref(joint_cap, -1);
2550                                 continue;
2551                         }
2552
2553                         if (ast_stream_get_type(req_stream) == AST_MEDIA_TYPE_AUDIO) {
2554                                 /*
2555                                  * By appending codecs from the endpoint after compatible ones this
2556                                  * guarantees that priority is given to those while also allowing
2557                                  * translation to occur for non-compatible.
2558                                  */
2559                                 ast_format_cap_append_from_cap(joint_cap,
2560                                         endpoint->media.codecs, AST_MEDIA_TYPE_AUDIO);
2561                         }
2562
2563                         ast_stream_set_formats(clone_stream, joint_cap);
2564                         ao2_ref(joint_cap, -1);
2565
2566                         if (!session->pending_media_state->topology) {
2567                                 session->pending_media_state->topology = ast_stream_topology_alloc();
2568                                 if (!session->pending_media_state->topology) {
2569                                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2570                                         ao2_ref(session, -1);
2571                                         return NULL;
2572                                 }
2573                         }
2574
2575                         if (ast_stream_topology_append_stream(session->pending_media_state->topology, clone_stream) < 0) {
2576                                 ast_stream_free(clone_stream);
2577                                 continue;
2578                         }
2579                 }
2580         }
2581
2582         if (!session->pending_media_state->topology) {
2583                 /* Use the configured topology on the endpoint as the pending one */
2584                 session->pending_media_state->topology = ast_stream_topology_clone(endpoint->media.topology);
2585                 if (!session->pending_media_state->topology) {
2586                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2587                         ao2_ref(session, -1);
2588                         return NULL;
2589                 }
2590         }
2591
2592         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2593                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2594                 /* Since we are not notifying ourselves that the INVITE session is being terminated
2595                  * we need to manually drop its reference to session
2596                  */
2597                 ao2_ref(session, -1);
2598                 return NULL;
2599         }
2600
2601         /* Avoid unnecessary ref manipulation to return a session */
2602         ret_session = session;
2603         session = NULL;
2604         return ret_session;
2605 }
2606
2607 static int session_end(void *vsession);
2608 static int session_end_completion(void *vsession);
2609
2610 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
2611 {
2612         pj_status_t status;
2613         pjsip_tx_data *packet = NULL;
2614
2615         if (session->defer_terminate) {
2616                 session->terminate_while_deferred = 1;
2617                 return;
2618         }
2619
2620         if (!response) {
2621                 response = 603;
2622         }
2623
2624         /* The media sessions need to exist for the lifetime of the underlying channel
2625          * to ensure that anything (such as bridge_native_rtp) has access to them as
2626          * appropriate. Since ast_sip_session_terminate is called by chan_pjsip and other
2627          * places when the session is to be terminated we terminate any existing
2628          * media sessions here.
2629          */
2630         SWAP(session->active_media_state, session->pending_media_state);
2631         ast_sip_session_media_state_reset(session->pending_media_state);
2632
2633         switch (session->inv_session->state) {
2634         case PJSIP_INV_STATE_NULL:
2635                 if (!session->inv_session->invite_tsx) {
2636                         /*
2637                          * Normally, it's pjproject's transaction cleanup that ultimately causes the
2638                          * final session reference to be released but if both STATE and invite_tsx are NULL,
2639                          * we never created a transaction in the first place.  In this case, we need to
2640                          * do the cleanup ourselves.
2641                          */
2642                         /* Transfer the inv_session session reference to the session_end_task */
2643                         session->inv_session->mod_data[session_module.id] = NULL;
2644                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2645                         session_end(session);
2646                         /*
2647                          * session_end_completion will cleanup the final session reference unless
2648                          * ast_sip_session_terminate's caller is holding one.
2649                          */
2650                         session_end_completion(session);
2651                 } else {
2652                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2653                 }
2654                 break;
2655         case PJSIP_INV_STATE_CONFIRMED:
2656                 if (session->inv_session->invite_tsx) {
2657                         ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
2658                                         ast_sorcery_object_get_id(session->endpoint));
2659                         /* If this is delayed the only thing that will happen is a BYE request so we don't
2660                          * actually need to store the response code for when it happens.
2661                          */
2662                         delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE, NULL);
2663                         break;
2664                 }
2665                 /* Fall through */
2666         default:
2667                 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
2668                 if (status == PJ_SUCCESS && packet) {
2669                         struct ast_sip_session_delayed_request *delay;
2670
2671                         /* Flush any delayed requests so they cannot overlap this transaction. */
2672                         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2673                                 delayed_request_free(delay);
2674                         }
2675
2676                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
2677                                 ast_sip_session_send_response(session, packet);
2678                         } else {
2679                                 ast_sip_session_send_request(session, packet);
2680                         }
2681                 }
2682                 break;
2683         }
2684 }
2685
2686 static int session_termination_task(void *data)
2687 {
2688         struct ast_sip_session *session = data;
2689
2690         if (session->defer_terminate) {
2691                 session->defer_terminate = 0;
2692                 if (session->inv_session) {
2693                         ast_sip_session_terminate(session, 0);
2694                 }
2695         }
2696
2697         ao2_ref(session, -1);
2698         return 0;
2699 }
2700
2701 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
2702 {
2703         struct ast_sip_session *session = entry->user_data;
2704
2705         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
2706                 ao2_cleanup(session);
2707         }
2708 }
2709
2710 int ast_sip_session_defer_termination(struct ast_sip_session *session)
2711 {
2712         pj_time_val delay = { .sec = 60, };
2713         int res;
2714
2715         /* The session should not have an active deferred termination request. */
2716         ast_assert(!session->defer_terminate);
2717
2718         session->defer_terminate = 1;
2719
2720         session->defer_end = 1;
2721         session->ended_while_deferred = 0;
2722
2723         ao2_ref(session, +1);
2724         pj_timer_entry_init(&session->scheduled_termination, 0, session, session_termination_cb);
2725
2726         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2727                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
2728         if (res) {
2729                 session->defer_terminate = 0;
2730                 ao2_ref(session, -1);
2731         }
2732         return res;
2733 }
2734
2735 /*!
2736  * \internal
2737  * \brief Stop the defer termination timer if it is still running.
2738  * \since 13.5.0
2739  *
2740  * \param session Which session to stop the timer.
2741  *
2742  * \return Nothing
2743  */
2744 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
2745 {
2746         if (pj_timer_heap_cancel_if_active(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
2747                 &session->scheduled_termination, session->scheduled_termination.id)) {
2748                 ao2_ref(session, -1);
2749         }
2750 }
2751
2752 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
2753 {
2754         if (!session->defer_terminate) {
2755                 /* Already canceled or timer fired. */
2756                 return;
2757         }
2758
2759         session->defer_terminate = 0;
2760
2761         if (session->terminate_while_deferred) {
2762                 /* Complete the termination started by the upper layer. */
2763                 ast_sip_session_terminate(session, 0);
2764         }
2765
2766         /* Stop the termination timer if it is still running. */
2767         sip_session_defer_termination_stop_timer(session);
2768 }
2769
2770 void ast_sip_session_end_if_deferred(struct ast_sip_session *session)
2771 {
2772         if (!session->defer_end) {
2773                 return;
2774         }
2775
2776         session->defer_end = 0;
2777
2778         if (session->ended_while_deferred) {
2779                 /* Complete the session end started by the remote hangup. */
2780                 ast_debug(3, "Ending session (%p) after being deferred\n", session);
2781                 session->ended_while_deferred = 0;
2782                 session_end(session);
2783         }
2784 }
2785
2786 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
2787 {
2788         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
2789         struct ast_sip_session *session;
2790
2791         if (!inv_session ||
2792                 !(session = inv_session->mod_data[session_module.id])) {
2793                 return NULL;
2794         }
2795
2796         ao2_ref(session, +1);
2797
2798         return session;
2799 }
2800
2801 enum sip_get_destination_result {
2802         /*! The extension was successfully found */
2803         SIP_GET_DEST_EXTEN_FOUND,
2804         /*! The extension specified in the RURI was not found */
2805         SIP_GET_DEST_EXTEN_NOT_FOUND,
2806         /*! The extension specified in the RURI was a partial match */
2807         SIP_GET_DEST_EXTEN_PARTIAL,
2808         /*! The RURI is of an unsupported scheme */
2809         SIP_GET_DEST_UNSUPPORTED_URI,
2810 };
2811
2812 /*!
2813  * \brief Determine where in the dialplan a call should go
2814  *
2815  * This uses the username in the request URI to try to match
2816  * an extension in the endpoint's configured context in order
2817  * to route the call.
2818  *
2819  * \param session The inbound SIP session
2820  * \param rdata The SIP INVITE
2821  */
2822 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
2823 {
2824         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
2825         pjsip_sip_uri *sip_ruri;
2826         struct ast_features_pickup_config *pickup_cfg;
2827         const char *pickupexten;
2828
2829         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
2830                 return SIP_GET_DEST_UNSUPPORTED_URI;
2831         }
2832
2833         sip_ruri = pjsip_uri_get_uri(ruri);
2834         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
2835
2836         /*
2837          * We may want to match in the dialplan without any user
2838          * options getting in the way.
2839          */
2840         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);
2841
2842         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2843         if (!pickup_cfg) {
2844                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
2845                 pickupexten = "";
2846         } else {
2847                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
2848                 ao2_ref(pickup_cfg, -1);
2849         }
2850
2851         if (!strcmp(session->exten, pickupexten) ||
2852                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
2853                 size_t size = pj_strlen(&sip_ruri->host) + 1;
2854                 char *domain = ast_alloca(size);
2855
2856                 ast_copy_pj_str(domain, &sip_ruri->host, size);
2857                 pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);
2858
2859                 /*
2860                  * Save off the INVITE Request-URI in case it is
2861                  * needed: CHANNEL(pjsip,request_uri)
2862                  */
2863                 session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);
2864
2865                 return SIP_GET_DEST_EXTEN_FOUND;
2866         }
2867
2868         /*
2869          * Check for partial match via overlap dialling (if enabled)
2870          */
2871         if (session->endpoint->allow_overlap && (
2872                 !strncmp(session->exten, pickupexten, strlen(session->exten)) ||
2873                 ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {
2874                 /* Overlap partial match */
2875                 return SIP_GET_DEST_EXTEN_PARTIAL;
2876         }
2877
2878         return SIP_GET_DEST_EXTEN_NOT_FOUND;
2879 }
2880
2881 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
2882 {
2883         pjsip_tx_data *tdata;
2884         pjsip_dialog *dlg;
2885         pjsip_inv_session *inv_session;
2886         unsigned int options = endpoint->extensions.flags;
2887         pj_status_t dlg_status;
2888
2889         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
2890                 if (tdata) {
2891                         if (pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL) != PJ_SUCCESS) {
2892                                 pjsip_tx_data_dec_ref(tdata);
2893                         }
2894                 } else {
2895                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2896                 }
2897                 return NULL;
2898         }
2899         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
2900         if (!dlg) {
2901                 if (dlg_status != PJ_EEXISTS) {
2902                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2903                 }
2904                 return NULL;
2905         }
2906         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
2907                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2908                 pjsip_dlg_terminate(dlg);
2909                 return NULL;
2910         }
2911
2912 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2913         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2914 #endif
2915         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2916                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
2917                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2918                 }
2919                 pjsip_inv_send_msg(inv_session, tdata);
2920                 return NULL;
2921         }
2922         return inv_session;
2923 }
2924
2925 struct new_invite {
2926         /*! \brief Session created for the new INVITE */
2927         struct ast_sip_session *session;
2928
2929         /*! \brief INVITE request itself */
2930         pjsip_rx_data *rdata;
2931 };
2932
2933 static int new_invite(struct new_invite *invite)
2934 {
2935         pjsip_tx_data *tdata = NULL;
2936         pjsip_timer_setting timer;
2937         pjsip_rdata_sdp_info *sdp_info;
2938         pjmedia_sdp_session *local = NULL;
2939         char buffer[AST_SOCKADDR_BUFLEN];
2940
2941         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
2942          * so that we will be notified so we can destroy the session properly
2943          */
2944
2945         if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2946                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2947                         invite->session->inv_session->cause,
2948                         pjsip_get_status_text(invite->session->inv_session->cause)->ptr);
2949 #ifdef HAVE_PJSIP_INV_SESSION_REF
2950                 pjsip_inv_dec_ref(invite->session->inv_session);
2951 #endif
2952                 return -1;
2953         }
2954
2955         switch (get_destination(invite->session, invite->rdata)) {
2956         case SIP_GET_DEST_EXTEN_FOUND:
2957                 /* Things worked. Keep going */
2958                 break;
2959         case SIP_GET_DEST_UNSUPPORTED_URI:
2960                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
2961                         ast_sip_session_send_response(invite->session, tdata);
2962                 } else  {
2963                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
2964                 }
2965                 goto end;
2966         case SIP_GET_DEST_EXTEN_PARTIAL:
2967                 ast_debug(1, "Call from '%s' (%s:%s) to extension '%s' - partial match\n",
2968                         ast_sorcery_object_get_id(invite->session->endpoint),
2969                         invite->rdata->tp_info.transport->type_name,
2970                         pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
2971                         invite->session->exten);
2972
2973                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {
2974                         ast_sip_session_send_response(invite->session, tdata);
2975                 } else  {
2976                         pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);
2977                 }
2978                 goto end;
2979         case SIP_GET_DEST_EXTEN_NOT_FOUND:
2980         default:
2981                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s) to extension '%s' rejected because extension not found in context '%s'.\n",
2982                         ast_sorcery_object_get_id(invite->session->endpoint),
2983                         invite->rdata->tp_info.transport->type_name,
2984                         pj_sockaddr_print(&invite->rdata->pkt_info.src_addr, buffer, sizeof(buffer), 3),
2985                         invite->session->exten,
2986                         invite->session->endpoint->context);
2987
2988                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
2989                         ast_sip_session_send_response(invite->session, tdata);
2990                 } else  {
2991                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
2992                 }
2993                 goto end;
2994         };
2995
2996         pjsip_timer_setting_default(&timer);
2997         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
2998         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
2999         pjsip_timer_init_session(invite->session->inv_session, &timer);
3000
3001         /*
3002          * At this point, we've verified what we can that won't take awhile,
3003          * so let's go ahead and send a 100 Trying out to stop any
3004          * retransmissions.
3005          */
3006         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
3007                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
3008                 goto end;
3009         }
3010         ast_sip_session_send_response(invite->session, tdata);
3011
3012         sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);
3013         if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
3014                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
3015                         tdata = NULL;
3016                         if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS
3017                                 && tdata) {
3018                                 ast_sip_session_send_response(invite->session, tdata);
3019                         }
3020                         goto end;
3021                 }
3022                 /* We are creating a local SDP which is an answer to their offer */
3023                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
3024         } else {
3025                 /* We are creating a local SDP which is an offer */
3026                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
3027         }
3028
3029         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
3030         if (!local) {
3031                 tdata = NULL;
3032                 if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS
3033                         && tdata) {
3034                         ast_sip_session_send_response(invite->session, tdata);
3035                 }
3036                 goto end;
3037         }
3038
3039         pjsip_inv_set_local_sdp(invite->session->inv_session, local);
3040         pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
3041 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
3042         if (!invite->session->endpoint->preferred_codec_only) {
3043                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
3044         }
3045 #endif
3046
3047         handle_incoming_request(invite->session, invite->rdata);
3048
3049 end:
3050 #ifdef HAVE_PJSIP_INV_SESSION_REF
3051         pjsip_inv_dec_ref(invite->session->inv_session);
3052 #endif
3053         return 0;
3054 }
3055
3056 static void handle_new_invite_request(pjsip_rx_data *rdata)
3057 {
3058         RAII_VAR(struct ast_sip_endpoint *, endpoint,
3059                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
3060         pjsip_tx_data *tdata = NULL;
3061         pjsip_inv_session *inv_session = NULL;
3062         struct ast_sip_session *session;
3063         struct new_invite invite;
3064
3065         ast_assert(endpoint != NULL);
3066
3067         inv_session = pre_session_setup(rdata, endpoint);
3068         if (!inv_session) {
3069                 /* pre_session_setup() returns a response on failure */
3070                 return;
3071         }
3072
3073 #ifdef HAVE_PJSIP_INV_SESSION_REF
3074         if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {
3075                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
3076                 if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {
3077                         if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
3078                                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
3079                         } else {
3080                                 pjsip_inv_send_msg(inv_session, tdata);
3081                         }
3082                 }
3083                 return;
3084         }
3085 #endif
3086
3087         session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);