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