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