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