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