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