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