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