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