fd136082df3ca2333687519169e6d7006e31ad7f
[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         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
951                 return -1;
952         }
953         return 0;
954 }
955
956 static int datastore_hash(const void *obj, int flags)
957 {
958         const struct ast_datastore *datastore = obj;
959         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
960
961         ast_assert(uid != NULL);
962
963         return ast_str_hash(uid);
964 }
965
966 static int datastore_cmp(void *obj, void *arg, int flags)
967 {
968         const struct ast_datastore *datastore1 = obj;
969         const struct ast_datastore *datastore2 = arg;
970         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
971
972         ast_assert(datastore1->uid != NULL);
973         ast_assert(uid2 != NULL);
974
975         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
976 }
977
978 static void session_media_dtor(void *obj)
979 {
980         struct ast_sip_session_media *session_media = obj;
981         if (session_media->handler) {
982                 session_media->handler->stream_destroy(session_media);
983         }
984         if (session_media->srtp) {
985                 ast_sdp_srtp_destroy(session_media->srtp);
986         }
987 }
988
989 static void session_destructor(void *obj)
990 {
991         struct ast_sip_session *session = obj;
992         struct ast_sip_session_supplement *supplement;
993         struct ast_sip_session_delayed_request *delay;
994
995         ast_debug(3, "Destroying SIP session with endpoint %s\n",
996                         ast_sorcery_object_get_id(session->endpoint));
997
998         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
999                 if (supplement->session_destroy) {
1000                         supplement->session_destroy(session);
1001                 }
1002                 ast_free(supplement);
1003         }
1004
1005         ast_taskprocessor_unreference(session->serializer);
1006         ao2_cleanup(session->datastores);
1007         ao2_cleanup(session->media);
1008
1009         AST_LIST_HEAD_DESTROY(&session->supplements);
1010         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1011                 ast_free(delay);
1012         }
1013         ast_party_id_free(&session->id);
1014         ao2_cleanup(session->endpoint);
1015         ast_format_cap_destroy(session->req_caps);
1016
1017         if (session->dsp) {
1018                 ast_dsp_free(session->dsp);
1019         }
1020
1021         if (session->inv_session) {
1022                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1023         }
1024 }
1025
1026 static int add_supplements(struct ast_sip_session *session)
1027 {
1028         struct ast_sip_session_supplement *iter;
1029         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1030
1031         AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1032                 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1033                 if (!copy) {
1034                         return -1;
1035                 }
1036                 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1037         }
1038         return 0;
1039 }
1040
1041 static int add_session_media(void *obj, void *arg, int flags)
1042 {
1043         struct sdp_handler_list *handler_list = obj;
1044         struct ast_sip_session * session = arg;
1045         RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1046         session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
1047         if (!session_media) {
1048                 return CMP_STOP;
1049         }
1050         /* Safe use of strcpy */
1051         strcpy(session_media->stream_type, handler_list->stream_type);
1052         ao2_link(session->media, session_media);
1053         return 0;
1054 }
1055
1056 /*! \brief Destructor for SIP channel */
1057 static void sip_channel_destroy(void *obj)
1058 {
1059         struct ast_sip_channel_pvt *channel = obj;
1060
1061         ao2_cleanup(channel->pvt);
1062         ao2_cleanup(channel->session);
1063 }
1064
1065 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1066 {
1067         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1068
1069         if (!channel) {
1070                 return NULL;
1071         }
1072
1073         ao2_ref(pvt, +1);
1074         channel->pvt = pvt;
1075         ao2_ref(session, +1);
1076         channel->session = session;
1077
1078         return channel;
1079 }
1080
1081 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint, pjsip_inv_session *inv_session)
1082 {
1083         RAII_VAR(struct ast_sip_session *, session, ao2_alloc(sizeof(*session), session_destructor), ao2_cleanup);
1084         struct ast_sip_session_supplement *iter;
1085         int dsp_features = 0;
1086         if (!session) {
1087                 return NULL;
1088         }
1089         AST_LIST_HEAD_INIT(&session->supplements);
1090         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1091         if (!session->datastores) {
1092                 return NULL;
1093         }
1094
1095         session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
1096         if (!session->media) {
1097                 return NULL;
1098         }
1099         /* fill session->media with available types */
1100         ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
1101
1102         session->serializer = ast_sip_create_serializer();
1103         if (!session->serializer) {
1104                 return NULL;
1105         }
1106         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
1107         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
1108         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
1109         ao2_ref(session, +1);
1110         inv_session->mod_data[session_module.id] = session;
1111         ao2_ref(endpoint, +1);
1112         session->endpoint = endpoint;
1113         session->inv_session = inv_session;
1114         session->req_caps = ast_format_cap_alloc_nolock();
1115
1116         if (endpoint->dtmf == AST_SIP_DTMF_INBAND) {
1117                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
1118         }
1119
1120         if (endpoint->faxdetect) {
1121                 dsp_features |= DSP_FEATURE_FAX_DETECT;
1122         }
1123
1124         if (dsp_features) {
1125                 if (!(session->dsp = ast_dsp_new())) {
1126                         ao2_ref(session, -1);
1127                         return NULL;
1128                 }
1129
1130                 ast_dsp_set_features(session->dsp, dsp_features);
1131         }
1132
1133         if (add_supplements(session)) {
1134                 ao2_ref(session, -1);
1135                 return NULL;
1136         }
1137         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1138                 if (iter->session_begin) {
1139                         iter->session_begin(session);
1140                 }
1141         }
1142         session->direct_media_cap = ast_format_cap_alloc_nolock();
1143         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
1144         ast_party_id_init(&session->id);
1145         ao2_ref(session, +1);
1146         return session;
1147 }
1148
1149 static int session_outbound_auth(pjsip_dialog *dlg, pjsip_tx_data *tdata, void *user_data)
1150 {
1151         pjsip_inv_session *inv = pjsip_dlg_get_inv_session(dlg);
1152         struct ast_sip_session *session = inv->mod_data[session_module.id];
1153
1154         if (inv->state < PJSIP_INV_STATE_CONFIRMED && tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) {
1155                 pjsip_inv_uac_restart(inv, PJ_TRUE);
1156         }
1157         ast_sip_session_send_request(session, tdata);
1158         return 0;
1159 }
1160
1161 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)
1162 {
1163         const char *uri = NULL;
1164         RAII_VAR(struct ast_sip_contact *, contact, NULL, ao2_cleanup);
1165         pjsip_timer_setting timer;
1166         pjsip_dialog *dlg;
1167         struct pjsip_inv_session *inv_session;
1168         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1169
1170         /* If no location has been provided use the AOR list from the endpoint itself */
1171         location = S_OR(location, endpoint->aors);
1172
1173         contact = ast_sip_location_retrieve_contact_from_aor_list(location);
1174         if (!contact || ast_strlen_zero(contact->uri)) {
1175                 uri = location;
1176         } else {
1177                 uri = contact->uri;
1178         }
1179
1180         /* If we still have no URI to dial fail to create the session */
1181         if (ast_strlen_zero(uri)) {
1182                 return NULL;
1183         }
1184
1185         if (!(dlg = ast_sip_create_dialog(endpoint, uri, request_user))) {
1186                 return NULL;
1187         }
1188
1189         if (ast_sip_dialog_setup_outbound_authentication(dlg, endpoint, session_outbound_auth, NULL)) {
1190                 pjsip_dlg_terminate(dlg);
1191                 return NULL;
1192         }
1193
1194         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1195                 pjsip_dlg_terminate(dlg);
1196                 return NULL;
1197         }
1198 #ifdef PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE
1199         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1200 #endif
1201
1202         pjsip_timer_setting_default(&timer);
1203         timer.min_se = endpoint->extensions.timer.min_se;
1204         timer.sess_expires = endpoint->extensions.timer.sess_expires;
1205         pjsip_timer_init_session(inv_session, &timer);
1206
1207         if (!(session = ast_sip_session_alloc(endpoint, inv_session))) {
1208                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1209                 return NULL;
1210         }
1211
1212         ast_format_cap_copy(session->req_caps, req_caps);
1213         if ((pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS)) {
1214                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1215                 /* Since we are not notifying ourselves that the INVITE session is being terminated
1216                  * we need to manually drop its reference to session
1217                  */
1218                 ao2_ref(session, -1);
1219                 return NULL;
1220         }
1221
1222         ao2_ref(session, +1);
1223         return session;
1224 }
1225
1226 static int session_termination_task(void *data)
1227 {
1228         RAII_VAR(struct ast_sip_session *, session, data, ao2_cleanup);
1229         pjsip_tx_data *packet = NULL;
1230
1231         if (!session->inv_session) {
1232                 return 0;
1233         }
1234
1235         if (pjsip_inv_end_session(session->inv_session, 603, NULL, &packet) == PJ_SUCCESS) {
1236                 ast_sip_session_send_request(session, packet);
1237         }
1238
1239         return 0;
1240 }
1241
1242 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1243 {
1244         struct ast_sip_session *session = entry->user_data;
1245
1246         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1247                 ao2_cleanup(session);
1248         }
1249 }
1250
1251 void ast_sip_session_defer_termination(struct ast_sip_session *session)
1252 {
1253         pj_time_val delay = { .sec = 60, };
1254
1255         session->defer_terminate = 1;
1256
1257         session->scheduled_termination.id = 0;
1258         ao2_ref(session, +1);
1259         session->scheduled_termination.user_data = session;
1260         session->scheduled_termination.cb = session_termination_cb;
1261
1262         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->scheduled_termination, &delay) != PJ_SUCCESS) {
1263                 ao2_ref(session, -1);
1264         }
1265 }
1266
1267 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1268 {
1269         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1270         struct ast_sip_session *session;
1271
1272         if (!inv_session ||
1273                 !(session = inv_session->mod_data[session_module.id])) {
1274                 return NULL;
1275         }
1276
1277         ao2_ref(session, +1);
1278
1279         return session;
1280 }
1281
1282 enum sip_get_destination_result {
1283         /*! The extension was successfully found */
1284         SIP_GET_DEST_EXTEN_FOUND,
1285         /*! The extension specified in the RURI was not found */
1286         SIP_GET_DEST_EXTEN_NOT_FOUND,
1287         /*! The extension specified in the RURI was a partial match */
1288         SIP_GET_DEST_EXTEN_PARTIAL,
1289         /*! The RURI is of an unsupported scheme */
1290         SIP_GET_DEST_UNSUPPORTED_URI,
1291 };
1292
1293 /*!
1294  * \brief Determine where in the dialplan a call should go
1295  *
1296  * This uses the username in the request URI to try to match
1297  * an extension in the endpoint's configured context in order
1298  * to route the call.
1299  *
1300  * \param session The inbound SIP session
1301  * \param rdata The SIP INVITE
1302  */
1303 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1304 {
1305         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1306         pjsip_sip_uri *sip_ruri;
1307         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1308                 return SIP_GET_DEST_UNSUPPORTED_URI;
1309         }
1310         sip_ruri = pjsip_uri_get_uri(ruri);
1311         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1312         if (ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1313                 return SIP_GET_DEST_EXTEN_FOUND;
1314         }
1315         /* XXX In reality, we'll likely have further options so that partial matches
1316          * can be indicated here, but for getting something up and running, we're going
1317          * to return a "not exists" error here.
1318          */
1319         return SIP_GET_DEST_EXTEN_NOT_FOUND;
1320 }
1321
1322 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1323 {
1324         pjsip_tx_data *tdata;
1325         pjsip_dialog *dlg;
1326         pjsip_inv_session *inv_session;
1327         unsigned int options = endpoint->extensions.flags;
1328
1329         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
1330                 if (tdata) {
1331                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1332                 } else {
1333                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1334                 }
1335                 return NULL;
1336         }
1337         if (pjsip_dlg_create_uas(pjsip_ua_instance(), rdata, NULL, &dlg) != PJ_SUCCESS) {
1338                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1339                 return NULL;
1340         }
1341         if (pjsip_inv_create_uas(dlg, rdata, NULL, 0, &inv_session) != PJ_SUCCESS) {
1342                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1343                 pjsip_dlg_terminate(dlg);
1344                 return NULL;
1345         }
1346 #ifdef PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE
1347         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1348 #endif
1349         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1350                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
1351                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1352                 }
1353                 pjsip_inv_send_msg(inv_session, tdata);
1354                 return NULL;
1355         }
1356         return inv_session;
1357 }
1358
1359 struct new_invite {
1360         /*! \brief Session created for the new INVITE */
1361         struct ast_sip_session *session;
1362
1363         /*! \brief INVITE request itself */
1364         pjsip_rx_data *rdata;
1365 };
1366
1367 static void new_invite_destroy(void *obj)
1368 {
1369         struct new_invite *invite = obj;
1370
1371         ao2_cleanup(invite->session);
1372
1373         if (invite->rdata) {
1374                 pjsip_rx_data_free_cloned(invite->rdata);
1375         }
1376 }
1377
1378 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
1379 {
1380         struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
1381
1382         if (!invite) {
1383                 return NULL;
1384         }
1385
1386         ao2_ref(session, +1);
1387         invite->session = session;
1388
1389         if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
1390                 ao2_ref(invite, -1);
1391                 return NULL;
1392         }
1393
1394         return invite;
1395 }
1396
1397 static int new_invite(void *data)
1398 {
1399         RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
1400         pjsip_tx_data *tdata = NULL;
1401         pjsip_timer_setting timer;
1402         pjsip_rdata_sdp_info *sdp_info;
1403         pjmedia_sdp_session *local = NULL;
1404
1405         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
1406          * so that we will be notified so we can destroy the session properly
1407          */
1408
1409         switch (get_destination(invite->session, invite->rdata)) {
1410         case SIP_GET_DEST_EXTEN_FOUND:
1411                 /* Things worked. Keep going */
1412                 break;
1413         case SIP_GET_DEST_UNSUPPORTED_URI:
1414                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
1415                         ast_sip_session_send_response(invite->session, tdata);
1416                 } else  {
1417                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
1418                 }
1419                 return 0;
1420         case SIP_GET_DEST_EXTEN_NOT_FOUND:
1421         case SIP_GET_DEST_EXTEN_PARTIAL:
1422         default:
1423                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
1424                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
1425                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
1426
1427                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
1428                         ast_sip_session_send_response(invite->session, tdata);
1429                 } else  {
1430                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
1431                 }
1432                 return 0;
1433         };
1434
1435         if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
1436                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
1437                         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
1438                                 ast_sip_session_send_response(invite->session, tdata);
1439                         } else  {
1440                                 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
1441                         }
1442                         return 0;
1443                 }
1444                 /* We are creating a local SDP which is an answer to their offer */
1445                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
1446         } else {
1447                 /* We are creating a local SDP which is an offer */
1448                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
1449         }
1450
1451         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
1452         if (!local) {
1453                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1454                         ast_sip_session_send_response(invite->session, tdata);
1455                 } else  {
1456                         pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1457                 }
1458                 return 0;
1459         } else {
1460                 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
1461                 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
1462         }
1463
1464         pjsip_timer_setting_default(&timer);
1465         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
1466         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
1467         pjsip_timer_init_session(invite->session->inv_session, &timer);
1468
1469         /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
1470         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
1471                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1472                 return 0;
1473         }
1474         ast_sip_session_send_response(invite->session, tdata);
1475
1476         handle_incoming_request(invite->session, invite->rdata);
1477
1478         return 0;
1479 }
1480
1481 static void handle_new_invite_request(pjsip_rx_data *rdata)
1482 {
1483         RAII_VAR(struct ast_sip_endpoint *, endpoint,
1484                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1485         pjsip_tx_data *tdata = NULL;
1486         pjsip_inv_session *inv_session = NULL;
1487         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1488         struct new_invite *invite;
1489
1490         ast_assert(endpoint != NULL);
1491
1492         inv_session = pre_session_setup(rdata, endpoint);
1493         if (!inv_session) {
1494                 /* pre_session_setup() returns a response on failure */
1495                 return;
1496         }
1497
1498         session = ast_sip_session_alloc(endpoint, inv_session);
1499         if (!session) {
1500                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1501                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1502                 } else {
1503                         pjsip_inv_send_msg(inv_session, tdata);
1504                 }
1505                 return;
1506         }
1507
1508         invite = new_invite_alloc(session, rdata);
1509         if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
1510                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1511                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1512                 } else {
1513                         pjsip_inv_send_msg(inv_session, tdata);
1514                 }
1515                 ao2_ref(session, -1);
1516                 ao2_cleanup(invite);
1517                 return;
1518         }
1519 }
1520
1521 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
1522 {
1523         pj_str_t method;
1524
1525         if (ast_strlen_zero(supplement_method)) {
1526                 return PJ_TRUE;
1527         }
1528
1529         pj_cstr(&method, supplement_method);
1530
1531         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
1532 }
1533
1534 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
1535 {
1536         struct ast_sip_session_supplement *supplement;
1537         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
1538
1539         if (!session) {
1540                 return PJ_FALSE;
1541         }
1542
1543         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1544                 if (does_method_match(&method->name, supplement->method)) {
1545                         return PJ_TRUE;
1546                 }
1547         }
1548         return PJ_FALSE;
1549 }
1550 /*!
1551  * \brief Called when a new SIP request comes into PJSIP
1552  *
1553  * This function is called under two circumstances
1554  * 1) An out-of-dialog request is received by PJSIP
1555  * 2) An in-dialog request that the inv_session layer does not
1556  *    handle is received (such as an in-dialog INFO)
1557  *
1558  * In all cases, there is very little we actually do in this function
1559  * 1) For requests we don't handle, we return PJ_FALSE
1560  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
1561  *    there to free up the thread(s) handling incoming requests
1562  * 3) For in-dialog requests we handle, we defer handling them until the
1563  *    on_inv_state_change() callback instead (where we will end up putting
1564  *    them into the threadpool).
1565  */
1566 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
1567 {
1568         pj_status_t handled = PJ_FALSE;
1569         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
1570         pjsip_inv_session *inv_session;
1571
1572         switch (rdata->msg_info.msg->line.req.method.id) {
1573         case PJSIP_INVITE_METHOD:
1574                 if (dlg) {
1575                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
1576                         break;
1577                 }
1578                 handled = PJ_TRUE;
1579                 handle_new_invite_request(rdata);
1580                 break;
1581         default:
1582                 /* Handle other in-dialog methods if their supplements have been registered */
1583                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
1584                         has_supplement(inv_session->mod_data[session_module.id], rdata);
1585                 break;
1586         }
1587
1588         return handled;
1589 }
1590
1591 struct reschedule_reinvite_data {
1592         struct ast_sip_session *session;
1593         struct ast_sip_session_delayed_request *delay;
1594 };
1595
1596 static struct reschedule_reinvite_data *reschedule_reinvite_data_alloc(
1597                 struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
1598 {
1599         struct reschedule_reinvite_data *rrd = ast_malloc(sizeof(*rrd));
1600         if (!rrd) {
1601                 return NULL;
1602         }
1603         ao2_ref(session, +1);
1604         rrd->session = session;
1605         rrd->delay = delay;
1606         return rrd;
1607 }
1608
1609 static void reschedule_reinvite_data_destroy(struct reschedule_reinvite_data *rrd)
1610 {
1611         ao2_cleanup(rrd->session);
1612         ast_free(rrd->delay);
1613         ast_free(rrd);
1614 }
1615
1616 static int really_resend_reinvite(void *data)
1617 {
1618         RAII_VAR(struct reschedule_reinvite_data *, rrd, data, reschedule_reinvite_data_destroy);
1619
1620         return send_delayed_request(rrd->session, rrd->delay);
1621 }
1622
1623 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
1624 {
1625         struct reschedule_reinvite_data *rrd = entry->user_data;
1626
1627         ast_sip_push_task(rrd->session->serializer, really_resend_reinvite, entry->user_data);
1628 }
1629
1630 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response, pjsip_tx_data *tdata)
1631 {
1632         struct ast_sip_session_delayed_request *delay = delayed_request_alloc("INVITE",
1633                         NULL, NULL, on_response, tdata);
1634         pjsip_inv_session *inv = session->inv_session;
1635         struct reschedule_reinvite_data *rrd = reschedule_reinvite_data_alloc(session, delay);
1636         pj_time_val tv;
1637         
1638         if (!rrd || !delay) {
1639                 return;
1640         }
1641
1642         tv.sec = 0;
1643         if (inv->role == PJSIP_ROLE_UAC) {
1644                 tv.msec = 2100 + ast_random() % 2000;
1645         } else {
1646                 tv.msec = ast_random() % 2000;
1647         }
1648
1649         pj_timer_entry_init(&session->rescheduled_reinvite, 0, rrd, resend_reinvite);
1650
1651         pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(), &session->rescheduled_reinvite, &tv);
1652 }
1653
1654 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
1655 {
1656         struct ast_sip_session *session;
1657         ast_debug(5, "Function %s called on event %s\n", function, pjsip_event_str(e->type));
1658         if (!inv) {
1659                 ast_debug(5, "Transaction %p does not belong to an inv_session?\n", tsx);
1660                 ast_debug(5, "The transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
1661                 return;
1662         }
1663         session = inv->mod_data[session_module.id];
1664         if (!session) {
1665                 ast_debug(5, "inv_session %p has no ast session\n", inv);
1666         } else {
1667                 ast_debug(5, "The state change pertains to the session with %s\n",
1668                                 ast_sorcery_object_get_id(session->endpoint));
1669         }
1670         if (inv->invite_tsx) {
1671                 ast_debug(5, "The inv session still has an invite_tsx (%p)\n", inv->invite_tsx);
1672         } else {
1673                 ast_debug(5, "The inv session does NOT have an invite_tsx\n");
1674         }
1675         if (tsx) {
1676                 ast_debug(5, "The transaction involved in this state change is %p\n", tsx);
1677                 ast_debug(5, "The current transaction state is %s\n", pjsip_tsx_state_str(tsx->state));
1678                 ast_debug(5, "The transaction state change event is %s\n", pjsip_event_str(e->body.tsx_state.type));
1679         } else {
1680                 ast_debug(5, "There is no transaction involved in this state change\n");
1681         }
1682         ast_debug(5, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
1683 }
1684
1685 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
1686
1687 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
1688 {
1689         struct ast_sip_session_supplement *supplement;
1690         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
1691
1692         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
1693         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1694                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
1695                         if (supplement->incoming_request(session, rdata)) {
1696                                 break;
1697                         }
1698                 }
1699         }
1700 }
1701
1702 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata)
1703 {
1704         struct ast_sip_session_supplement *supplement;
1705         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
1706
1707         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
1708                         pj_strbuf(&status.reason));
1709
1710         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1711                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
1712                         supplement->incoming_response(session, rdata);
1713                 }
1714         }
1715 }
1716
1717 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata)
1718 {
1719         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
1720                         "request" : "response");
1721
1722         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
1723                 handle_incoming_request(session, rdata);
1724         } else {
1725                 handle_incoming_response(session, rdata);
1726         }
1727
1728         return 0;
1729 }
1730
1731 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1732 {
1733         struct ast_sip_session_supplement *supplement;
1734         struct pjsip_request_line req = tdata->msg->line.req;
1735
1736         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
1737         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1738                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
1739                         supplement->outgoing_request(session, tdata);
1740                 }
1741         }
1742 }
1743
1744 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
1745 {
1746         struct ast_sip_session_supplement *supplement;
1747         struct pjsip_status_line status = tdata->msg->line.status;
1748         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
1749         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
1750                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
1751                 pj_strbuf(&status.reason));
1752
1753         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
1754                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
1755                         supplement->outgoing_response(session, tdata);
1756                 }
1757         }
1758 }
1759
1760 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
1761 {
1762         ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
1763                         "request" : "response");
1764         if (tdata->msg->type == PJSIP_REQUEST_MSG) {
1765                 handle_outgoing_request(session, tdata);
1766         } else {
1767                 handle_outgoing_response(session, tdata);
1768         }
1769 }
1770
1771 static int session_end(struct ast_sip_session *session)
1772 {
1773         struct ast_sip_session_supplement *iter;
1774
1775         /* Stop the scheduled termination */
1776         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
1777                 ao2_ref(session, -1);
1778         }
1779
1780         /* Session is dead. Let's get rid of the reference to the session */
1781         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1782                 if (iter->session_end) {
1783                         iter->session_end(session);
1784                 }
1785         }
1786
1787         session->inv_session->mod_data[session_module.id] = NULL;
1788         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
1789         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
1790         ao2_cleanup(session);
1791         return 0;
1792 }
1793
1794 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
1795 {
1796         struct ast_sip_session *session = inv->mod_data[session_module.id];
1797
1798         print_debug_details(inv, NULL, e);
1799
1800         switch(e->type) {
1801         case PJSIP_EVENT_TX_MSG:
1802                 handle_outgoing(session, e->body.tx_msg.tdata);
1803                 break;
1804         case PJSIP_EVENT_RX_MSG:
1805                 handle_incoming(session, e->body.rx_msg.rdata);
1806                 break;
1807         case PJSIP_EVENT_TSX_STATE:
1808                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
1809                 /* Transaction state changes are prompted by some other underlying event. */
1810                 switch(e->body.tsx_state.type) {
1811                 case PJSIP_EVENT_TX_MSG:
1812                         handle_outgoing(session, e->body.tsx_state.src.tdata);
1813                         break;
1814                 case PJSIP_EVENT_RX_MSG:
1815                         handle_incoming(session, e->body.tsx_state.src.rdata);
1816                         break;
1817                 case PJSIP_EVENT_TRANSPORT_ERROR:
1818                 case PJSIP_EVENT_TIMER:
1819                 case PJSIP_EVENT_USER:
1820                 case PJSIP_EVENT_UNKNOWN:
1821                 case PJSIP_EVENT_TSX_STATE:
1822                         /* Inception? */
1823                         break;
1824                 }
1825                 break;
1826         case PJSIP_EVENT_TRANSPORT_ERROR:
1827         case PJSIP_EVENT_TIMER:
1828         case PJSIP_EVENT_UNKNOWN:
1829         case PJSIP_EVENT_USER:
1830         default:
1831                 break;
1832         }
1833
1834         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
1835                 session_end(session);
1836         }
1837 }
1838
1839 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
1840 {
1841         /* XXX STUB */
1842 }
1843
1844 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
1845 {
1846         struct ast_sip_session *session = inv->mod_data[session_module.id];
1847         print_debug_details(inv, tsx, e);
1848         if (!session) {
1849                 /* Transaction likely timed out after the call was hung up. Just
1850                  * ignore such transaction changes
1851                  */
1852                 return;
1853         }
1854         switch (e->body.tsx_state.type) {
1855         case PJSIP_EVENT_TX_MSG:
1856                 /* When we create an outgoing request, we do not have access to the transaction that
1857                  * is created. Instead, We have to place transaction-specific data in the tdata. Here,
1858                  * we transfer the data into the transaction. This way, when we receive a response, we
1859                  * can dig this data out again
1860                  */
1861                 tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
1862                 break;
1863         case PJSIP_EVENT_RX_MSG:
1864                 if (tsx->method.id == PJSIP_INVITE_METHOD) {
1865                         if (tsx->role == PJSIP_ROLE_UAC && tsx->state == PJSIP_TSX_STATE_COMPLETED) {
1866                                 /* This means we got a non 2XX final response to our outgoing INVITE */
1867                                 if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
1868                                         reschedule_reinvite(session, tsx->mod_data[session_module.id], tsx->last_tx);
1869                                         return;
1870                                 } else if (inv->state == PJSIP_INV_STATE_CONFIRMED &&
1871                                            tsx->status_code != 488) {
1872                                         /* Other reinvite failures (except 488) result in destroying the session. */
1873                                         pjsip_tx_data *tdata;
1874                                         if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
1875                                                 ast_sip_session_send_request(session, tdata);
1876                                         }
1877                                 }
1878                         }
1879                 } else {
1880                         if (tsx->role == PJSIP_ROLE_UAS && tsx->state == PJSIP_TSX_STATE_TRYING) {
1881                                 handle_incoming_request(session, e->body.tsx_state.src.rdata);
1882                         }
1883                 }
1884                 if (tsx->mod_data[session_module.id]) {
1885                         ast_sip_session_response_cb cb = tsx->mod_data[session_module.id];
1886                         cb(session, e->body.tsx_state.src.rdata);
1887                 }
1888         case PJSIP_EVENT_TRANSPORT_ERROR:
1889         case PJSIP_EVENT_TIMER:
1890         case PJSIP_EVENT_USER:
1891         case PJSIP_EVENT_UNKNOWN:
1892         case PJSIP_EVENT_TSX_STATE:
1893                 /* Inception? */
1894                 break;
1895         }
1896
1897         /* Terminated INVITE transactions always should result in queuing delayed requests,
1898          * no matter what event caused the transaction to terminate
1899          */
1900         if (tsx->method.id == PJSIP_INVITE_METHOD && tsx->state == PJSIP_TSX_STATE_TERMINATED) {
1901                 queue_delayed_request(session);
1902         }
1903 }
1904
1905 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
1906 {
1907         struct ast_sip_session_media *session_media = obj;
1908         pjmedia_sdp_session *answer = arg;
1909         struct ast_sip_session *session = data;
1910         struct ast_sip_session_sdp_handler *handler = session_media->handler;
1911         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1912
1913         if (handler) {
1914                 /* if an already assigned handler does not handle the session_media or reports a catastrophic error, fail */
1915                 if (handler->create_outgoing_sdp_stream(session, session_media, answer) <= 0) {
1916                         return 0;
1917                 }
1918                 return CMP_MATCH;
1919         }
1920
1921         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
1922         if (!handler_list) {
1923                 return CMP_MATCH;
1924         }
1925
1926         /* no handler for this stream type and we have a list to search */
1927         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1928                 int res = handler->create_outgoing_sdp_stream(session, session_media, answer);
1929                 if (res < 0) {
1930                         /* catastrophic error */
1931                         return 0;
1932                 }
1933                 if (res > 0) {
1934                         /* handled */
1935                         return CMP_MATCH;
1936                 }
1937         }
1938
1939         /* streams that weren't handled won't be included in generated outbound SDP */
1940         return CMP_MATCH;
1941 }
1942
1943 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
1944 {
1945         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
1946         static const pj_str_t STR_IN = { "IN", 2 };
1947         static const pj_str_t STR_IP4 = { "IP4", 3 };
1948         static const pj_str_t STR_IP6 = { "IP6", 3 };
1949         pjmedia_sdp_session *local;
1950
1951         if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
1952                 return NULL;
1953         }
1954
1955         if (!offer) {
1956                 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
1957         } else {
1958                 local->origin.version = offer->origin.version + 1;
1959                 local->origin.id = offer->origin.id;
1960         }
1961
1962         pj_strdup2(inv->pool, &local->origin.user, session->endpoint->media.sdpowner);
1963         local->origin.net_type = STR_IN;
1964         local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
1965         local->origin.addr = *pj_gethostname();
1966         pj_strdup2(inv->pool, &local->name, session->endpoint->media.sdpsession);
1967
1968         /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
1969         successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
1970         if (!successful || ao2_container_count(successful->c) != ao2_container_count(session->media)) {
1971                 /* Something experienced a catastrophic failure */
1972                 return NULL;
1973         }
1974
1975         /* Use the connection details of the first media stream if possible for SDP level */
1976         if (local->media_count) {
1977                 local->conn = local->media[0]->conn;
1978         }
1979
1980         return local;
1981 }
1982
1983 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
1984 {
1985         struct ast_sip_session *session = inv->mod_data[session_module.id];
1986         pjmedia_sdp_session *answer;
1987
1988         if (handle_incoming_sdp(session, offer)) {
1989                 return;
1990         }
1991
1992         if ((answer = create_local_sdp(inv, session, offer))) {
1993                 pjsip_inv_set_sdp_answer(inv, answer);
1994         }
1995 }
1996
1997 #if 0
1998 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
1999 {
2000         /* XXX STUB */
2001 }
2002 #endif
2003
2004 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2005 {
2006         struct ast_sip_session *session = inv->mod_data[session_module.id];
2007         const pjmedia_sdp_session *local, *remote;
2008
2009         if (!session->channel) {
2010                 /* If we don't have a channel. We really don't care about media updates.
2011                  * Just ignore
2012                  */
2013                 return;
2014         }
2015
2016         if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
2017                 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
2018                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2019                 ast_queue_hangup(session->channel);
2020                 return;
2021         }
2022
2023         handle_negotiated_sdp(session, local, remote);
2024 }
2025
2026 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
2027 {
2028         struct ast_sip_session *session = inv->mod_data[session_module.id];
2029
2030         if (PJSIP_URI_SCHEME_IS_SIP(target) || PJSIP_URI_SCHEME_IS_SIPS(target)) {
2031                 const pjsip_sip_uri *uri = pjsip_uri_get_uri(target);
2032                 char exten[AST_MAX_EXTENSION];
2033
2034                 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
2035                 ast_channel_call_forward_set(session->channel, exten);
2036         }
2037
2038         return PJSIP_REDIRECT_STOP;
2039 }
2040
2041 static pjsip_inv_callback inv_callback = {
2042         .on_state_changed = session_inv_on_state_changed,
2043         .on_new_session = session_inv_on_new_session,
2044         .on_tsx_state_changed = session_inv_on_tsx_state_changed,
2045         .on_rx_offer = session_inv_on_rx_offer,
2046         .on_media_update = session_inv_on_media_update,
2047         .on_redirected = session_inv_on_redirected,
2048 };
2049
2050 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
2051 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
2052 {
2053         struct ast_sip_nat_hook *hook = tdata->mod_data[session_module.id];
2054         struct pjmedia_sdp_session *sdp;
2055         int stream;
2056
2057         /* SDP produced by us directly will never be multipart */
2058         if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
2059                 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
2060                 return;
2061         }
2062
2063         sdp = tdata->msg->body->data;
2064
2065         for (stream = 0; stream < sdp->media_count; ++stream) {
2066                 /* See if there are registered handlers for this media stream type */
2067                 char media[20];
2068                 struct ast_sip_session_sdp_handler *handler;
2069                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2070
2071                 /* We need a null-terminated version of the media string */
2072                 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
2073
2074                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2075                 if (!handler_list) {
2076                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
2077                         continue;
2078                 }
2079                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2080                         if (handler->change_outgoing_sdp_stream_media_address) {
2081                                 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
2082                         }
2083                 }
2084         }
2085
2086         /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
2087         tdata->mod_data[session_module.id] = nat_hook;
2088 }
2089
2090 static int load_module(void)
2091 {
2092         pjsip_endpoint *endpt;
2093         if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
2094                 return AST_MODULE_LOAD_DECLINE;
2095         }
2096         if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
2097                 return AST_MODULE_LOAD_DECLINE;
2098         }
2099         nat_hook->outgoing_external_message = session_outgoing_nat_hook;
2100         ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
2101         sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
2102                         sdp_handler_list_hash, sdp_handler_list_cmp);
2103         if (!sdp_handlers) {
2104                 return AST_MODULE_LOAD_DECLINE;
2105         }
2106         endpt = ast_sip_get_pjsip_endpoint();
2107         pjsip_inv_usage_init(endpt, &inv_callback);
2108         pjsip_100rel_init_module(endpt);
2109         pjsip_timer_init_module(endpt);
2110         if (ast_sip_register_service(&session_module)) {
2111                 return AST_MODULE_LOAD_DECLINE;
2112         }
2113         ast_sip_register_service(&session_reinvite_module);
2114         return AST_MODULE_LOAD_SUCCESS;
2115 }
2116
2117 static int unload_module(void)
2118 {
2119         ast_sip_unregister_service(&session_module);
2120         ast_sip_unregister_service(&session_reinvite_module);
2121         if (nat_hook) {
2122                 ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
2123                 nat_hook = NULL;
2124         }
2125         return 0;
2126 }
2127
2128 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
2129                 .load = load_module,
2130                 .unload = unload_module,
2131                 .load_pri = AST_MODPRI_APP_DEPEND,
2132                );