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