Merge "res_pjsip_t38.c: Fix always false if test."
[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) || (endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
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 /*!
1422  * \internal
1423  * \brief Handle initial INVITE challenge response message.
1424  * \since 13.5.0
1425  *
1426  * \param rdata PJSIP receive response message data.
1427  *
1428  * \retval PJ_FALSE Did not handle message.
1429  * \retval PJ_TRUE Handled message.
1430  */
1431 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
1432 {
1433         pjsip_transaction *tsx;
1434         pjsip_dialog *dlg;
1435         pjsip_inv_session *inv;
1436         pjsip_tx_data *tdata;
1437         struct ast_sip_session *session;
1438
1439         if (rdata->msg_info.msg->line.status.code != 401
1440                 && rdata->msg_info.msg->line.status.code != 407) {
1441                 /* Doesn't pertain to us. Move on */
1442                 return PJ_FALSE;
1443         }
1444
1445         tsx = pjsip_rdata_get_tsx(rdata);
1446         dlg = pjsip_rdata_get_dlg(rdata);
1447         if (!dlg || !tsx) {
1448                 return PJ_FALSE;
1449         }
1450
1451         if (tsx->method.id != PJSIP_INVITE_METHOD) {
1452                 /* Not an INVITE that needs authentication */
1453                 return PJ_FALSE;
1454         }
1455
1456         inv = pjsip_dlg_get_inv_session(dlg);
1457         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
1458                 /*
1459                  * We cannot handle reINVITE authentication at this
1460                  * time because the reINVITE transaction is still in
1461                  * progress.
1462                  */
1463                 ast_debug(1, "A reINVITE is being challenged.\n");
1464                 return PJ_FALSE;
1465         }
1466         ast_debug(1, "Initial INVITE is being challenged.\n");
1467
1468         session = inv->mod_data[session_module.id];
1469
1470         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
1471                 tsx->last_tx, &tdata)) {
1472                 return PJ_FALSE;
1473         }
1474
1475         /*
1476          * Restart the outgoing initial INVITE transaction to deal
1477          * with authentication.
1478          */
1479         pjsip_inv_uac_restart(inv, PJ_FALSE);
1480
1481         ast_sip_session_send_request(session, tdata);
1482         return PJ_TRUE;
1483 }
1484
1485 static pjsip_module outbound_invite_auth_module = {
1486         .name = {"Outbound INVITE Auth", 20},
1487         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
1488         .on_rx_response = outbound_invite_auth,
1489 };
1490
1491 /*!
1492  * \internal
1493  * \brief Setup outbound initial INVITE authentication.
1494  * \since 13.5.0
1495  *
1496  * \param dlg PJSIP dialog to attach outbound authentication.
1497  *
1498  * \retval 0 on success.
1499  * \retval -1 on error.
1500  */
1501 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
1502 {
1503         pj_status_t status;
1504
1505         ++dlg->sess_count;
1506         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
1507         --dlg->sess_count;
1508
1509         return status != PJ_SUCCESS ? -1 : 0;
1510 }
1511
1512 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
1513         struct ast_sip_contact *contact, const char *location, const char *request_user,
1514         struct ast_format_cap *req_caps)
1515 {
1516         const char *uri = NULL;
1517         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
1518         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
1519         pjsip_timer_setting timer;
1520         pjsip_dialog *dlg;
1521         struct pjsip_inv_session *inv_session;
1522         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1523
1524         /* If no location has been provided use the AOR list from the endpoint itself */
1525         if (location || !contact) {
1526                 location = S_OR(location, endpoint->aors);
1527
1528                 ast_sip_location_retrieve_contact_and_aor_from_list(location, &found_aor, &found_contact);
1529                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
1530                         uri = location;
1531                 } else {
1532                         uri = found_contact->uri;
1533                 }
1534         } else {
1535                 uri = contact->uri;
1536         }
1537
1538         /* If we still have no URI to dial fail to create the session */
1539         if (ast_strlen_zero(uri)) {
1540                 return NULL;
1541         }
1542
1543         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
1544                 return NULL;
1545         }
1546
1547         if (setup_outbound_invite_auth(dlg)) {
1548                 pjsip_dlg_terminate(dlg);
1549                 return NULL;
1550         }
1551
1552         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1553                 pjsip_dlg_terminate(dlg);
1554                 return NULL;
1555         }
1556 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1557         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1558 #endif
1559
1560         pjsip_timer_setting_default(&timer);
1561         timer.min_se = endpoint->extensions.timer.min_se;
1562         timer.sess_expires = endpoint->extensions.timer.sess_expires;
1563         pjsip_timer_init_session(inv_session, &timer);
1564
1565         if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
1566                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1567                 return NULL;
1568         }
1569         session->aor = ao2_bump(found_aor);
1570         ast_party_id_copy(&session->id, &endpoint->id.self);
1571
1572         if (ast_format_cap_count(req_caps)) {
1573                 /* get joint caps between req_caps and endpoint caps */
1574                 struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1575                 ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
1576
1577                 /* if joint caps */
1578                 if (ast_format_cap_count(joint_caps)) {
1579                         /* copy endpoint caps into session->req_caps */
1580                         ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
1581                         /* replace instances of joint caps equivalents in session->req_caps */
1582                         ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
1583                 }
1584                 ao2_cleanup(joint_caps);
1585         }
1586
1587         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1588                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1589                 /* Since we are not notifying ourselves that the INVITE session is being terminated
1590                  * we need to manually drop its reference to session
1591                  */
1592                 ao2_ref(session, -1);
1593                 return NULL;
1594         }
1595
1596         ao2_ref(session, +1);
1597         return session;
1598 }
1599
1600 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
1601 {
1602         pj_status_t status;
1603         pjsip_tx_data *packet = NULL;
1604
1605         if (session->defer_terminate) {
1606                 session->terminate_while_deferred = 1;
1607                 return;
1608         }
1609
1610         if (!response) {
1611                 response = 603;
1612         }
1613
1614         if ((session->inv_session->state == PJSIP_INV_STATE_CONFIRMED) && session->inv_session->invite_tsx) {
1615                 ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
1616                                 ast_sorcery_object_get_id(session->endpoint));
1617                 /* If this is delayed the only thing that will happen is a BYE request so we don't
1618                  * actually need to store the response code for when it happens.
1619                  */
1620                 delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);
1621         } else if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1622                 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
1623         } else if (((status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet)) == PJ_SUCCESS)
1624                 && packet) {
1625                 struct ast_sip_session_delayed_request *delay;
1626
1627                 /* Flush any delayed requests so they cannot overlap this transaction. */
1628                 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1629                         ast_free(delay);
1630                 }
1631
1632                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1633                         ast_sip_session_send_response(session, packet);
1634                 } else {
1635                         ast_sip_session_send_request(session, packet);
1636                 }
1637         }
1638 }
1639
1640 static int session_termination_task(void *data)
1641 {
1642         struct ast_sip_session *session = data;
1643
1644         if (session->defer_terminate) {
1645                 session->defer_terminate = 0;
1646                 if (session->inv_session) {
1647                         ast_sip_session_terminate(session, 0);
1648                 }
1649         }
1650
1651         ao2_ref(session, -1);
1652         return 0;
1653 }
1654
1655 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1656 {
1657         struct ast_sip_session *session = entry->user_data;
1658
1659         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1660                 ao2_cleanup(session);
1661         }
1662 }
1663
1664 int ast_sip_session_defer_termination(struct ast_sip_session *session)
1665 {
1666         pj_time_val delay = { .sec = 60, };
1667         int res;
1668
1669         /* The session should not have an active deferred termination request. */
1670         ast_assert(!session->defer_terminate);
1671
1672         session->defer_terminate = 1;
1673
1674         session->scheduled_termination.id = 0;
1675         ao2_ref(session, +1);
1676         session->scheduled_termination.user_data = session;
1677         session->scheduled_termination.cb = session_termination_cb;
1678
1679         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
1680                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
1681         if (res) {
1682                 session->defer_terminate = 0;
1683                 ao2_ref(session, -1);
1684         }
1685         return res;
1686 }
1687
1688 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
1689 {
1690         if (!session->defer_terminate) {
1691                 /* Already canceled or timer fired. */
1692                 return;
1693         }
1694         session->defer_terminate = 0;
1695
1696         if (session->terminate_while_deferred) {
1697                 /* Complete the termination started by the upper layer. */
1698                 ast_sip_session_terminate(session, 0);
1699         }
1700
1701         /* Stop the termination timer if it is still running. */
1702         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
1703                 &session->scheduled_termination)) {
1704                 ao2_ref(session, -1);
1705         }
1706 }
1707
1708 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1709 {
1710         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1711         struct ast_sip_session *session;
1712
1713         if (!inv_session ||
1714                 !(session = inv_session->mod_data[session_module.id])) {
1715                 return NULL;
1716         }
1717
1718         ao2_ref(session, +1);
1719
1720         return session;
1721 }
1722
1723 enum sip_get_destination_result {
1724         /*! The extension was successfully found */
1725         SIP_GET_DEST_EXTEN_FOUND,
1726         /*! The extension specified in the RURI was not found */
1727         SIP_GET_DEST_EXTEN_NOT_FOUND,
1728         /*! The extension specified in the RURI was a partial match */
1729         SIP_GET_DEST_EXTEN_PARTIAL,
1730         /*! The RURI is of an unsupported scheme */
1731         SIP_GET_DEST_UNSUPPORTED_URI,
1732 };
1733
1734 /*!
1735  * \brief Determine where in the dialplan a call should go
1736  *
1737  * This uses the username in the request URI to try to match
1738  * an extension in the endpoint's configured context in order
1739  * to route the call.
1740  *
1741  * \param session The inbound SIP session
1742  * \param rdata The SIP INVITE
1743  */
1744 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1745 {
1746         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1747         pjsip_sip_uri *sip_ruri;
1748         struct ast_features_pickup_config *pickup_cfg;
1749         const char *pickupexten;
1750
1751         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1752                 return SIP_GET_DEST_UNSUPPORTED_URI;
1753         }
1754
1755         sip_ruri = pjsip_uri_get_uri(ruri);
1756         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1757
1758         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
1759         if (!pickup_cfg) {
1760                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
1761                 pickupexten = "";
1762         } else {
1763                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
1764                 ao2_ref(pickup_cfg, -1);
1765         }
1766
1767         if (!strcmp(session->exten, pickupexten) ||
1768                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1769                 return SIP_GET_DEST_EXTEN_FOUND;
1770         }
1771         /* XXX In reality, we'll likely have further options so that partial matches
1772          * can be indicated here, but for getting something up and running, we're going
1773          * to return a "not exists" error here.
1774          */
1775         return SIP_GET_DEST_EXTEN_NOT_FOUND;
1776 }
1777
1778 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1779 {
1780         pjsip_tx_data *tdata;
1781         pjsip_dialog *dlg;
1782         pjsip_inv_session *inv_session;
1783         unsigned int options = endpoint->extensions.flags;
1784         pj_status_t dlg_status;
1785
1786         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
1787                 if (tdata) {
1788                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1789                 } else {
1790                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1791                 }
1792                 return NULL;
1793         }
1794         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
1795         if (!dlg) {
1796                 if (dlg_status != PJ_EEXISTS) {
1797                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1798                 }
1799                 return NULL;
1800         }
1801         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
1802                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1803                 pjsip_dlg_terminate(dlg);
1804                 return NULL;
1805         }
1806
1807 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1808         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1809 #endif
1810         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1811                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
1812                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1813                 }
1814                 pjsip_inv_send_msg(inv_session, tdata);
1815                 return NULL;
1816         }
1817         return inv_session;
1818 }
1819
1820 struct new_invite {
1821         /*! \brief Session created for the new INVITE */
1822         struct ast_sip_session *session;
1823
1824         /*! \brief INVITE request itself */
1825         pjsip_rx_data *rdata;
1826 };
1827
1828 static void new_invite_destroy(void *obj)
1829 {
1830         struct new_invite *invite = obj;
1831
1832         ao2_cleanup(invite->session);
1833
1834         if (invite->rdata) {
1835                 pjsip_rx_data_free_cloned(invite->rdata);
1836         }
1837 }
1838
1839 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
1840 {
1841         struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
1842
1843         if (!invite) {
1844                 return NULL;
1845         }
1846
1847         ao2_ref(session, +1);
1848         invite->session = session;
1849
1850         if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
1851                 ao2_ref(invite, -1);
1852                 return NULL;
1853         }
1854
1855         return invite;
1856 }
1857
1858 static int new_invite(void *data)
1859 {
1860         RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
1861         pjsip_tx_data *tdata = NULL;
1862         pjsip_timer_setting timer;
1863         pjsip_rdata_sdp_info *sdp_info;
1864         pjmedia_sdp_session *local = NULL;
1865
1866         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
1867          * so that we will be notified so we can destroy the session properly
1868          */
1869
1870         switch (get_destination(invite->session, invite->rdata)) {
1871         case SIP_GET_DEST_EXTEN_FOUND:
1872                 /* Things worked. Keep going */
1873                 break;
1874         case SIP_GET_DEST_UNSUPPORTED_URI:
1875                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
1876                         ast_sip_session_send_response(invite->session, tdata);
1877                 } else  {
1878                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
1879                 }
1880                 return 0;
1881         case SIP_GET_DEST_EXTEN_NOT_FOUND:
1882         case SIP_GET_DEST_EXTEN_PARTIAL:
1883         default:
1884                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
1885                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
1886                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
1887
1888                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
1889                         ast_sip_session_send_response(invite->session, tdata);
1890                 } else  {
1891                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
1892                 }
1893                 return 0;
1894         };
1895
1896         if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
1897                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
1898                         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
1899                                 ast_sip_session_send_response(invite->session, tdata);
1900                         } else  {
1901                                 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
1902                         }
1903                         return 0;
1904                 }
1905                 /* We are creating a local SDP which is an answer to their offer */
1906                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
1907         } else {
1908                 /* We are creating a local SDP which is an offer */
1909                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
1910         }
1911
1912         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
1913         if (!local) {
1914                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1915                         ast_sip_session_send_response(invite->session, tdata);
1916                 } else  {
1917                         pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1918                 }
1919                 return 0;
1920         } else {
1921                 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
1922                 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
1923 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1924                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
1925 #endif
1926         }
1927
1928         pjsip_timer_setting_default(&timer);
1929         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
1930         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
1931         pjsip_timer_init_session(invite->session->inv_session, &timer);
1932
1933         /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
1934         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
1935                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1936                 return 0;
1937         }
1938         ast_sip_session_send_response(invite->session, tdata);
1939
1940         handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
1941
1942         return 0;
1943 }
1944
1945 static void handle_new_invite_request(pjsip_rx_data *rdata)
1946 {
1947         RAII_VAR(struct ast_sip_endpoint *, endpoint,
1948                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1949         pjsip_tx_data *tdata = NULL;
1950         pjsip_inv_session *inv_session = NULL;
1951         struct ast_sip_session *session;
1952         struct new_invite *invite;
1953
1954         ast_assert(endpoint != NULL);
1955
1956         inv_session = pre_session_setup(rdata, endpoint);
1957         if (!inv_session) {
1958                 /* pre_session_setup() returns a response on failure */
1959                 return;
1960         }
1961
1962         session = ast_sip_session_alloc(endpoint, NULL, inv_session);
1963         if (!session) {
1964                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1965                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1966                 } else {
1967                         pjsip_inv_send_msg(inv_session, tdata);
1968                 }
1969                 return;
1970         }
1971
1972         invite = new_invite_alloc(session, rdata);
1973         if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
1974                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1975                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1976                 } else {
1977                         pjsip_inv_send_msg(inv_session, tdata);
1978                 }
1979                 ao2_cleanup(invite);
1980         }
1981         ao2_ref(session, -1);
1982 }
1983
1984 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
1985 {
1986         pj_str_t method;
1987
1988         if (ast_strlen_zero(supplement_method)) {
1989                 return PJ_TRUE;
1990         }
1991
1992         pj_cstr(&method, supplement_method);
1993
1994         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
1995 }
1996
1997 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
1998 {
1999         struct ast_sip_session_supplement *supplement;
2000         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
2001
2002         if (!session) {
2003                 return PJ_FALSE;
2004         }
2005
2006         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2007                 if (does_method_match(&method->name, supplement->method)) {
2008                         return PJ_TRUE;
2009                 }
2010         }
2011         return PJ_FALSE;
2012 }
2013 /*!
2014  * \brief Called when a new SIP request comes into PJSIP
2015  *
2016  * This function is called under two circumstances
2017  * 1) An out-of-dialog request is received by PJSIP
2018  * 2) An in-dialog request that the inv_session layer does not
2019  *    handle is received (such as an in-dialog INFO)
2020  *
2021  * In all cases, there is very little we actually do in this function
2022  * 1) For requests we don't handle, we return PJ_FALSE
2023  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
2024  *    there to free up the thread(s) handling incoming requests
2025  * 3) For in-dialog requests we handle, we defer handling them until the
2026  *    on_inv_state_change() callback instead (where we will end up putting
2027  *    them into the threadpool).
2028  */
2029 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
2030 {
2031         pj_status_t handled = PJ_FALSE;
2032         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
2033         pjsip_inv_session *inv_session;
2034
2035         switch (rdata->msg_info.msg->line.req.method.id) {
2036         case PJSIP_INVITE_METHOD:
2037                 if (dlg) {
2038                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
2039                         break;
2040                 }
2041                 handled = PJ_TRUE;
2042                 handle_new_invite_request(rdata);
2043                 break;
2044         default:
2045                 /* Handle other in-dialog methods if their supplements have been registered */
2046                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
2047                         has_supplement(inv_session->mod_data[session_module.id], rdata);
2048                 break;
2049         }
2050
2051         return handled;
2052 }
2053
2054 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
2055 {
2056         struct ast_sip_session *session = entry->user_data;
2057
2058         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
2059                 ast_sorcery_object_get_id(session->endpoint),
2060                 session->channel ? ast_channel_name(session->channel) : "");
2061
2062         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2063                 /* No delayed request pending, so just return */
2064                 ao2_ref(session, -1);
2065                 return;
2066         }
2067         if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
2068                 /*
2069                  * Uh oh.  We now have nothing in the foreseeable future
2070                  * to trigger sending the delayed requests.
2071                  */
2072                 ao2_ref(session, -1);
2073         }
2074 }
2075
2076 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
2077 {
2078         pjsip_inv_session *inv = session->inv_session;
2079         pj_time_val tv;
2080
2081         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
2082                 ast_sorcery_object_get_id(session->endpoint),
2083                 session->channel ? ast_channel_name(session->channel) : "");
2084         if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {
2085                 return;
2086         }
2087         if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
2088                 /* Timer already running.  Something weird is going on. */
2089                 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
2090                         ast_sorcery_object_get_id(session->endpoint),
2091                         session->channel ? ast_channel_name(session->channel) : "");
2092                 return;
2093         }
2094
2095         tv.sec = 0;
2096         if (inv->role == PJSIP_ROLE_UAC) {
2097                 tv.msec = 2100 + ast_random() % 2000;
2098         } else {
2099                 tv.msec = ast_random() % 2000;
2100         }
2101         pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
2102
2103         ao2_ref(session, +1);
2104         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2105                 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
2106                 ao2_ref(session, -1);
2107         }
2108 }
2109
2110 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2111 {
2112         struct ast_sip_session *session;
2113
2114         if (!DEBUG_ATLEAST(5)) {
2115                 /* Debug not spamy enough */
2116                 return;
2117         }
2118
2119         ast_log(LOG_DEBUG, "Function %s called on event %s\n",
2120                 function, pjsip_event_str(e->type));
2121         if (!inv) {
2122                 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
2123                 ast_log(LOG_DEBUG, "The transaction state is %s\n",
2124                         pjsip_tsx_state_str(tsx->state));
2125                 return;
2126         }
2127         session = inv->mod_data[session_module.id];
2128         if (!session) {
2129                 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
2130         } else {
2131                 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
2132                         ast_sorcery_object_get_id(session->endpoint),
2133                         session->channel ? ast_channel_name(session->channel) : "");
2134         }
2135         if (inv->invite_tsx) {
2136                 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
2137                         inv->invite_tsx);
2138         } else {
2139                 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
2140         }
2141         if (tsx) {
2142                 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
2143                         pjsip_role_name(tsx->role),
2144                         (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2145                         tsx);
2146                 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
2147                         pjsip_tsx_state_str(tsx->state));
2148                 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
2149                         pjsip_event_str(e->body.tsx_state.type));
2150         } else {
2151                 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
2152         }
2153         ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
2154 }
2155
2156 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
2157
2158 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
2159 {
2160         struct ast_sip_session_supplement *supplement;
2161         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
2162
2163         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2164         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2165                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
2166                         if (supplement->incoming_request(session, rdata)) {
2167                                 break;
2168                         }
2169                 }
2170         }
2171 }
2172
2173 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2174                 enum ast_sip_session_response_priority response_priority)
2175 {
2176         struct ast_sip_session_supplement *supplement;
2177         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2178
2179         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
2180                         pj_strbuf(&status.reason));
2181
2182         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2183                 if (!(supplement->response_priority & response_priority)) {
2184                         continue;
2185                 }
2186                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
2187                         supplement->incoming_response(session, rdata);
2188                 }
2189         }
2190 }
2191
2192 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2193                 enum ast_sip_session_response_priority response_priority)
2194 {
2195         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
2196                         "request" : "response");
2197
2198         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
2199                 handle_incoming_request(session, rdata, type);
2200         } else {
2201                 handle_incoming_response(session, rdata, type, response_priority);
2202         }
2203
2204         return 0;
2205 }
2206
2207 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2208 {
2209         struct ast_sip_session_supplement *supplement;
2210         struct pjsip_request_line req = tdata->msg->line.req;
2211
2212         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2213         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2214                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
2215                         supplement->outgoing_request(session, tdata);
2216                 }
2217         }
2218 }
2219
2220 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
2221 {
2222         struct ast_sip_session_supplement *supplement;
2223         struct pjsip_status_line status = tdata->msg->line.status;
2224         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
2225         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
2226                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
2227                 pj_strbuf(&status.reason));
2228
2229         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2230                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
2231                         supplement->outgoing_response(session, tdata);
2232                 }
2233         }
2234 }
2235
2236 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
2237 {
2238         ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
2239                         "request" : "response");
2240         if (tdata->msg->type == PJSIP_REQUEST_MSG) {
2241                 handle_outgoing_request(session, tdata);
2242         } else {
2243                 handle_outgoing_response(session, tdata);
2244         }
2245 }
2246
2247 static int session_end(struct ast_sip_session *session)
2248 {
2249         struct ast_sip_session_supplement *iter;
2250
2251         /* Stop the scheduled termination */
2252         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
2253                 ao2_ref(session, -1);
2254         }
2255
2256         /* Session is dead. Let's get rid of the reference to the session */
2257         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2258                 if (iter->session_end) {
2259                         iter->session_end(session);
2260                 }
2261         }
2262
2263         session->inv_session->mod_data[session_module.id] = NULL;
2264         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
2265         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
2266         ao2_cleanup(session);
2267         return 0;
2268 }
2269
2270 static int check_request_status(pjsip_inv_session *inv, pjsip_event *e)
2271 {
2272         struct ast_sip_session *session = inv->mod_data[session_module.id];
2273         pjsip_transaction *tsx = e->body.tsx_state.tsx;
2274
2275         if (tsx->status_code != 503 && tsx->status_code != 408) {
2276                 return 0;
2277         }
2278
2279         if (!ast_sip_failover_request(tsx->last_tx)) {
2280                 return 0;
2281         }
2282
2283         pjsip_inv_uac_restart(inv, PJ_FALSE);
2284         /*
2285          * Bump the ref since it will be on a new transaction and
2286          * we don't want it to go away along with the old transaction.
2287          */
2288         pjsip_tx_data_add_ref(tsx->last_tx);
2289         ast_sip_session_send_request(session, tsx->last_tx);
2290         return 1;
2291 }
2292
2293 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
2294 {
2295         struct ast_sip_session *session = inv->mod_data[session_module.id];
2296         pjsip_event_id_e type;
2297
2298         if (e) {
2299                 print_debug_details(inv, NULL, e);
2300                 type = e->type;
2301         } else {
2302                 type = PJSIP_EVENT_UNKNOWN;
2303         }
2304
2305         if (!session) {
2306                 return;
2307         }
2308
2309         switch(type) {
2310         case PJSIP_EVENT_TX_MSG:
2311                 handle_outgoing(session, e->body.tx_msg.tdata);
2312                 break;
2313         case PJSIP_EVENT_RX_MSG:
2314                 handle_incoming(session, e->body.rx_msg.rdata, type,
2315                                 AST_SIP_SESSION_BEFORE_MEDIA);
2316                 break;
2317         case PJSIP_EVENT_TSX_STATE:
2318                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
2319                 /* Transaction state changes are prompted by some other underlying event. */
2320                 switch(e->body.tsx_state.type) {
2321                 case PJSIP_EVENT_TX_MSG:
2322                         handle_outgoing(session, e->body.tsx_state.src.tdata);
2323                         break;
2324                 case PJSIP_EVENT_RX_MSG:
2325                         if (!check_request_status(inv, e)) {
2326                                 handle_incoming(session, e->body.tsx_state.src.rdata, type,
2327                                                 AST_SIP_SESSION_BEFORE_MEDIA);
2328                         }
2329                         break;
2330                 case PJSIP_EVENT_TRANSPORT_ERROR:
2331                 case PJSIP_EVENT_TIMER:
2332                         /*
2333                          * Check the request status on transport error or timeout. A transport
2334                          * error can occur when a TCP socket closes and that can be the result
2335                          * of a 503. Also we may need to failover on a timeout (408).
2336                          */
2337                         check_request_status(inv, e);
2338                         break;
2339                 case PJSIP_EVENT_USER:
2340                 case PJSIP_EVENT_UNKNOWN:
2341                 case PJSIP_EVENT_TSX_STATE:
2342                         /* Inception? */
2343                         break;
2344                 }
2345                 break;
2346         case PJSIP_EVENT_TRANSPORT_ERROR:
2347         case PJSIP_EVENT_TIMER:
2348         case PJSIP_EVENT_UNKNOWN:
2349         case PJSIP_EVENT_USER:
2350         default:
2351                 break;
2352         }
2353
2354         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2355                 session_end(session);
2356         }
2357 }
2358
2359 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
2360 {
2361         /* XXX STUB */
2362 }
2363
2364 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2365 {
2366         ast_sip_session_response_cb cb;
2367         struct ast_sip_session *session = inv->mod_data[session_module.id];
2368         pjsip_tx_data *tdata;
2369
2370         print_debug_details(inv, tsx, e);
2371         if (!session) {
2372                 /* Transaction likely timed out after the call was hung up. Just
2373                  * ignore such transaction changes
2374                  */
2375                 return;
2376         }
2377         switch (e->body.tsx_state.type) {
2378         case PJSIP_EVENT_TX_MSG:
2379                 handle_outgoing(session, e->body.tsx_state.src.tdata);
2380                 /* When we create an outgoing request, we do not have access to the transaction that
2381                  * is created. Instead, We have to place transaction-specific data in the tdata. Here,
2382                  * we transfer the data into the transaction. This way, when we receive a response, we
2383                  * can dig this data out again
2384                  */
2385                 tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
2386                 break;
2387         case PJSIP_EVENT_RX_MSG:
2388                 cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id, MOD_DATA_ON_RESPONSE);
2389                 handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
2390                                 AST_SIP_SESSION_AFTER_MEDIA);
2391                 if (tsx->method.id == PJSIP_INVITE_METHOD) {
2392                         if (tsx->role == PJSIP_ROLE_UAC) {
2393                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2394                                         /* This means we got a non 2XX final response to our outgoing INVITE */
2395                                         if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
2396                                                 reschedule_reinvite(session, cb);
2397                                                 return;
2398                                         }
2399                                         if (inv->state == PJSIP_INV_STATE_CONFIRMED) {
2400                                                 ast_debug(1, "reINVITE received final response code %d\n",
2401                                                         tsx->status_code);
2402                                                 if ((tsx->status_code == 401 || tsx->status_code == 407)
2403                                                         && !ast_sip_create_request_with_auth(
2404                                                                 &session->endpoint->outbound_auths,
2405                                                                 e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2406                                                         /* Send authed reINVITE */
2407                                                         ast_sip_session_send_request_with_cb(session, tdata, cb);
2408                                                         return;
2409                                                 }
2410                                                 if (tsx->status_code != 488) {
2411                                                         /* Other reinvite failures (except 488) result in destroying the session. */
2412                                                         if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2413                                                                 ast_sip_session_send_request(session, tdata);
2414                                                         }
2415                                                 }
2416                                         }
2417                                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2418                                         if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
2419                                                 /* This is a race condition detailed in RFC 5407 section 3.1.2.
2420                                                  * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
2421                                                  * the original INVITE. As a result, we have now received a 200 OK for
2422                                                  * a cancelled call. Our role is to immediately send a BYE to end the
2423                                                  * dialog.
2424                                                  */
2425                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2426                                                         ast_sip_session_send_request(session, tdata);
2427                                                 }
2428                                         }
2429                                 }
2430                         }
2431                 } else {
2432                         /* All other methods */
2433                         if (tsx->role == PJSIP_ROLE_UAC) {
2434                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2435                                         /* This means we got a final response to our outgoing method */
2436                                         ast_debug(1, "%.*s received final response code %d\n",
2437                                                 (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2438                                                 tsx->status_code);
2439                                         if ((tsx->status_code == 401 || tsx->status_code == 407)
2440                                                 && !ast_sip_create_request_with_auth(
2441                                                         &session->endpoint->outbound_auths,
2442                                                         e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2443                                                 /* Send authed version of the method */
2444                                                 ast_sip_session_send_request_with_cb(session, tdata, cb);
2445                                                 return;
2446                                         }
2447                                 }
2448                         }
2449                 }
2450                 if (cb) {
2451                         cb(session, e->body.tsx_state.src.rdata);
2452                 }
2453                 break;
2454         case PJSIP_EVENT_TRANSPORT_ERROR:
2455         case PJSIP_EVENT_TIMER:
2456         case PJSIP_EVENT_USER:
2457         case PJSIP_EVENT_UNKNOWN:
2458         case PJSIP_EVENT_TSX_STATE:
2459                 /* Inception? */
2460                 break;
2461         }
2462
2463         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2464                 /* No delayed request pending, so just return */
2465                 return;
2466         }
2467
2468         if (tsx->method.id == PJSIP_INVITE_METHOD) {
2469                 if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
2470                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2471                                 ast_sorcery_object_get_id(session->endpoint),
2472                                 session->channel ? ast_channel_name(session->channel) : "",
2473                                 pjsip_tsx_state_str(tsx->state));
2474                         check_delayed_requests(session, invite_proceeding);
2475                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2476                         /*
2477                          * Terminated INVITE transactions always should result in
2478                          * queuing delayed requests, no matter what event caused
2479                          * the transaction to terminate.
2480                          */
2481                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2482                                 ast_sorcery_object_get_id(session->endpoint),
2483                                 session->channel ? ast_channel_name(session->channel) : "",
2484                                 pjsip_tsx_state_str(tsx->state));
2485                         check_delayed_requests(session, invite_terminated);
2486                 }
2487         } else if (tsx->role == PJSIP_ROLE_UAC
2488                 && tsx->state == PJSIP_TSX_STATE_COMPLETED
2489                 && !pj_strcmp2(&tsx->method.name, "UPDATE")) {
2490                 ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",
2491                         ast_sorcery_object_get_id(session->endpoint),
2492                         session->channel ? ast_channel_name(session->channel) : "",
2493                         pjsip_tsx_state_str(tsx->state));
2494                 check_delayed_requests(session, update_completed);
2495         }
2496 }
2497
2498 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
2499 {
2500         struct ast_sip_session_media *session_media = obj;
2501         pjmedia_sdp_session *answer = arg;
2502         struct ast_sip_session *session = data;
2503         struct ast_sip_session_sdp_handler *handler = session_media->handler;
2504         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2505         int res;
2506
2507         if (handler) {
2508                 /* if an already assigned handler reports a catastrophic error, fail */
2509                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2510                 if (res < 0) {
2511                         return 0;
2512                 }
2513                 return CMP_MATCH;
2514         }
2515
2516         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
2517         if (!handler_list) {
2518                 return CMP_MATCH;
2519         }
2520
2521         /* no handler for this stream type and we have a list to search */
2522         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2523                 if (handler == session_media->handler) {
2524                         continue;
2525                 }
2526                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2527                 if (res < 0) {
2528                         /* catastrophic error */
2529                         return 0;
2530                 }
2531                 if (res > 0) {
2532                         /* Handled by this handler. Move to the next stream */
2533                         session_media_set_handler(session_media, handler);
2534                         return CMP_MATCH;
2535                 }
2536         }
2537
2538         /* streams that weren't handled won't be included in generated outbound SDP */
2539         return CMP_MATCH;
2540 }
2541
2542 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
2543 {
2544         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
2545         static const pj_str_t STR_IN = { "IN", 2 };
2546         static const pj_str_t STR_IP4 = { "IP4", 3 };
2547         static const pj_str_t STR_IP6 = { "IP6", 3 };
2548         pjmedia_sdp_session *local;
2549
2550         if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
2551                 return NULL;
2552         }
2553
2554         if (!offer) {
2555                 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
2556         } else {
2557                 local->origin.version = offer->origin.version + 1;
2558                 local->origin.id = offer->origin.id;
2559         }
2560
2561         pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
2562         pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
2563
2564         /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
2565         successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
2566         if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
2567                 /* Something experienced a catastrophic failure */
2568                 return NULL;
2569         }
2570
2571         /* Use the connection details of the first media stream if possible for SDP level */
2572         if (local->media_count) {
2573                 int stream;
2574
2575                 /* Since we are using the first media stream as the SDP level we can get rid of it
2576                  * from the stream itself
2577                  */
2578                 local->conn = local->media[0]->conn;
2579                 local->media[0]->conn = NULL;
2580                 pj_strassign(&local->origin.net_type, &local->conn->net_type);
2581                 pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
2582                 pj_strassign(&local->origin.addr, &local->conn->addr);
2583
2584                 /* Go through each media stream seeing if the connection details actually differ,
2585                  * if not just use SDP level and reduce the SDP size
2586                  */
2587                 for (stream = 1; stream < local->media_count; stream++) {
2588                         if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
2589                                 !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
2590                                 !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
2591                                 local->media[stream]->conn = NULL;
2592                         }
2593                 }
2594         } else {
2595                 local->origin.net_type = STR_IN;
2596                 local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
2597
2598                 if (!ast_strlen_zero(session->endpoint->media.address)) {
2599                         pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
2600                 } else {
2601                         pj_sockaddr localaddr;
2602                         char our_ip[PJ_INET6_ADDRSTRLEN];
2603
2604                         pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
2605                         pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
2606                         pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
2607                 }
2608         }
2609
2610         return local;
2611 }
2612
2613 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
2614 {
2615         struct ast_sip_session *session = inv->mod_data[session_module.id];
2616         pjmedia_sdp_session *answer;
2617
2618         if (handle_incoming_sdp(session, offer)) {
2619                 return;
2620         }
2621
2622         if ((answer = create_local_sdp(inv, session, offer))) {
2623                 pjsip_inv_set_sdp_answer(inv, answer);
2624         }
2625 }
2626
2627 #if 0
2628 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
2629 {
2630         /* XXX STUB */
2631 }
2632 #endif
2633
2634 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2635 {
2636         struct ast_sip_session *session = inv->mod_data[session_module.id];
2637         const pjmedia_sdp_session *local, *remote;
2638
2639         if (!session->channel) {
2640                 /* If we don't have a channel. We really don't care about media updates.
2641                  * Just ignore
2642                  */
2643                 return;
2644         }
2645
2646         if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
2647                 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
2648                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2649                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2650                 ast_queue_hangup(session->channel);
2651                 return;
2652         }
2653
2654         handle_negotiated_sdp(session, local, remote);
2655 }
2656
2657 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
2658 {
2659         struct ast_sip_session *session = inv->mod_data[session_module.id];
2660         const pjsip_sip_uri *uri;
2661
2662         if (!session->channel) {
2663                 return PJSIP_REDIRECT_STOP;
2664         }
2665
2666         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
2667                 return PJSIP_REDIRECT_ACCEPT;
2668         }
2669
2670         if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
2671                 return PJSIP_REDIRECT_STOP;
2672         }
2673
2674         handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
2675                         AST_SIP_SESSION_BEFORE_REDIRECTING);
2676
2677         uri = pjsip_uri_get_uri(target);
2678
2679         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
2680                 char exten[AST_MAX_EXTENSION];
2681
2682                 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
2683                 ast_channel_call_forward_set(session->channel, exten);
2684         } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
2685                 char target_uri[PJSIP_MAX_URL_SIZE];
2686                 /* PJSIP/ + endpoint length + / + max URL size */
2687                 char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
2688
2689                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
2690                 sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
2691                 ast_channel_call_forward_set(session->channel, forward);
2692         }
2693
2694         return PJSIP_REDIRECT_STOP;
2695 }
2696
2697 static pjsip_inv_callback inv_callback = {
2698         .on_state_changed = session_inv_on_state_changed,
2699         .on_new_session = session_inv_on_new_session,
2700         .on_tsx_state_changed = session_inv_on_tsx_state_changed,
2701         .on_rx_offer = session_inv_on_rx_offer,
2702         .on_media_update = session_inv_on_media_update,
2703         .on_redirected = session_inv_on_redirected,
2704 };
2705
2706 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
2707 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
2708 {
2709         struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
2710                 tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
2711         struct pjmedia_sdp_session *sdp;
2712         int stream;
2713
2714         /* SDP produced by us directly will never be multipart */
2715         if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
2716                 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
2717                 return;
2718         }
2719
2720         sdp = tdata->msg->body->data;
2721
2722         if (sdp->conn) {
2723                 char host[NI_MAXHOST];
2724                 struct ast_sockaddr addr = { { 0, } };
2725
2726                 ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
2727                 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
2728
2729                 if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
2730                         pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
2731                 }
2732         }
2733
2734         for (stream = 0; stream < sdp->media_count; ++stream) {
2735                 /* See if there are registered handlers for this media stream type */
2736                 char media[20];
2737                 struct ast_sip_session_sdp_handler *handler;
2738                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2739
2740                 /* We need a null-terminated version of the media string */
2741                 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
2742
2743                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2744                 if (!handler_list) {
2745                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
2746                         continue;
2747                 }
2748                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2749                         if (handler->change_outgoing_sdp_stream_media_address) {
2750                                 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
2751                         }
2752                 }
2753         }
2754
2755         /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
2756         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
2757 }
2758
2759 static int load_module(void)
2760 {
2761         pjsip_endpoint *endpt;
2762
2763         CHECK_PJSIP_MODULE_LOADED();
2764
2765         if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
2766                 return AST_MODULE_LOAD_DECLINE;
2767         }
2768         if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
2769                 return AST_MODULE_LOAD_DECLINE;
2770         }
2771         nat_hook->outgoing_external_message = session_outgoing_nat_hook;
2772         ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
2773         sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
2774                         sdp_handler_list_hash, sdp_handler_list_cmp);
2775         if (!sdp_handlers) {
2776                 return AST_MODULE_LOAD_DECLINE;
2777         }
2778         endpt = ast_sip_get_pjsip_endpoint();
2779         pjsip_inv_usage_init(endpt, &inv_callback);
2780         pjsip_100rel_init_module(endpt);
2781         pjsip_timer_init_module(endpt);
2782         if (ast_sip_register_service(&session_module)) {
2783                 return AST_MODULE_LOAD_DECLINE;
2784         }
2785         ast_sip_register_service(&session_reinvite_module);
2786         ast_sip_register_service(&outbound_invite_auth_module);
2787
2788         ast_module_shutdown_ref(ast_module_info->self);
2789
2790         return AST_MODULE_LOAD_SUCCESS;
2791 }
2792
2793 static int unload_module(void)
2794 {
2795         ast_sip_unregister_service(&outbound_invite_auth_module);
2796         ast_sip_unregister_service(&session_reinvite_module);
2797         ast_sip_unregister_service(&session_module);
2798         ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
2799         ao2_cleanup(nat_hook);
2800         ao2_cleanup(sdp_handlers);
2801         return 0;
2802 }
2803
2804 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
2805         .support_level = AST_MODULE_SUPPORT_CORE,
2806         .load = load_module,
2807         .unload = unload_module,
2808         .load_pri = AST_MODPRI_APP_DEPEND,
2809 );