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