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