format_mp3: Made the get script conditionally apply patch if not already there.
[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 static int validate_port_hash(const void *obj, int flags)
190 {
191         const int *port = obj;
192         return *port;
193 }
194
195 static int validate_port_cmp(void *obj, void *arg, int flags)
196 {
197         int *port1 = obj;
198         int *port2 = arg;
199
200         return *port1 == *port2 ? CMP_MATCH | CMP_STOP : 0;
201 }
202
203 struct bundle_assoc {
204         int port;
205         char tag[1];
206 };
207
208 static int bundle_assoc_hash(const void *obj, int flags)
209 {
210         const struct bundle_assoc *assoc = obj;
211         const char *tag = flags & OBJ_KEY ? obj : assoc->tag;
212
213         return ast_str_hash(tag);
214 }
215
216 static int bundle_assoc_cmp(void *obj, void *arg, int flags)
217 {
218         struct bundle_assoc *assoc1 = obj;
219         struct bundle_assoc *assoc2 = arg;
220         const char *tag2 = flags & OBJ_KEY ? arg : assoc2->tag;
221
222         return strcmp(assoc1->tag, tag2) ? 0 : CMP_MATCH | CMP_STOP;
223 }
224
225 /* return must be ast_freed */
226 static pjmedia_sdp_attr *media_get_mid(pjmedia_sdp_media *media)
227 {
228         pjmedia_sdp_attr *attr = pjmedia_sdp_media_find_attr2(media, "mid", NULL);
229         if (!attr) {
230                 return NULL;
231         }
232
233         return attr;
234 }
235
236 static int get_bundle_port(const pjmedia_sdp_session *sdp, const char *mid)
237 {
238         int i;
239         for (i = 0; i < sdp->media_count; ++i) {
240                 pjmedia_sdp_attr *mid_attr = media_get_mid(sdp->media[i]);
241                 if (mid_attr && !pj_strcmp2(&mid_attr->value, mid)) {
242                         return sdp->media[i]->desc.port;
243                 }
244         }
245
246         return -1;
247 }
248
249 static int validate_incoming_sdp(const pjmedia_sdp_session *sdp)
250 {
251         int i;
252         RAII_VAR(struct ao2_container *, portlist, ao2_container_alloc(5, validate_port_hash, validate_port_cmp), ao2_cleanup);
253         RAII_VAR(struct ao2_container *, bundle_assoc_list, ao2_container_alloc(5, bundle_assoc_hash, bundle_assoc_cmp), ao2_cleanup);
254
255         /* check for bundles (for websocket RTP multiplexing, there can be more than one) */
256         for (i = 0; i < sdp->attr_count; ++i) {
257                 char *bundle_list;
258                 int bundle_port = 0;
259                 if (pj_stricmp2(&sdp->attr[i]->name, "group")) {
260                         continue;
261                 }
262
263                 /* check to see if this group is a bundle */
264                 if (7 >= sdp->attr[i]->value.slen || pj_strnicmp2(&sdp->attr[i]->value, "bundle ", 7)) {
265                         continue;
266                 }
267
268                 bundle_list = ast_alloca(sdp->attr[i]->value.slen - 6);
269                 strncpy(bundle_list, sdp->attr[i]->value.ptr + 7, sdp->attr[i]->value.slen - 7);
270                 bundle_list[sdp->attr[i]->value.slen - 7] = '\0';
271                 while (bundle_list) {
272                         char *item;
273                         RAII_VAR(struct bundle_assoc *, assoc, NULL, ao2_cleanup);
274                         item = strsep(&bundle_list, " ,");
275                         if (!bundle_port) {
276                                 RAII_VAR(int *, port, ao2_alloc(sizeof(int), NULL), ao2_cleanup);
277                                 RAII_VAR(int *, port_match, NULL, ao2_cleanup);
278                                 bundle_port = get_bundle_port(sdp, item);
279                                 if (bundle_port < 0) {
280                                         return -1;
281                                 }
282                                 port_match = ao2_find(portlist, &bundle_port, OBJ_KEY);
283                                 if (port_match) {
284                                         /* bundle port aready consumed by a different bundle */
285                                         return -1;
286                                 }
287                                 *port = bundle_port;
288                                 ao2_link(portlist, port);
289                         }
290                         assoc = ao2_alloc(sizeof(*assoc) + strlen(item), NULL);
291                         if (!assoc) {
292                                 return -1;
293                         }
294
295                         /* safe use of strcpy */
296                         strcpy(assoc->tag, item);
297                         assoc->port = bundle_port;
298                         ao2_link(bundle_assoc_list, assoc);
299                 }
300         }
301
302         /* validate all streams */
303         for (i = 0; i < sdp->media_count; ++i) {
304                 RAII_VAR(int *, port, ao2_alloc(sizeof(int), NULL), ao2_cleanup);
305                 RAII_VAR(int *, port_match, NULL, ao2_cleanup);
306
307                 *port = sdp->media[i]->desc.port;
308                 port_match = ao2_find(portlist, port, OBJ_KEY);
309                 if (port_match) {
310                         RAII_VAR(struct bundle_assoc *, assoc, NULL, ao2_cleanup);
311                         pjmedia_sdp_attr *mid = media_get_mid(sdp->media[i]);
312                         char *mid_val;
313
314                         if (!mid) {
315                                 /* not part of a bundle */
316                                 return -1;
317                         }
318
319                         mid_val = ast_alloca(mid->value.slen + 1);
320                         strncpy(mid_val, mid->value.ptr, mid->value.slen);
321                         mid_val[mid->value.slen] = '\0';
322
323                         assoc = ao2_find(bundle_assoc_list, mid_val, OBJ_KEY);
324                         if (!assoc || assoc->port != *port) {
325                                 /* This port already exists elsewhere in the SDP
326                                  * and is not an appropriate bundle port, fail
327                                  * catastrophically */
328                                 return -1;
329                         }
330                 }
331                 ao2_link(portlist, port);
332         }
333         return 0;
334 }
335
336 static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
337 {
338         int i;
339
340         if (validate_incoming_sdp(sdp)) {
341                 return -1;
342         }
343
344         for (i = 0; i < sdp->media_count; ++i) {
345                 /* See if there are registered handlers for this media stream type */
346                 char media[20];
347                 struct ast_sip_session_sdp_handler *handler;
348                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
349                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
350                 int res;
351
352                 /* We need a null-terminated version of the media string */
353                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
354
355                 session_media = ao2_find(session->media, media, OBJ_KEY);
356                 if (!session_media) {
357                         /* if the session_media doesn't exist, there weren't
358                          * any handlers at the time of its creation */
359                         continue;
360                 }
361
362                 if (session_media->handler) {
363                         handler = session_media->handler;
364                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
365                                 sdp->media[i]);
366                         if (res <= 0) {
367                                 /* Catastrophic failure or ignored by assigned handler. Abort! */
368                                 return -1;
369                         }
370                         /* Handled by this handler. Move to the next stream */
371                         continue;
372                 }
373
374                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
375                 if (!handler_list) {
376                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
377                         continue;
378                 }
379                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
380                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
381                                 sdp->media[i]);
382                         if (res < 0) {
383                                 /* Catastrophic failure. Abort! */
384                                 return -1;
385                         }
386                         if (res > 0) {
387                                 /* Handled by this handler. Move to the next stream */
388                                 session_media->handler = handler;
389                                 break;
390                         }
391                 }
392         }
393         return 0;
394 }
395
396 struct handle_negotiated_sdp_cb {
397         struct ast_sip_session *session;
398         const pjmedia_sdp_session *local;
399         const pjmedia_sdp_session *remote;
400 };
401
402 static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)
403 {
404         struct ast_sip_session_media *session_media = obj;
405         struct handle_negotiated_sdp_cb *callback_data = arg;
406         struct ast_sip_session *session = callback_data->session;
407         const pjmedia_sdp_session *local = callback_data->local;
408         const pjmedia_sdp_session *remote = callback_data->remote;
409         int i;
410
411         for (i = 0; i < local->media_count; ++i) {
412                 /* See if there are registered handlers for this media stream type */
413                 char media[20];
414                 struct ast_sip_session_sdp_handler *handler;
415                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
416                 int res;
417
418                 if (!remote->media[i]) {
419                         continue;
420                 }
421
422                 /* We need a null-terminated version of the media string */
423                 ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));
424
425                 /* stream type doesn't match the one we're looking to fill */
426                 if (strcasecmp(session_media->stream_type, media)) {
427                         continue;
428                 }
429
430                 handler = session_media->handler;
431                 if (handler) {
432                         res = handler->apply_negotiated_sdp_stream(session, session_media, local,
433                                 local->media[i], remote, remote->media[i]);
434                         if (res >= 0) {
435                                 return CMP_MATCH;
436                         }
437                         return 0;
438                 }
439
440                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
441                 if (!handler_list) {
442                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
443                         continue;
444                 }
445                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
446                         res = handler->apply_negotiated_sdp_stream(session, session_media, local,
447                                 local->media[i], remote, remote->media[i]);
448                         if (res < 0) {
449                                 /* Catastrophic failure. Abort! */
450                                 return 0;
451                         }
452                         if (res > 0) {
453                                 /* Handled by this handler. Move to the next stream */
454                                 session_media->handler = handler;
455                                 return CMP_MATCH;
456                         }
457                 }
458         }
459         return CMP_MATCH;
460 }
461
462 static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
463 {
464         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
465         struct handle_negotiated_sdp_cb callback_data = {
466                 .session = session,
467                 .local = local,
468                 .remote = remote,
469         };
470
471         successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);
472         if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {
473                 /* Nothing experienced a catastrophic failure */
474                 ast_queue_frame(session->channel, &ast_null_frame);
475                 return 0;
476         }
477         return -1;
478 }
479
480 AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);
481
482 int ast_sip_session_register_supplement(struct ast_sip_session_supplement *supplement)
483 {
484         struct ast_sip_session_supplement *iter;
485         int inserted = 0;
486         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
487
488         if (!supplement->response_priority) {
489                 supplement->response_priority = AST_SIP_SESSION_BEFORE_MEDIA;
490         }
491
492         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
493                 if (iter->priority > supplement->priority) {
494                         AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
495                         inserted = 1;
496                         break;
497                 }
498         }
499         AST_RWLIST_TRAVERSE_SAFE_END;
500
501         if (!inserted) {
502                 AST_RWLIST_INSERT_TAIL(&session_supplements, supplement, next);
503         }
504         ast_module_ref(ast_module_info->self);
505         return 0;
506 }
507
508 void ast_sip_session_unregister_supplement(struct ast_sip_session_supplement *supplement)
509 {
510         struct ast_sip_session_supplement *iter;
511         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
512         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
513                 if (supplement == iter) {
514                         AST_RWLIST_REMOVE_CURRENT(next);
515                         ast_module_unref(ast_module_info->self);
516                         break;
517                 }
518         }
519         AST_RWLIST_TRAVERSE_SAFE_END;
520 }
521
522 static struct ast_sip_session_supplement *supplement_dup(const struct ast_sip_session_supplement *src)
523 {
524         struct ast_sip_session_supplement *dst = ast_calloc(1, sizeof(*dst));
525         if (!dst) {
526                 return NULL;
527         }
528         /* Will need to revisit if shallow copy becomes an issue */
529         *dst = *src;
530         return dst;
531 }
532
533 #define DATASTORE_BUCKETS 53
534 #define MEDIA_BUCKETS 7
535
536 static void session_datastore_destroy(void *obj)
537 {
538         struct ast_datastore *datastore = obj;
539
540         /* Using the destroy function (if present) destroy the data */
541         if (datastore->info->destroy != NULL && datastore->data != NULL) {
542                 datastore->info->destroy(datastore->data);
543                 datastore->data = NULL;
544         }
545
546         ast_free((void *) datastore->uid);
547         datastore->uid = NULL;
548 }
549
550 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
551 {
552         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
553         const char *uid_ptr = uid;
554
555         if (!info) {
556                 return NULL;
557         }
558
559         datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
560         if (!datastore) {
561                 return NULL;
562         }
563
564         datastore->info = info;
565         if (ast_strlen_zero(uid)) {
566                 /* They didn't provide an ID so we'll provide one ourself */
567                 struct ast_uuid *uuid = ast_uuid_generate();
568                 char uuid_buf[AST_UUID_STR_LEN];
569                 if (!uuid) {
570                         return NULL;
571                 }
572                 uid_ptr = ast_uuid_to_str(uuid, uuid_buf, sizeof(uuid_buf));
573                 ast_free(uuid);
574         }
575
576         datastore->uid = ast_strdup(uid_ptr);
577         if (!datastore->uid) {
578                 return NULL;
579         }
580
581         ao2_ref(datastore, +1);
582         return datastore;
583 }
584
585 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
586 {
587         ast_assert(datastore != NULL);
588         ast_assert(datastore->info != NULL);
589         ast_assert(ast_strlen_zero(datastore->uid) == 0);
590
591         if (!ao2_link(session->datastores, datastore)) {
592                 return -1;
593         }
594         return 0;
595 }
596
597 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
598 {
599         return ao2_find(session->datastores, name, OBJ_KEY);
600 }
601
602 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
603 {
604         ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
605 }
606
607 /*!
608  * \brief Structure used for sending delayed requests
609  *
610  * Requests are typically delayed because the current transaction
611  * state of an INVITE. Once the pending INVITE transaction terminates,
612  * the delayed request will be sent
613  */
614 struct ast_sip_session_delayed_request {
615         /*! Method of the request */
616         char method[15];
617         /*! Callback to call when the delayed request is created. */
618         ast_sip_session_request_creation_cb on_request_creation;
619         /*! Callback to call when the delayed request SDP is created */
620         ast_sip_session_sdp_creation_cb on_sdp_creation;
621         /*! Callback to call when the delayed request receives a response */
622         ast_sip_session_response_cb on_response;
623         /*! Request to send */
624         pjsip_tx_data *tdata;
625         AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
626 };
627
628 static struct ast_sip_session_delayed_request *delayed_request_alloc(const char *method,
629                 ast_sip_session_request_creation_cb on_request_creation,
630                 ast_sip_session_sdp_creation_cb on_sdp_creation,
631                 ast_sip_session_response_cb on_response,
632                 pjsip_tx_data *tdata)
633 {
634         struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
635         if (!delay) {
636                 return NULL;
637         }
638         ast_copy_string(delay->method, method, sizeof(delay->method));
639         delay->on_request_creation = on_request_creation;
640         delay->on_sdp_creation = on_sdp_creation;
641         delay->on_response = on_response;
642         delay->tdata = tdata;
643         return delay;
644 }
645
646 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
647 {
648         ast_debug(3, "Sending delayed %s request to %s\n", delay->method, ast_sorcery_object_get_id(session->endpoint));
649
650         if (delay->tdata) {
651                 ast_sip_session_send_request_with_cb(session, delay->tdata, delay->on_response);
652                 return 0;
653         }
654
655         if (!strcmp(delay->method, "INVITE")) {
656                 ast_sip_session_refresh(session, delay->on_request_creation,
657                                 delay->on_sdp_creation, delay->on_response, AST_SIP_SESSION_REFRESH_METHOD_INVITE, 1);
658         } else if (!strcmp(delay->method, "UPDATE")) {
659                 ast_sip_session_refresh(session, delay->on_request_creation,
660                                 delay->on_sdp_creation, delay->on_response, AST_SIP_SESSION_REFRESH_METHOD_UPDATE, 1);
661         } else {
662                 ast_log(LOG_WARNING, "Unexpected delayed %s request with no existing request structure\n", delay->method);
663                 return -1;
664         }
665         return 0;
666 }
667
668 static int queued_delayed_request_send(void *data)
669 {
670         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
671         RAII_VAR(struct ast_sip_session_delayed_request *, delay, NULL, ast_free_ptr);
672
673         delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next);
674         if (!delay) {
675                 return 0;
676         }
677
678         return send_delayed_request(session, delay);
679 }
680
681 static void queue_delayed_request(struct ast_sip_session *session)
682 {
683         if (AST_LIST_EMPTY(&session->delayed_requests)) {
684                 /* No delayed request to send, so just return */
685                 return;
686         }
687
688         ast_debug(3, "Queuing delayed request to run for %s\n",
689                         ast_sorcery_object_get_id(session->endpoint));
690
691         ao2_ref(session, +1);
692         ast_sip_push_task(session->serializer, queued_delayed_request_send, session);
693 }
694
695 static int delay_request(struct ast_sip_session *session, ast_sip_session_request_creation_cb on_request,
696                 ast_sip_session_sdp_creation_cb on_sdp_creation, ast_sip_session_response_cb on_response,
697                 const char *method, pjsip_tx_data *tdata)
698 {
699         struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
700                         on_request, on_sdp_creation, on_response, tdata);
701
702         if (!delay) {
703                 return -1;
704         }
705
706         AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
707         return 0;
708 }
709
710 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
711 {
712         pjsip_inv_session *inv_session = session->inv_session;
713         const pjmedia_sdp_session *previous_sdp;
714
715         if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
716                 pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
717         } else {
718                 pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
719         }
720         return create_local_sdp(inv_session, session, previous_sdp);
721 }
722
723 int ast_sip_session_refresh(struct ast_sip_session *session,
724                 ast_sip_session_request_creation_cb on_request_creation,
725                 ast_sip_session_sdp_creation_cb on_sdp_creation,
726                 ast_sip_session_response_cb on_response,
727                 enum ast_sip_session_refresh_method method, int generate_new_sdp)
728 {
729         pjsip_inv_session *inv_session = session->inv_session;
730         pjmedia_sdp_session *new_sdp = NULL;
731         pjsip_tx_data *tdata;
732
733         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
734                 /* Don't try to do anything with a hung-up call */
735                 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
736                                 ast_sorcery_object_get_id(session->endpoint));
737                 return 0;
738         }
739
740         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
741                 if (inv_session->invite_tsx) {
742                         /* We can't send a reinvite yet, so delay it */
743                         ast_debug(3, "Delaying sending reinvite to %s because of outstanding transaction...\n",
744                                         ast_sorcery_object_get_id(session->endpoint));
745                         return delay_request(session, on_request_creation, on_sdp_creation, on_response, "INVITE", NULL);
746                 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
747                         /* Initial INVITE transaction failed to progress us to a confirmed state
748                          * which means re-invites are not possible
749                          */
750                         ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
751                                         ast_sorcery_object_get_id(session->endpoint));
752                         return 0;
753                 }
754         }
755
756         if (generate_new_sdp) {
757                 new_sdp = generate_session_refresh_sdp(session);
758                 if (!new_sdp) {
759                         ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
760                         return -1;
761                 }
762                 if (on_sdp_creation) {
763                         if (on_sdp_creation(session, new_sdp)) {
764                                 return -1;
765                         }
766                 }
767         }
768
769         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
770                 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
771                         ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
772                         return -1;
773                 }
774         } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
775                 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
776                 return -1;
777         }
778         if (on_request_creation) {
779                 if (on_request_creation(session, tdata)) {
780                         return -1;
781                 }
782         }
783         ast_debug(3, "Sending session refresh SDP via %s to %s\n",
784                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
785                 ast_sorcery_object_get_id(session->endpoint));
786         ast_sip_session_send_request_with_cb(session, tdata, on_response);
787         return 0;
788 }
789
790 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
791 {
792         handle_outgoing_response(session, tdata);
793         pjsip_inv_send_msg(session->inv_session, tdata);
794         return;
795 }
796
797 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
798
799 static pjsip_module session_module = {
800         .name = {"Session Module", 14},
801         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
802         .on_rx_request = session_on_rx_request,
803 };
804
805 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
806  *
807  * \retval 1 re-invite should be deferred and resumed later
808  * \retval 0 re-invite should not be deferred
809  */
810 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
811 {
812         int i;
813
814         if (validate_incoming_sdp(sdp)) {
815                 return 0;
816         }
817
818         for (i = 0; i < sdp->media_count; ++i) {
819                 /* See if there are registered handlers for this media stream type */
820                 char media[20];
821                 struct ast_sip_session_sdp_handler *handler;
822                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
823                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
824                 enum ast_sip_session_sdp_stream_defer res;
825
826                 /* We need a null-terminated version of the media string */
827                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
828
829                 session_media = ao2_find(session->media, media, OBJ_KEY);
830                 if (!session_media) {
831                         /* if the session_media doesn't exist, there weren't
832                          * any handlers at the time of its creation */
833                         continue;
834                 }
835
836                 if (session_media->handler) {
837                         handler = session_media->handler;
838                         if (handler->defer_incoming_sdp_stream) {
839                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
840                                         sdp->media[i]);
841                                 switch (res) {
842                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
843                                         break;
844                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
845                                         return 0;
846                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
847                                         break;
848                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
849                                         return 1;
850                                 }
851                         }
852                         /* Handled by this handler. Move to the next stream */
853                         continue;
854                 }
855
856                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
857                 if (!handler_list) {
858                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
859                         continue;
860                 }
861                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
862                         if (!handler->defer_incoming_sdp_stream) {
863                                 continue;
864                         }
865                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
866                                 sdp->media[i]);
867                         switch (res) {
868                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
869                                 continue;
870                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
871                                 session_media->handler = handler;
872                                 return 0;
873                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
874                                 /* Handled by this handler. */
875                                 session_media->handler = handler;
876                                 break;
877                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
878                                 /* Handled by this handler. */
879                                 session_media->handler = handler;
880                                 return 1;
881                         }
882                         /* Move to the next stream */
883                         break;
884                 }
885         }
886         return 0;
887 }
888
889 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
890 {
891         pjsip_dialog *dlg;
892         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
893         pjsip_rdata_sdp_info *sdp_info;
894
895         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
896                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
897                 !(session = ast_sip_dialog_get_session(dlg))) {
898                 return PJ_FALSE;
899         }
900
901         if (session->deferred_reinvite) {
902                 pj_str_t key, deferred_key;
903                 pjsip_tx_data *tdata;
904
905                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
906                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
907                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
908                         session->deferred_reinvite);
909
910                 /* If this is a retransmission ignore it */
911                 if (!pj_strcmp(&key, &deferred_key)) {
912                         return PJ_TRUE;
913                 }
914
915                 /* Otherwise this is a new re-invite, so reject it */
916                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
917                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
918                 }
919
920                 return PJ_TRUE;
921         }
922
923         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
924                 (sdp_info->sdp_err != PJ_SUCCESS)) {
925                 return PJ_FALSE;
926         }
927
928         if (!sdp_info->sdp) {
929                 ast_queue_unhold(session->channel);
930                 return PJ_FALSE;
931         }
932
933         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
934                 return PJ_FALSE;
935         }
936
937         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
938
939         return PJ_TRUE;
940 }
941
942 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
943 {
944         if (!session->deferred_reinvite) {
945                 return;
946         }
947
948         pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(), session->deferred_reinvite, NULL, NULL);
949         pjsip_rx_data_free_cloned(session->deferred_reinvite);
950         session->deferred_reinvite = NULL;
951 }
952
953 static pjsip_module session_reinvite_module = {
954         .name = { "Session Re-Invite Module", 24 },
955         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
956         .on_rx_request = session_reinvite_on_rx_request,
957 };
958
959 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
960                 ast_sip_session_response_cb on_response)
961 {
962         pjsip_inv_session *inv_session = session->inv_session;
963
964         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
965                 /* Don't try to do anything with a hung-up call */
966                 return;
967         }
968
969         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
970                              MOD_DATA_ON_RESPONSE, on_response);
971
972         if (!ast_strlen_zero(session->endpoint->fromuser) ||
973                 !ast_strlen_zero(session->endpoint->fromdomain)) {
974                 pjsip_fromto_hdr *from = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_FROM, tdata->msg->hdr.next);
975                 pjsip_sip_uri *uri = pjsip_uri_get_uri(from->uri);
976
977                 if (!ast_strlen_zero(session->endpoint->fromuser)) {
978                         pj_strdup2(tdata->pool, &uri->user, session->endpoint->fromuser);
979                 }
980                 if (!ast_strlen_zero(session->endpoint->fromdomain)) {
981                         pj_strdup2(tdata->pool, &uri->host, session->endpoint->fromdomain);
982                 }
983         }
984
985         handle_outgoing_request(session, tdata);
986         pjsip_inv_send_msg(session->inv_session, tdata);
987         return;
988 }
989
990 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
991 {
992         ast_sip_session_send_request_with_cb(session, tdata, NULL);
993 }
994
995 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
996 {
997         pjmedia_sdp_session *offer;
998
999         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1000                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1001                 return -1;
1002         }
1003
1004         pjsip_inv_set_local_sdp(session->inv_session, offer);
1005         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
1006 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1007         pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
1008 #endif
1009         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
1010                 return -1;
1011         }
1012         return 0;
1013 }
1014
1015 static int datastore_hash(const void *obj, int flags)
1016 {
1017         const struct ast_datastore *datastore = obj;
1018         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1019
1020         ast_assert(uid != NULL);
1021
1022         return ast_str_hash(uid);
1023 }
1024
1025 static int datastore_cmp(void *obj, void *arg, int flags)
1026 {
1027         const struct ast_datastore *datastore1 = obj;
1028         const struct ast_datastore *datastore2 = arg;
1029         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1030
1031         ast_assert(datastore1->uid != NULL);
1032         ast_assert(uid2 != NULL);
1033
1034         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1035 }
1036
1037 static void session_media_dtor(void *obj)
1038 {
1039         struct ast_sip_session_media *session_media = obj;
1040         if (session_media->handler) {
1041                 session_media->handler->stream_destroy(session_media);
1042         }
1043         if (session_media->srtp) {
1044                 ast_sdp_srtp_destroy(session_media->srtp);
1045         }
1046 }
1047
1048 static void session_destructor(void *obj)
1049 {
1050         struct ast_sip_session *session = obj;
1051         struct ast_sip_session_supplement *supplement;
1052         struct ast_sip_session_delayed_request *delay;
1053
1054         ast_debug(3, "Destroying SIP session with endpoint %s\n",
1055                         ast_sorcery_object_get_id(session->endpoint));
1056
1057         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
1058                 if (supplement->session_destroy) {
1059                         supplement->session_destroy(session);
1060                 }
1061                 ast_free(supplement);
1062         }
1063
1064         ast_taskprocessor_unreference(session->serializer);
1065         ao2_cleanup(session->datastores);
1066         ao2_cleanup(session->media);
1067
1068         AST_LIST_HEAD_DESTROY(&session->supplements);
1069         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1070                 ast_free(delay);
1071         }
1072         ast_party_id_free(&session->id);
1073         ao2_cleanup(session->endpoint);
1074         ao2_cleanup(session->contact);
1075         ao2_cleanup(session->req_caps);
1076         ao2_cleanup(session->direct_media_cap);
1077
1078         if (session->dsp) {
1079                 ast_dsp_free(session->dsp);
1080         }
1081
1082         if (session->inv_session) {
1083                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1084         }
1085 }
1086
1087 static int add_supplements(struct ast_sip_session *session)
1088 {
1089         struct ast_sip_session_supplement *iter;
1090         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1091
1092         AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1093                 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1094                 if (!copy) {
1095                         return -1;
1096                 }
1097                 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1098         }
1099         return 0;
1100 }
1101
1102 static int add_session_media(void *obj, void *arg, int flags)
1103 {
1104         struct sdp_handler_list *handler_list = obj;
1105         struct ast_sip_session * session = arg;
1106         RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1107         session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
1108         if (!session_media) {
1109                 return CMP_STOP;
1110         }
1111         /* Safe use of strcpy */
1112         strcpy(session_media->stream_type, handler_list->stream_type);
1113         ao2_link(session->media, session_media);
1114         return 0;
1115 }
1116
1117 /*! \brief Destructor for SIP channel */
1118 static void sip_channel_destroy(void *obj)
1119 {
1120         struct ast_sip_channel_pvt *channel = obj;
1121
1122         ao2_cleanup(channel->pvt);
1123         ao2_cleanup(channel->session);
1124 }
1125
1126 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1127 {
1128         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1129
1130         if (!channel) {
1131                 return NULL;
1132         }
1133
1134         ao2_ref(pvt, +1);
1135         channel->pvt = pvt;
1136         ao2_ref(session, +1);
1137         channel->session = session;
1138
1139         return channel;
1140 }
1141
1142 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
1143         struct ast_sip_contact *contact, pjsip_inv_session *inv_session)
1144 {
1145         RAII_VAR(struct ast_sip_session *, session, ao2_alloc(sizeof(*session), session_destructor), ao2_cleanup);
1146         struct ast_sip_session_supplement *iter;
1147         int dsp_features = 0;
1148         if (!session) {
1149                 return NULL;
1150         }
1151         AST_LIST_HEAD_INIT(&session->supplements);
1152         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1153         if (!session->datastores) {
1154                 return NULL;
1155         }
1156
1157         session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
1158         if (!session->media) {
1159                 return NULL;
1160         }
1161         /* fill session->media with available types */
1162         ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
1163
1164         session->serializer = ast_sip_create_serializer();
1165         if (!session->serializer) {
1166                 return NULL;
1167         }
1168         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
1169         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
1170         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
1171         inv_session->mod_data[session_module.id] = ao2_bump(session);
1172         session->endpoint = ao2_bump(endpoint);
1173         session->contact = ao2_bump(contact);
1174         session->inv_session = inv_session;
1175         session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1176
1177         if (endpoint->dtmf == AST_SIP_DTMF_INBAND) {
1178                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
1179         }
1180
1181         if (endpoint->faxdetect) {
1182                 dsp_features |= DSP_FEATURE_FAX_DETECT;
1183         }
1184
1185         if (dsp_features) {
1186                 if (!(session->dsp = ast_dsp_new())) {
1187                         ao2_ref(session, -1);
1188                         return NULL;
1189                 }
1190
1191                 ast_dsp_set_features(session->dsp, dsp_features);
1192         }
1193
1194         if (add_supplements(session)) {
1195                 ao2_ref(session, -1);
1196                 return NULL;
1197         }
1198         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1199                 if (iter->session_begin) {
1200                         iter->session_begin(session);
1201                 }
1202         }
1203         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1204         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
1205         ast_party_id_init(&session->id);
1206         ao2_ref(session, +1);
1207         return session;
1208 }
1209
1210 static int session_outbound_auth(pjsip_dialog *dlg, pjsip_tx_data *tdata, void *user_data)
1211 {
1212         pjsip_inv_session *inv = pjsip_dlg_get_inv_session(dlg);
1213         struct ast_sip_session *session = inv->mod_data[session_module.id];
1214
1215         if (inv->state < PJSIP_INV_STATE_CONFIRMED && tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) {
1216                 pjsip_inv_uac_restart(inv, PJ_FALSE);
1217         }
1218         ast_sip_session_send_request(session, tdata);
1219         return 0;
1220 }
1221
1222 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
1223         struct ast_sip_contact *contact, const char *location, const char *request_user,
1224         struct ast_format_cap *req_caps)
1225 {
1226         const char *uri = NULL;
1227         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
1228         pjsip_timer_setting timer;
1229         pjsip_dialog *dlg;
1230         struct pjsip_inv_session *inv_session;
1231         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1232
1233         /* If no location has been provided use the AOR list from the endpoint itself */
1234         if (location || !contact) {
1235                 location = S_OR(location, endpoint->aors);
1236
1237                 found_contact = ast_sip_location_retrieve_contact_from_aor_list(location);
1238                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
1239                         uri = location;
1240                 } else {
1241                         uri = found_contact->uri;
1242                 }
1243         } else {
1244                 uri = contact->uri;
1245         }
1246
1247         /* If we still have no URI to dial fail to create the session */
1248         if (ast_strlen_zero(uri)) {
1249                 return NULL;
1250         }
1251
1252         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
1253                 return NULL;
1254         }
1255
1256         if (ast_sip_dialog_setup_outbound_authentication(dlg, endpoint, session_outbound_auth, NULL)) {
1257                 pjsip_dlg_terminate(dlg);
1258                 return NULL;
1259         }
1260
1261         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1262                 pjsip_dlg_terminate(dlg);
1263                 return NULL;
1264         }
1265 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1266         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1267 #endif
1268
1269         pjsip_timer_setting_default(&timer);
1270         timer.min_se = endpoint->extensions.timer.min_se;
1271         timer.sess_expires = endpoint->extensions.timer.sess_expires;
1272         pjsip_timer_init_session(inv_session, &timer);
1273
1274         if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
1275                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1276                 return NULL;
1277         }
1278         ast_party_id_copy(&session->id, &endpoint->id.self);
1279
1280         if (ast_format_cap_count(req_caps)) {
1281                 /* get joint caps between req_caps and endpoint caps */
1282                 struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1283                 ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
1284
1285                 /* if joint caps */
1286                 if (ast_format_cap_count(joint_caps)) {
1287                         /* copy endpoint caps into session->req_caps */
1288                         ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
1289                         /* replace instances of joint caps equivalents in session->req_caps */
1290                         ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
1291                 }
1292                 ao2_cleanup(joint_caps);
1293         }
1294
1295         if ((pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS)) {
1296                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1297                 /* Since we are not notifying ourselves that the INVITE session is being terminated
1298                  * we need to manually drop its reference to session
1299                  */
1300                 ao2_ref(session, -1);
1301                 return NULL;
1302         }
1303
1304         ao2_ref(session, +1);
1305         return session;
1306 }
1307
1308 static int session_termination_task(void *data)
1309 {
1310         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1311         pjsip_tx_data *packet = NULL;
1312
1313         if (!session->inv_session) {
1314                 return 0;
1315         }
1316
1317         if (pjsip_inv_end_session(session->inv_session, 603, NULL, &packet) == PJ_SUCCESS) {
1318                 ast_sip_session_send_request(session, packet);
1319         }
1320
1321         return 0;
1322 }
1323
1324 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1325 {
1326         struct ast_sip_session *session = entry->user_data;
1327
1328         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1329                 ao2_cleanup(session);
1330         }
1331 }
1332
1333 void ast_sip_session_defer_termination(struct ast_sip_session *session)
1334 {
1335         pj_time_val delay = { .sec = 60, };
1336
1337         session->defer_terminate = 1;
1338
1339         session->scheduled_termination.id = 0;
1340         ao2_ref(session, +1);
1341         session->scheduled_termination.user_data = session;
1342         session->scheduled_termination.cb = session_termination_cb;
1343
1344         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->scheduled_termination, &delay) != PJ_SUCCESS) {
1345                 ao2_ref(session, -1);
1346         }
1347 }
1348
1349 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1350 {
1351         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1352         struct ast_sip_session *session;
1353
1354         if (!inv_session ||
1355                 !(session = inv_session->mod_data[session_module.id])) {
1356                 return NULL;
1357         }
1358
1359         ao2_ref(session, +1);
1360
1361         return session;
1362 }
1363
1364 enum sip_get_destination_result {
1365         /*! The extension was successfully found */
1366         SIP_GET_DEST_EXTEN_FOUND,
1367         /*! The extension specified in the RURI was not found */
1368         SIP_GET_DEST_EXTEN_NOT_FOUND,
1369         /*! The extension specified in the RURI was a partial match */
1370         SIP_GET_DEST_EXTEN_PARTIAL,
1371         /*! The RURI is of an unsupported scheme */
1372         SIP_GET_DEST_UNSUPPORTED_URI,
1373 };
1374
1375 /*!
1376  * \brief Determine where in the dialplan a call should go
1377  *
1378  * This uses the username in the request URI to try to match
1379  * an extension in the endpoint's configured context in order
1380  * to route the call.
1381  *
1382  * \param session The inbound SIP session
1383  * \param rdata The SIP INVITE
1384  */
1385 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1386 {
1387         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1388         pjsip_sip_uri *sip_ruri;
1389         struct ast_features_pickup_config *pickup_cfg;
1390         const char *pickupexten;
1391
1392         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1393                 return SIP_GET_DEST_UNSUPPORTED_URI;
1394         }
1395
1396         sip_ruri = pjsip_uri_get_uri(ruri);
1397         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1398
1399         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
1400         if (!pickup_cfg) {
1401                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
1402                 pickupexten = "";
1403         } else {
1404                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
1405                 ao2_ref(pickup_cfg, -1);
1406         }
1407
1408         if (!strcmp(session->exten, pickupexten) ||
1409                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1410                 return SIP_GET_DEST_EXTEN_FOUND;
1411         }
1412         /* XXX In reality, we'll likely have further options so that partial matches
1413          * can be indicated here, but for getting something up and running, we're going
1414          * to return a "not exists" error here.
1415          */
1416         return SIP_GET_DEST_EXTEN_NOT_FOUND;
1417 }
1418
1419 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1420 {
1421         pjsip_tx_data *tdata;
1422         pjsip_dialog *dlg;
1423         pjsip_inv_session *inv_session;
1424         unsigned int options = endpoint->extensions.flags;
1425
1426         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
1427                 if (tdata) {
1428                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1429                 } else {
1430                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1431                 }
1432                 return NULL;
1433         }
1434         dlg = ast_sip_create_dialog_uas(endpoint, rdata);
1435         if (!dlg) {
1436                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1437                 return NULL;
1438         }
1439         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
1440                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1441                 pjsip_dlg_terminate(dlg);
1442                 return NULL;
1443         }
1444
1445 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1446         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1447 #endif
1448         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1449                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
1450                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1451                 }
1452                 pjsip_inv_send_msg(inv_session, tdata);
1453                 return NULL;
1454         }
1455         return inv_session;
1456 }
1457
1458 struct new_invite {
1459         /*! \brief Session created for the new INVITE */
1460         struct ast_sip_session *session;
1461
1462         /*! \brief INVITE request itself */
1463         pjsip_rx_data *rdata;
1464 };
1465
1466 static void new_invite_destroy(void *obj)
1467 {
1468         struct new_invite *invite = obj;
1469
1470         ao2_cleanup(invite->session);
1471
1472         if (invite->rdata) {
1473                 pjsip_rx_data_free_cloned(invite->rdata);
1474         }
1475 }
1476
1477 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
1478 {
1479         struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
1480
1481         if (!invite) {
1482                 return NULL;
1483         }
1484
1485         ao2_ref(session, +1);
1486         invite->session = session;
1487
1488         if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
1489                 ao2_ref(invite, -1);
1490                 return NULL;
1491         }
1492
1493         return invite;
1494 }
1495
1496 static int new_invite(void *data)
1497 {
1498         RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
1499         pjsip_tx_data *tdata = NULL;
1500         pjsip_timer_setting timer;
1501         pjsip_rdata_sdp_info *sdp_info;
1502         pjmedia_sdp_session *local = NULL;
1503
1504         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
1505          * so that we will be notified so we can destroy the session properly
1506          */
1507
1508         switch (get_destination(invite->session, invite->rdata)) {
1509         case SIP_GET_DEST_EXTEN_FOUND:
1510                 /* Things worked. Keep going */
1511                 break;
1512         case SIP_GET_DEST_UNSUPPORTED_URI:
1513                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
1514                         ast_sip_session_send_response(invite->session, tdata);
1515                 } else  {
1516                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
1517                 }
1518                 return 0;
1519         case SIP_GET_DEST_EXTEN_NOT_FOUND:
1520         case SIP_GET_DEST_EXTEN_PARTIAL:
1521         default:
1522                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
1523                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
1524                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
1525
1526                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
1527                         ast_sip_session_send_response(invite->session, tdata);
1528                 } else  {
1529                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
1530                 }
1531                 return 0;
1532         };
1533
1534         if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
1535                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
1536                         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
1537                                 ast_sip_session_send_response(invite->session, tdata);
1538                         } else  {
1539                                 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
1540                         }
1541                         return 0;
1542                 }
1543                 /* We are creating a local SDP which is an answer to their offer */
1544                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
1545         } else {
1546                 /* We are creating a local SDP which is an offer */
1547                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
1548         }
1549
1550         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
1551         if (!local) {
1552                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1553                         ast_sip_session_send_response(invite->session, tdata);
1554                 } else  {
1555                         pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1556                 }
1557                 return 0;
1558         } else {
1559                 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
1560                 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
1561 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1562                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
1563 #endif
1564         }
1565
1566         pjsip_timer_setting_default(&timer);
1567         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
1568         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
1569         pjsip_timer_init_session(invite->session->inv_session, &timer);
1570
1571         /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
1572         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
1573                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1574                 return 0;
1575         }
1576         ast_sip_session_send_response(invite->session, tdata);
1577
1578         handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
1579
1580         return 0;
1581 }
1582
1583 static void handle_new_invite_request(pjsip_rx_data *rdata)
1584 {
1585         RAII_VAR(struct ast_sip_endpoint *, endpoint,
1586                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1587         pjsip_tx_data *tdata = NULL;
1588         pjsip_inv_session *inv_session = NULL;
1589         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1590         struct new_invite *invite;
1591
1592         ast_assert(endpoint != NULL);
1593
1594         inv_session = pre_session_setup(rdata, endpoint);
1595         if (!inv_session) {
1596                 /* pre_session_setup() returns a response on failure */
1597                 return;
1598         }
1599
1600         session = ast_sip_session_alloc(endpoint, NULL, inv_session);
1601         if (!session) {
1602                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1603                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1604                 } else {
1605                         pjsip_inv_send_msg(inv_session, tdata);
1606                 }
1607                 return;
1608         }
1609
1610         invite = new_invite_alloc(session, rdata);
1611         if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
1612                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1613                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1614                 } else {
1615                         pjsip_inv_send_msg(inv_session, tdata);
1616                 }
1617                 ao2_ref(session, -1);
1618                 ao2_cleanup(invite);
1619                 return;
1620         }
1621 }
1622
1623 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
1624 {
1625         pj_str_t method;
1626
1627         if (ast_strlen_zero(supplement_method)) {
1628                 return PJ_TRUE;
1629         }
1630
1631         pj_cstr(&method, supplement_method);
1632
1633         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
1634 }
1635
1636 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
1637 {
1638         struct ast_sip_session_supplement *supplement;
1639         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
1640
1641         if (!session) {
1642                 return PJ_FALSE;
1643         }
1644
1645         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1646                 if (does_method_match(&method->name, supplement->method)) {
1647                         return PJ_TRUE;
1648                 }
1649         }
1650         return PJ_FALSE;
1651 }
1652 /*!
1653  * \brief Called when a new SIP request comes into PJSIP
1654  *
1655  * This function is called under two circumstances
1656  * 1) An out-of-dialog request is received by PJSIP
1657  * 2) An in-dialog request that the inv_session layer does not
1658  *    handle is received (such as an in-dialog INFO)
1659  *
1660  * In all cases, there is very little we actually do in this function
1661  * 1) For requests we don't handle, we return PJ_FALSE
1662  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
1663  *    there to free up the thread(s) handling incoming requests
1664  * 3) For in-dialog requests we handle, we defer handling them until the
1665  *    on_inv_state_change() callback instead (where we will end up putting
1666  *    them into the threadpool).
1667  */
1668 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
1669 {
1670         pj_status_t handled = PJ_FALSE;
1671         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
1672         pjsip_inv_session *inv_session;
1673
1674         switch (rdata->msg_info.msg->line.req.method.id) {
1675         case PJSIP_INVITE_METHOD:
1676                 if (dlg) {
1677                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
1678                         break;
1679                 }
1680                 handled = PJ_TRUE;
1681                 handle_new_invite_request(rdata);
1682                 break;
1683         default:
1684                 /* Handle other in-dialog methods if their supplements have been registered */
1685                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
1686                         has_supplement(inv_session->mod_data[session_module.id], rdata);
1687                 break;
1688         }
1689
1690         return handled;
1691 }
1692
1693 struct reschedule_reinvite_data {
1694         struct ast_sip_session *session;
1695         struct ast_sip_session_delayed_request *delay;
1696 };
1697
1698 static struct reschedule_reinvite_data *reschedule_reinvite_data_alloc(
1699                 struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
1700 {
1701         struct reschedule_reinvite_data *rrd = ast_malloc(sizeof(*rrd));
1702         if (!rrd) {
1703                 return NULL;
1704         }
1705         ao2_ref(session, +1);
1706         rrd->session = session;
1707         rrd->delay = delay;
1708         return rrd;
1709 }
1710
1711 static void reschedule_reinvite_data_destroy(struct reschedule_reinvite_data *rrd)
1712 {
1713         ao2_cleanup(rrd->session);
1714         ast_free(rrd->delay);
1715         ast_free(rrd);
1716 }
1717
1718 static int really_resend_reinvite(void *data)
1719 {
1720         RAII_VAR(struct reschedule_reinvite_data *, rrd, data, reschedule_reinvite_data_destroy);
1721
1722         return send_delayed_request(rrd->session, rrd->delay);
1723 }
1724
1725 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
1726 {
1727         struct reschedule_reinvite_data *rrd = entry->user_data;
1728
1729         ast_sip_push_task(rrd->session->serializer, really_resend_reinvite, entry->user_data);
1730 }
1731
1732 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response, pjsip_tx_data *tdata)
1733 {
1734         struct ast_sip_session_delayed_request *delay = delayed_request_alloc("INVITE",
1735                         NULL, NULL, on_response, tdata);
1736         pjsip_inv_session *inv = session->inv_session;
1737         struct reschedule_reinvite_data *rrd = reschedule_reinvite_data_alloc(session, delay);
1738         pj_time_val tv;
1739
1740         if (!rrd || !delay) {
1741                 return;
1742         }
1743
1744         tv.sec = 0;
1745         if (inv->role == PJSIP_ROLE_UAC) {
1746                 tv.msec = 2100 + ast_random() % 2000;
1747         } else {
1748                 tv.msec = ast_random() % 2000;
1749         }
1750
1751         pj_timer_entry_init(&session->rescheduled_reinvite, 0, rrd, resend_reinvite);
1752
1753         pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->rescheduled_reinvite, &tv);
1754 }
1755
1756 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
1757 {
1758         struct ast_sip_session *session;
1759         ast_debug(5, "Function %s called on event %s\n", function, pjsip_event_str(e->type));
1760         if (!inv) {
1761                 ast_debug(5, "Transaction %p does not belong to an inv_session?\n", tsx);
1762                 ast_debug(5, "The transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
1763                 return;
1764         }
1765         session = inv->mod_data[session_module.id];
1766         if (!session) {
1767                 ast_debug(5, "inv_session %p has no ast session\n", inv);
1768         } else {
1769                 ast_debug(5, "The state change pertains to the session with %s\n",
1770                                 ast_sorcery_object_get_id(session->endpoint));
1771         }
1772         if (inv->invite_tsx) {
1773                 ast_debug(5, "The inv session still has an invite_tsx (%p)\n", inv->invite_tsx);
1774         } else {
1775                 ast_debug(5, "The inv session does NOT have an invite_tsx\n");
1776         }
1777         if (tsx) {
1778                 ast_debug(5, "The transaction involved in this state change is %p\n", tsx);
1779                 ast_debug(5, "The current transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
1780                 ast_debug(5, "The transaction state change event is %s\n", pjsip_event_str(e->body.tsx_state.type));
1781         } else {
1782                 ast_debug(5, "There is no transaction involved in this state change\n");
1783         }
1784         ast_debug(5, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
1785 }
1786
1787 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
1788
1789 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
1790 {
1791         struct ast_sip_session_supplement *supplement;
1792         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
1793
1794         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
1795         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1796                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
1797                         if (supplement->incoming_request(session, rdata)) {
1798                                 break;
1799                         }
1800                 }
1801         }
1802 }
1803
1804 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
1805                 enum ast_sip_session_response_priority response_priority)
1806 {
1807         struct ast_sip_session_supplement *supplement;
1808         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
1809
1810         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
1811                         pj_strbuf(&status.reason));
1812
1813         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1814                 if (!(supplement->response_priority & response_priority)) {
1815                         continue;
1816                 }
1817                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
1818                         supplement->incoming_response(session, rdata);
1819                 }
1820         }
1821 }
1822
1823 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
1824                 enum ast_sip_session_response_priority response_priority)
1825 {
1826         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
1827                         "request" : "response");
1828
1829         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
1830                 handle_incoming_request(session, rdata, type);
1831         } else {
1832                 handle_incoming_response(session, rdata, type, response_priority);
1833         }
1834
1835         return 0;
1836 }
1837
1838 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1839 {
1840         struct ast_sip_session_supplement *supplement;
1841         struct pjsip_request_line req = tdata->msg->line.req;
1842
1843         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
1844         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1845                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
1846                         supplement->outgoing_request(session, tdata);
1847                 }
1848         }
1849 }
1850
1851 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1852 {
1853         struct ast_sip_session_supplement *supplement;
1854         struct pjsip_status_line status = tdata->msg->line.status;
1855         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
1856         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
1857                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
1858                 pj_strbuf(&status.reason));
1859
1860         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1861                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
1862                         supplement->outgoing_response(session, tdata);
1863                 }
1864         }
1865 }
1866
1867 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
1868 {
1869         ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
1870                         "request" : "response");
1871         if (tdata->msg->type == PJSIP_REQUEST_MSG) {
1872                 handle_outgoing_request(session, tdata);
1873         } else {
1874                 handle_outgoing_response(session, tdata);
1875         }
1876 }
1877
1878 static int session_end(struct ast_sip_session *session)
1879 {
1880         struct ast_sip_session_supplement *iter;
1881
1882         /* Stop the scheduled termination */
1883         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
1884                 ao2_ref(session, -1);
1885         }
1886
1887         /* Session is dead. Let's get rid of the reference to the session */
1888         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1889                 if (iter->session_end) {
1890                         iter->session_end(session);
1891                 }
1892         }
1893
1894         session->inv_session->mod_data[session_module.id] = NULL;
1895         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
1896         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
1897         ao2_cleanup(session);
1898         return 0;
1899 }
1900
1901 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
1902 {
1903         struct ast_sip_session *session = inv->mod_data[session_module.id];
1904         pjsip_event_id_e type;
1905
1906         if (e) {
1907                 print_debug_details(inv, NULL, e);
1908                 type = e->type;
1909         } else {
1910                 type = PJSIP_EVENT_UNKNOWN;
1911         }
1912
1913         if (!session) {
1914                 return;
1915         }
1916
1917         switch(type) {
1918         case PJSIP_EVENT_TX_MSG:
1919                 handle_outgoing(session, e->body.tx_msg.tdata);
1920                 break;
1921         case PJSIP_EVENT_RX_MSG:
1922                 handle_incoming(session, e->body.rx_msg.rdata, type,
1923                                 AST_SIP_SESSION_BEFORE_MEDIA);
1924                 break;
1925         case PJSIP_EVENT_TSX_STATE:
1926                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
1927                 /* Transaction state changes are prompted by some other underlying event. */
1928                 switch(e->body.tsx_state.type) {
1929                 case PJSIP_EVENT_TX_MSG:
1930                         handle_outgoing(session, e->body.tsx_state.src.tdata);
1931                         break;
1932                 case PJSIP_EVENT_RX_MSG:
1933                         handle_incoming(session, e->body.tsx_state.src.rdata, type,
1934                                         AST_SIP_SESSION_BEFORE_MEDIA);
1935                         break;
1936                 case PJSIP_EVENT_TRANSPORT_ERROR:
1937                 case PJSIP_EVENT_TIMER:
1938                 case PJSIP_EVENT_USER:
1939                 case PJSIP_EVENT_UNKNOWN:
1940                 case PJSIP_EVENT_TSX_STATE:
1941                         /* Inception? */
1942                         break;
1943                 }
1944                 break;
1945         case PJSIP_EVENT_TRANSPORT_ERROR:
1946         case PJSIP_EVENT_TIMER:
1947         case PJSIP_EVENT_UNKNOWN:
1948         case PJSIP_EVENT_USER:
1949         default:
1950                 break;
1951         }
1952
1953         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
1954                 session_end(session);
1955         }
1956 }
1957
1958 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
1959 {
1960         /* XXX STUB */
1961 }
1962
1963 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
1964 {
1965         ast_sip_session_response_cb cb;
1966         struct ast_sip_session *session = inv->mod_data[session_module.id];
1967         print_debug_details(inv, tsx, e);
1968         if (!session) {
1969                 /* Transaction likely timed out after the call was hung up. Just
1970                  * ignore such transaction changes
1971                  */
1972                 return;
1973         }
1974         switch (e->body.tsx_state.type) {
1975         case PJSIP_EVENT_TX_MSG:
1976                 handle_outgoing(session, e->body.tsx_state.src.tdata);
1977                 /* When we create an outgoing request, we do not have access to the transaction that
1978                  * is created. Instead, We have to place transaction-specific data in the tdata. Here,
1979                  * we transfer the data into the transaction. This way, when we receive a response, we
1980                  * can dig this data out again
1981                  */
1982                 tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
1983                 break;
1984         case PJSIP_EVENT_RX_MSG:
1985                 handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
1986                                 AST_SIP_SESSION_AFTER_MEDIA);
1987                 if (tsx->method.id == PJSIP_INVITE_METHOD) {
1988                         if (tsx->role == PJSIP_ROLE_UAC) {
1989                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
1990                                         /* This means we got a non 2XX final response to our outgoing INVITE */
1991                                         if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
1992                                                 reschedule_reinvite(session, tsx->mod_data[session_module.id], tsx->last_tx);
1993                                                 return;
1994                                         } else if (inv->state == PJSIP_INV_STATE_CONFIRMED &&
1995                                                    tsx->status_code != 488) {
1996                                                 /* Other reinvite failures (except 488) result in destroying the session. */
1997                                                 pjsip_tx_data *tdata;
1998                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
1999                                                         ast_sip_session_send_request(session, tdata);
2000                                                 }
2001                                         }
2002                                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2003                                         if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
2004                                                 /* This is a race condition detailed in RFC 5407 section 3.1.2.
2005                                                  * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
2006                                                  * the original INVITE. As a result, we have now received a 200 OK for
2007                                                  * a cancelled call. Our role is to immediately send a BYE to end the
2008                                                  * dialog.
2009                                                  */
2010                                                 pjsip_tx_data *tdata;
2011
2012                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2013                                                         ast_sip_session_send_request(session, tdata);
2014                                                 }
2015                                         }
2016                                 }
2017                         }
2018                 }
2019                 if ((cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id,
2020                                                MOD_DATA_ON_RESPONSE))) {
2021                         cb(session, e->body.tsx_state.src.rdata);
2022                 }
2023         case PJSIP_EVENT_TRANSPORT_ERROR:
2024         case PJSIP_EVENT_TIMER:
2025         case PJSIP_EVENT_USER:
2026         case PJSIP_EVENT_UNKNOWN:
2027         case PJSIP_EVENT_TSX_STATE:
2028                 /* Inception? */
2029                 break;
2030         }
2031
2032         /* Terminated INVITE transactions always should result in queuing delayed requests,
2033          * no matter what event caused the transaction to terminate
2034          */
2035         if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2036                 queue_delayed_request(session);
2037         }
2038 }
2039
2040 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
2041 {
2042         struct ast_sip_session_media *session_media = obj;
2043         pjmedia_sdp_session *answer = arg;
2044         struct ast_sip_session *session = data;
2045         struct ast_sip_session_sdp_handler *handler = session_media->handler;
2046         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2047         int res;
2048
2049         if (handler) {
2050                 /* if an already assigned handler does not handle the session_media or reports a catastrophic error, fail */
2051                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2052                 if (res <= 0) {
2053                         return 0;
2054                 }
2055                 return CMP_MATCH;
2056         }
2057
2058         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
2059         if (!handler_list) {
2060                 return CMP_MATCH;
2061         }
2062
2063         /* no handler for this stream type and we have a list to search */
2064         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2065                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2066                 if (res < 0) {
2067                         /* catastrophic error */
2068                         return 0;
2069                 }
2070                 if (res > 0) {
2071                         /* Handled by this handler. Move to the next stream */
2072                         session_media->handler = handler;
2073                         return CMP_MATCH;
2074                 }
2075         }
2076
2077         /* streams that weren't handled won't be included in generated outbound SDP */
2078         return CMP_MATCH;
2079 }
2080
2081 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
2082 {
2083         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
2084         static const pj_str_t STR_IN = { "IN", 2 };
2085         static const pj_str_t STR_IP4 = { "IP4", 3 };
2086         static const pj_str_t STR_IP6 = { "IP6", 3 };
2087         pjmedia_sdp_session *local;
2088
2089         if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
2090                 return NULL;
2091         }
2092
2093         if (!offer) {
2094                 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
2095         } else {
2096                 local->origin.version = offer->origin.version + 1;
2097                 local->origin.id = offer->origin.id;
2098         }
2099
2100         pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
2101         pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
2102
2103         /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
2104         successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
2105         if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
2106                 /* Something experienced a catastrophic failure */
2107                 return NULL;
2108         }
2109
2110         /* Use the connection details of the first media stream if possible for SDP level */
2111         if (local->media_count) {
2112                 local->conn = local->media[0]->conn;
2113                 pj_strassign(&local->origin.net_type, &local->conn->net_type);
2114                 pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
2115                 pj_strassign(&local->origin.addr, &local->conn->addr);
2116         } else {
2117                 local->origin.net_type = STR_IN;
2118                 local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
2119
2120                 if (!ast_strlen_zero(session->endpoint->media.address)) {
2121                         pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
2122                 } else {
2123                         pj_sockaddr localaddr;
2124                         char our_ip[PJ_INET6_ADDRSTRLEN];
2125
2126                         pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
2127                         pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
2128                         pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
2129                 }
2130         }
2131
2132         return local;
2133 }
2134
2135 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
2136 {
2137         struct ast_sip_session *session = inv->mod_data[session_module.id];
2138         pjmedia_sdp_session *answer;
2139
2140         if (handle_incoming_sdp(session, offer)) {
2141                 return;
2142         }
2143
2144         if ((answer = create_local_sdp(inv, session, offer))) {
2145                 pjsip_inv_set_sdp_answer(inv, answer);
2146         }
2147 }
2148
2149 #if 0
2150 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
2151 {
2152         /* XXX STUB */
2153 }
2154 #endif
2155
2156 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2157 {
2158         struct ast_sip_session *session = inv->mod_data[session_module.id];
2159         const pjmedia_sdp_session *local, *remote;
2160
2161         if (!session->channel) {
2162                 /* If we don't have a channel. We really don't care about media updates.
2163                  * Just ignore
2164                  */
2165                 return;
2166         }
2167
2168         if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
2169                 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
2170                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2171                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2172                 ast_queue_hangup(session->channel);
2173                 return;
2174         }
2175
2176         handle_negotiated_sdp(session, local, remote);
2177 }
2178
2179 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
2180 {
2181         struct ast_sip_session *session = inv->mod_data[session_module.id];
2182         const pjsip_sip_uri *uri;
2183
2184         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
2185                 return PJSIP_REDIRECT_ACCEPT;
2186         }
2187
2188         if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
2189                 return PJSIP_REDIRECT_STOP;
2190         }
2191
2192         handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
2193                         AST_SIP_SESSION_BEFORE_REDIRECTING);
2194
2195         uri = pjsip_uri_get_uri(target);
2196
2197         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
2198                 char exten[AST_MAX_EXTENSION];
2199
2200                 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
2201                 ast_channel_call_forward_set(session->channel, exten);
2202         } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
2203                 char target_uri[PJSIP_MAX_URL_SIZE];
2204                 /* PJSIP/ + endpoint length + / + max URL size */
2205                 char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
2206
2207                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
2208                 sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
2209                 ast_channel_call_forward_set(session->channel, forward);
2210         }
2211
2212         return PJSIP_REDIRECT_STOP;
2213 }
2214
2215 static pjsip_inv_callback inv_callback = {
2216         .on_state_changed = session_inv_on_state_changed,
2217         .on_new_session = session_inv_on_new_session,
2218         .on_tsx_state_changed = session_inv_on_tsx_state_changed,
2219         .on_rx_offer = session_inv_on_rx_offer,
2220         .on_media_update = session_inv_on_media_update,
2221         .on_redirected = session_inv_on_redirected,
2222 };
2223
2224 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
2225 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
2226 {
2227         struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
2228                 tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
2229         struct pjmedia_sdp_session *sdp;
2230         int stream;
2231
2232         /* SDP produced by us directly will never be multipart */
2233         if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
2234                 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
2235                 return;
2236         }
2237
2238         sdp = tdata->msg->body->data;
2239
2240         if (sdp->conn) {
2241                 char host[NI_MAXHOST];
2242                 struct ast_sockaddr addr = { { 0, } };
2243
2244                 ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
2245                 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
2246
2247                 if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
2248                         pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
2249                 }
2250         }
2251
2252         for (stream = 0; stream < sdp->media_count; ++stream) {
2253                 /* See if there are registered handlers for this media stream type */
2254                 char media[20];
2255                 struct ast_sip_session_sdp_handler *handler;
2256                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2257
2258                 /* We need a null-terminated version of the media string */
2259                 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
2260
2261                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2262                 if (!handler_list) {
2263                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
2264                         continue;
2265                 }
2266                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2267                         if (handler->change_outgoing_sdp_stream_media_address) {
2268                                 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
2269                         }
2270                 }
2271         }
2272
2273         /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
2274         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
2275 }
2276
2277 static int load_module(void)
2278 {
2279         pjsip_endpoint *endpt;
2280
2281         if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
2282                 return AST_MODULE_LOAD_DECLINE;
2283         }
2284         if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
2285                 return AST_MODULE_LOAD_DECLINE;
2286         }
2287         nat_hook->outgoing_external_message = session_outgoing_nat_hook;
2288         ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
2289         sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
2290                         sdp_handler_list_hash, sdp_handler_list_cmp);
2291         if (!sdp_handlers) {
2292                 return AST_MODULE_LOAD_DECLINE;
2293         }
2294         endpt = ast_sip_get_pjsip_endpoint();
2295         pjsip_inv_usage_init(endpt, &inv_callback);
2296         pjsip_100rel_init_module(endpt);
2297         pjsip_timer_init_module(endpt);
2298         if (ast_sip_register_service(&session_module)) {
2299                 return AST_MODULE_LOAD_DECLINE;
2300         }
2301         ast_sip_register_service(&session_reinvite_module);
2302
2303         ast_module_ref(ast_module_info->self);
2304
2305         return AST_MODULE_LOAD_SUCCESS;
2306 }
2307
2308 static int unload_module(void)
2309 {
2310         /* This will never get called as this module can't be unloaded */
2311         return 0;
2312 }
2313
2314 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
2315                 .support_level = AST_MODULE_SUPPORT_CORE,
2316                 .load = load_module,
2317                 .unload = unload_module,
2318                 .load_pri = AST_MODPRI_APP_DEPEND,
2319                );