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