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