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