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