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