res_srtp: Add support for libsrtp2.1.
[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 int ast_sip_session_regenerate_answer(struct ast_sip_session *session,
1554                 ast_sip_session_sdp_creation_cb on_sdp_creation)
1555 {
1556         pjsip_inv_session *inv_session = session->inv_session;
1557         pjmedia_sdp_session *new_answer = NULL;
1558         const pjmedia_sdp_session *previous_offer = NULL;
1559
1560         /* The SDP answer can only be regenerated if it is still pending to be sent */
1561         if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&
1562                 pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {
1563                 ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",
1564                         ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));
1565                 return -1;
1566         }
1567
1568         pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);
1569         if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {
1570                 /* Transition the SDP negotiator back to when it received the remote offer */
1571                 pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);
1572                 pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);
1573         }
1574
1575         new_answer = create_local_sdp(inv_session, session, previous_offer);
1576         if (!new_answer) {
1577                 ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",
1578                         ast_channel_name(session->channel));
1579                 return -1;
1580         }
1581
1582         if (on_sdp_creation) {
1583                 if (on_sdp_creation(session, new_answer)) {
1584                         return -1;
1585                 }
1586         }
1587
1588         pjsip_inv_set_sdp_answer(inv_session, new_answer);
1589
1590         return 0;
1591 }
1592
1593 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1594 {
1595         handle_outgoing_response(session, tdata);
1596         pjsip_inv_send_msg(session->inv_session, tdata);
1597         return;
1598 }
1599
1600 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
1601
1602 static pjsip_module session_module = {
1603         .name = {"Session Module", 14},
1604         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1605         .on_rx_request = session_on_rx_request,
1606 };
1607
1608 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
1609  *
1610  * \retval 1 re-invite should be deferred and resumed later
1611  * \retval 0 re-invite should not be deferred
1612  */
1613 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
1614 {
1615         int i;
1616
1617         if (!session->pending_media_state->topology) {
1618                 session->pending_media_state->topology = ast_stream_topology_alloc();
1619                 if (!session->pending_media_state->topology) {
1620                         return -1;
1621                 }
1622         }
1623
1624         for (i = 0; i < sdp->media_count; ++i) {
1625                 /* See if there are registered handlers for this media stream type */
1626                 char media[20];
1627                 struct ast_sip_session_sdp_handler *handler;
1628                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1629                 struct ast_stream *stream;
1630                 enum ast_media_type type;
1631                 struct ast_sip_session_media *session_media = NULL;
1632                 enum ast_sip_session_sdp_stream_defer res;
1633
1634                 /* We need a null-terminated version of the media string */
1635                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
1636
1637                 type = ast_media_type_from_str(media);
1638                 stream = ast_stream_alloc(ast_codec_media_type2str(type), type);
1639                 if (!stream) {
1640                         return -1;
1641                 }
1642
1643                 /* As this is only called on an incoming SDP offer before processing it is not possible
1644                  * for streams and their media sessions to exist.
1645                  */
1646                 ast_stream_topology_set_stream(session->pending_media_state->topology, i, stream);
1647
1648                 session_media = ast_sip_session_media_state_add(session, session->pending_media_state, ast_media_type_from_str(media), i);
1649                 if (!session_media) {
1650                         return -1;
1651                 }
1652
1653                 if (session_media->handler) {
1654                         handler = session_media->handler;
1655                         if (handler->defer_incoming_sdp_stream) {
1656                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1657                                         sdp->media[i]);
1658                                 switch (res) {
1659                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1660                                         break;
1661                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
1662                                         return 0;
1663                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1664                                         break;
1665                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1666                                         return 1;
1667                                 }
1668                         }
1669                         /* Handled by this handler. Move to the next stream */
1670                         continue;
1671                 }
1672
1673                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1674                 if (!handler_list) {
1675                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
1676                         continue;
1677                 }
1678                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1679                         if (handler == session_media->handler) {
1680                                 continue;
1681                         }
1682                         if (!handler->defer_incoming_sdp_stream) {
1683                                 continue;
1684                         }
1685                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1686                                 sdp->media[i]);
1687                         switch (res) {
1688                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1689                                 continue;
1690                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
1691                                 session_media_set_handler(session_media, handler);
1692                                 return 0;
1693                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1694                                 /* Handled by this handler. */
1695                                 session_media_set_handler(session_media, handler);
1696                                 break;
1697                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1698                                 /* Handled by this handler. */
1699                                 session_media_set_handler(session_media, handler);
1700                                 return 1;
1701                         }
1702                         /* Move to the next stream */
1703                         break;
1704                 }
1705         }
1706         return 0;
1707 }
1708
1709 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
1710 {
1711         pjsip_dialog *dlg;
1712         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1713         pjsip_rdata_sdp_info *sdp_info;
1714
1715         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
1716                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
1717                 !(session = ast_sip_dialog_get_session(dlg)) ||
1718                 !session->channel) {
1719                 return PJ_FALSE;
1720         }
1721
1722         if (session->deferred_reinvite) {
1723                 pj_str_t key, deferred_key;
1724                 pjsip_tx_data *tdata;
1725
1726                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1727                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1728                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1729                         session->deferred_reinvite);
1730
1731                 /* If this is a retransmission ignore it */
1732                 if (!pj_strcmp(&key, &deferred_key)) {
1733                         return PJ_TRUE;
1734                 }
1735
1736                 /* Otherwise this is a new re-invite, so reject it */
1737                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1738                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1739                 }
1740
1741                 return PJ_TRUE;
1742         }
1743
1744         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1745                 (sdp_info->sdp_err != PJ_SUCCESS)) {
1746                 return PJ_FALSE;
1747         }
1748
1749         if (!sdp_info->sdp) {
1750                 const pjmedia_sdp_session *local;
1751                 int i;
1752
1753                 ast_queue_unhold(session->channel);
1754
1755                 pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);
1756                 if (!local) {
1757                         return PJ_FALSE;
1758                 }
1759
1760                 /*
1761                  * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).
1762                  * When hold is initially indicated, we
1763                  * - Receive an INVITE with no SDP
1764                  * - Send a 200 OK with SDP, indicating sendrecv in the media streams
1765                  * - Receive an ACK with SDP, indicating sendonly in the media streams
1766                  *
1767                  * At this point, the pjmedia negotiator saves the state of the media direction so that
1768                  * if we are to send any offers, we'll offer recvonly in the media streams. This is
1769                  * problematic if the device is attempting to unhold, though. If the device unholds
1770                  * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.
1771                  * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond
1772                  * with sendonly or inactive. The result of this is that the stream is not off hold.
1773                  *
1774                  * Therefore, in this case, when we receive a reinvite while the stream is on hold, we
1775                  * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv
1776                  * in order to get the stream off hold. If this is actually a different purpose reinvite
1777                  * (like a session timer refresh), then the answerer can respond to our sendrecv with
1778                  * sendonly, keeping the stream on hold.
1779                  */
1780                 for (i = 0; i < local->media_count; ++i) {
1781                         pjmedia_sdp_media *m = local->media[i];
1782                         pjmedia_sdp_attr *recvonly;
1783                         pjmedia_sdp_attr *inactive;
1784
1785                         recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);
1786                         inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);
1787                         if (recvonly || inactive) {
1788                                 pjmedia_sdp_attr *to_remove = recvonly ?: inactive;
1789                                 pjmedia_sdp_attr *sendrecv;
1790
1791                                 pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);
1792
1793                                 sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);
1794                                 pjmedia_sdp_media_add_attr(m, sendrecv);
1795                         }
1796                 }
1797
1798                 return PJ_FALSE;
1799         }
1800
1801         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1802                 return PJ_FALSE;
1803         }
1804
1805         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1806
1807         return PJ_TRUE;
1808 }
1809
1810 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1811 {
1812         if (!session->deferred_reinvite) {
1813                 return;
1814         }
1815
1816         if (session->channel) {
1817                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1818                         session->deferred_reinvite, NULL, NULL);
1819         }
1820         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1821         session->deferred_reinvite = NULL;
1822 }
1823
1824 static pjsip_module session_reinvite_module = {
1825         .name = { "Session Re-Invite Module", 24 },
1826         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1827         .on_rx_request = session_reinvite_on_rx_request,
1828 };
1829
1830
1831 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1832                 ast_sip_session_response_cb on_response)
1833 {
1834         pjsip_inv_session *inv_session = session->inv_session;
1835
1836         /* For every request except BYE we disallow sending of the message when
1837          * the session has been disconnected. A BYE request is special though
1838          * because it can be sent again after the session is disconnected except
1839          * with credentials.
1840          */
1841         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&
1842                 tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {
1843                 return;
1844         }
1845
1846         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
1847                              MOD_DATA_ON_RESPONSE, on_response);
1848
1849         handle_outgoing_request(session, tdata);
1850         pjsip_inv_send_msg(session->inv_session, tdata);
1851
1852         return;
1853 }
1854
1855 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1856 {
1857         ast_sip_session_send_request_with_cb(session, tdata, NULL);
1858 }
1859
1860 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
1861 {
1862         pjmedia_sdp_session *offer;
1863
1864         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1865                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1866                 return -1;
1867         }
1868
1869         pjsip_inv_set_local_sdp(session->inv_session, offer);
1870         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
1871 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1872         if (!session->endpoint->preferred_codec_only) {
1873                 pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
1874         }
1875 #endif
1876
1877         /*
1878          * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the
1879          * From in the initial INVITE will be wrong but the rest of the messages will be OK.
1880          */
1881         set_from_header(session);
1882
1883         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
1884                 return -1;
1885         }
1886
1887         return 0;
1888 }
1889
1890 static int datastore_hash(const void *obj, int flags)
1891 {
1892         const struct ast_datastore *datastore = obj;
1893         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1894
1895         ast_assert(uid != NULL);
1896
1897         return ast_str_hash(uid);
1898 }
1899
1900 static int datastore_cmp(void *obj, void *arg, int flags)
1901 {
1902         const struct ast_datastore *datastore1 = obj;
1903         const struct ast_datastore *datastore2 = arg;
1904         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1905
1906         ast_assert(datastore1->uid != NULL);
1907         ast_assert(uid2 != NULL);
1908
1909         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1910 }
1911
1912 static void session_destructor(void *obj)
1913 {
1914         struct ast_sip_session *session = obj;
1915         struct ast_sip_session_supplement *supplement;
1916         struct ast_sip_session_delayed_request *delay;
1917         const char *endpoint_name = session->endpoint ?
1918                 ast_sorcery_object_get_id(session->endpoint) : "<none>";
1919
1920         ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);
1921
1922         ast_test_suite_event_notify("SESSION_DESTROYING",
1923                 "Endpoint: %s\r\n"
1924                 "AOR: %s\r\n"
1925                 "Contact: %s"
1926                 , endpoint_name
1927                 , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"
1928                 , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"
1929                 );
1930
1931         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
1932                 if (supplement->session_destroy) {
1933                         supplement->session_destroy(session);
1934                 }
1935                 ast_free(supplement);
1936         }
1937
1938         ast_taskprocessor_unreference(session->serializer);
1939         ao2_cleanup(session->datastores);
1940         ast_sip_session_media_state_free(session->active_media_state);
1941         ast_sip_session_media_state_free(session->pending_media_state);
1942
1943         AST_LIST_HEAD_DESTROY(&session->supplements);
1944         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1945                 delayed_request_free(delay);
1946         }
1947         ast_party_id_free(&session->id);
1948         ao2_cleanup(session->endpoint);
1949         ao2_cleanup(session->aor);
1950         ao2_cleanup(session->contact);
1951         ao2_cleanup(session->direct_media_cap);
1952
1953         ast_dsp_free(session->dsp);
1954
1955         if (session->inv_session) {
1956                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1957         }
1958
1959         ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);
1960 }
1961
1962 static int add_supplements(struct ast_sip_session *session)
1963 {
1964         struct ast_sip_session_supplement *iter;
1965         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1966
1967         AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1968                 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1969                 if (!copy) {
1970                         return -1;
1971                 }
1972                 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1973         }
1974         return 0;
1975 }
1976
1977 /*! \brief Destructor for SIP channel */
1978 static void sip_channel_destroy(void *obj)
1979 {
1980         struct ast_sip_channel_pvt *channel = obj;
1981
1982         ao2_cleanup(channel->pvt);
1983         ao2_cleanup(channel->session);
1984 }
1985
1986 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1987 {
1988         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1989
1990         if (!channel) {
1991                 return NULL;
1992         }
1993
1994         ao2_ref(pvt, +1);
1995         channel->pvt = pvt;
1996         ao2_ref(session, +1);
1997         channel->session = session;
1998
1999         return channel;
2000 }
2001
2002 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
2003         struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
2004 {
2005         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2006         struct ast_sip_session *ret_session;
2007         struct ast_sip_session_supplement *iter;
2008         int dsp_features = 0;
2009
2010         session = ao2_alloc(sizeof(*session), session_destructor);
2011         if (!session) {
2012                 return NULL;
2013         }
2014
2015         AST_LIST_HEAD_INIT(&session->supplements);
2016         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
2017         ast_party_id_init(&session->id);
2018
2019         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2020         if (!session->direct_media_cap) {
2021                 return NULL;
2022         }
2023         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
2024         if (!session->datastores) {
2025                 return NULL;
2026         }
2027         session->active_media_state = ast_sip_session_media_state_alloc();
2028         if (!session->active_media_state) {
2029                 return NULL;
2030         }
2031         session->pending_media_state = ast_sip_session_media_state_alloc();
2032         if (!session->pending_media_state) {
2033                 return NULL;
2034         }
2035
2036         if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {
2037                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
2038         }
2039         if (endpoint->faxdetect) {
2040                 dsp_features |= DSP_FEATURE_FAX_DETECT;
2041         }
2042         if (dsp_features) {
2043                 session->dsp = ast_dsp_new();
2044                 if (!session->dsp) {
2045                         return NULL;
2046                 }
2047
2048                 ast_dsp_set_features(session->dsp, dsp_features);
2049         }
2050
2051         session->endpoint = ao2_bump(endpoint);
2052
2053         if (rdata) {
2054                 /*
2055                  * We must continue using the serializer that the original
2056                  * INVITE came in on for the dialog.  There may be
2057                  * retransmissions already enqueued in the original
2058                  * serializer that can result in reentrancy and message
2059                  * sequencing problems.
2060                  */
2061                 session->serializer = ast_sip_get_distributor_serializer(rdata);
2062         } else {
2063                 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
2064
2065                 /* Create name with seq number appended. */
2066                 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
2067                         ast_sorcery_object_get_id(endpoint));
2068
2069                 session->serializer = ast_sip_create_serializer(tps_name);
2070         }
2071         if (!session->serializer) {
2072                 return NULL;
2073         }
2074         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
2075         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
2076         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
2077         inv_session->mod_data[session_module.id] = ao2_bump(session);
2078         session->contact = ao2_bump(contact);
2079         session->inv_session = inv_session;
2080
2081         session->dtmf = endpoint->dtmf;
2082
2083         if (add_supplements(session)) {
2084                 /* Release the ref held by session->inv_session */
2085                 ao2_ref(session, -1);
2086                 return NULL;
2087         }
2088         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2089                 if (iter->session_begin) {
2090                         iter->session_begin(session);
2091                 }
2092         }
2093
2094         /* Avoid unnecessary ref manipulation to return a session */
2095         ret_session = session;
2096         session = NULL;
2097         return ret_session;
2098 }
2099
2100 /*! \brief struct controlling the suspension of the session's serializer. */
2101 struct ast_sip_session_suspender {
2102         ast_cond_t cond_suspended;
2103         ast_cond_t cond_complete;
2104         int suspended;
2105         int complete;
2106 };
2107
2108 static void sip_session_suspender_dtor(void *vdoomed)
2109 {
2110         struct ast_sip_session_suspender *doomed = vdoomed;
2111
2112         ast_cond_destroy(&doomed->cond_suspended);
2113         ast_cond_destroy(&doomed->cond_complete);
2114 }
2115
2116 /*!
2117  * \internal
2118  * \brief Block the session serializer thread task.
2119  *
2120  * \param data Pushed serializer task data for suspension.
2121  *
2122  * \retval 0
2123  */
2124 static int sip_session_suspend_task(void *data)
2125 {
2126         struct ast_sip_session_suspender *suspender = data;
2127
2128         ao2_lock(suspender);
2129
2130         /* Signal that the serializer task is now suspended. */
2131         suspender->suspended = 1;
2132         ast_cond_signal(&suspender->cond_suspended);
2133
2134         /* Wait for the the serializer suspension to be completed. */
2135         while (!suspender->complete) {
2136                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
2137         }
2138
2139         ao2_unlock(suspender);
2140         ao2_ref(suspender, -1);
2141
2142         return 0;
2143 }
2144
2145 void ast_sip_session_suspend(struct ast_sip_session *session)
2146 {
2147         struct ast_sip_session_suspender *suspender;
2148         int res;
2149
2150         ast_assert(session->suspended == NULL);
2151
2152         if (ast_taskprocessor_is_task(session->serializer)) {
2153                 /* I am the session's serializer thread so I cannot suspend. */
2154                 return;
2155         }
2156
2157         if (ast_taskprocessor_is_suspended(session->serializer)) {
2158                 /* The serializer already suspended. */
2159                 return;
2160         }
2161
2162         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
2163         if (!suspender) {
2164                 /* We will just have to hope that the system does not deadlock */
2165                 return;
2166         }
2167         ast_cond_init(&suspender->cond_suspended, NULL);
2168         ast_cond_init(&suspender->cond_complete, NULL);
2169
2170         ao2_ref(suspender, +1);
2171         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
2172         if (res) {
2173                 /* We will just have to hope that the system does not deadlock */
2174                 ao2_ref(suspender, -2);
2175                 return;
2176         }
2177
2178         session->suspended = suspender;
2179
2180         /* Wait for the serializer to get suspended. */
2181         ao2_lock(suspender);
2182         while (!suspender->suspended) {
2183                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
2184         }
2185         ao2_unlock(suspender);
2186
2187         ast_taskprocessor_suspend(session->serializer);
2188 }
2189
2190 void ast_sip_session_unsuspend(struct ast_sip_session *session)
2191 {
2192         struct ast_sip_session_suspender *suspender = session->suspended;
2193
2194         if (!suspender) {
2195                 /* Nothing to do */
2196                 return;
2197         }
2198         session->suspended = NULL;
2199
2200         /* Signal that the serializer task suspension is now complete. */
2201         ao2_lock(suspender);
2202         suspender->complete = 1;
2203         ast_cond_signal(&suspender->cond_complete);
2204         ao2_unlock(suspender);
2205
2206         ao2_ref(suspender, -1);
2207
2208         ast_taskprocessor_unsuspend(session->serializer);
2209 }
2210
2211 /*!
2212  * \internal
2213  * \brief Handle initial INVITE challenge response message.
2214  * \since 13.5.0
2215  *
2216  * \param rdata PJSIP receive response message data.
2217  *
2218  * \retval PJ_FALSE Did not handle message.
2219  * \retval PJ_TRUE Handled message.
2220  */
2221 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
2222 {
2223         pjsip_transaction *tsx;
2224         pjsip_dialog *dlg;
2225         pjsip_inv_session *inv;
2226         pjsip_tx_data *tdata;
2227         struct ast_sip_session *session;
2228
2229         if (rdata->msg_info.msg->line.status.code != 401
2230                 && rdata->msg_info.msg->line.status.code != 407) {
2231                 /* Doesn't pertain to us. Move on */
2232                 return PJ_FALSE;
2233         }
2234
2235         tsx = pjsip_rdata_get_tsx(rdata);
2236         dlg = pjsip_rdata_get_dlg(rdata);
2237         if (!dlg || !tsx) {
2238                 return PJ_FALSE;
2239         }
2240
2241         if (tsx->method.id != PJSIP_INVITE_METHOD) {
2242                 /* Not an INVITE that needs authentication */
2243                 return PJ_FALSE;
2244         }
2245
2246         inv = pjsip_dlg_get_inv_session(dlg);
2247         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
2248                 /*
2249                  * We cannot handle reINVITE authentication at this
2250                  * time because the reINVITE transaction is still in
2251                  * progress.
2252                  */
2253                 ast_debug(1, "A reINVITE is being challenged.\n");
2254                 return PJ_FALSE;
2255         }
2256         ast_debug(1, "Initial INVITE is being challenged.\n");
2257
2258         session = inv->mod_data[session_module.id];
2259
2260         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
2261                 tsx->last_tx, &tdata)) {
2262                 return PJ_FALSE;
2263         }
2264
2265         /*
2266          * Restart the outgoing initial INVITE transaction to deal
2267          * with authentication.
2268          */
2269         pjsip_inv_uac_restart(inv, PJ_FALSE);
2270
2271         ast_sip_session_send_request(session, tdata);
2272         return PJ_TRUE;
2273 }
2274
2275 static pjsip_module outbound_invite_auth_module = {
2276         .name = {"Outbound INVITE Auth", 20},
2277         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
2278         .on_rx_response = outbound_invite_auth,
2279 };
2280
2281 /*!
2282  * \internal
2283  * \brief Setup outbound initial INVITE authentication.
2284  * \since 13.5.0
2285  *
2286  * \param dlg PJSIP dialog to attach outbound authentication.
2287  *
2288  * \retval 0 on success.
2289  * \retval -1 on error.
2290  */
2291 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
2292 {
2293         pj_status_t status;
2294
2295         ++dlg->sess_count;
2296         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
2297         --dlg->sess_count;
2298
2299         return status != PJ_SUCCESS ? -1 : 0;
2300 }
2301
2302 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
2303         struct ast_sip_contact *contact, const char *location, const char *request_user,
2304         struct ast_stream_topology *req_topology)
2305 {
2306         const char *uri = NULL;
2307         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
2308         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
2309         pjsip_timer_setting timer;
2310         pjsip_dialog *dlg;
2311         struct pjsip_inv_session *inv_session;
2312         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
2313         struct ast_sip_session *ret_session;
2314
2315         /* If no location has been provided use the AOR list from the endpoint itself */
2316         if (location || !contact) {
2317                 location = S_OR(location, endpoint->aors);
2318
2319                 ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,
2320                         &found_aor, &found_contact);
2321                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
2322                         uri = location;
2323                 } else {
2324                         uri = found_contact->uri;
2325                 }
2326         } else {
2327                 uri = contact->uri;
2328         }
2329
2330         /* If we still have no URI to dial fail to create the session */
2331         if (ast_strlen_zero(uri)) {
2332                 ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",
2333                         ast_sorcery_object_get_id(endpoint));
2334                 return NULL;
2335         }
2336
2337         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
2338                 return NULL;
2339         }
2340
2341         if (setup_outbound_invite_auth(dlg)) {
2342                 pjsip_dlg_terminate(dlg);
2343                 return NULL;
2344         }
2345
2346         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
2347                 pjsip_dlg_terminate(dlg);
2348                 return NULL;
2349         }
2350 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2351         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2352 #endif
2353
2354         pjsip_timer_setting_default(&timer);
2355         timer.min_se = endpoint->extensions.timer.min_se;
2356         timer.sess_expires = endpoint->extensions.timer.sess_expires;
2357         pjsip_timer_init_session(inv_session, &timer);
2358
2359         session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
2360                 inv_session, NULL);
2361         if (!session) {
2362                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2363                 return NULL;
2364         }
2365         session->aor = ao2_bump(found_aor);
2366         ast_party_id_copy(&session->id, &endpoint->id.self);
2367
2368         if (ast_stream_topology_get_count(req_topology) > 0) {
2369                 /* get joint caps between req_topology and endpoint topology */
2370                 int i;
2371
2372                 for (i = 0; i < ast_stream_topology_get_count(req_topology); ++i) {
2373                         struct ast_stream *req_stream;
2374                         struct ast_format_cap *req_cap;
2375                         struct ast_format_cap *joint_cap;
2376                         struct ast_stream *clone_stream;
2377
2378                         req_stream = ast_stream_topology_get_stream(req_topology, i);
2379
2380                         if (ast_stream_get_state(req_stream) == AST_STREAM_STATE_REMOVED) {
2381                                 continue;
2382                         }
2383
2384                         req_cap = ast_stream_get_formats(req_stream);
2385
2386                         joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
2387                         if (!joint_cap) {
2388                                 continue;
2389                         }
2390
2391                         ast_format_cap_get_compatible(req_cap, endpoint->media.codecs, joint_cap);
2392                         if (!ast_format_cap_count(joint_cap)) {
2393                                 ao2_ref(joint_cap, -1);
2394                                 continue;
2395                         }
2396
2397                         clone_stream = ast_stream_clone(req_stream, NULL);
2398                         if (!clone_stream) {
2399                                 ao2_ref(joint_cap, -1);
2400                                 continue;
2401                         }
2402
2403                         ast_stream_set_formats(clone_stream, joint_cap);
2404                         ao2_ref(joint_cap, -1);
2405
2406                         if (!session->pending_media_state->topology) {
2407                                 session->pending_media_state->topology = ast_stream_topology_alloc();
2408                                 if (!session->pending_media_state->topology) {
2409                                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2410                                         ao2_ref(session, -1);
2411                                         return NULL;
2412                                 }
2413                         }
2414
2415                         if (ast_stream_topology_append_stream(session->pending_media_state->topology, clone_stream) < 0) {
2416                                 ast_stream_free(clone_stream);
2417                                 continue;
2418                         }
2419                 }
2420         }
2421
2422         if (!session->pending_media_state->topology) {
2423                 /* Use the configured topology on the endpoint as the pending one */
2424                 session->pending_media_state->topology = ast_stream_topology_clone(endpoint->media.topology);
2425                 if (!session->pending_media_state->topology) {
2426                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2427                         ao2_ref(session, -1);
2428                         return NULL;
2429                 }
2430         }
2431
2432         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2433                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2434                 /* Since we are not notifying ourselves that the INVITE session is being terminated
2435                  * we need to manually drop its reference to session
2436                  */
2437                 ao2_ref(session, -1);
2438                 return NULL;
2439         }
2440
2441         /* Avoid unnecessary ref manipulation to return a session */
2442         ret_session = session;
2443         session = NULL;
2444         return ret_session;
2445 }
2446
2447 static int session_end(void *vsession);
2448 static int session_end_completion(void *vsession);
2449
2450 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
2451 {
2452         pj_status_t status;
2453         pjsip_tx_data *packet = NULL;
2454
2455         if (session->defer_terminate) {
2456                 session->terminate_while_deferred = 1;
2457                 return;
2458         }
2459
2460         if (!response) {
2461                 response = 603;
2462         }
2463
2464         /* The media sessions need to exist for the lifetime of the underlying channel
2465          * to ensure that anything (such as bridge_native_rtp) has access to them as
2466          * appropriate. Since ast_sip_session_terminate is called by chan_pjsip and other
2467          * places when the session is to be terminated we terminate any existing
2468          * media sessions here.
2469          */
2470         SWAP(session->active_media_state, session->pending_media_state);
2471         ast_sip_session_media_state_reset(session->pending_media_state);
2472
2473         switch (session->inv_session->state) {
2474         case PJSIP_INV_STATE_NULL:
2475                 if (!session->inv_session->invite_tsx) {
2476                         /*
2477                          * Normally, it's pjproject's transaction cleanup that ultimately causes the
2478                          * final session reference to be released but if both STATE and invite_tsx are NULL,
2479                          * we never created a transaction in the first place.  In this case, we need to
2480                          * do the cleanup ourselves.
2481                          */
2482                         /* Transfer the inv_session session reference to the session_end_task */
2483                         session->inv_session->mod_data[session_module.id] = NULL;
2484                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2485                         session_end(session);
2486                         /*
2487                          * session_end_completion will cleanup the final session reference unless
2488                          * ast_sip_session_terminate's caller is holding one.
2489                          */
2490                         session_end_completion(session);
2491                 } else {
2492                         pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
2493                 }
2494                 break;
2495         case PJSIP_INV_STATE_CONFIRMED:
2496                 if (session->inv_session->invite_tsx) {
2497                         ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
2498                                         ast_sorcery_object_get_id(session->endpoint));
2499                         /* If this is delayed the only thing that will happen is a BYE request so we don't
2500                          * actually need to store the response code for when it happens.
2501                          */
2502                         delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE, NULL);
2503                         break;
2504                 }
2505                 /* Fall through */
2506         default:
2507                 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
2508                 if (status == PJ_SUCCESS && packet) {
2509                         struct ast_sip_session_delayed_request *delay;
2510
2511                         /* Flush any delayed requests so they cannot overlap this transaction. */
2512                         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
2513                                 delayed_request_free(delay);
2514                         }
2515
2516                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
2517                                 ast_sip_session_send_response(session, packet);
2518                         } else {
2519                                 ast_sip_session_send_request(session, packet);
2520                         }
2521                 }
2522                 break;
2523         }
2524 }
2525
2526 static int session_termination_task(void *data)
2527 {
2528         struct ast_sip_session *session = data;
2529
2530         if (session->defer_terminate) {
2531                 session->defer_terminate = 0;
2532                 if (session->inv_session) {
2533                         ast_sip_session_terminate(session, 0);
2534                 }
2535         }
2536
2537         ao2_ref(session, -1);
2538         return 0;
2539 }
2540
2541 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
2542 {
2543         struct ast_sip_session *session = entry->user_data;
2544
2545         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
2546                 ao2_cleanup(session);
2547         }
2548 }
2549
2550 int ast_sip_session_defer_termination(struct ast_sip_session *session)
2551 {
2552         pj_time_val delay = { .sec = 60, };
2553         int res;
2554
2555         /* The session should not have an active deferred termination request. */
2556         ast_assert(!session->defer_terminate);
2557
2558         session->defer_terminate = 1;
2559
2560         session->defer_end = 1;
2561         session->ended_while_deferred = 0;
2562
2563         session->scheduled_termination.id = 0;
2564         ao2_ref(session, +1);
2565         session->scheduled_termination.user_data = session;
2566         session->scheduled_termination.cb = session_termination_cb;
2567
2568         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2569                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
2570         if (res) {
2571                 session->defer_terminate = 0;
2572                 ao2_ref(session, -1);
2573         }
2574         return res;
2575 }
2576
2577 /*!
2578  * \internal
2579  * \brief Stop the defer termination timer if it is still running.
2580  * \since 13.5.0
2581  *
2582  * \param session Which session to stop the timer.
2583  *
2584  * \return Nothing
2585  */
2586 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
2587 {
2588         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
2589                 &session->scheduled_termination)) {
2590                 ao2_ref(session, -1);
2591         }
2592 }
2593
2594 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
2595 {
2596         if (!session->defer_terminate) {
2597                 /* Already canceled or timer fired. */
2598                 return;
2599         }
2600
2601         session->defer_terminate = 0;
2602
2603         if (session->terminate_while_deferred) {
2604                 /* Complete the termination started by the upper layer. */
2605                 ast_sip_session_terminate(session, 0);
2606         }
2607
2608         /* Stop the termination timer if it is still running. */
2609         sip_session_defer_termination_stop_timer(session);
2610 }
2611
2612 void ast_sip_session_end_if_deferred(struct ast_sip_session *session)
2613 {
2614         if (!session->defer_end) {
2615                 return;
2616         }
2617
2618         session->defer_end = 0;
2619
2620         if (session->ended_while_deferred) {
2621                 /* Complete the session end started by the remote hangup. */
2622                 ast_debug(3, "Ending session (%p) after being deferred\n", session);
2623                 session->ended_while_deferred = 0;
2624                 session_end(session);
2625         }
2626 }
2627
2628 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
2629 {
2630         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
2631         struct ast_sip_session *session;
2632
2633         if (!inv_session ||
2634                 !(session = inv_session->mod_data[session_module.id])) {
2635                 return NULL;
2636         }
2637
2638         ao2_ref(session, +1);
2639
2640         return session;
2641 }
2642
2643 enum sip_get_destination_result {
2644         /*! The extension was successfully found */
2645         SIP_GET_DEST_EXTEN_FOUND,
2646         /*! The extension specified in the RURI was not found */
2647         SIP_GET_DEST_EXTEN_NOT_FOUND,
2648         /*! The extension specified in the RURI was a partial match */
2649         SIP_GET_DEST_EXTEN_PARTIAL,
2650         /*! The RURI is of an unsupported scheme */
2651         SIP_GET_DEST_UNSUPPORTED_URI,
2652 };
2653
2654 /*!
2655  * \brief Determine where in the dialplan a call should go
2656  *
2657  * This uses the username in the request URI to try to match
2658  * an extension in the endpoint's configured context in order
2659  * to route the call.
2660  *
2661  * \param session The inbound SIP session
2662  * \param rdata The SIP INVITE
2663  */
2664 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
2665 {
2666         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
2667         pjsip_sip_uri *sip_ruri;
2668         struct ast_features_pickup_config *pickup_cfg;
2669         const char *pickupexten;
2670
2671         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
2672                 return SIP_GET_DEST_UNSUPPORTED_URI;
2673         }
2674
2675         sip_ruri = pjsip_uri_get_uri(ruri);
2676         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
2677
2678         /*
2679          * We may want to match in the dialplan without any user
2680          * options getting in the way.
2681          */
2682         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);
2683
2684         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
2685         if (!pickup_cfg) {
2686                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
2687                 pickupexten = "";
2688         } else {
2689                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
2690                 ao2_ref(pickup_cfg, -1);
2691         }
2692
2693         if (!strcmp(session->exten, pickupexten) ||
2694                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
2695                 size_t size = pj_strlen(&sip_ruri->host) + 1;
2696                 char *domain = ast_alloca(size);
2697
2698                 ast_copy_pj_str(domain, &sip_ruri->host, size);
2699                 pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);
2700
2701                 return SIP_GET_DEST_EXTEN_FOUND;
2702         }
2703
2704         /*
2705          * Check for partial match via overlap dialling (if enabled)
2706          */
2707         if (session->endpoint->allow_overlap && (
2708                 !strncmp(session->exten, pickupexten, strlen(session->exten)) ||
2709                 ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {
2710                 /* Overlap partial match */
2711                 return SIP_GET_DEST_EXTEN_PARTIAL;
2712         }
2713
2714         return SIP_GET_DEST_EXTEN_NOT_FOUND;
2715 }
2716
2717 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
2718 {
2719         pjsip_tx_data *tdata;
2720         pjsip_dialog *dlg;
2721         pjsip_inv_session *inv_session;
2722         unsigned int options = endpoint->extensions.flags;
2723         pj_status_t dlg_status;
2724
2725         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
2726                 if (tdata) {
2727                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
2728                 } else {
2729                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2730                 }
2731                 return NULL;
2732         }
2733         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
2734         if (!dlg) {
2735                 if (dlg_status != PJ_EEXISTS) {
2736                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2737                 }
2738                 return NULL;
2739         }
2740         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
2741                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2742                 pjsip_dlg_terminate(dlg);
2743                 return NULL;
2744         }
2745
2746 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2747         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2748 #endif
2749         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2750                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
2751                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2752                 }
2753                 pjsip_inv_send_msg(inv_session, tdata);
2754                 return NULL;
2755         }
2756         return inv_session;
2757 }
2758
2759 struct new_invite {
2760         /*! \brief Session created for the new INVITE */
2761         struct ast_sip_session *session;
2762
2763         /*! \brief INVITE request itself */
2764         pjsip_rx_data *rdata;
2765 };
2766
2767 static int new_invite(struct new_invite *invite)
2768 {
2769         pjsip_tx_data *tdata = NULL;
2770         pjsip_timer_setting timer;
2771         pjsip_rdata_sdp_info *sdp_info;
2772         pjmedia_sdp_session *local = NULL;
2773
2774         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
2775          * so that we will be notified so we can destroy the session properly
2776          */
2777
2778         if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
2779                 ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",
2780                         invite->session->inv_session->cause,
2781                         pjsip_get_status_text(invite->session->inv_session->cause)->ptr);
2782 #ifdef HAVE_PJSIP_INV_SESSION_REF
2783                 pjsip_inv_dec_ref(invite->session->inv_session);
2784 #endif
2785                 return -1;
2786         }
2787
2788         switch (get_destination(invite->session, invite->rdata)) {
2789         case SIP_GET_DEST_EXTEN_FOUND:
2790                 /* Things worked. Keep going */
2791                 break;
2792         case SIP_GET_DEST_UNSUPPORTED_URI:
2793                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
2794                         ast_sip_session_send_response(invite->session, tdata);
2795                 } else  {
2796                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
2797                 }
2798                 goto end;
2799         case SIP_GET_DEST_EXTEN_PARTIAL:
2800                 ast_debug(1, "Call from '%s' (%s:%s:%d) to extension '%s' - partial match\n", ast_sorcery_object_get_id(invite->session->endpoint),
2801                         invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name, invite->rdata->pkt_info.src_port, invite->session->exten);
2802
2803                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {
2804                         ast_sip_session_send_response(invite->session, tdata);
2805                 } else  {
2806                         pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);
2807                 }
2808                 goto end;
2809         case SIP_GET_DEST_EXTEN_NOT_FOUND:
2810         default:
2811                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
2812                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
2813                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
2814
2815                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
2816                         ast_sip_session_send_response(invite->session, tdata);
2817                 } else  {
2818                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
2819                 }
2820                 goto end;
2821         };
2822
2823         pjsip_timer_setting_default(&timer);
2824         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
2825         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
2826         pjsip_timer_init_session(invite->session->inv_session, &timer);
2827
2828         /*
2829          * At this point, we've verified what we can that won't take awhile,
2830          * so let's go ahead and send a 100 Trying out to stop any
2831          * retransmissions.
2832          */
2833         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
2834                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
2835                 goto end;
2836         }
2837         ast_sip_session_send_response(invite->session, tdata);
2838
2839         sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);
2840         if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
2841                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
2842                         tdata = NULL;
2843                         if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS
2844                                 && tdata) {
2845                                 ast_sip_session_send_response(invite->session, tdata);
2846                         }
2847                         goto end;
2848                 }
2849                 /* We are creating a local SDP which is an answer to their offer */
2850                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
2851         } else {
2852                 /* We are creating a local SDP which is an offer */
2853                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
2854         }
2855
2856         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
2857         if (!local) {
2858                 tdata = NULL;
2859                 if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS
2860                         && tdata) {
2861                         ast_sip_session_send_response(invite->session, tdata);
2862                 }
2863                 goto end;
2864         }
2865
2866         pjsip_inv_set_local_sdp(invite->session->inv_session, local);
2867         pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
2868 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2869         if (!invite->session->endpoint->preferred_codec_only) {
2870                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
2871         }
2872 #endif
2873
2874         handle_incoming_request(invite->session, invite->rdata);
2875
2876 end:
2877 #ifdef HAVE_PJSIP_INV_SESSION_REF
2878         pjsip_inv_dec_ref(invite->session->inv_session);
2879 #endif
2880         return 0;
2881 }
2882
2883 static void handle_new_invite_request(pjsip_rx_data *rdata)
2884 {
2885         RAII_VAR(struct ast_sip_endpoint *, endpoint,
2886                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
2887         pjsip_tx_data *tdata = NULL;
2888         pjsip_inv_session *inv_session = NULL;
2889         struct ast_sip_session *session;
2890         struct new_invite invite;
2891
2892         ast_assert(endpoint != NULL);
2893
2894         inv_session = pre_session_setup(rdata, endpoint);
2895         if (!inv_session) {
2896                 /* pre_session_setup() returns a response on failure */
2897                 return;
2898         }
2899
2900 #ifdef HAVE_PJSIP_INV_SESSION_REF
2901         if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {
2902                 ast_log(LOG_ERROR, "Can't increase the session reference counter\n");
2903                 if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {
2904                         if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
2905                                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2906                         } else {
2907                                 pjsip_inv_send_msg(inv_session, tdata);
2908                         }
2909                 }
2910                 return;
2911         }
2912 #endif
2913
2914         session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);
2915         if (!session) {
2916                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
2917                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2918                 } else {
2919                         pjsip_inv_send_msg(inv_session, tdata);
2920                 }
2921 #ifdef HAVE_PJSIP_INV_SESSION_REF
2922                 pjsip_inv_dec_ref(inv_session);
2923 #endif
2924                 return;
2925         }
2926
2927         /*
2928          * The current thread is supposed be the session serializer to prevent
2929          * any initial INVITE retransmissions from trying to setup the same
2930          * call again.
2931          */
2932         ast_assert(ast_taskprocessor_is_task(session->serializer));
2933
2934         invite.session = session;
2935         invite.rdata = rdata;
2936         new_invite(&invite);
2937
2938         ao2_ref(session, -1);
2939 }
2940
2941 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
2942 {
2943         pj_str_t method;
2944
2945         if (ast_strlen_zero(supplement_method)) {
2946                 return PJ_TRUE;
2947         }
2948
2949         pj_cstr(&method, supplement_method);
2950
2951         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
2952 }
2953
2954 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
2955 {
2956         struct ast_sip_session_supplement *supplement;
2957         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
2958
2959         if (!session) {
2960                 return PJ_FALSE;
2961         }
2962
2963         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2964                 if (does_method_match(&method->name, supplement->method)) {
2965                         return PJ_TRUE;
2966                 }
2967         }
2968         return PJ_FALSE;
2969 }
2970 /*!
2971  * \brief Called when a new SIP request comes into PJSIP
2972  *
2973  * This function is called under two circumstances
2974  * 1) An out-of-dialog request is received by PJSIP
2975  * 2) An in-dialog request that the inv_session layer does not
2976  *    handle is received (such as an in-dialog INFO)
2977  *
2978  * Except for INVITEs, there is very little we actually do in this function
2979  * 1) For requests we don't handle, we return PJ_FALSE
2980  * 2) For new INVITEs, handle them now to prevent retransmissions from
2981  *    trying to setup the same call again.
2982  * 3) For in-dialog requests we handle, we process them in the
2983  *    .on_state_changed = session_inv_on_state_changed or
2984  *    .on_tsx_state_changed = session_inv_on_tsx_state_changed
2985  *    callbacks instead.
2986  */
2987 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
2988 {
2989         pj_status_t handled = PJ_FALSE;
2990         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
2991         pjsip_inv_session *inv_session;
2992
2993         switch (rdata->msg_info.msg->line.req.method.id) {
2994         case PJSIP_INVITE_METHOD:
2995                 if (dlg) {
2996                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
2997                         break;
2998                 }
2999                 handled = PJ_TRUE;
3000                 handle_new_invite_request(rdata);
3001                 break;
3002         default:
3003                 /* Handle other in-dialog methods if their supplements have been registered */
3004                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
3005                         has_supplement(inv_session->mod_data[session_module.id], rdata);
3006                 break;
3007         }
3008
3009         return handled;
3010 }
3011
3012 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
3013 {
3014         struct ast_sip_session *session = entry->user_data;
3015
3016         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
3017                 ast_sorcery_object_get_id(session->endpoint),
3018                 session->channel ? ast_channel_name(session->channel) : "");
3019
3020         if (AST_LIST_EMPTY(&session->delayed_requests)) {
3021                 /* No delayed request pending, so just return */
3022                 ao2_ref(session, -1);
3023                 return;
3024         }
3025         if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
3026                 /*
3027                  * Uh oh.  We now have nothing in the foreseeable future
3028                  * to trigger sending the delayed requests.
3029                  */
3030                 ao2_ref(session, -1);
3031         }
3032 }
3033
3034 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
3035 {
3036         pjsip_inv_session *inv = session->inv_session;
3037         pj_time_val tv;
3038
3039         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
3040                 ast_sorcery_object_get_id(session->endpoint),
3041                 session->channel ? ast_channel_name(session->channel) : "");
3042         if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE, NULL)) {
3043                 return;
3044         }
3045         if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
3046                 /* Timer already running.  Something weird is going on. */
3047                 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
3048                         ast_sorcery_object_get_id(session->endpoint),
3049                         session->channel ? ast_channel_name(session->channel) : "");
3050                 return;
3051         }
3052
3053         tv.sec = 0;
3054         if (inv->role == PJSIP_ROLE_UAC) {
3055                 tv.msec = 2100 + ast_random() % 2000;
3056         } else {
3057                 tv.msec = ast_random() % 2000;
3058         }
3059         pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
3060
3061         ao2_ref(session, +1);
3062         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
3063                 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
3064                 ao2_ref(session, -1);
3065         }
3066 }
3067
3068 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
3069 {
3070         int id = session_module.id;
3071         struct ast_sip_session *session = NULL;
3072
3073         if (!DEBUG_ATLEAST(5)) {
3074                 /* Debug not spamy enough */
3075                 return;
3076         }
3077
3078         ast_log(LOG_DEBUG, "Function %s called on event %s\n",
3079                 function, pjsip_event_str(e->type));
3080         if (!inv) {
3081                 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
3082                 ast_log(LOG_DEBUG, "The transaction state is %s\n",
3083                         pjsip_tsx_state_str(tsx->state));
3084                 return;
3085         }
3086         if (id > -1) {
3087                 session = inv->mod_data[session_module.id];
3088         }
3089         if (!session) {
3090                 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
3091         } else {
3092                 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
3093                         ast_sorcery_object_get_id(session->endpoint),
3094                         session->channel ? ast_channel_name(session->channel) : "");
3095         }
3096         if (inv->invite_tsx) {
3097                 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
3098                         inv->invite_tsx);
3099         } else {
3100                 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
3101         }
3102         if (tsx) {
3103                 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
3104                         pjsip_role_name(tsx->role),
3105                         (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
3106                         tsx);
3107                 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
3108                         pjsip_tsx_state_str(tsx->state));
3109                 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
3110                         pjsip_event_str(e->body.tsx_state.type));
3111         } else {
3112                 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
3113         }
3114         ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
3115 }
3116
3117 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
3118
3119 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
3120 {
3121         struct ast_sip_session_supplement *supplement;
3122         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
3123
3124         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
3125         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3126                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
3127                         if (supplement->incoming_request(session, rdata)) {
3128                                 break;
3129                         }
3130                 }
3131         }
3132 }
3133
3134 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
3135                 enum ast_sip_session_response_priority response_priority)
3136 {
3137         struct ast_sip_session_supplement *supplement;
3138         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
3139
3140         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
3141                         pj_strbuf(&status.reason));
3142
3143         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
3144                 if (!(supplement->response_priority & response_priority)) {
3145                         continue;
3146                 }
3147                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
3148                         supplement->incoming_response(session, rdata);
3149                 }