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