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