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