res_pjsip_session.c: Fix crashes seen when call cancelled.
[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         if (session->channel) {
1043                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1044                         session->deferred_reinvite, NULL, NULL);
1045         }
1046         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1047         session->deferred_reinvite = NULL;
1048 }
1049
1050 static pjsip_module session_reinvite_module = {
1051         .name = { "Session Re-Invite Module", 24 },
1052         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1053         .on_rx_request = session_reinvite_on_rx_request,
1054 };
1055
1056 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1057                 ast_sip_session_response_cb on_response)
1058 {
1059         pjsip_inv_session *inv_session = session->inv_session;
1060
1061         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1062                 /* Don't try to do anything with a hung-up call */
1063                 return;
1064         }
1065
1066         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
1067                              MOD_DATA_ON_RESPONSE, on_response);
1068
1069         if (!ast_strlen_zero(session->endpoint->fromuser) ||
1070                 !ast_strlen_zero(session->endpoint->fromdomain)) {
1071                 pjsip_fromto_hdr *from = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_FROM, tdata->msg->hdr.next);
1072                 pjsip_sip_uri *uri = pjsip_uri_get_uri(from->uri);
1073
1074                 if (!ast_strlen_zero(session->endpoint->fromuser)) {
1075                         pj_strdup2(tdata->pool, &uri->user, session->endpoint->fromuser);
1076                 }
1077                 if (!ast_strlen_zero(session->endpoint->fromdomain)) {
1078                         pj_strdup2(tdata->pool, &uri->host, session->endpoint->fromdomain);
1079                 }
1080         }
1081
1082         handle_outgoing_request(session, tdata);
1083         pjsip_inv_send_msg(session->inv_session, tdata);
1084         return;
1085 }
1086
1087 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1088 {
1089         ast_sip_session_send_request_with_cb(session, tdata, NULL);
1090 }
1091
1092 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
1093 {
1094         pjmedia_sdp_session *offer;
1095
1096         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1097                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1098                 return -1;
1099         }
1100
1101         pjsip_inv_set_local_sdp(session->inv_session, offer);
1102         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
1103 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1104         pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
1105 #endif
1106         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
1107                 return -1;
1108         }
1109         return 0;
1110 }
1111
1112 static int datastore_hash(const void *obj, int flags)
1113 {
1114         const struct ast_datastore *datastore = obj;
1115         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1116
1117         ast_assert(uid != NULL);
1118
1119         return ast_str_hash(uid);
1120 }
1121
1122 static int datastore_cmp(void *obj, void *arg, int flags)
1123 {
1124         const struct ast_datastore *datastore1 = obj;
1125         const struct ast_datastore *datastore2 = arg;
1126         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1127
1128         ast_assert(datastore1->uid != NULL);
1129         ast_assert(uid2 != NULL);
1130
1131         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1132 }
1133
1134 static void session_media_dtor(void *obj)
1135 {
1136         struct ast_sip_session_media *session_media = obj;
1137         struct sdp_handler_list *handler_list;
1138         /* It is possible for SDP handlers to allocate memory on a session_media but
1139          * not end up getting set as the handler for this session_media. This traversal
1140          * ensures that all memory allocated by SDP handlers on the session_media is
1141          * cleared (as well as file descriptors, etc.).
1142          */
1143         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
1144         if (handler_list) {
1145                 struct ast_sip_session_sdp_handler *handler;
1146
1147                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1148                         handler->stream_destroy(session_media);
1149                 }
1150         }
1151         ao2_cleanup(handler_list);
1152         if (session_media->srtp) {
1153                 ast_sdp_srtp_destroy(session_media->srtp);
1154         }
1155 }
1156
1157 static void session_destructor(void *obj)
1158 {
1159         struct ast_sip_session *session = obj;
1160         struct ast_sip_session_supplement *supplement;
1161         struct ast_sip_session_delayed_request *delay;
1162
1163         ast_debug(3, "Destroying SIP session with endpoint %s\n",
1164                 session->endpoint ? ast_sorcery_object_get_id(session->endpoint) : "<none>");
1165
1166         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
1167                 if (supplement->session_destroy) {
1168                         supplement->session_destroy(session);
1169                 }
1170                 ast_free(supplement);
1171         }
1172
1173         ast_taskprocessor_unreference(session->serializer);
1174         ao2_cleanup(session->datastores);
1175         ao2_cleanup(session->media);
1176
1177         AST_LIST_HEAD_DESTROY(&session->supplements);
1178         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1179                 ast_free(delay);
1180         }
1181         ast_party_id_free(&session->id);
1182         ao2_cleanup(session->endpoint);
1183         ao2_cleanup(session->aor);
1184         ao2_cleanup(session->contact);
1185         ao2_cleanup(session->req_caps);
1186         ao2_cleanup(session->direct_media_cap);
1187
1188         if (session->dsp) {
1189                 ast_dsp_free(session->dsp);
1190         }
1191
1192         if (session->inv_session) {
1193                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1194         }
1195 }
1196
1197 static int add_supplements(struct ast_sip_session *session)
1198 {
1199         struct ast_sip_session_supplement *iter;
1200         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1201
1202         AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1203                 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1204                 if (!copy) {
1205                         return -1;
1206                 }
1207                 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1208         }
1209         return 0;
1210 }
1211
1212 static int add_session_media(void *obj, void *arg, int flags)
1213 {
1214         struct sdp_handler_list *handler_list = obj;
1215         struct ast_sip_session *session = arg;
1216         RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1217
1218         session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
1219         if (!session_media) {
1220                 return CMP_STOP;
1221         }
1222         session_media->encryption = session->endpoint->media.rtp.encryption;
1223         session_media->keepalive_sched_id = -1;
1224         session_media->timeout_sched_id = -1;
1225         /* Safe use of strcpy */
1226         strcpy(session_media->stream_type, handler_list->stream_type);
1227         ao2_link(session->media, session_media);
1228         return 0;
1229 }
1230
1231 /*! \brief Destructor for SIP channel */
1232 static void sip_channel_destroy(void *obj)
1233 {
1234         struct ast_sip_channel_pvt *channel = obj;
1235
1236         ao2_cleanup(channel->pvt);
1237         ao2_cleanup(channel->session);
1238 }
1239
1240 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1241 {
1242         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1243
1244         if (!channel) {
1245                 return NULL;
1246         }
1247
1248         ao2_ref(pvt, +1);
1249         channel->pvt = pvt;
1250         ao2_ref(session, +1);
1251         channel->session = session;
1252
1253         return channel;
1254 }
1255
1256 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
1257         struct ast_sip_contact *contact, pjsip_inv_session *inv_session)
1258 {
1259         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1260         struct ast_sip_session_supplement *iter;
1261         int dsp_features = 0;
1262
1263         session = ao2_alloc(sizeof(*session), session_destructor);
1264         if (!session) {
1265                 return NULL;
1266         }
1267         AST_LIST_HEAD_INIT(&session->supplements);
1268         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1269         if (!session->datastores) {
1270                 return NULL;
1271         }
1272
1273         session->endpoint = ao2_bump(endpoint);
1274
1275         session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
1276         if (!session->media) {
1277                 return NULL;
1278         }
1279         /* fill session->media with available types */
1280         ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
1281
1282         session->serializer = ast_sip_create_serializer();
1283         if (!session->serializer) {
1284                 return NULL;
1285         }
1286         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
1287         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
1288         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
1289         inv_session->mod_data[session_module.id] = ao2_bump(session);
1290         session->contact = ao2_bump(contact);
1291         session->inv_session = inv_session;
1292         session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1293
1294         if ((endpoint->dtmf == AST_SIP_DTMF_INBAND) || (endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
1295                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
1296         }
1297
1298         if (endpoint->faxdetect) {
1299                 dsp_features |= DSP_FEATURE_FAX_DETECT;
1300         }
1301
1302         if (dsp_features) {
1303                 if (!(session->dsp = ast_dsp_new())) {
1304                         /* Release the ref held by session->inv_session */
1305                         ao2_ref(session, -1);
1306                         return NULL;
1307                 }
1308
1309                 ast_dsp_set_features(session->dsp, dsp_features);
1310         }
1311
1312         if (add_supplements(session)) {
1313                 /* Release the ref held by session->inv_session */
1314                 ao2_ref(session, -1);
1315                 return NULL;
1316         }
1317         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1318                 if (iter->session_begin) {
1319                         iter->session_begin(session);
1320                 }
1321         }
1322         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1323         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
1324         ast_party_id_init(&session->id);
1325         ao2_ref(session, +1);
1326         return session;
1327 }
1328
1329 /*! \brief struct controlling the suspension of the session's serializer. */
1330 struct ast_sip_session_suspender {
1331         ast_cond_t cond_suspended;
1332         ast_cond_t cond_complete;
1333         int suspended;
1334         int complete;
1335 };
1336
1337 static void sip_session_suspender_dtor(void *vdoomed)
1338 {
1339         struct ast_sip_session_suspender *doomed = vdoomed;
1340
1341         ast_cond_destroy(&doomed->cond_suspended);
1342         ast_cond_destroy(&doomed->cond_complete);
1343 }
1344
1345 /*!
1346  * \internal
1347  * \brief Block the session serializer thread task.
1348  *
1349  * \param data Pushed serializer task data for suspension.
1350  *
1351  * \retval 0
1352  */
1353 static int sip_session_suspend_task(void *data)
1354 {
1355         struct ast_sip_session_suspender *suspender = data;
1356
1357         ao2_lock(suspender);
1358
1359         /* Signal that the serializer task is now suspended. */
1360         suspender->suspended = 1;
1361         ast_cond_signal(&suspender->cond_suspended);
1362
1363         /* Wait for the the serializer suspension to be completed. */
1364         while (!suspender->complete) {
1365                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
1366         }
1367
1368         ao2_unlock(suspender);
1369         ao2_ref(suspender, -1);
1370
1371         return 0;
1372 }
1373
1374 void ast_sip_session_suspend(struct ast_sip_session *session)
1375 {
1376         struct ast_sip_session_suspender *suspender;
1377         int res;
1378
1379         ast_assert(session->suspended == NULL);
1380
1381         if (ast_taskprocessor_is_task(session->serializer)) {
1382                 /* I am the session's serializer thread so I cannot suspend. */
1383                 return;
1384         }
1385
1386         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
1387         if (!suspender) {
1388                 /* We will just have to hope that the system does not deadlock */
1389                 return;
1390         }
1391         ast_cond_init(&suspender->cond_suspended, NULL);
1392         ast_cond_init(&suspender->cond_complete, NULL);
1393
1394         ao2_ref(suspender, +1);
1395         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
1396         if (res) {
1397                 /* We will just have to hope that the system does not deadlock */
1398                 ao2_ref(suspender, -2);
1399                 return;
1400         }
1401
1402         session->suspended = suspender;
1403
1404         /* Wait for the serializer to get suspended. */
1405         ao2_lock(suspender);
1406         while (!suspender->suspended) {
1407                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
1408         }
1409         ao2_unlock(suspender);
1410 }
1411
1412 void ast_sip_session_unsuspend(struct ast_sip_session *session)
1413 {
1414         struct ast_sip_session_suspender *suspender = session->suspended;
1415
1416         if (!suspender) {
1417                 /* Nothing to do */
1418                 return;
1419         }
1420         session->suspended = NULL;
1421
1422         /* Signal that the serializer task suspension is now complete. */
1423         ao2_lock(suspender);
1424         suspender->complete = 1;
1425         ast_cond_signal(&suspender->cond_complete);
1426         ao2_unlock(suspender);
1427
1428         ao2_ref(suspender, -1);
1429 }
1430
1431 /*!
1432  * \internal
1433  * \brief Handle initial INVITE challenge response message.
1434  * \since 13.5.0
1435  *
1436  * \param rdata PJSIP receive response message data.
1437  *
1438  * \retval PJ_FALSE Did not handle message.
1439  * \retval PJ_TRUE Handled message.
1440  */
1441 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
1442 {
1443         pjsip_transaction *tsx;
1444         pjsip_dialog *dlg;
1445         pjsip_inv_session *inv;
1446         pjsip_tx_data *tdata;
1447         struct ast_sip_session *session;
1448
1449         if (rdata->msg_info.msg->line.status.code != 401
1450                 && rdata->msg_info.msg->line.status.code != 407) {
1451                 /* Doesn't pertain to us. Move on */
1452                 return PJ_FALSE;
1453         }
1454
1455         tsx = pjsip_rdata_get_tsx(rdata);
1456         dlg = pjsip_rdata_get_dlg(rdata);
1457         if (!dlg || !tsx) {
1458                 return PJ_FALSE;
1459         }
1460
1461         if (tsx->method.id != PJSIP_INVITE_METHOD) {
1462                 /* Not an INVITE that needs authentication */
1463                 return PJ_FALSE;
1464         }
1465
1466         inv = pjsip_dlg_get_inv_session(dlg);
1467         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
1468                 /*
1469                  * We cannot handle reINVITE authentication at this
1470                  * time because the reINVITE transaction is still in
1471                  * progress.
1472                  */
1473                 ast_debug(1, "A reINVITE is being challenged.\n");
1474                 return PJ_FALSE;
1475         }
1476         ast_debug(1, "Initial INVITE is being challenged.\n");
1477
1478         session = inv->mod_data[session_module.id];
1479
1480         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
1481                 tsx->last_tx, &tdata)) {
1482                 return PJ_FALSE;
1483         }
1484
1485         /*
1486          * Restart the outgoing initial INVITE transaction to deal
1487          * with authentication.
1488          */
1489         pjsip_inv_uac_restart(inv, PJ_FALSE);
1490
1491         ast_sip_session_send_request(session, tdata);
1492         return PJ_TRUE;
1493 }
1494
1495 static pjsip_module outbound_invite_auth_module = {
1496         .name = {"Outbound INVITE Auth", 20},
1497         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
1498         .on_rx_response = outbound_invite_auth,
1499 };
1500
1501 /*!
1502  * \internal
1503  * \brief Setup outbound initial INVITE authentication.
1504  * \since 13.5.0
1505  *
1506  * \param dlg PJSIP dialog to attach outbound authentication.
1507  *
1508  * \retval 0 on success.
1509  * \retval -1 on error.
1510  */
1511 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
1512 {
1513         pj_status_t status;
1514
1515         ++dlg->sess_count;
1516         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
1517         --dlg->sess_count;
1518
1519         return status != PJ_SUCCESS ? -1 : 0;
1520 }
1521
1522 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
1523         struct ast_sip_contact *contact, const char *location, const char *request_user,
1524         struct ast_format_cap *req_caps)
1525 {
1526         const char *uri = NULL;
1527         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
1528         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
1529         pjsip_timer_setting timer;
1530         pjsip_dialog *dlg;
1531         struct pjsip_inv_session *inv_session;
1532         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1533
1534         /* If no location has been provided use the AOR list from the endpoint itself */
1535         if (location || !contact) {
1536                 location = S_OR(location, endpoint->aors);
1537
1538                 ast_sip_location_retrieve_contact_and_aor_from_list(location, &found_aor, &found_contact);
1539                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
1540                         uri = location;
1541                 } else {
1542                         uri = found_contact->uri;
1543                 }
1544         } else {
1545                 uri = contact->uri;
1546         }
1547
1548         /* If we still have no URI to dial fail to create the session */
1549         if (ast_strlen_zero(uri)) {
1550                 return NULL;
1551         }
1552
1553         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
1554                 return NULL;
1555         }
1556
1557         if (setup_outbound_invite_auth(dlg)) {
1558                 pjsip_dlg_terminate(dlg);
1559                 return NULL;
1560         }
1561
1562         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1563                 pjsip_dlg_terminate(dlg);
1564                 return NULL;
1565         }
1566 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1567         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1568 #endif
1569
1570         pjsip_timer_setting_default(&timer);
1571         timer.min_se = endpoint->extensions.timer.min_se;
1572         timer.sess_expires = endpoint->extensions.timer.sess_expires;
1573         pjsip_timer_init_session(inv_session, &timer);
1574
1575         if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
1576                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1577                 return NULL;
1578         }
1579         session->aor = ao2_bump(found_aor);
1580         ast_party_id_copy(&session->id, &endpoint->id.self);
1581
1582         if (ast_format_cap_count(req_caps)) {
1583                 /* get joint caps between req_caps and endpoint caps */
1584                 struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1585                 ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
1586
1587                 /* if joint caps */
1588                 if (ast_format_cap_count(joint_caps)) {
1589                         /* copy endpoint caps into session->req_caps */
1590                         ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
1591                         /* replace instances of joint caps equivalents in session->req_caps */
1592                         ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
1593                 }
1594                 ao2_cleanup(joint_caps);
1595         }
1596
1597         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1598                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1599                 /* Since we are not notifying ourselves that the INVITE session is being terminated
1600                  * we need to manually drop its reference to session
1601                  */
1602                 ao2_ref(session, -1);
1603                 return NULL;
1604         }
1605
1606         ao2_ref(session, +1);
1607         return session;
1608 }
1609
1610 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
1611 {
1612         pj_status_t status;
1613         pjsip_tx_data *packet = NULL;
1614
1615         if (session->defer_terminate) {
1616                 session->terminate_while_deferred = 1;
1617                 return;
1618         }
1619
1620         if (!response) {
1621                 response = 603;
1622         }
1623
1624         if ((session->inv_session->state == PJSIP_INV_STATE_CONFIRMED) && session->inv_session->invite_tsx) {
1625                 ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
1626                                 ast_sorcery_object_get_id(session->endpoint));
1627                 /* If this is delayed the only thing that will happen is a BYE request so we don't
1628                  * actually need to store the response code for when it happens.
1629                  */
1630                 delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);
1631         } else if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
1632                 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
1633         } else if (((status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet)) == PJ_SUCCESS)
1634                 && packet) {
1635                 struct ast_sip_session_delayed_request *delay;
1636
1637                 /* Flush any delayed requests so they cannot overlap this transaction. */
1638                 while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1639                         ast_free(delay);
1640                 }
1641
1642                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1643                         ast_sip_session_send_response(session, packet);
1644                 } else {
1645                         ast_sip_session_send_request(session, packet);
1646                 }
1647         }
1648 }
1649
1650 static int session_termination_task(void *data)
1651 {
1652         struct ast_sip_session *session = data;
1653
1654         if (session->defer_terminate) {
1655                 session->defer_terminate = 0;
1656                 if (session->inv_session) {
1657                         ast_sip_session_terminate(session, 0);
1658                 }
1659         }
1660
1661         ao2_ref(session, -1);
1662         return 0;
1663 }
1664
1665 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1666 {
1667         struct ast_sip_session *session = entry->user_data;
1668
1669         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1670                 ao2_cleanup(session);
1671         }
1672 }
1673
1674 int ast_sip_session_defer_termination(struct ast_sip_session *session)
1675 {
1676         pj_time_val delay = { .sec = 60, };
1677         int res;
1678
1679         /* The session should not have an active deferred termination request. */
1680         ast_assert(!session->defer_terminate);
1681
1682         session->defer_terminate = 1;
1683
1684         session->scheduled_termination.id = 0;
1685         ao2_ref(session, +1);
1686         session->scheduled_termination.user_data = session;
1687         session->scheduled_termination.cb = session_termination_cb;
1688
1689         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
1690                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
1691         if (res) {
1692                 session->defer_terminate = 0;
1693                 ao2_ref(session, -1);
1694         }
1695         return res;
1696 }
1697
1698 /*!
1699  * \internal
1700  * \brief Stop the defer termination timer if it is still running.
1701  * \since 13.5.0
1702  *
1703  * \param session Which session to stop the timer.
1704  *
1705  * \return Nothing
1706  */
1707 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
1708 {
1709         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
1710                 &session->scheduled_termination)) {
1711                 ao2_ref(session, -1);
1712         }
1713 }
1714
1715 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
1716 {
1717         if (!session->defer_terminate) {
1718                 /* Already canceled or timer fired. */
1719                 return;
1720         }
1721         session->defer_terminate = 0;
1722
1723         if (session->terminate_while_deferred) {
1724                 /* Complete the termination started by the upper layer. */
1725                 ast_sip_session_terminate(session, 0);
1726         }
1727
1728         /* Stop the termination timer if it is still running. */
1729         sip_session_defer_termination_stop_timer(session);
1730 }
1731
1732 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1733 {
1734         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1735         struct ast_sip_session *session;
1736
1737         if (!inv_session ||
1738                 !(session = inv_session->mod_data[session_module.id])) {
1739                 return NULL;
1740         }
1741
1742         ao2_ref(session, +1);
1743
1744         return session;
1745 }
1746
1747 enum sip_get_destination_result {
1748         /*! The extension was successfully found */
1749         SIP_GET_DEST_EXTEN_FOUND,
1750         /*! The extension specified in the RURI was not found */
1751         SIP_GET_DEST_EXTEN_NOT_FOUND,
1752         /*! The extension specified in the RURI was a partial match */
1753         SIP_GET_DEST_EXTEN_PARTIAL,
1754         /*! The RURI is of an unsupported scheme */
1755         SIP_GET_DEST_UNSUPPORTED_URI,
1756 };
1757
1758 /*!
1759  * \brief Determine where in the dialplan a call should go
1760  *
1761  * This uses the username in the request URI to try to match
1762  * an extension in the endpoint's configured context in order
1763  * to route the call.
1764  *
1765  * \param session The inbound SIP session
1766  * \param rdata The SIP INVITE
1767  */
1768 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1769 {
1770         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1771         pjsip_sip_uri *sip_ruri;
1772         struct ast_features_pickup_config *pickup_cfg;
1773         const char *pickupexten;
1774
1775         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1776                 return SIP_GET_DEST_UNSUPPORTED_URI;
1777         }
1778
1779         sip_ruri = pjsip_uri_get_uri(ruri);
1780         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1781
1782         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
1783         if (!pickup_cfg) {
1784                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
1785                 pickupexten = "";
1786         } else {
1787                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
1788                 ao2_ref(pickup_cfg, -1);
1789         }
1790
1791         if (!strcmp(session->exten, pickupexten) ||
1792                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1793                 return SIP_GET_DEST_EXTEN_FOUND;
1794         }
1795         /* XXX In reality, we'll likely have further options so that partial matches
1796          * can be indicated here, but for getting something up and running, we're going
1797          * to return a "not exists" error here.
1798          */
1799         return SIP_GET_DEST_EXTEN_NOT_FOUND;
1800 }
1801
1802 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1803 {
1804         pjsip_tx_data *tdata;
1805         pjsip_dialog *dlg;
1806         pjsip_inv_session *inv_session;
1807         unsigned int options = endpoint->extensions.flags;
1808         pj_status_t dlg_status;
1809
1810         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
1811                 if (tdata) {
1812                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1813                 } else {
1814                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1815                 }
1816                 return NULL;
1817         }
1818         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
1819         if (!dlg) {
1820                 if (dlg_status != PJ_EEXISTS) {
1821                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1822                 }
1823                 return NULL;
1824         }
1825         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
1826                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
1827                 pjsip_dlg_terminate(dlg);
1828                 return NULL;
1829         }
1830
1831 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1832         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1833 #endif
1834         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1835                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
1836                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1837                 }
1838                 pjsip_inv_send_msg(inv_session, tdata);
1839                 return NULL;
1840         }
1841         return inv_session;
1842 }
1843
1844 struct new_invite {
1845         /*! \brief Session created for the new INVITE */
1846         struct ast_sip_session *session;
1847
1848         /*! \brief INVITE request itself */
1849         pjsip_rx_data *rdata;
1850 };
1851
1852 static void new_invite_destroy(void *obj)
1853 {
1854         struct new_invite *invite = obj;
1855
1856         ao2_cleanup(invite->session);
1857
1858         if (invite->rdata) {
1859                 pjsip_rx_data_free_cloned(invite->rdata);
1860         }
1861 }
1862
1863 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
1864 {
1865         struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
1866
1867         if (!invite) {
1868                 return NULL;
1869         }
1870
1871         ao2_ref(session, +1);
1872         invite->session = session;
1873
1874         if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
1875                 ao2_ref(invite, -1);
1876                 return NULL;
1877         }
1878
1879         return invite;
1880 }
1881
1882 static int new_invite(void *data)
1883 {
1884         RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
1885         pjsip_tx_data *tdata = NULL;
1886         pjsip_timer_setting timer;
1887         pjsip_rdata_sdp_info *sdp_info;
1888         pjmedia_sdp_session *local = NULL;
1889
1890         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
1891          * so that we will be notified so we can destroy the session properly
1892          */
1893
1894         switch (get_destination(invite->session, invite->rdata)) {
1895         case SIP_GET_DEST_EXTEN_FOUND:
1896                 /* Things worked. Keep going */
1897                 break;
1898         case SIP_GET_DEST_UNSUPPORTED_URI:
1899                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
1900                         ast_sip_session_send_response(invite->session, tdata);
1901                 } else  {
1902                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
1903                 }
1904                 return 0;
1905         case SIP_GET_DEST_EXTEN_NOT_FOUND:
1906         case SIP_GET_DEST_EXTEN_PARTIAL:
1907         default:
1908                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
1909                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
1910                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
1911
1912                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
1913                         ast_sip_session_send_response(invite->session, tdata);
1914                 } else  {
1915                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
1916                 }
1917                 return 0;
1918         };
1919
1920         if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
1921                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
1922                         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
1923                                 ast_sip_session_send_response(invite->session, tdata);
1924                         } else  {
1925                                 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
1926                         }
1927                         return 0;
1928                 }
1929                 /* We are creating a local SDP which is an answer to their offer */
1930                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
1931         } else {
1932                 /* We are creating a local SDP which is an offer */
1933                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
1934         }
1935
1936         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
1937         if (!local) {
1938                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1939                         ast_sip_session_send_response(invite->session, tdata);
1940                 } else  {
1941                         pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1942                 }
1943                 return 0;
1944         } else {
1945                 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
1946                 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
1947 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1948                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
1949 #endif
1950         }
1951
1952         pjsip_timer_setting_default(&timer);
1953         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
1954         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
1955         pjsip_timer_init_session(invite->session->inv_session, &timer);
1956
1957         /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
1958         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
1959                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
1960                 return 0;
1961         }
1962         ast_sip_session_send_response(invite->session, tdata);
1963
1964         handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
1965
1966         return 0;
1967 }
1968
1969 static void handle_new_invite_request(pjsip_rx_data *rdata)
1970 {
1971         RAII_VAR(struct ast_sip_endpoint *, endpoint,
1972                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
1973         pjsip_tx_data *tdata = NULL;
1974         pjsip_inv_session *inv_session = NULL;
1975         struct ast_sip_session *session;
1976         struct new_invite *invite;
1977
1978         ast_assert(endpoint != NULL);
1979
1980         inv_session = pre_session_setup(rdata, endpoint);
1981         if (!inv_session) {
1982                 /* pre_session_setup() returns a response on failure */
1983                 return;
1984         }
1985
1986         session = ast_sip_session_alloc(endpoint, NULL, inv_session);
1987         if (!session) {
1988                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1989                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1990                 } else {
1991                         pjsip_inv_send_msg(inv_session, tdata);
1992                 }
1993                 return;
1994         }
1995
1996         invite = new_invite_alloc(session, rdata);
1997         if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
1998                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
1999                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2000                 } else {
2001                         pjsip_inv_send_msg(inv_session, tdata);
2002                 }
2003                 ao2_cleanup(invite);
2004         }
2005         ao2_ref(session, -1);
2006 }
2007
2008 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
2009 {
2010         pj_str_t method;
2011
2012         if (ast_strlen_zero(supplement_method)) {
2013                 return PJ_TRUE;
2014         }
2015
2016         pj_cstr(&method, supplement_method);
2017
2018         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
2019 }
2020
2021 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
2022 {
2023         struct ast_sip_session_supplement *supplement;
2024         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
2025
2026         if (!session) {
2027                 return PJ_FALSE;
2028         }
2029
2030         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2031                 if (does_method_match(&method->name, supplement->method)) {
2032                         return PJ_TRUE;
2033                 }
2034         }
2035         return PJ_FALSE;
2036 }
2037 /*!
2038  * \brief Called when a new SIP request comes into PJSIP
2039  *
2040  * This function is called under two circumstances
2041  * 1) An out-of-dialog request is received by PJSIP
2042  * 2) An in-dialog request that the inv_session layer does not
2043  *    handle is received (such as an in-dialog INFO)
2044  *
2045  * In all cases, there is very little we actually do in this function
2046  * 1) For requests we don't handle, we return PJ_FALSE
2047  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
2048  *    there to free up the thread(s) handling incoming requests
2049  * 3) For in-dialog requests we handle, we defer handling them until the
2050  *    on_inv_state_change() callback instead (where we will end up putting
2051  *    them into the threadpool).
2052  */
2053 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
2054 {
2055         pj_status_t handled = PJ_FALSE;
2056         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
2057         pjsip_inv_session *inv_session;
2058
2059         switch (rdata->msg_info.msg->line.req.method.id) {
2060         case PJSIP_INVITE_METHOD:
2061                 if (dlg) {
2062                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
2063                         break;
2064                 }
2065                 handled = PJ_TRUE;
2066                 handle_new_invite_request(rdata);
2067                 break;
2068         default:
2069                 /* Handle other in-dialog methods if their supplements have been registered */
2070                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
2071                         has_supplement(inv_session->mod_data[session_module.id], rdata);
2072                 break;
2073         }
2074
2075         return handled;
2076 }
2077
2078 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
2079 {
2080         struct ast_sip_session *session = entry->user_data;
2081
2082         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
2083                 ast_sorcery_object_get_id(session->endpoint),
2084                 session->channel ? ast_channel_name(session->channel) : "");
2085
2086         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2087                 /* No delayed request pending, so just return */
2088                 ao2_ref(session, -1);
2089                 return;
2090         }
2091         if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
2092                 /*
2093                  * Uh oh.  We now have nothing in the foreseeable future
2094                  * to trigger sending the delayed requests.
2095                  */
2096                 ao2_ref(session, -1);
2097         }
2098 }
2099
2100 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
2101 {
2102         pjsip_inv_session *inv = session->inv_session;
2103         pj_time_val tv;
2104
2105         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
2106                 ast_sorcery_object_get_id(session->endpoint),
2107                 session->channel ? ast_channel_name(session->channel) : "");
2108         if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {
2109                 return;
2110         }
2111         if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
2112                 /* Timer already running.  Something weird is going on. */
2113                 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
2114                         ast_sorcery_object_get_id(session->endpoint),
2115                         session->channel ? ast_channel_name(session->channel) : "");
2116                 return;
2117         }
2118
2119         tv.sec = 0;
2120         if (inv->role == PJSIP_ROLE_UAC) {
2121                 tv.msec = 2100 + ast_random() % 2000;
2122         } else {
2123                 tv.msec = ast_random() % 2000;
2124         }
2125         pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
2126
2127         ao2_ref(session, +1);
2128         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2129                 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
2130                 ao2_ref(session, -1);
2131         }
2132 }
2133
2134 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2135 {
2136         struct ast_sip_session *session;
2137
2138         if (!DEBUG_ATLEAST(5)) {
2139                 /* Debug not spamy enough */
2140                 return;
2141         }
2142
2143         ast_log(LOG_DEBUG, "Function %s called on event %s\n",
2144                 function, pjsip_event_str(e->type));
2145         if (!inv) {
2146                 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
2147                 ast_log(LOG_DEBUG, "The transaction state is %s\n",
2148                         pjsip_tsx_state_str(tsx->state));
2149                 return;
2150         }
2151         session = inv->mod_data[session_module.id];
2152         if (!session) {
2153                 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
2154         } else {
2155                 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
2156                         ast_sorcery_object_get_id(session->endpoint),
2157                         session->channel ? ast_channel_name(session->channel) : "");
2158         }
2159         if (inv->invite_tsx) {
2160                 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
2161                         inv->invite_tsx);
2162         } else {
2163                 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
2164         }
2165         if (tsx) {
2166                 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
2167                         pjsip_role_name(tsx->role),
2168                         (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2169                         tsx);
2170                 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
2171                         pjsip_tsx_state_str(tsx->state));
2172                 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
2173                         pjsip_event_str(e->body.tsx_state.type));
2174         } else {
2175                 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
2176         }
2177         ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
2178 }
2179
2180 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
2181
2182 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
2183 {
2184         struct ast_sip_session_supplement *supplement;
2185         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
2186
2187         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2188         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2189                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
2190                         if (supplement->incoming_request(session, rdata)) {
2191                                 break;
2192                         }
2193                 }
2194         }
2195 }
2196
2197 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2198                 enum ast_sip_session_response_priority response_priority)
2199 {
2200         struct ast_sip_session_supplement *supplement;
2201         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2202
2203         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
2204                         pj_strbuf(&status.reason));
2205
2206         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2207                 if (!(supplement->response_priority & response_priority)) {
2208                         continue;
2209                 }
2210                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
2211                         supplement->incoming_response(session, rdata);
2212                 }
2213         }
2214 }
2215
2216 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
2217                 enum ast_sip_session_response_priority response_priority)
2218 {
2219         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
2220                         "request" : "response");
2221
2222         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
2223                 handle_incoming_request(session, rdata, type);
2224         } else {
2225                 handle_incoming_response(session, rdata, type, response_priority);
2226         }
2227
2228         return 0;
2229 }
2230
2231 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2232 {
2233         struct ast_sip_session_supplement *supplement;
2234         struct pjsip_request_line req = tdata->msg->line.req;
2235
2236         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2237         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2238                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
2239                         supplement->outgoing_request(session, tdata);
2240                 }
2241         }
2242 }
2243
2244 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
2245 {
2246         struct ast_sip_session_supplement *supplement;
2247         struct pjsip_status_line status = tdata->msg->line.status;
2248         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
2249         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
2250                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
2251                 pj_strbuf(&status.reason));
2252
2253         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2254                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
2255                         supplement->outgoing_response(session, tdata);
2256                 }
2257         }
2258 }
2259
2260 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
2261 {
2262         ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
2263                         "request" : "response");
2264         if (tdata->msg->type == PJSIP_REQUEST_MSG) {
2265                 handle_outgoing_request(session, tdata);
2266         } else {
2267                 handle_outgoing_response(session, tdata);
2268         }
2269 }
2270
2271 static void session_end(struct ast_sip_session *session)
2272 {
2273         struct ast_sip_session_supplement *iter;
2274
2275         /* Stop the scheduled termination */
2276         sip_session_defer_termination_stop_timer(session);
2277
2278         /* Session is dead.  Notify the supplements. */
2279         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2280                 if (iter->session_end) {
2281                         iter->session_end(session);
2282                 }
2283         }
2284 }
2285
2286 /*!
2287  * \internal
2288  * \brief Complete ending session activities.
2289  * \since 13.5.0
2290  *
2291  * \param vsession Which session to complete stopping.
2292  *
2293  * \retval 0 on success.
2294  * \retval -1 on error.
2295  */
2296 static int session_end_completion(void *vsession)
2297 {
2298         struct ast_sip_session *session = vsession;
2299
2300         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
2301         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
2302
2303         /* Now we can release the ref that was held by session->inv_session */
2304         ao2_cleanup(session);
2305         return 0;
2306 }
2307
2308 static int check_request_status(pjsip_inv_session *inv, pjsip_event *e)
2309 {
2310         struct ast_sip_session *session = inv->mod_data[session_module.id];
2311         pjsip_transaction *tsx = e->body.tsx_state.tsx;
2312
2313         if (tsx->status_code != 503 && tsx->status_code != 408) {
2314                 return 0;
2315         }
2316
2317         if (!ast_sip_failover_request(tsx->last_tx)) {
2318                 return 0;
2319         }
2320
2321         pjsip_inv_uac_restart(inv, PJ_FALSE);
2322         /*
2323          * Bump the ref since it will be on a new transaction and
2324          * we don't want it to go away along with the old transaction.
2325          */
2326         pjsip_tx_data_add_ref(tsx->last_tx);
2327         ast_sip_session_send_request(session, tsx->last_tx);
2328         return 1;
2329 }
2330
2331 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
2332 {
2333         struct ast_sip_session *session = inv->mod_data[session_module.id];
2334         pjsip_event_id_e type;
2335
2336         if (e) {
2337                 print_debug_details(inv, NULL, e);
2338                 type = e->type;
2339         } else {
2340                 type = PJSIP_EVENT_UNKNOWN;
2341         }
2342
2343         if (!session) {
2344                 return;
2345         }
2346
2347         switch(type) {
2348         case PJSIP_EVENT_TX_MSG:
2349                 handle_outgoing(session, e->body.tx_msg.tdata);
2350                 break;
2351         case PJSIP_EVENT_RX_MSG:
2352                 handle_incoming(session, e->body.rx_msg.rdata, type,
2353                                 AST_SIP_SESSION_BEFORE_MEDIA);
2354                 break;
2355         case PJSIP_EVENT_TSX_STATE:
2356                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
2357                 /* Transaction state changes are prompted by some other underlying event. */
2358                 switch(e->body.tsx_state.type) {
2359                 case PJSIP_EVENT_TX_MSG:
2360                         handle_outgoing(session, e->body.tsx_state.src.tdata);
2361                         break;
2362                 case PJSIP_EVENT_RX_MSG:
2363                         if (!check_request_status(inv, e)) {
2364                                 handle_incoming(session, e->body.tsx_state.src.rdata, type,
2365                                                 AST_SIP_SESSION_BEFORE_MEDIA);
2366                         }
2367                         break;
2368                 case PJSIP_EVENT_TRANSPORT_ERROR:
2369                 case PJSIP_EVENT_TIMER:
2370                         /*
2371                          * Check the request status on transport error or timeout. A transport
2372                          * error can occur when a TCP socket closes and that can be the result
2373                          * of a 503. Also we may need to failover on a timeout (408).
2374                          */
2375                         check_request_status(inv, e);
2376                         break;
2377                 case PJSIP_EVENT_USER:
2378                 case PJSIP_EVENT_UNKNOWN:
2379                 case PJSIP_EVENT_TSX_STATE:
2380                         /* Inception? */
2381                         break;
2382                 }
2383                 break;
2384         case PJSIP_EVENT_TRANSPORT_ERROR:
2385         case PJSIP_EVENT_TIMER:
2386         case PJSIP_EVENT_UNKNOWN:
2387         case PJSIP_EVENT_USER:
2388         default:
2389                 break;
2390         }
2391
2392         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2393                 session_end(session);
2394         }
2395 }
2396
2397 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
2398 {
2399         /* XXX STUB */
2400 }
2401
2402 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2403 {
2404         ast_sip_session_response_cb cb;
2405         struct ast_sip_session *session = inv->mod_data[session_module.id];
2406         pjsip_tx_data *tdata;
2407
2408         print_debug_details(inv, tsx, e);
2409         if (!session) {
2410                 /* The session has ended.  Ignore the transaction change. */
2411                 return;
2412         }
2413         switch (e->body.tsx_state.type) {
2414         case PJSIP_EVENT_TX_MSG:
2415                 handle_outgoing(session, e->body.tsx_state.src.tdata);
2416                 /* When we create an outgoing request, we do not have access to the transaction that
2417                  * is created. Instead, We have to place transaction-specific data in the tdata. Here,
2418                  * we transfer the data into the transaction. This way, when we receive a response, we
2419                  * can dig this data out again
2420                  */
2421                 tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
2422                 break;
2423         case PJSIP_EVENT_RX_MSG:
2424                 cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id, MOD_DATA_ON_RESPONSE);
2425                 handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
2426                                 AST_SIP_SESSION_AFTER_MEDIA);
2427                 if (tsx->method.id == PJSIP_INVITE_METHOD) {
2428                         if (tsx->role == PJSIP_ROLE_UAC) {
2429                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2430                                         /* This means we got a non 2XX final response to our outgoing INVITE */
2431                                         if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
2432                                                 reschedule_reinvite(session, cb);
2433                                                 return;
2434                                         }
2435                                         if (inv->state == PJSIP_INV_STATE_CONFIRMED) {
2436                                                 ast_debug(1, "reINVITE received final response code %d\n",
2437                                                         tsx->status_code);
2438                                                 if ((tsx->status_code == 401 || tsx->status_code == 407)
2439                                                         && !ast_sip_create_request_with_auth(
2440                                                                 &session->endpoint->outbound_auths,
2441                                                                 e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2442                                                         /* Send authed reINVITE */
2443                                                         ast_sip_session_send_request_with_cb(session, tdata, cb);
2444                                                         return;
2445                                                 }
2446                                                 if (tsx->status_code != 488) {
2447                                                         /* Other reinvite failures (except 488) result in destroying the session. */
2448                                                         if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2449                                                                 ast_sip_session_send_request(session, tdata);
2450                                                         }
2451                                                 }
2452                                         }
2453                                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2454                                         if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
2455                                                 /* This is a race condition detailed in RFC 5407 section 3.1.2.
2456                                                  * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
2457                                                  * the original INVITE. As a result, we have now received a 200 OK for
2458                                                  * a cancelled call. Our role is to immediately send a BYE to end the
2459                                                  * dialog.
2460                                                  */
2461                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
2462                                                         ast_sip_session_send_request(session, tdata);
2463                                                 }
2464                                         }
2465                                 }
2466                         }
2467                 } else {
2468                         /* All other methods */
2469                         if (tsx->role == PJSIP_ROLE_UAC) {
2470                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2471                                         /* This means we got a final response to our outgoing method */
2472                                         ast_debug(1, "%.*s received final response code %d\n",
2473                                                 (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2474                                                 tsx->status_code);
2475                                         if ((tsx->status_code == 401 || tsx->status_code == 407)
2476                                                 && !ast_sip_create_request_with_auth(
2477                                                         &session->endpoint->outbound_auths,
2478                                                         e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2479                                                 /* Send authed version of the method */
2480                                                 ast_sip_session_send_request_with_cb(session, tdata, cb);
2481                                                 return;
2482                                         }
2483                                 }
2484                         }
2485                 }
2486                 if (cb) {
2487                         cb(session, e->body.tsx_state.src.rdata);
2488                 }
2489                 break;
2490         case PJSIP_EVENT_TRANSPORT_ERROR:
2491                 /*
2492                  * Clear the module data now to block session_inv_on_state_changed()
2493                  * from calling session_end() if it hasn't already done so.
2494                  */
2495                 inv->mod_data[session_module.id] = NULL;
2496
2497                 if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
2498                         session_end(session);
2499                 }
2500
2501                 /*
2502                  * Pass the session ref held by session->inv_session to
2503                  * session_end_completion().
2504                  */
2505                 session_end_completion(session);
2506                 return;
2507         case PJSIP_EVENT_TIMER:
2508                 /*
2509                  * The timer event is run by the pjsip monitor thread and not
2510                  * by the session serializer.
2511                  */
2512                 if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2513                         /*
2514                          * We are locking because ast_sip_dialog_get_session() needs
2515                          * the dialog locked to get the session by other threads.
2516                          */
2517                         pjsip_dlg_inc_lock(inv->dlg);
2518                         session = inv->mod_data[session_module.id];
2519                         inv->mod_data[session_module.id] = NULL;
2520                         pjsip_dlg_dec_lock(inv->dlg);
2521
2522                         /*
2523                          * Pass the session ref held by session->inv_session to
2524                          * session_end_completion().
2525                          */
2526                         if (ast_sip_push_task(session->serializer, session_end_completion, session)) {
2527                                 /* Do it anyway even though this is not the right thread. */
2528                                 session_end_completion(session);
2529                         }
2530                         return;
2531                 }
2532                 break;
2533         case PJSIP_EVENT_USER:
2534         case PJSIP_EVENT_UNKNOWN:
2535         case PJSIP_EVENT_TSX_STATE:
2536                 /* Inception? */
2537                 break;
2538         }
2539
2540         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2541                 /* No delayed request pending, so just return */
2542                 return;
2543         }
2544
2545         if (tsx->method.id == PJSIP_INVITE_METHOD) {
2546                 if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
2547                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2548                                 ast_sorcery_object_get_id(session->endpoint),
2549                                 session->channel ? ast_channel_name(session->channel) : "",
2550                                 pjsip_tsx_state_str(tsx->state));
2551                         check_delayed_requests(session, invite_proceeding);
2552                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2553                         /*
2554                          * Terminated INVITE transactions always should result in
2555                          * queuing delayed requests, no matter what event caused
2556                          * the transaction to terminate.
2557                          */
2558                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2559                                 ast_sorcery_object_get_id(session->endpoint),
2560                                 session->channel ? ast_channel_name(session->channel) : "",
2561                                 pjsip_tsx_state_str(tsx->state));
2562                         check_delayed_requests(session, invite_terminated);
2563                 }
2564         } else if (tsx->role == PJSIP_ROLE_UAC
2565                 && tsx->state == PJSIP_TSX_STATE_COMPLETED
2566                 && !pj_strcmp2(&tsx->method.name, "UPDATE")) {
2567                 ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",
2568                         ast_sorcery_object_get_id(session->endpoint),
2569                         session->channel ? ast_channel_name(session->channel) : "",
2570                         pjsip_tsx_state_str(tsx->state));
2571                 check_delayed_requests(session, update_completed);
2572         }
2573 }
2574
2575 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
2576 {
2577         struct ast_sip_session_media *session_media = obj;
2578         pjmedia_sdp_session *answer = arg;
2579         struct ast_sip_session *session = data;
2580         struct ast_sip_session_sdp_handler *handler = session_media->handler;
2581         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2582         int res;
2583
2584         if (handler) {
2585                 /* if an already assigned handler reports a catastrophic error, fail */
2586                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2587                 if (res < 0) {
2588                         return 0;
2589                 }
2590                 return CMP_MATCH;
2591         }
2592
2593         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
2594         if (!handler_list) {
2595                 return CMP_MATCH;
2596         }
2597
2598         /* no handler for this stream type and we have a list to search */
2599         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2600                 if (handler == session_media->handler) {
2601                         continue;
2602                 }
2603                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2604                 if (res < 0) {
2605                         /* catastrophic error */
2606                         return 0;
2607                 }
2608                 if (res > 0) {
2609                         /* Handled by this handler. Move to the next stream */
2610                         session_media_set_handler(session_media, handler);
2611                         return CMP_MATCH;
2612                 }
2613         }
2614
2615         /* streams that weren't handled won't be included in generated outbound SDP */
2616         return CMP_MATCH;
2617 }
2618
2619 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
2620 {
2621         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
2622         static const pj_str_t STR_IN = { "IN", 2 };
2623         static const pj_str_t STR_IP4 = { "IP4", 3 };
2624         static const pj_str_t STR_IP6 = { "IP6", 3 };
2625         pjmedia_sdp_session *local;
2626
2627         if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
2628                 return NULL;
2629         }
2630
2631         if (!offer) {
2632                 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
2633         } else {
2634                 local->origin.version = offer->origin.version + 1;
2635                 local->origin.id = offer->origin.id;
2636         }
2637
2638         pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
2639         pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
2640
2641         /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
2642         successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
2643         if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
2644                 /* Something experienced a catastrophic failure */
2645                 return NULL;
2646         }
2647
2648         /* Use the connection details of the first media stream if possible for SDP level */
2649         if (local->media_count) {
2650                 int stream;
2651
2652                 /* Since we are using the first media stream as the SDP level we can get rid of it
2653                  * from the stream itself
2654                  */
2655                 local->conn = local->media[0]->conn;
2656                 local->media[0]->conn = NULL;
2657                 pj_strassign(&local->origin.net_type, &local->conn->net_type);
2658                 pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
2659                 pj_strassign(&local->origin.addr, &local->conn->addr);
2660
2661                 /* Go through each media stream seeing if the connection details actually differ,
2662                  * if not just use SDP level and reduce the SDP size
2663                  */
2664                 for (stream = 1; stream < local->media_count; stream++) {
2665                         if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
2666                                 !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
2667                                 !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
2668                                 local->media[stream]->conn = NULL;
2669                         }
2670                 }
2671         } else {
2672                 local->origin.net_type = STR_IN;
2673                 local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
2674
2675                 if (!ast_strlen_zero(session->endpoint->media.address)) {
2676                         pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
2677                 } else {
2678                         pj_sockaddr localaddr;
2679                         char our_ip[PJ_INET6_ADDRSTRLEN];
2680
2681                         pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
2682                         pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
2683                         pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
2684                 }
2685         }
2686
2687         return local;
2688 }
2689
2690 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
2691 {
2692         struct ast_sip_session *session = inv->mod_data[session_module.id];
2693         pjmedia_sdp_session *answer;
2694
2695         if (handle_incoming_sdp(session, offer)) {
2696                 return;
2697         }
2698
2699         if ((answer = create_local_sdp(inv, session, offer))) {
2700                 pjsip_inv_set_sdp_answer(inv, answer);
2701         }
2702 }
2703
2704 #if 0
2705 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
2706 {
2707         /* XXX STUB */
2708 }
2709 #endif
2710
2711 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2712 {
2713         struct ast_sip_session *session = inv->mod_data[session_module.id];
2714         const pjmedia_sdp_session *local, *remote;
2715
2716         if (!session || !session->channel) {
2717                 /*
2718                  * If we don't have a session or channel then we really
2719                  * don't care about media updates.
2720                  * Just ignore
2721                  */
2722                 return;
2723         }
2724
2725         if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
2726                 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
2727                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
2728                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
2729                 ast_queue_hangup(session->channel);
2730                 return;
2731         }
2732
2733         handle_negotiated_sdp(session, local, remote);
2734 }
2735
2736 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
2737 {
2738         struct ast_sip_session *session = inv->mod_data[session_module.id];
2739         const pjsip_sip_uri *uri;
2740
2741         if (!session->channel) {
2742                 return PJSIP_REDIRECT_STOP;
2743         }
2744
2745         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
2746                 return PJSIP_REDIRECT_ACCEPT;
2747         }
2748
2749         if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
2750                 return PJSIP_REDIRECT_STOP;
2751         }
2752
2753         handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
2754                         AST_SIP_SESSION_BEFORE_REDIRECTING);
2755
2756         uri = pjsip_uri_get_uri(target);
2757
2758         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
2759                 char exten[AST_MAX_EXTENSION];
2760
2761                 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
2762                 ast_channel_call_forward_set(session->channel, exten);
2763         } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
2764                 char target_uri[PJSIP_MAX_URL_SIZE];
2765                 /* PJSIP/ + endpoint length + / + max URL size */
2766                 char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
2767
2768                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
2769                 sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
2770                 ast_channel_call_forward_set(session->channel, forward);
2771         }
2772
2773         return PJSIP_REDIRECT_STOP;
2774 }
2775
2776 static pjsip_inv_callback inv_callback = {
2777         .on_state_changed = session_inv_on_state_changed,
2778         .on_new_session = session_inv_on_new_session,
2779         .on_tsx_state_changed = session_inv_on_tsx_state_changed,
2780         .on_rx_offer = session_inv_on_rx_offer,
2781         .on_media_update = session_inv_on_media_update,
2782         .on_redirected = session_inv_on_redirected,
2783 };
2784
2785 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
2786 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
2787 {
2788         struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
2789                 tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
2790         struct pjmedia_sdp_session *sdp;
2791         int stream;
2792
2793         /* SDP produced by us directly will never be multipart */
2794         if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
2795                 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
2796                 return;
2797         }
2798
2799         sdp = tdata->msg->body->data;
2800
2801         if (sdp->conn) {
2802                 char host[NI_MAXHOST];
2803                 struct ast_sockaddr addr = { { 0, } };
2804
2805                 ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
2806                 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
2807
2808                 if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
2809                         pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
2810                 }
2811         }
2812
2813         for (stream = 0; stream < sdp->media_count; ++stream) {
2814                 /* See if there are registered handlers for this media stream type */
2815                 char media[20];
2816                 struct ast_sip_session_sdp_handler *handler;
2817                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2818
2819                 /* We need a null-terminated version of the media string */
2820                 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
2821
2822                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
2823                 if (!handler_list) {
2824                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
2825                         continue;
2826                 }
2827                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2828                         if (handler->change_outgoing_sdp_stream_media_address) {
2829                                 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
2830                         }
2831                 }
2832         }
2833
2834         /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
2835         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
2836 }
2837
2838 static int load_module(void)
2839 {
2840         pjsip_endpoint *endpt;
2841
2842         CHECK_PJSIP_MODULE_LOADED();
2843
2844         if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
2845                 return AST_MODULE_LOAD_DECLINE;
2846         }
2847         if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
2848                 return AST_MODULE_LOAD_DECLINE;
2849         }
2850         nat_hook->outgoing_external_message = session_outgoing_nat_hook;
2851         ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
2852         sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
2853                         sdp_handler_list_hash, sdp_handler_list_cmp);
2854         if (!sdp_handlers) {
2855                 return AST_MODULE_LOAD_DECLINE;
2856         }
2857         endpt = ast_sip_get_pjsip_endpoint();
2858         pjsip_inv_usage_init(endpt, &inv_callback);
2859         pjsip_100rel_init_module(endpt);
2860         pjsip_timer_init_module(endpt);
2861         if (ast_sip_register_service(&session_module)) {
2862                 return AST_MODULE_LOAD_DECLINE;
2863         }
2864         ast_sip_register_service(&session_reinvite_module);
2865         ast_sip_register_service(&outbound_invite_auth_module);
2866
2867         ast_module_shutdown_ref(ast_module_info->self);
2868
2869         return AST_MODULE_LOAD_SUCCESS;
2870 }
2871
2872 static int unload_module(void)
2873 {
2874         ast_sip_unregister_service(&outbound_invite_auth_module);
2875         ast_sip_unregister_service(&session_reinvite_module);
2876         ast_sip_unregister_service(&session_module);
2877         ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
2878         ao2_cleanup(nat_hook);
2879         ao2_cleanup(sdp_handlers);
2880         return 0;
2881 }
2882
2883 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
2884         .support_level = AST_MODULE_SUPPORT_CORE,
2885         .load = load_module,
2886         .unload = unload_module,
2887         .load_pri = AST_MODPRI_APP_DEPEND,
2888 );