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