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