315393fdb895e6005eddedfd1c99cce72c2da0e2
[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/callerid.h"
34 #include "asterisk/datastore.h"
35 #include "asterisk/module.h"
36 #include "asterisk/logger.h"
37 #include "asterisk/res_pjsip.h"
38 #include "asterisk/astobj2.h"
39 #include "asterisk/lock.h"
40 #include "asterisk/uuid.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/taskprocessor.h"
43 #include "asterisk/causes.h"
44 #include "asterisk/sdp_srtp.h"
45 #include "asterisk/dsp.h"
46 #include "asterisk/acl.h"
47 #include "asterisk/features_config.h"
48 #include "asterisk/pickup.h"
49 #include "asterisk/test.h"
50
51 #define SDP_HANDLER_BUCKETS 11
52
53 #define MOD_DATA_ON_RESPONSE "on_response"
54 #define MOD_DATA_NAT_HOOK "nat_hook"
55
56 /* Some forward declarations */
57 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata);
58 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
59                 enum ast_sip_session_response_priority response_priority);
60 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,
61                 enum ast_sip_session_response_priority response_priority);
62 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);
63 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);
64 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata);
65
66 /*! \brief NAT hook for modifying outgoing messages with SDP */
67 static struct ast_sip_nat_hook *nat_hook;
68
69 /*!
70  * \brief Registered SDP stream handlers
71  *
72  * This container is keyed on stream types. Each
73  * object in the container is a linked list of
74  * handlers for the stream type.
75  */
76 static struct ao2_container *sdp_handlers;
77
78 /*!
79  * These are the objects in the sdp_handlers container
80  */
81 struct sdp_handler_list {
82         /* The list of handlers to visit */
83         AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;
84         /* The handlers in this list handle streams of this type */
85         char stream_type[1];
86 };
87
88 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);
89
90 static int sdp_handler_list_hash(const void *obj, int flags)
91 {
92         const struct sdp_handler_list *handler_list = obj;
93         const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
94
95         return ast_str_hash(stream_type);
96 }
97
98 static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
99 {
100         struct sdp_handler_list *handler_list1 = obj;
101         struct sdp_handler_list *handler_list2 = arg;
102         const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;
103
104         return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
105 }
106
107 static int session_media_hash(const void *obj, int flags)
108 {
109         const struct ast_sip_session_media *session_media = obj;
110         const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;
111
112         return ast_str_hash(stream_type);
113 }
114
115 static int session_media_cmp(void *obj, void *arg, int flags)
116 {
117         struct ast_sip_session_media *session_media1 = obj;
118         struct ast_sip_session_media *session_media2 = arg;
119         const char *stream_type2 = flags & OBJ_KEY ? arg : session_media2->stream_type;
120
121         return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
122 }
123
124 int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
125 {
126         RAII_VAR(struct sdp_handler_list *, handler_list,
127                         ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);
128         SCOPED_AO2LOCK(lock, sdp_handlers);
129
130         if (handler_list) {
131                 struct ast_sip_session_sdp_handler *iter;
132                 /* Check if this handler is already registered for this stream type */
133                 AST_LIST_TRAVERSE(&handler_list->list, iter, next) {
134                         if (!strcmp(iter->id, handler->id)) {
135                                 ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);
136                                 return -1;
137                         }
138                 }
139                 AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
140                 ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
141                 ast_module_ref(ast_module_info->self);
142                 return 0;
143         }
144
145         /* No stream of this type has been registered yet, so we need to create a new list */
146         handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);
147         if (!handler_list) {
148                 return -1;
149         }
150         /* Safe use of strcpy */
151         strcpy(handler_list->stream_type, stream_type);
152         AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);
153         AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
154         if (!ao2_link(sdp_handlers, handler_list)) {
155                 return -1;
156         }
157         ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
158         ast_module_ref(ast_module_info->self);
159         return 0;
160 }
161
162 static int remove_handler(void *obj, void *arg, void *data, int flags)
163 {
164         struct sdp_handler_list *handler_list = obj;
165         struct ast_sip_session_sdp_handler *handler = data;
166         struct ast_sip_session_sdp_handler *iter;
167         const char *stream_type = arg;
168
169         AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {
170                 if (!strcmp(iter->id, handler->id)) {
171                         AST_LIST_REMOVE_CURRENT(next);
172                         ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
173                         ast_module_unref(ast_module_info->self);
174                 }
175         }
176         AST_LIST_TRAVERSE_SAFE_END;
177
178         if (AST_LIST_EMPTY(&handler_list->list)) {
179                 ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
180                 return CMP_MATCH;
181         } else {
182                 return CMP_STOP;
183         }
184 }
185
186 void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
187 {
188         ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);
189 }
190
191 /*!
192  * \brief Set an SDP stream handler for a corresponding session media.
193  *
194  * \note Always use this function to set the SDP handler for a session media.
195  *
196  * This function will properly free resources on the SDP handler currently being
197  * used by the session media, then set the session media to use the new SDP
198  * handler.
199  */
200 static void session_media_set_handler(struct ast_sip_session_media *session_media,
201                 struct ast_sip_session_sdp_handler *handler)
202 {
203         ast_assert(session_media->handler != handler);
204
205         if (session_media->handler) {
206                 session_media->handler->stream_destroy(session_media);
207         }
208         session_media->handler = handler;
209 }
210
211 static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
212 {
213         int i;
214         int handled = 0;
215
216         for (i = 0; i < sdp->media_count; ++i) {
217                 /* See if there are registered handlers for this media stream type */
218                 char media[20];
219                 struct ast_sip_session_sdp_handler *handler;
220                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
221                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
222                 int res;
223
224                 /* We need a null-terminated version of the media string */
225                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
226
227                 session_media = ao2_find(session->media, media, OBJ_KEY);
228                 if (!session_media) {
229                         /* if the session_media doesn't exist, there weren't
230                          * any handlers at the time of its creation */
231                         continue;
232                 }
233
234                 if (session_media->handler) {
235                         handler = session_media->handler;
236                         ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
237                                 session_media->stream_type,
238                                 session_media->handler->id);
239                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
240                                 sdp->media[i]);
241                         if (res < 0) {
242                                 /* Catastrophic failure. Abort! */
243                                 return -1;
244                         } else if (res > 0) {
245                                 ast_debug(1, "Media stream '%s' handled by %s\n",
246                                         session_media->stream_type,
247                                         session_media->handler->id);
248                                 /* Handled by this handler. Move to the next stream */
249                                 handled = 1;
250                                 continue;
251                         }
252                 }
253
254                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
255                 if (!handler_list) {
256                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
257                         continue;
258                 }
259                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
260                         if (handler == session_media->handler) {
261                                 continue;
262                         }
263                         ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
264                                 session_media->stream_type,
265                                 handler->id);
266                         res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
267                                 sdp->media[i]);
268                         if (res < 0) {
269                                 /* Catastrophic failure. Abort! */
270                                 return -1;
271                         }
272                         if (res > 0) {
273                                 ast_debug(1, "Media stream '%s' handled by %s\n",
274                                         session_media->stream_type,
275                                         handler->id);
276                                 /* Handled by this handler. Move to the next stream */
277                                 session_media_set_handler(session_media, handler);
278                                 handled = 1;
279                                 break;
280                         }
281                 }
282         }
283         if (!handled) {
284                 return -1;
285         }
286         return 0;
287 }
288
289 struct handle_negotiated_sdp_cb {
290         struct ast_sip_session *session;
291         const pjmedia_sdp_session *local;
292         const pjmedia_sdp_session *remote;
293 };
294
295 static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)
296 {
297         struct ast_sip_session_media *session_media = obj;
298         struct handle_negotiated_sdp_cb *callback_data = arg;
299         struct ast_sip_session *session = callback_data->session;
300         const pjmedia_sdp_session *local = callback_data->local;
301         const pjmedia_sdp_session *remote = callback_data->remote;
302         int i;
303
304         for (i = 0; i < local->media_count; ++i) {
305                 /* See if there are registered handlers for this media stream type */
306                 char media[20];
307                 struct ast_sip_session_sdp_handler *handler;
308                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
309                 int res;
310
311                 if (!remote->media[i]) {
312                         continue;
313                 }
314
315                 /* We need a null-terminated version of the media string */
316                 ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));
317
318                 /* stream type doesn't match the one we're looking to fill */
319                 if (strcasecmp(session_media->stream_type, media)) {
320                         continue;
321                 }
322
323                 handler = session_media->handler;
324                 if (handler) {
325                         ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
326                                 session_media->stream_type,
327                                 handler->id);
328                         res = handler->apply_negotiated_sdp_stream(session, session_media, local,
329                                 local->media[i], remote, remote->media[i]);
330                         if (res >= 0) {
331                                 ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
332                                         session_media->stream_type,
333                                         handler->id);
334                                 return CMP_MATCH;
335                         }
336                         return 0;
337                 }
338
339                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
340                 if (!handler_list) {
341                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
342                         continue;
343                 }
344                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
345                         if (handler == session_media->handler) {
346                                 continue;
347                         }
348                         ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
349                                 session_media->stream_type,
350                                 handler->id);
351                         res = handler->apply_negotiated_sdp_stream(session, session_media, local,
352                                 local->media[i], remote, remote->media[i]);
353                         if (res < 0) {
354                                 /* Catastrophic failure. Abort! */
355                                 return 0;
356                         }
357                         if (res > 0) {
358                                 ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
359                                         session_media->stream_type,
360                                         handler->id);
361                                 /* Handled by this handler. Move to the next stream */
362                                 session_media_set_handler(session_media, handler);
363                                 return CMP_MATCH;
364                         }
365                 }
366         }
367
368         if (session_media->handler && session_media->handler->stream_stop) {
369                 ast_debug(1, "Stopping SDP media stream '%s' as it is not currently negotiated\n",
370                         session_media->stream_type);
371                 session_media->handler->stream_stop(session_media);
372         }
373
374         return CMP_MATCH;
375 }
376
377 static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
378 {
379         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
380         struct handle_negotiated_sdp_cb callback_data = {
381                 .session = session,
382                 .local = local,
383                 .remote = remote,
384         };
385
386         successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);
387         if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {
388                 /* Nothing experienced a catastrophic failure */
389                 ast_queue_frame(session->channel, &ast_null_frame);
390                 return 0;
391         }
392         return -1;
393 }
394
395 AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);
396
397 int ast_sip_session_register_supplement(struct ast_sip_session_supplement *supplement)
398 {
399         struct ast_sip_session_supplement *iter;
400         int inserted = 0;
401         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
402
403         if (!supplement->response_priority) {
404                 supplement->response_priority = AST_SIP_SESSION_BEFORE_MEDIA;
405         }
406
407         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
408                 if (iter->priority > supplement->priority) {
409                         AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
410                         inserted = 1;
411                         break;
412                 }
413         }
414         AST_RWLIST_TRAVERSE_SAFE_END;
415
416         if (!inserted) {
417                 AST_RWLIST_INSERT_TAIL(&session_supplements, supplement, next);
418         }
419         ast_module_ref(ast_module_info->self);
420         return 0;
421 }
422
423 void ast_sip_session_unregister_supplement(struct ast_sip_session_supplement *supplement)
424 {
425         struct ast_sip_session_supplement *iter;
426         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
427         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
428                 if (supplement == iter) {
429                         AST_RWLIST_REMOVE_CURRENT(next);
430                         ast_module_unref(ast_module_info->self);
431                         break;
432                 }
433         }
434         AST_RWLIST_TRAVERSE_SAFE_END;
435 }
436
437 static struct ast_sip_session_supplement *supplement_dup(const struct ast_sip_session_supplement *src)
438 {
439         struct ast_sip_session_supplement *dst = ast_calloc(1, sizeof(*dst));
440         if (!dst) {
441                 return NULL;
442         }
443         /* Will need to revisit if shallow copy becomes an issue */
444         *dst = *src;
445         return dst;
446 }
447
448 #define DATASTORE_BUCKETS 53
449 #define MEDIA_BUCKETS 7
450
451 static void session_datastore_destroy(void *obj)
452 {
453         struct ast_datastore *datastore = obj;
454
455         /* Using the destroy function (if present) destroy the data */
456         if (datastore->info->destroy != NULL && datastore->data != NULL) {
457                 datastore->info->destroy(datastore->data);
458                 datastore->data = NULL;
459         }
460
461         ast_free((void *) datastore->uid);
462         datastore->uid = NULL;
463 }
464
465 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
466 {
467         RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
468         char uuid_buf[AST_UUID_STR_LEN];
469         const char *uid_ptr = uid;
470
471         if (!info) {
472                 return NULL;
473         }
474
475         datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
476         if (!datastore) {
477                 return NULL;
478         }
479
480         datastore->info = info;
481         if (ast_strlen_zero(uid)) {
482                 /* They didn't provide an ID so we'll provide one ourself */
483                 uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
484         }
485
486         datastore->uid = ast_strdup(uid_ptr);
487         if (!datastore->uid) {
488                 return NULL;
489         }
490
491         ao2_ref(datastore, +1);
492         return datastore;
493 }
494
495 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
496 {
497         ast_assert(datastore != NULL);
498         ast_assert(datastore->info != NULL);
499         ast_assert(ast_strlen_zero(datastore->uid) == 0);
500
501         if (!ao2_link(session->datastores, datastore)) {
502                 return -1;
503         }
504         return 0;
505 }
506
507 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
508 {
509         return ao2_find(session->datastores, name, OBJ_KEY);
510 }
511
512 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
513 {
514         ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
515 }
516
517 enum delayed_method {
518         DELAYED_METHOD_INVITE,
519         DELAYED_METHOD_UPDATE,
520         DELAYED_METHOD_BYE,
521 };
522
523 /*!
524  * \internal
525  * \brief Convert delayed method enum value to to a string.
526  * \since 13.3.0
527  *
528  * \param method Delayed method enum value to convert to a string.
529  *
530  * \return String value of delayed method.
531  */
532 static const char *delayed_method2str(enum delayed_method method)
533 {
534         const char *str = "<unknown>";
535
536         switch (method) {
537         case DELAYED_METHOD_INVITE:
538                 str = "INVITE";
539                 break;
540         case DELAYED_METHOD_UPDATE:
541                 str = "UPDATE";
542                 break;
543         case DELAYED_METHOD_BYE:
544                 str = "BYE";
545                 break;
546         }
547
548         return str;
549 }
550
551 /*!
552  * \brief Structure used for sending delayed requests
553  *
554  * Requests are typically delayed because the current transaction
555  * state of an INVITE. Once the pending INVITE transaction terminates,
556  * the delayed request will be sent
557  */
558 struct ast_sip_session_delayed_request {
559         /*! Method of the request */
560         enum delayed_method method;
561         /*! Callback to call when the delayed request is created. */
562         ast_sip_session_request_creation_cb on_request_creation;
563         /*! Callback to call when the delayed request SDP is created */
564         ast_sip_session_sdp_creation_cb on_sdp_creation;
565         /*! Callback to call when the delayed request receives a response */
566         ast_sip_session_response_cb on_response;
567         /*! Whether to generate new SDP */
568         int generate_new_sdp;
569         AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
570 };
571
572 static struct ast_sip_session_delayed_request *delayed_request_alloc(
573         enum delayed_method method,
574         ast_sip_session_request_creation_cb on_request_creation,
575         ast_sip_session_sdp_creation_cb on_sdp_creation,
576         ast_sip_session_response_cb on_response,
577         int generate_new_sdp)
578 {
579         struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
580
581         if (!delay) {
582                 return NULL;
583         }
584         delay->method = method;
585         delay->on_request_creation = on_request_creation;
586         delay->on_sdp_creation = on_sdp_creation;
587         delay->on_response = on_response;
588         delay->generate_new_sdp = generate_new_sdp;
589         return delay;
590 }
591
592 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
593 {
594         ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",
595                 ast_sorcery_object_get_id(session->endpoint),
596                 session->channel ? ast_channel_name(session->channel) : "",
597                 delayed_method2str(delay->method));
598
599         switch (delay->method) {
600         case DELAYED_METHOD_INVITE:
601                 ast_sip_session_refresh(session, delay->on_request_creation,
602                         delay->on_sdp_creation, delay->on_response,
603                         AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);
604                 return 0;
605         case DELAYED_METHOD_UPDATE:
606                 ast_sip_session_refresh(session, delay->on_request_creation,
607                         delay->on_sdp_creation, delay->on_response,
608                         AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);
609                 return 0;
610         case DELAYED_METHOD_BYE:
611                 ast_sip_session_terminate(session, 0);
612                 return 0;
613         }
614         ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",
615                 delayed_method2str(delay->method), delay->method);
616         return -1;
617 }
618
619 /*!
620  * \internal
621  * \brief The current INVITE transaction is in the PROCEEDING state.
622  * \since 13.3.0
623  *
624  * \param vsession Session object.
625  *
626  * \retval 0 on success.
627  * \retval -1 on error.
628  */
629 static int invite_proceeding(void *vsession)
630 {
631         struct ast_sip_session *session = vsession;
632         struct ast_sip_session_delayed_request *delay;
633         int found = 0;
634         int res = 0;
635
636         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
637                 switch (delay->method) {
638                 case DELAYED_METHOD_INVITE:
639                         break;
640                 case DELAYED_METHOD_UPDATE:
641                         AST_LIST_REMOVE_CURRENT(next);
642                         res = send_delayed_request(session, delay);
643                         ast_free(delay);
644                         found = 1;
645                         break;
646                 case DELAYED_METHOD_BYE:
647                         /* A BYE is pending so don't bother anymore. */
648                         found = 1;
649                         break;
650                 }
651                 if (found) {
652                         break;
653                 }
654         }
655         AST_LIST_TRAVERSE_SAFE_END;
656
657         ao2_ref(session, -1);
658         return res;
659 }
660
661 /*!
662  * \internal
663  * \brief The current INVITE transaction is in the TERMINATED state.
664  * \since 13.3.0
665  *
666  * \param vsession Session object.
667  *
668  * \retval 0 on success.
669  * \retval -1 on error.
670  */
671 static int invite_terminated(void *vsession)
672 {
673         struct ast_sip_session *session = vsession;
674         struct ast_sip_session_delayed_request *delay;
675         int found = 0;
676         int res = 0;
677         int timer_running;
678
679         /* re-INVITE collision timer running? */
680         timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
681
682         AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
683                 switch (delay->method) {
684                 case DELAYED_METHOD_INVITE:
685                         if (!timer_running) {
686                                 found = 1;
687                         }
688                         break;
689                 case DELAYED_METHOD_UPDATE:
690                 case DELAYED_METHOD_BYE:
691                         found = 1;
692                         break;
693                 }
694                 if (found) {
695                         AST_LIST_REMOVE_CURRENT(next);
696                         res = send_delayed_request(session, delay);
697                         ast_free(delay);
698                         break;
699                 }
700         }
701         AST_LIST_TRAVERSE_SAFE_END;
702
703         ao2_ref(session, -1);
704         return res;
705 }
706
707 /*!
708  * \internal
709  * \brief INVITE collision timeout.
710  * \since 13.3.0
711  *
712  * \param vsession Session object.
713  *
714  * \retval 0 on success.
715  * \retval -1 on error.
716  */
717 static int invite_collision_timeout(void *vsession)
718 {
719         struct ast_sip_session *session = vsession;
720         int res;
721
722         if (session->inv_session->invite_tsx) {
723                 /*
724                  * INVITE transaction still active.  Let it send
725                  * the collision re-INVITE when it terminates.
726                  */
727                 ao2_ref(session, -1);
728                 res = 0;
729         } else {
730                 res = invite_terminated(session);
731         }
732
733         return res;
734 }
735
736 /*!
737  * \internal
738  * \brief The current UPDATE transaction is in the COMPLETED state.
739  * \since 13.3.0
740  *
741  * \param vsession Session object.
742  *
743  * \retval 0 on success.
744  * \retval -1 on error.
745  */
746 static int update_completed(void *vsession)
747 {
748         struct ast_sip_session *session = vsession;
749         int res;
750
751         if (session->inv_session->invite_tsx) {
752                 res = invite_proceeding(session);
753         } else {
754                 res = invite_terminated(session);
755         }
756
757         return res;
758 }
759
760 static void check_delayed_requests(struct ast_sip_session *session,
761         int (*cb)(void *vsession))
762 {
763         ao2_ref(session, +1);
764         if (ast_sip_push_task(session->serializer, cb, session)) {
765                 ao2_ref(session, -1);
766         }
767 }
768
769 static int delay_request(struct ast_sip_session *session,
770         ast_sip_session_request_creation_cb on_request,
771         ast_sip_session_sdp_creation_cb on_sdp_creation,
772         ast_sip_session_response_cb on_response,
773         int generate_new_sdp,
774         enum delayed_method method)
775 {
776         struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
777                         on_request, on_sdp_creation, on_response, generate_new_sdp);
778
779         if (!delay) {
780                 return -1;
781         }
782
783         if (method == DELAYED_METHOD_BYE) {
784                 /* Send BYE as early as possible */
785                 AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
786         } else {
787                 AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
788         }
789         return 0;
790 }
791
792 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
793 {
794         pjsip_inv_session *inv_session = session->inv_session;
795         const pjmedia_sdp_session *previous_sdp = NULL;
796
797         if (inv_session->neg) {
798                 if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
799                         pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
800                 } else {
801                         pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
802                 }
803         }
804         return create_local_sdp(inv_session, session, previous_sdp);
805 }
806
807 static void set_from_header(struct ast_sip_session *session)
808 {
809         struct ast_party_id effective_id;
810         struct ast_party_id connected_id;
811         pj_pool_t *dlg_pool;
812         pjsip_fromto_hdr *dlg_info;
813         pjsip_name_addr *dlg_info_name_addr;
814         pjsip_sip_uri *dlg_info_uri;
815         int restricted;
816
817         if (!session->channel || session->saved_from_hdr) {
818                 return;
819         }
820
821         /* We need to save off connected_id for RPID/PAI generation */
822         ast_party_id_init(&connected_id);
823         ast_channel_lock(session->channel);
824         effective_id = ast_channel_connected_effective_id(session->channel);
825         ast_party_id_copy(&connected_id, &effective_id);
826         ast_channel_unlock(session->channel);
827
828         restricted =
829                 ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);
830
831         /* Now set up dlg->local.info so pjsip can correctly generate From */
832
833         dlg_pool = session->inv_session->dlg->pool;
834         dlg_info = session->inv_session->dlg->local.info;
835         dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;
836         dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);
837
838         if (session->endpoint->id.trust_outbound || !restricted) {
839                 ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);
840         }
841
842         ast_party_id_free(&connected_id);
843
844         if (!ast_strlen_zero(session->endpoint->fromuser)) {
845                 dlg_info_name_addr->display.ptr = NULL;
846                 dlg_info_name_addr->display.slen = 0;
847                 pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);
848         }
849
850         if (!ast_strlen_zero(session->endpoint->fromdomain)) {
851                 pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);
852         }
853
854         ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);
855
856         /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */
857         session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);
858
859         /* In chan_sip, fromuser and fromdomain trump restricted so we only
860          * anonymize if they're not set.
861          */
862         if (restricted) {
863                 /* fromuser doesn't provide a display name so we always set it */
864                 pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");
865
866                 if (ast_strlen_zero(session->endpoint->fromuser)) {
867                         pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");
868                 }
869
870                 if (ast_strlen_zero(session->endpoint->fromdomain)) {
871                         pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");
872                 }
873         }
874 }
875
876 int ast_sip_session_refresh(struct ast_sip_session *session,
877                 ast_sip_session_request_creation_cb on_request_creation,
878                 ast_sip_session_sdp_creation_cb on_sdp_creation,
879                 ast_sip_session_response_cb on_response,
880                 enum ast_sip_session_refresh_method method, int generate_new_sdp)
881 {
882         pjsip_inv_session *inv_session = session->inv_session;
883         pjmedia_sdp_session *new_sdp = NULL;
884         pjsip_tx_data *tdata;
885
886         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
887                 /* Don't try to do anything with a hung-up call */
888                 ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
889                                 ast_sorcery_object_get_id(session->endpoint));
890                 return 0;
891         }
892
893         /* If the dialog has not yet been established we have to defer until it has */
894         if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
895                 ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
896                         ast_sorcery_object_get_id(session->endpoint));
897                 return delay_request(session, on_request_creation, on_sdp_creation, on_response,
898                         generate_new_sdp,
899                         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
900                                 ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
901         }
902
903         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
904                 if (inv_session->invite_tsx) {
905                         /* We can't send a reinvite yet, so delay it */
906                         ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
907                                         ast_sorcery_object_get_id(session->endpoint));
908                         return delay_request(session, on_request_creation, on_sdp_creation,
909                                 on_response, generate_new_sdp, DELAYED_METHOD_INVITE);
910                 } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
911                         /* Initial INVITE transaction failed to progress us to a confirmed state
912                          * which means re-invites are not possible
913                          */
914                         ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
915                                         ast_sorcery_object_get_id(session->endpoint));
916                         return 0;
917                 }
918         }
919
920         if (generate_new_sdp) {
921                 /* SDP can only be generated if current negotiation has already completed */
922                 if (inv_session->neg
923                         && pjmedia_sdp_neg_get_state(inv_session->neg)
924                                 != PJMEDIA_SDP_NEG_STATE_DONE) {
925                         ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
926                                 ast_sorcery_object_get_id(session->endpoint));
927                         return delay_request(session, on_request_creation, on_sdp_creation,
928                                 on_response, generate_new_sdp,
929                                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
930                                         ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
931                 }
932
933                 new_sdp = generate_session_refresh_sdp(session);
934                 if (!new_sdp) {
935                         ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
936                         return -1;
937                 }
938                 if (on_sdp_creation) {
939                         if (on_sdp_creation(session, new_sdp)) {
940                                 return -1;
941                         }
942                 }
943         }
944
945         /*
946          * We MUST call set_from_header() before pjsip_inv_(reinvite|update).  If we don't, the
947          * From in the reINVITE/UPDATE will be wrong but the rest of the messages will be OK.
948          */
949         set_from_header(session);
950
951         if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
952                 if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
953                         ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
954                         return -1;
955                 }
956         } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
957                 ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
958                 return -1;
959         }
960         if (on_request_creation) {
961                 if (on_request_creation(session, tdata)) {
962                         return -1;
963                 }
964         }
965         ast_debug(3, "Sending session refresh SDP via %s to %s\n",
966                 method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
967                 ast_sorcery_object_get_id(session->endpoint));
968         ast_sip_session_send_request_with_cb(session, tdata, on_response);
969         return 0;
970 }
971
972 /*!
973  * \internal
974  * \brief Wrapper for pjsip_inv_send_msg
975  *
976  * This function (re)sets the transport before sending to catch cases
977  * where the transport might have changed.
978  *
979  * If pjproject gives us the ability to resend, we'll only reset the transport
980  * if PJSIP_ETPNOTAVAIL is returned from send.
981  *
982  * \returns pj_status_t
983  */
984 static pj_status_t internal_pjsip_inv_send_msg(pjsip_inv_session *inv, const char *transport_name, pjsip_tx_data *tdata)
985 {
986         pjsip_tpselector selector = { .type = PJSIP_TPSELECTOR_NONE, };
987
988         ast_sip_set_tpselector_from_transport_name(transport_name, &selector);
989         pjsip_dlg_set_transport(inv->dlg, &selector);
990
991         return pjsip_inv_send_msg(inv, tdata);
992 }
993
994 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
995 {
996         handle_outgoing_response(session, tdata);
997         internal_pjsip_inv_send_msg(session->inv_session, session->endpoint->transport, tdata);
998         return;
999 }
1000
1001 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
1002
1003 static pjsip_module session_module = {
1004         .name = {"Session Module", 14},
1005         .priority = PJSIP_MOD_PRIORITY_APPLICATION,
1006         .on_rx_request = session_on_rx_request,
1007 };
1008
1009 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
1010  *
1011  * \retval 1 re-invite should be deferred and resumed later
1012  * \retval 0 re-invite should not be deferred
1013  */
1014 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
1015 {
1016         int i;
1017
1018         for (i = 0; i < sdp->media_count; ++i) {
1019                 /* See if there are registered handlers for this media stream type */
1020                 char media[20];
1021                 struct ast_sip_session_sdp_handler *handler;
1022                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
1023                 RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1024                 enum ast_sip_session_sdp_stream_defer res;
1025
1026                 /* We need a null-terminated version of the media string */
1027                 ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
1028
1029                 session_media = ao2_find(session->media, media, OBJ_KEY);
1030                 if (!session_media) {
1031                         /* if the session_media doesn't exist, there weren't
1032                          * any handlers at the time of its creation */
1033                         continue;
1034                 }
1035
1036                 if (session_media->handler) {
1037                         handler = session_media->handler;
1038                         if (handler->defer_incoming_sdp_stream) {
1039                                 res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1040                                         sdp->media[i]);
1041                                 switch (res) {
1042                                 case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1043                                         break;
1044                                 case AST_SIP_SESSION_SDP_DEFER_ERROR:
1045                                         return 0;
1046                                 case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1047                                         break;
1048                                 case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1049                                         return 1;
1050                                 }
1051                         }
1052                         /* Handled by this handler. Move to the next stream */
1053                         continue;
1054                 }
1055
1056                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
1057                 if (!handler_list) {
1058                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
1059                         continue;
1060                 }
1061                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1062                         if (handler == session_media->handler) {
1063                                 continue;
1064                         }
1065                         if (!handler->defer_incoming_sdp_stream) {
1066                                 continue;
1067                         }
1068                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
1069                                 sdp->media[i]);
1070                         switch (res) {
1071                         case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
1072                                 continue;
1073                         case AST_SIP_SESSION_SDP_DEFER_ERROR:
1074                                 session_media_set_handler(session_media, handler);
1075                                 return 0;
1076                         case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
1077                                 /* Handled by this handler. */
1078                                 session_media_set_handler(session_media, handler);
1079                                 break;
1080                         case AST_SIP_SESSION_SDP_DEFER_NEEDED:
1081                                 /* Handled by this handler. */
1082                                 session_media_set_handler(session_media, handler);
1083                                 return 1;
1084                         }
1085                         /* Move to the next stream */
1086                         break;
1087                 }
1088         }
1089         return 0;
1090 }
1091
1092 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
1093 {
1094         pjsip_dialog *dlg;
1095         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1096         pjsip_rdata_sdp_info *sdp_info;
1097
1098         if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
1099                 !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
1100                 !(session = ast_sip_dialog_get_session(dlg)) ||
1101                 !session->channel) {
1102                 return PJ_FALSE;
1103         }
1104
1105         if (session->deferred_reinvite) {
1106                 pj_str_t key, deferred_key;
1107                 pjsip_tx_data *tdata;
1108
1109                 /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
1110                 pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
1111                 pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
1112                         session->deferred_reinvite);
1113
1114                 /* If this is a retransmission ignore it */
1115                 if (!pj_strcmp(&key, &deferred_key)) {
1116                         return PJ_TRUE;
1117                 }
1118
1119                 /* Otherwise this is a new re-invite, so reject it */
1120                 if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
1121                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
1122                 }
1123
1124                 return PJ_TRUE;
1125         }
1126
1127         if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
1128                 (sdp_info->sdp_err != PJ_SUCCESS)) {
1129                 return PJ_FALSE;
1130         }
1131
1132         if (!sdp_info->sdp) {
1133                 const pjmedia_sdp_session *local;
1134                 int i;
1135
1136                 ast_queue_unhold(session->channel);
1137
1138                 pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);
1139                 if (!local) {
1140                         return PJ_FALSE;
1141                 }
1142
1143                 /*
1144                  * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).
1145                  * When hold is initially indicated, we
1146                  * - Receive an INVITE with no SDP
1147                  * - Send a 200 OK with SDP, indicating sendrecv in the media streams
1148                  * - Receive an ACK with SDP, indicating sendonly in the media streams
1149                  *
1150                  * At this point, the pjmedia negotiator saves the state of the media direction so that
1151                  * if we are to send any offers, we'll offer recvonly in the media streams. This is
1152                  * problematic if the device is attempting to unhold, though. If the device unholds
1153                  * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.
1154                  * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond
1155                  * with sendonly or inactive. The result of this is that the stream is not off hold.
1156                  *
1157                  * Therefore, in this case, when we receive a reinvite while the stream is on hold, we
1158                  * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv
1159                  * in order to get the stream off hold. If this is actually a different purpose reinvite
1160                  * (like a session timer refresh), then the answerer can respond to our sendrecv with
1161                  * sendonly, keeping the stream on hold.
1162                  */
1163                 for (i = 0; i < local->media_count; ++i) {
1164                         pjmedia_sdp_media *m = local->media[i];
1165                         pjmedia_sdp_attr *recvonly;
1166                         pjmedia_sdp_attr *inactive;
1167
1168                         recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);
1169                         inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);
1170                         if (recvonly || inactive) {
1171                                 pjmedia_sdp_attr *to_remove = recvonly ?: inactive;
1172                                 pjmedia_sdp_attr *sendrecv;
1173
1174                                 pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);
1175
1176                                 sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);
1177                                 pjmedia_sdp_media_add_attr(m, sendrecv);
1178                         }
1179                 }
1180
1181                 return PJ_FALSE;
1182         }
1183
1184         if (!sdp_requires_deferral(session, sdp_info->sdp)) {
1185                 return PJ_FALSE;
1186         }
1187
1188         pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
1189
1190         return PJ_TRUE;
1191 }
1192
1193 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
1194 {
1195         if (!session->deferred_reinvite) {
1196                 return;
1197         }
1198
1199         if (session->channel) {
1200                 pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),
1201                         session->deferred_reinvite, NULL, NULL);
1202         }
1203         pjsip_rx_data_free_cloned(session->deferred_reinvite);
1204         session->deferred_reinvite = NULL;
1205 }
1206
1207 static pjsip_module session_reinvite_module = {
1208         .name = { "Session Re-Invite Module", 24 },
1209         .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
1210         .on_rx_request = session_reinvite_on_rx_request,
1211 };
1212
1213
1214 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
1215                 ast_sip_session_response_cb on_response)
1216 {
1217         pjsip_inv_session *inv_session = session->inv_session;
1218
1219         if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
1220                 /* Don't try to do anything with a hung-up call */
1221                 return;
1222         }
1223
1224         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
1225                              MOD_DATA_ON_RESPONSE, on_response);
1226
1227         handle_outgoing_request(session, tdata);
1228         internal_pjsip_inv_send_msg(session->inv_session, session->endpoint->transport, tdata);
1229
1230         return;
1231 }
1232
1233 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
1234 {
1235         ast_sip_session_send_request_with_cb(session, tdata, NULL);
1236 }
1237
1238 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
1239 {
1240         pjmedia_sdp_session *offer;
1241
1242         if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
1243                 pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
1244                 return -1;
1245         }
1246
1247         pjsip_inv_set_local_sdp(session->inv_session, offer);
1248         pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
1249 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
1250         pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
1251 #endif
1252
1253         /*
1254          * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the
1255          * From in the initial INVITE will be wrong but the rest of the messages will be OK.
1256          */
1257         set_from_header(session);
1258
1259         if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
1260                 return -1;
1261         }
1262
1263         return 0;
1264 }
1265
1266 static int datastore_hash(const void *obj, int flags)
1267 {
1268         const struct ast_datastore *datastore = obj;
1269         const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
1270
1271         ast_assert(uid != NULL);
1272
1273         return ast_str_hash(uid);
1274 }
1275
1276 static int datastore_cmp(void *obj, void *arg, int flags)
1277 {
1278         const struct ast_datastore *datastore1 = obj;
1279         const struct ast_datastore *datastore2 = arg;
1280         const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
1281
1282         ast_assert(datastore1->uid != NULL);
1283         ast_assert(uid2 != NULL);
1284
1285         return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
1286 }
1287
1288 static void session_media_dtor(void *obj)
1289 {
1290         struct ast_sip_session_media *session_media = obj;
1291         struct sdp_handler_list *handler_list;
1292         /* It is possible for SDP handlers to allocate memory on a session_media but
1293          * not end up getting set as the handler for this session_media. This traversal
1294          * ensures that all memory allocated by SDP handlers on the session_media is
1295          * cleared (as well as file descriptors, etc.).
1296          */
1297         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
1298         if (handler_list) {
1299                 struct ast_sip_session_sdp_handler *handler;
1300
1301                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
1302                         handler->stream_destroy(session_media);
1303                 }
1304         }
1305         ao2_cleanup(handler_list);
1306         if (session_media->srtp) {
1307                 ast_sdp_srtp_destroy(session_media->srtp);
1308         }
1309 }
1310
1311 static void session_destructor(void *obj)
1312 {
1313         struct ast_sip_session *session = obj;
1314         struct ast_sip_session_supplement *supplement;
1315         struct ast_sip_session_delayed_request *delay;
1316
1317         ast_debug(3, "Destroying SIP session with endpoint %s\n",
1318                 session->endpoint ? ast_sorcery_object_get_id(session->endpoint) : "<none>");
1319
1320         while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
1321                 if (supplement->session_destroy) {
1322                         supplement->session_destroy(session);
1323                 }
1324                 ast_free(supplement);
1325         }
1326
1327         ast_taskprocessor_unreference(session->serializer);
1328         ao2_cleanup(session->datastores);
1329         ao2_cleanup(session->media);
1330
1331         AST_LIST_HEAD_DESTROY(&session->supplements);
1332         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1333                 ast_free(delay);
1334         }
1335         ast_party_id_free(&session->id);
1336         ao2_cleanup(session->endpoint);
1337         ao2_cleanup(session->aor);
1338         ao2_cleanup(session->contact);
1339         ao2_cleanup(session->req_caps);
1340         ao2_cleanup(session->direct_media_cap);
1341
1342         if (session->dsp) {
1343                 ast_dsp_free(session->dsp);
1344         }
1345
1346         if (session->inv_session) {
1347                 pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
1348         }
1349 }
1350
1351 static int add_supplements(struct ast_sip_session *session)
1352 {
1353         struct ast_sip_session_supplement *iter;
1354         SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
1355
1356         AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
1357                 struct ast_sip_session_supplement *copy = supplement_dup(iter);
1358                 if (!copy) {
1359                         return -1;
1360                 }
1361                 AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
1362         }
1363         return 0;
1364 }
1365
1366 static int add_session_media(void *obj, void *arg, int flags)
1367 {
1368         struct sdp_handler_list *handler_list = obj;
1369         struct ast_sip_session *session = arg;
1370         RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
1371
1372         session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
1373         if (!session_media) {
1374                 return CMP_STOP;
1375         }
1376         session_media->encryption = session->endpoint->media.rtp.encryption;
1377         session_media->keepalive_sched_id = -1;
1378         session_media->timeout_sched_id = -1;
1379         /* Safe use of strcpy */
1380         strcpy(session_media->stream_type, handler_list->stream_type);
1381         ao2_link(session->media, session_media);
1382         return 0;
1383 }
1384
1385 /*! \brief Destructor for SIP channel */
1386 static void sip_channel_destroy(void *obj)
1387 {
1388         struct ast_sip_channel_pvt *channel = obj;
1389
1390         ao2_cleanup(channel->pvt);
1391         ao2_cleanup(channel->session);
1392 }
1393
1394 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
1395 {
1396         struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
1397
1398         if (!channel) {
1399                 return NULL;
1400         }
1401
1402         ao2_ref(pvt, +1);
1403         channel->pvt = pvt;
1404         ao2_ref(session, +1);
1405         channel->session = session;
1406
1407         return channel;
1408 }
1409
1410 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
1411         struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)
1412 {
1413         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1414         struct ast_sip_session_supplement *iter;
1415         int dsp_features = 0;
1416
1417         session = ao2_alloc(sizeof(*session), session_destructor);
1418         if (!session) {
1419                 return NULL;
1420         }
1421         AST_LIST_HEAD_INIT(&session->supplements);
1422         session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
1423         if (!session->datastores) {
1424                 return NULL;
1425         }
1426
1427         session->endpoint = ao2_bump(endpoint);
1428
1429         session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
1430         if (!session->media) {
1431                 return NULL;
1432         }
1433         /* fill session->media with available types */
1434         ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
1435
1436         if (rdata) {
1437                 /*
1438                  * We must continue using the serializer that the original
1439                  * INVITE came in on for the dialog.  There may be
1440                  * retransmissions already enqueued in the original
1441                  * serializer that can result in reentrancy and message
1442                  * sequencing problems.
1443                  */
1444                 session->serializer = ast_sip_get_distributor_serializer(rdata);
1445         } else {
1446                 char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
1447
1448                 /* Create name with seq number appended. */
1449                 ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",
1450                         ast_sorcery_object_get_id(endpoint));
1451
1452                 session->serializer = ast_sip_create_serializer(tps_name);
1453         }
1454         if (!session->serializer) {
1455                 return NULL;
1456         }
1457         ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
1458         ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
1459         pjsip_dlg_inc_session(inv_session->dlg, &session_module);
1460         inv_session->mod_data[session_module.id] = ao2_bump(session);
1461         session->contact = ao2_bump(contact);
1462         session->inv_session = inv_session;
1463         session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1464         if (!session->req_caps) {
1465                 /* Release the ref held by session->inv_session */
1466                 ao2_ref(session, -1);
1467                 return NULL;
1468         }
1469
1470         if ((endpoint->dtmf == AST_SIP_DTMF_INBAND) || (endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
1471                 dsp_features |= DSP_FEATURE_DIGIT_DETECT;
1472         }
1473
1474         if (endpoint->faxdetect) {
1475                 dsp_features |= DSP_FEATURE_FAX_DETECT;
1476         }
1477
1478         if (dsp_features) {
1479                 if (!(session->dsp = ast_dsp_new())) {
1480                         /* Release the ref held by session->inv_session */
1481                         ao2_ref(session, -1);
1482                         return NULL;
1483                 }
1484
1485                 ast_dsp_set_features(session->dsp, dsp_features);
1486         }
1487
1488         if (add_supplements(session)) {
1489                 /* Release the ref held by session->inv_session */
1490                 ao2_ref(session, -1);
1491                 return NULL;
1492         }
1493         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
1494                 if (iter->session_begin) {
1495                         iter->session_begin(session);
1496                 }
1497         }
1498         session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1499         AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
1500         ast_party_id_init(&session->id);
1501         ao2_ref(session, +1);
1502         return session;
1503 }
1504
1505 /*! \brief struct controlling the suspension of the session's serializer. */
1506 struct ast_sip_session_suspender {
1507         ast_cond_t cond_suspended;
1508         ast_cond_t cond_complete;
1509         int suspended;
1510         int complete;
1511 };
1512
1513 static void sip_session_suspender_dtor(void *vdoomed)
1514 {
1515         struct ast_sip_session_suspender *doomed = vdoomed;
1516
1517         ast_cond_destroy(&doomed->cond_suspended);
1518         ast_cond_destroy(&doomed->cond_complete);
1519 }
1520
1521 /*!
1522  * \internal
1523  * \brief Block the session serializer thread task.
1524  *
1525  * \param data Pushed serializer task data for suspension.
1526  *
1527  * \retval 0
1528  */
1529 static int sip_session_suspend_task(void *data)
1530 {
1531         struct ast_sip_session_suspender *suspender = data;
1532
1533         ao2_lock(suspender);
1534
1535         /* Signal that the serializer task is now suspended. */
1536         suspender->suspended = 1;
1537         ast_cond_signal(&suspender->cond_suspended);
1538
1539         /* Wait for the the serializer suspension to be completed. */
1540         while (!suspender->complete) {
1541                 ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
1542         }
1543
1544         ao2_unlock(suspender);
1545         ao2_ref(suspender, -1);
1546
1547         return 0;
1548 }
1549
1550 void ast_sip_session_suspend(struct ast_sip_session *session)
1551 {
1552         struct ast_sip_session_suspender *suspender;
1553         int res;
1554
1555         ast_assert(session->suspended == NULL);
1556
1557         if (ast_taskprocessor_is_task(session->serializer)) {
1558                 /* I am the session's serializer thread so I cannot suspend. */
1559                 return;
1560         }
1561
1562         if (ast_taskprocessor_is_suspended(session->serializer)) {
1563                 /* The serializer already suspended. */
1564                 return;
1565         }
1566
1567         suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
1568         if (!suspender) {
1569                 /* We will just have to hope that the system does not deadlock */
1570                 return;
1571         }
1572         ast_cond_init(&suspender->cond_suspended, NULL);
1573         ast_cond_init(&suspender->cond_complete, NULL);
1574
1575         ao2_ref(suspender, +1);
1576         res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
1577         if (res) {
1578                 /* We will just have to hope that the system does not deadlock */
1579                 ao2_ref(suspender, -2);
1580                 return;
1581         }
1582
1583         session->suspended = suspender;
1584
1585         /* Wait for the serializer to get suspended. */
1586         ao2_lock(suspender);
1587         while (!suspender->suspended) {
1588                 ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
1589         }
1590         ao2_unlock(suspender);
1591
1592         ast_taskprocessor_suspend(session->serializer);
1593 }
1594
1595 void ast_sip_session_unsuspend(struct ast_sip_session *session)
1596 {
1597         struct ast_sip_session_suspender *suspender = session->suspended;
1598
1599         if (!suspender) {
1600                 /* Nothing to do */
1601                 return;
1602         }
1603         session->suspended = NULL;
1604
1605         /* Signal that the serializer task suspension is now complete. */
1606         ao2_lock(suspender);
1607         suspender->complete = 1;
1608         ast_cond_signal(&suspender->cond_complete);
1609         ao2_unlock(suspender);
1610
1611         ao2_ref(suspender, -1);
1612
1613         ast_taskprocessor_unsuspend(session->serializer);
1614 }
1615
1616 /*!
1617  * \internal
1618  * \brief Handle initial INVITE challenge response message.
1619  * \since 13.5.0
1620  *
1621  * \param rdata PJSIP receive response message data.
1622  *
1623  * \retval PJ_FALSE Did not handle message.
1624  * \retval PJ_TRUE Handled message.
1625  */
1626 static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)
1627 {
1628         pjsip_transaction *tsx;
1629         pjsip_dialog *dlg;
1630         pjsip_inv_session *inv;
1631         pjsip_tx_data *tdata;
1632         struct ast_sip_session *session;
1633
1634         if (rdata->msg_info.msg->line.status.code != 401
1635                 && rdata->msg_info.msg->line.status.code != 407) {
1636                 /* Doesn't pertain to us. Move on */
1637                 return PJ_FALSE;
1638         }
1639
1640         tsx = pjsip_rdata_get_tsx(rdata);
1641         dlg = pjsip_rdata_get_dlg(rdata);
1642         if (!dlg || !tsx) {
1643                 return PJ_FALSE;
1644         }
1645
1646         if (tsx->method.id != PJSIP_INVITE_METHOD) {
1647                 /* Not an INVITE that needs authentication */
1648                 return PJ_FALSE;
1649         }
1650
1651         inv = pjsip_dlg_get_inv_session(dlg);
1652         if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {
1653                 /*
1654                  * We cannot handle reINVITE authentication at this
1655                  * time because the reINVITE transaction is still in
1656                  * progress.
1657                  */
1658                 ast_debug(1, "A reINVITE is being challenged.\n");
1659                 return PJ_FALSE;
1660         }
1661         ast_debug(1, "Initial INVITE is being challenged.\n");
1662
1663         session = inv->mod_data[session_module.id];
1664
1665         if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata,
1666                 tsx->last_tx, &tdata)) {
1667                 return PJ_FALSE;
1668         }
1669
1670         /*
1671          * Restart the outgoing initial INVITE transaction to deal
1672          * with authentication.
1673          */
1674         pjsip_inv_uac_restart(inv, PJ_FALSE);
1675
1676         ast_sip_session_send_request(session, tdata);
1677         return PJ_TRUE;
1678 }
1679
1680 static pjsip_module outbound_invite_auth_module = {
1681         .name = {"Outbound INVITE Auth", 20},
1682         .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,
1683         .on_rx_response = outbound_invite_auth,
1684 };
1685
1686 /*!
1687  * \internal
1688  * \brief Setup outbound initial INVITE authentication.
1689  * \since 13.5.0
1690  *
1691  * \param dlg PJSIP dialog to attach outbound authentication.
1692  *
1693  * \retval 0 on success.
1694  * \retval -1 on error.
1695  */
1696 static int setup_outbound_invite_auth(pjsip_dialog *dlg)
1697 {
1698         pj_status_t status;
1699
1700         ++dlg->sess_count;
1701         status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);
1702         --dlg->sess_count;
1703
1704         return status != PJ_SUCCESS ? -1 : 0;
1705 }
1706
1707 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
1708         struct ast_sip_contact *contact, const char *location, const char *request_user,
1709         struct ast_format_cap *req_caps)
1710 {
1711         const char *uri = NULL;
1712         RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
1713         RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
1714         pjsip_timer_setting timer;
1715         pjsip_dialog *dlg;
1716         struct pjsip_inv_session *inv_session;
1717         RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
1718
1719         /* If no location has been provided use the AOR list from the endpoint itself */
1720         if (location || !contact) {
1721                 location = S_OR(location, endpoint->aors);
1722
1723                 ast_sip_location_retrieve_contact_and_aor_from_list(location, &found_aor, &found_contact);
1724                 if (!found_contact || ast_strlen_zero(found_contact->uri)) {
1725                         uri = location;
1726                 } else {
1727                         uri = found_contact->uri;
1728                 }
1729         } else {
1730                 uri = contact->uri;
1731         }
1732
1733         /* If we still have no URI to dial fail to create the session */
1734         if (ast_strlen_zero(uri)) {
1735                 return NULL;
1736         }
1737
1738         if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
1739                 return NULL;
1740         }
1741
1742         if (setup_outbound_invite_auth(dlg)) {
1743                 pjsip_dlg_terminate(dlg);
1744                 return NULL;
1745         }
1746
1747         if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
1748                 pjsip_dlg_terminate(dlg);
1749                 return NULL;
1750         }
1751 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
1752         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
1753 #endif
1754
1755         pjsip_timer_setting_default(&timer);
1756         timer.min_se = endpoint->extensions.timer.min_se;
1757         timer.sess_expires = endpoint->extensions.timer.sess_expires;
1758         pjsip_timer_init_session(inv_session, &timer);
1759
1760         session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,
1761                 inv_session, NULL);
1762         if (!session) {
1763                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1764                 return NULL;
1765         }
1766         session->aor = ao2_bump(found_aor);
1767         ast_party_id_copy(&session->id, &endpoint->id.self);
1768
1769         if (ast_format_cap_count(req_caps)) {
1770                 /* get joint caps between req_caps and endpoint caps */
1771                 struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1772                 ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
1773
1774                 /* if joint caps */
1775                 if (ast_format_cap_count(joint_caps)) {
1776                         /* copy endpoint caps into session->req_caps */
1777                         ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
1778                         /* replace instances of joint caps equivalents in session->req_caps */
1779                         ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
1780                 }
1781                 ao2_cleanup(joint_caps);
1782         }
1783
1784         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
1785                 pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
1786                 /* Since we are not notifying ourselves that the INVITE session is being terminated
1787                  * we need to manually drop its reference to session
1788                  */
1789                 ao2_ref(session, -1);
1790                 return NULL;
1791         }
1792
1793         ao2_ref(session, +1);
1794         return session;
1795 }
1796
1797 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
1798 {
1799         pj_status_t status;
1800         pjsip_tx_data *packet = NULL;
1801
1802         if (session->defer_terminate) {
1803                 session->terminate_while_deferred = 1;
1804                 return;
1805         }
1806
1807         if (!response) {
1808                 response = 603;
1809         }
1810
1811         switch (session->inv_session->state) {
1812         case PJSIP_INV_STATE_NULL:
1813                 pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
1814                 break;
1815         case PJSIP_INV_STATE_CONFIRMED:
1816                 if (session->inv_session->invite_tsx) {
1817                         ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
1818                                         ast_sorcery_object_get_id(session->endpoint));
1819                         /* If this is delayed the only thing that will happen is a BYE request so we don't
1820                          * actually need to store the response code for when it happens.
1821                          */
1822                         delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);
1823                         break;
1824                 }
1825                 /* Fall through */
1826         default:
1827                 status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);
1828                 if (status == PJ_SUCCESS && packet) {
1829                         struct ast_sip_session_delayed_request *delay;
1830
1831                         /* Flush any delayed requests so they cannot overlap this transaction. */
1832                         while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
1833                                 ast_free(delay);
1834                         }
1835
1836                         if (packet->msg->type == PJSIP_RESPONSE_MSG) {
1837                                 ast_sip_session_send_response(session, packet);
1838                         } else {
1839                                 ast_sip_session_send_request(session, packet);
1840                         }
1841                 }
1842                 break;
1843         }
1844 }
1845
1846 static int session_termination_task(void *data)
1847 {
1848         struct ast_sip_session *session = data;
1849
1850         if (session->defer_terminate) {
1851                 session->defer_terminate = 0;
1852                 if (session->inv_session) {
1853                         ast_sip_session_terminate(session, 0);
1854                 }
1855         }
1856
1857         ao2_ref(session, -1);
1858         return 0;
1859 }
1860
1861 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
1862 {
1863         struct ast_sip_session *session = entry->user_data;
1864
1865         if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
1866                 ao2_cleanup(session);
1867         }
1868 }
1869
1870 int ast_sip_session_defer_termination(struct ast_sip_session *session)
1871 {
1872         pj_time_val delay = { .sec = 60, };
1873         int res;
1874
1875         /* The session should not have an active deferred termination request. */
1876         ast_assert(!session->defer_terminate);
1877
1878         session->defer_terminate = 1;
1879
1880         session->scheduled_termination.id = 0;
1881         ao2_ref(session, +1);
1882         session->scheduled_termination.user_data = session;
1883         session->scheduled_termination.cb = session_termination_cb;
1884
1885         res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
1886                 &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
1887         if (res) {
1888                 session->defer_terminate = 0;
1889                 ao2_ref(session, -1);
1890         }
1891         return res;
1892 }
1893
1894 /*!
1895  * \internal
1896  * \brief Stop the defer termination timer if it is still running.
1897  * \since 13.5.0
1898  *
1899  * \param session Which session to stop the timer.
1900  *
1901  * \return Nothing
1902  */
1903 static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)
1904 {
1905         if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
1906                 &session->scheduled_termination)) {
1907                 ao2_ref(session, -1);
1908         }
1909 }
1910
1911 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
1912 {
1913         if (!session->defer_terminate) {
1914                 /* Already canceled or timer fired. */
1915                 return;
1916         }
1917         session->defer_terminate = 0;
1918
1919         if (session->terminate_while_deferred) {
1920                 /* Complete the termination started by the upper layer. */
1921                 ast_sip_session_terminate(session, 0);
1922         }
1923
1924         /* Stop the termination timer if it is still running. */
1925         sip_session_defer_termination_stop_timer(session);
1926 }
1927
1928 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
1929 {
1930         pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
1931         struct ast_sip_session *session;
1932
1933         if (!inv_session ||
1934                 !(session = inv_session->mod_data[session_module.id])) {
1935                 return NULL;
1936         }
1937
1938         ao2_ref(session, +1);
1939
1940         return session;
1941 }
1942
1943 enum sip_get_destination_result {
1944         /*! The extension was successfully found */
1945         SIP_GET_DEST_EXTEN_FOUND,
1946         /*! The extension specified in the RURI was not found */
1947         SIP_GET_DEST_EXTEN_NOT_FOUND,
1948         /*! The extension specified in the RURI was a partial match */
1949         SIP_GET_DEST_EXTEN_PARTIAL,
1950         /*! The RURI is of an unsupported scheme */
1951         SIP_GET_DEST_UNSUPPORTED_URI,
1952 };
1953
1954 /*!
1955  * \brief Determine where in the dialplan a call should go
1956  *
1957  * This uses the username in the request URI to try to match
1958  * an extension in the endpoint's configured context in order
1959  * to route the call.
1960  *
1961  * \param session The inbound SIP session
1962  * \param rdata The SIP INVITE
1963  */
1964 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
1965 {
1966         pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
1967         pjsip_sip_uri *sip_ruri;
1968         struct ast_features_pickup_config *pickup_cfg;
1969         const char *pickupexten;
1970
1971         if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
1972                 return SIP_GET_DEST_UNSUPPORTED_URI;
1973         }
1974
1975         sip_ruri = pjsip_uri_get_uri(ruri);
1976         ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
1977
1978         pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
1979         if (!pickup_cfg) {
1980                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
1981                 pickupexten = "";
1982         } else {
1983                 pickupexten = ast_strdupa(pickup_cfg->pickupexten);
1984                 ao2_ref(pickup_cfg, -1);
1985         }
1986
1987         if (!strcmp(session->exten, pickupexten) ||
1988                 ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
1989                 return SIP_GET_DEST_EXTEN_FOUND;
1990         }
1991         /* XXX In reality, we'll likely have further options so that partial matches
1992          * can be indicated here, but for getting something up and running, we're going
1993          * to return a "not exists" error here.
1994          */
1995         return SIP_GET_DEST_EXTEN_NOT_FOUND;
1996 }
1997
1998 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
1999 {
2000         pjsip_tx_data *tdata;
2001         pjsip_dialog *dlg;
2002         pjsip_inv_session *inv_session;
2003         unsigned int options = endpoint->extensions.flags;
2004         pj_status_t dlg_status;
2005
2006         if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
2007                 if (tdata) {
2008                         pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
2009                 } else {
2010                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2011                 }
2012                 return NULL;
2013         }
2014         dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
2015         if (!dlg) {
2016                 if (dlg_status != PJ_EEXISTS) {
2017                         pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2018                 }
2019                 return NULL;
2020         }
2021         if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
2022                 pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
2023                 pjsip_dlg_terminate(dlg);
2024                 return NULL;
2025         }
2026
2027 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
2028         inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
2029 #endif
2030         if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
2031                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
2032                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2033                 }
2034                 internal_pjsip_inv_send_msg(inv_session, endpoint->transport, tdata);
2035                 return NULL;
2036         }
2037         return inv_session;
2038 }
2039
2040 struct new_invite {
2041         /*! \brief Session created for the new INVITE */
2042         struct ast_sip_session *session;
2043
2044         /*! \brief INVITE request itself */
2045         pjsip_rx_data *rdata;
2046 };
2047
2048 static void new_invite_destroy(void *obj)
2049 {
2050         struct new_invite *invite = obj;
2051
2052         ao2_cleanup(invite->session);
2053
2054         if (invite->rdata) {
2055                 pjsip_rx_data_free_cloned(invite->rdata);
2056         }
2057 }
2058
2059 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
2060 {
2061         struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
2062
2063         if (!invite) {
2064                 return NULL;
2065         }
2066
2067         ao2_ref(session, +1);
2068         invite->session = session;
2069
2070         if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
2071                 ao2_ref(invite, -1);
2072                 return NULL;
2073         }
2074
2075         return invite;
2076 }
2077
2078 static int new_invite(void *data)
2079 {
2080         RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
2081         pjsip_tx_data *tdata = NULL;
2082         pjsip_timer_setting timer;
2083         pjsip_rdata_sdp_info *sdp_info;
2084         pjmedia_sdp_session *local = NULL;
2085
2086         /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
2087          * so that we will be notified so we can destroy the session properly
2088          */
2089
2090         switch (get_destination(invite->session, invite->rdata)) {
2091         case SIP_GET_DEST_EXTEN_FOUND:
2092                 /* Things worked. Keep going */
2093                 break;
2094         case SIP_GET_DEST_UNSUPPORTED_URI:
2095                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
2096                         ast_sip_session_send_response(invite->session, tdata);
2097                 } else  {
2098                         pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
2099                 }
2100                 return 0;
2101         case SIP_GET_DEST_EXTEN_NOT_FOUND:
2102         case SIP_GET_DEST_EXTEN_PARTIAL:
2103         default:
2104                 ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
2105                         ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
2106                         invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
2107
2108                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
2109                         ast_sip_session_send_response(invite->session, tdata);
2110                 } else  {
2111                         pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
2112                 }
2113                 return 0;
2114         };
2115
2116         if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
2117                 if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
2118                         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
2119                                 ast_sip_session_send_response(invite->session, tdata);
2120                         } else  {
2121                                 pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
2122                         }
2123                         return 0;
2124                 }
2125                 /* We are creating a local SDP which is an answer to their offer */
2126                 local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
2127         } else {
2128                 /* We are creating a local SDP which is an offer */
2129                 local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
2130         }
2131
2132         /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
2133         if (!local) {
2134                 if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
2135                         ast_sip_session_send_response(invite->session, tdata);
2136                 } else  {
2137                         pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
2138                 }
2139                 return 0;
2140         } else {
2141                 pjsip_inv_set_local_sdp(invite->session->inv_session, local);
2142                 pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
2143 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
2144                 pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
2145 #endif
2146         }
2147
2148         pjsip_timer_setting_default(&timer);
2149         timer.min_se = invite->session->endpoint->extensions.timer.min_se;
2150         timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
2151         pjsip_timer_init_session(invite->session->inv_session, &timer);
2152
2153         /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
2154         if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
2155                 pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
2156                 return 0;
2157         }
2158         ast_sip_session_send_response(invite->session, tdata);
2159
2160         handle_incoming_request(invite->session, invite->rdata);
2161
2162         return 0;
2163 }
2164
2165 static void handle_new_invite_request(pjsip_rx_data *rdata)
2166 {
2167         RAII_VAR(struct ast_sip_endpoint *, endpoint,
2168                         ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
2169         pjsip_tx_data *tdata = NULL;
2170         pjsip_inv_session *inv_session = NULL;
2171         struct ast_sip_session *session;
2172         struct new_invite *invite;
2173
2174         ast_assert(endpoint != NULL);
2175
2176         inv_session = pre_session_setup(rdata, endpoint);
2177         if (!inv_session) {
2178                 /* pre_session_setup() returns a response on failure */
2179                 return;
2180         }
2181
2182         session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);
2183         if (!session) {
2184                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
2185                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2186                 } else {
2187                         internal_pjsip_inv_send_msg(inv_session, endpoint->transport, tdata);
2188                 }
2189                 return;
2190         }
2191
2192         invite = new_invite_alloc(session, rdata);
2193         if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
2194                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
2195                         pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
2196                 } else {
2197                         internal_pjsip_inv_send_msg(inv_session, endpoint->transport, tdata);
2198                 }
2199                 ao2_cleanup(invite);
2200         }
2201         ao2_ref(session, -1);
2202 }
2203
2204 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
2205 {
2206         pj_str_t method;
2207
2208         if (ast_strlen_zero(supplement_method)) {
2209                 return PJ_TRUE;
2210         }
2211
2212         pj_cstr(&method, supplement_method);
2213
2214         return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
2215 }
2216
2217 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
2218 {
2219         struct ast_sip_session_supplement *supplement;
2220         struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
2221
2222         if (!session) {
2223                 return PJ_FALSE;
2224         }
2225
2226         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2227                 if (does_method_match(&method->name, supplement->method)) {
2228                         return PJ_TRUE;
2229                 }
2230         }
2231         return PJ_FALSE;
2232 }
2233 /*!
2234  * \brief Called when a new SIP request comes into PJSIP
2235  *
2236  * This function is called under two circumstances
2237  * 1) An out-of-dialog request is received by PJSIP
2238  * 2) An in-dialog request that the inv_session layer does not
2239  *    handle is received (such as an in-dialog INFO)
2240  *
2241  * In all cases, there is very little we actually do in this function
2242  * 1) For requests we don't handle, we return PJ_FALSE
2243  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
2244  *    there to free up the thread(s) handling incoming requests
2245  * 3) For in-dialog requests we handle, we defer handling them until the
2246  *    on_inv_state_change() callback instead (where we will end up putting
2247  *    them into the threadpool).
2248  */
2249 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
2250 {
2251         pj_status_t handled = PJ_FALSE;
2252         pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
2253         pjsip_inv_session *inv_session;
2254
2255         switch (rdata->msg_info.msg->line.req.method.id) {
2256         case PJSIP_INVITE_METHOD:
2257                 if (dlg) {
2258                         ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
2259                         break;
2260                 }
2261                 handled = PJ_TRUE;
2262                 handle_new_invite_request(rdata);
2263                 break;
2264         default:
2265                 /* Handle other in-dialog methods if their supplements have been registered */
2266                 handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
2267                         has_supplement(inv_session->mod_data[session_module.id], rdata);
2268                 break;
2269         }
2270
2271         return handled;
2272 }
2273
2274 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
2275 {
2276         struct ast_sip_session *session = entry->user_data;
2277
2278         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
2279                 ast_sorcery_object_get_id(session->endpoint),
2280                 session->channel ? ast_channel_name(session->channel) : "");
2281
2282         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2283                 /* No delayed request pending, so just return */
2284                 ao2_ref(session, -1);
2285                 return;
2286         }
2287         if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
2288                 /*
2289                  * Uh oh.  We now have nothing in the foreseeable future
2290                  * to trigger sending the delayed requests.
2291                  */
2292                 ao2_ref(session, -1);
2293         }
2294 }
2295
2296 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
2297 {
2298         pjsip_inv_session *inv = session->inv_session;
2299         pj_time_val tv;
2300
2301         ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
2302                 ast_sorcery_object_get_id(session->endpoint),
2303                 session->channel ? ast_channel_name(session->channel) : "");
2304         if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {
2305                 return;
2306         }
2307         if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
2308                 /* Timer already running.  Something weird is going on. */
2309                 ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
2310                         ast_sorcery_object_get_id(session->endpoint),
2311                         session->channel ? ast_channel_name(session->channel) : "");
2312                 return;
2313         }
2314
2315         tv.sec = 0;
2316         if (inv->role == PJSIP_ROLE_UAC) {
2317                 tv.msec = 2100 + ast_random() % 2000;
2318         } else {
2319                 tv.msec = ast_random() % 2000;
2320         }
2321         pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
2322
2323         ao2_ref(session, +1);
2324         if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
2325                 &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
2326                 ao2_ref(session, -1);
2327         }
2328 }
2329
2330 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2331 {
2332         int id = session_module.id;
2333         struct ast_sip_session *session = NULL;
2334
2335         if (!DEBUG_ATLEAST(5)) {
2336                 /* Debug not spamy enough */
2337                 return;
2338         }
2339
2340         ast_log(LOG_DEBUG, "Function %s called on event %s\n",
2341                 function, pjsip_event_str(e->type));
2342         if (!inv) {
2343                 ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
2344                 ast_log(LOG_DEBUG, "The transaction state is %s\n",
2345                         pjsip_tsx_state_str(tsx->state));
2346                 return;
2347         }
2348         if (id > -1) {
2349                 session = inv->mod_data[session_module.id];
2350         }
2351         if (!session) {
2352                 ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
2353         } else {
2354                 ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
2355                         ast_sorcery_object_get_id(session->endpoint),
2356                         session->channel ? ast_channel_name(session->channel) : "");
2357         }
2358         if (inv->invite_tsx) {
2359                 ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
2360                         inv->invite_tsx);
2361         } else {
2362                 ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
2363         }
2364         if (tsx) {
2365                 ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
2366                         pjsip_role_name(tsx->role),
2367                         (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2368                         tsx);
2369                 ast_log(LOG_DEBUG, "The current transaction state is %s\n",
2370                         pjsip_tsx_state_str(tsx->state));
2371                 ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
2372                         pjsip_event_str(e->body.tsx_state.type));
2373         } else {
2374                 ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
2375         }
2376         ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
2377 }
2378
2379 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
2380
2381 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
2382 {
2383         struct ast_sip_session_supplement *supplement;
2384         struct pjsip_request_line req = rdata->msg_info.msg->line.req;
2385
2386         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2387         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2388                 if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
2389                         if (supplement->incoming_request(session, rdata)) {
2390                                 break;
2391                         }
2392                 }
2393         }
2394 }
2395
2396 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,
2397                 enum ast_sip_session_response_priority response_priority)
2398 {
2399         struct ast_sip_session_supplement *supplement;
2400         struct pjsip_status_line status = rdata->msg_info.msg->line.status;
2401
2402         ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
2403                         pj_strbuf(&status.reason));
2404
2405         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2406                 if (!(supplement->response_priority & response_priority)) {
2407                         continue;
2408                 }
2409                 if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
2410                         supplement->incoming_response(session, rdata);
2411                 }
2412         }
2413 }
2414
2415 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,
2416                 enum ast_sip_session_response_priority response_priority)
2417 {
2418         ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
2419                         "request" : "response");
2420
2421         if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
2422                 handle_incoming_request(session, rdata);
2423         } else {
2424                 handle_incoming_response(session, rdata, response_priority);
2425         }
2426
2427         return 0;
2428 }
2429
2430 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
2431 {
2432         struct ast_sip_session_supplement *supplement;
2433         struct pjsip_request_line req = tdata->msg->line.req;
2434
2435         ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
2436         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2437                 if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
2438                         supplement->outgoing_request(session, tdata);
2439                 }
2440         }
2441 }
2442
2443 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
2444 {
2445         struct ast_sip_session_supplement *supplement;
2446         struct pjsip_status_line status = tdata->msg->line.status;
2447         pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
2448         ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
2449                 pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
2450                 pj_strbuf(&status.reason));
2451
2452         AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
2453                 if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
2454                         supplement->outgoing_response(session, tdata);
2455                 }
2456         }
2457 }
2458
2459 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
2460 {
2461         ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
2462                         "request" : "response");
2463         if (tdata->msg->type == PJSIP_REQUEST_MSG) {
2464                 handle_outgoing_request(session, tdata);
2465         } else {
2466                 handle_outgoing_response(session, tdata);
2467         }
2468 }
2469
2470 static void session_end(struct ast_sip_session *session)
2471 {
2472         struct ast_sip_session_supplement *iter;
2473
2474         /* Stop the scheduled termination */
2475         sip_session_defer_termination_stop_timer(session);
2476
2477         /* Session is dead.  Notify the supplements. */
2478         AST_LIST_TRAVERSE(&session->supplements, iter, next) {
2479                 if (iter->session_end) {
2480                         iter->session_end(session);
2481                 }
2482         }
2483 }
2484
2485 /*!
2486  * \internal
2487  * \brief Complete ending session activities.
2488  * \since 13.5.0
2489  *
2490  * \param vsession Which session to complete stopping.
2491  *
2492  * \retval 0 on success.
2493  * \retval -1 on error.
2494  */
2495 static int session_end_completion(void *vsession)
2496 {
2497         struct ast_sip_session *session = vsession;
2498
2499         ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
2500         ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
2501
2502         /* Now we can release the ref that was held by session->inv_session */
2503         ao2_cleanup(session);
2504         return 0;
2505 }
2506
2507 static int check_request_status(pjsip_inv_session *inv, pjsip_event *e)
2508 {
2509         struct ast_sip_session *session = inv->mod_data[session_module.id];
2510         pjsip_transaction *tsx = e->body.tsx_state.tsx;
2511
2512         if (tsx->status_code != 503 && tsx->status_code != 408) {
2513                 return 0;
2514         }
2515
2516         if (!ast_sip_failover_request(tsx->last_tx)) {
2517                 return 0;
2518         }
2519
2520         pjsip_inv_uac_restart(inv, PJ_FALSE);
2521         /*
2522          * Bump the ref since it will be on a new transaction and
2523          * we don't want it to go away along with the old transaction.
2524          */
2525         pjsip_tx_data_add_ref(tsx->last_tx);
2526         ast_sip_session_send_request(session, tsx->last_tx);
2527         return 1;
2528 }
2529
2530 static void handle_incoming_before_media(pjsip_inv_session *inv,
2531         struct ast_sip_session *session, pjsip_rx_data *rdata)
2532 {
2533         pjsip_msg *msg;
2534
2535         handle_incoming(session, rdata, AST_SIP_SESSION_BEFORE_MEDIA);
2536         msg = rdata->msg_info.msg;
2537         if (msg->type == PJSIP_REQUEST_MSG
2538                 && msg->line.req.method.id == PJSIP_ACK_METHOD
2539                 && pjmedia_sdp_neg_get_state(inv->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
2540                 pjsip_tx_data *tdata;
2541
2542                 /*
2543                  * SDP negotiation failed on an incoming call that delayed
2544                  * negotiation and then gave us an invalid SDP answer.  We
2545                  * need to send a BYE to end the call because of the invalid
2546                  * SDP answer.
2547                  */
2548                 ast_debug(1,
2549                         "Endpoint '%s(%s)': Ending session due to incomplete SDP negotiation.  %s\n",
2550                         ast_sorcery_object_get_id(session->endpoint),
2551                         session->channel ? ast_channel_name(session->channel) : "",
2552                         pjsip_rx_data_get_info(rdata));
2553                 if (pjsip_inv_end_session(inv, 400, NULL, &tdata) == PJ_SUCCESS
2554                         && tdata) {
2555                         ast_sip_session_send_request(session, tdata);
2556                 }
2557         }
2558 }
2559
2560 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
2561 {
2562         struct ast_sip_session *session = inv->mod_data[session_module.id];
2563         pjsip_event_id_e type;
2564
2565         if (e) {
2566                 print_debug_details(inv, NULL, e);
2567                 type = e->type;
2568         } else {
2569                 type = PJSIP_EVENT_UNKNOWN;
2570         }
2571
2572         if (!session) {
2573                 return;
2574         }
2575
2576         switch(type) {
2577         case PJSIP_EVENT_TX_MSG:
2578                 handle_outgoing(session, e->body.tx_msg.tdata);
2579                 break;
2580         case PJSIP_EVENT_RX_MSG:
2581                 handle_incoming_before_media(inv, session, e->body.rx_msg.rdata);
2582                 break;
2583         case PJSIP_EVENT_TSX_STATE:
2584                 ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
2585                 /* Transaction state changes are prompted by some other underlying event. */
2586                 switch(e->body.tsx_state.type) {
2587                 case PJSIP_EVENT_TX_MSG:
2588                         handle_outgoing(session, e->body.tsx_state.src.tdata);
2589                         break;
2590                 case PJSIP_EVENT_RX_MSG:
2591                         if (!check_request_status(inv, e)) {
2592                                 handle_incoming_before_media(inv, session, e->body.tsx_state.src.rdata);
2593                         }
2594                         break;
2595                 case PJSIP_EVENT_TRANSPORT_ERROR:
2596                 case PJSIP_EVENT_TIMER:
2597                         /*
2598                          * Check the request status on transport error or timeout. A transport
2599                          * error can occur when a TCP socket closes and that can be the result
2600                          * of a 503. Also we may need to failover on a timeout (408).
2601                          */
2602                         check_request_status(inv, e);
2603                         break;
2604                 case PJSIP_EVENT_USER:
2605                 case PJSIP_EVENT_UNKNOWN:
2606                 case PJSIP_EVENT_TSX_STATE:
2607                         /* Inception? */
2608                         break;
2609                 }
2610                 break;
2611         case PJSIP_EVENT_TRANSPORT_ERROR:
2612         case PJSIP_EVENT_TIMER:
2613         case PJSIP_EVENT_UNKNOWN:
2614         case PJSIP_EVENT_USER:
2615         default:
2616                 break;
2617         }
2618
2619         if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2620                 session_end(session);
2621         }
2622 }
2623
2624 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
2625 {
2626         /* XXX STUB */
2627 }
2628
2629 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
2630 {
2631         ast_sip_session_response_cb cb;
2632         int id = session_module.id;
2633         struct ast_sip_session *session;
2634         pjsip_tx_data *tdata;
2635
2636         /*
2637          * A race condition exists at shutdown where the res_pjsip_session can be
2638          * unloaded but this callback may still get called afterwards. In this case
2639          * the id may end up being -1 which is useless to us. To work around this
2640          * we store the current value and check/use it.
2641          */
2642         if (id < 0) {
2643                 return;
2644         }
2645
2646         session = inv->mod_data[id];
2647
2648         print_debug_details(inv, tsx, e);
2649         if (!session) {
2650                 /* The session has ended.  Ignore the transaction change. */
2651                 return;
2652         }
2653         switch (e->body.tsx_state.type) {
2654         case PJSIP_EVENT_TX_MSG:
2655                 handle_outgoing(session, e->body.tsx_state.src.tdata);
2656                 /* When we create an outgoing request, we do not have access to the transaction that
2657                  * is created. Instead, We have to place transaction-specific data in the tdata. Here,
2658                  * we transfer the data into the transaction. This way, when we receive a response, we
2659                  * can dig this data out again
2660                  */
2661                 tsx->mod_data[id] = e->body.tsx_state.src.tdata->mod_data[id];
2662                 break;
2663         case PJSIP_EVENT_RX_MSG:
2664                 cb = ast_sip_mod_data_get(tsx->mod_data, id, MOD_DATA_ON_RESPONSE);
2665                 /* As the PJSIP invite session implementation responds with a 200 OK before we have a
2666                  * chance to be invoked session supplements for BYE requests actually end up executing
2667                  * in the invite session state callback as well. To prevent session supplements from
2668                  * running on the BYE request again we explicitly squash invocation of them here.
2669                  */
2670                 if ((e->body.tsx_state.src.rdata->msg_info.msg->type != PJSIP_REQUEST_MSG) ||
2671                         (tsx->method.id != PJSIP_BYE_METHOD)) {
2672                         handle_incoming(session, e->body.tsx_state.src.rdata,
2673                                 AST_SIP_SESSION_AFTER_MEDIA);
2674                 }
2675                 if (tsx->method.id == PJSIP_INVITE_METHOD) {
2676                         if (tsx->role == PJSIP_ROLE_UAC) {
2677                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2678                                         /* This means we got a non 2XX final response to our outgoing INVITE */
2679                                         if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
2680                                                 reschedule_reinvite(session, cb);
2681                                                 return;
2682                                         }
2683                                         if (inv->state == PJSIP_INV_STATE_CONFIRMED) {
2684                                                 ast_debug(1, "reINVITE received final response code %d\n",
2685                                                         tsx->status_code);
2686                                                 if ((tsx->status_code == 401 || tsx->status_code == 407)
2687                                                         && !ast_sip_create_request_with_auth(
2688                                                                 &session->endpoint->outbound_auths,
2689                                                                 e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2690                                                         /* Send authed reINVITE */
2691                                                         ast_sip_session_send_request_with_cb(session, tdata, cb);
2692                                                         return;
2693                                                 }
2694                                                 if (tsx->status_code != 488) {
2695                                                         /* Other reinvite failures (except 488) result in destroying the session. */
2696                                                         if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS
2697                                                                 && tdata) {
2698                                                                 ast_sip_session_send_request(session, tdata);
2699                                                         }
2700                                                 }
2701                                         }
2702                                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2703                                         if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
2704                                                 int sdp_negotiation_done =
2705                                                         pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE;
2706
2707                                                 /*
2708                                                  * We can get here for the following reasons.
2709                                                  *
2710                                                  * 1) The race condition detailed in RFC5407 section 3.1.2.
2711                                                  * We sent a CANCEL at the same time that the UAS sent us a
2712                                                  * 200 OK with a valid SDP for the original INVITE.  As a
2713                                                  * result, we have now received a 200 OK for a cancelled
2714                                                  * call and the SDP negotiation is complete.  We need to
2715                                                  * immediately send a BYE to end the dialog.
2716                                                  *
2717                                                  * 2) We sent a CANCEL and hit the race condition but the
2718                                                  * UAS sent us an invalid SDP with the 200 OK.  In this case
2719                                                  * the SDP negotiation is incomplete and PJPROJECT has
2720                                                  * already sent the BYE for us because of the invalid SDP.
2721                                                  *
2722                                                  * 3) We didn't send a CANCEL but the UAS sent us an invalid
2723                                                  * SDP with the 200 OK.  In this case the SDP negotiation is
2724                                                  * incomplete and PJPROJECT has already sent the BYE for us
2725                                                  * because of the invalid SDP.
2726                                                  */
2727                                                 ast_test_suite_event_notify("PJSIP_SESSION_CANCELED",
2728                                                         "Endpoint: %s\r\n"
2729                                                         "Channel: %s\r\n"
2730                                                         "Message: %s\r\n"
2731                                                         "SDP: %s",
2732                                                         ast_sorcery_object_get_id(session->endpoint),
2733                                                         session->channel ? ast_channel_name(session->channel) : "",
2734                                                         pjsip_rx_data_get_info(e->body.tsx_state.src.rdata),
2735                                                         sdp_negotiation_done ? "complete" : "incomplete");
2736                                                 if (!sdp_negotiation_done) {
2737                                                         ast_debug(1, "Endpoint '%s(%s)': Incomplete SDP negotiation cancelled session.  %s\n",
2738                                                                 ast_sorcery_object_get_id(session->endpoint),
2739                                                                 session->channel ? ast_channel_name(session->channel) : "",
2740                                                                 pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));
2741                                                 } else if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS
2742                                                         && tdata) {
2743                                                         ast_debug(1, "Endpoint '%s(%s)': Ending session due to RFC5407 race condition.  %s\n",
2744                                                                 ast_sorcery_object_get_id(session->endpoint),
2745                                                                 session->channel ? ast_channel_name(session->channel) : "",
2746                                                                 pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));
2747                                                         ast_sip_session_send_request(session, tdata);
2748                                                 }
2749                                         }
2750                                 }
2751                         }
2752                 } else {
2753                         /* All other methods */
2754                         if (tsx->role == PJSIP_ROLE_UAC) {
2755                                 if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
2756                                         /* This means we got a final response to our outgoing method */
2757                                         ast_debug(1, "%.*s received final response code %d\n",
2758                                                 (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
2759                                                 tsx->status_code);
2760                                         if ((tsx->status_code == 401 || tsx->status_code == 407)
2761                                                 && !ast_sip_create_request_with_auth(
2762                                                         &session->endpoint->outbound_auths,
2763                                                         e->body.tsx_state.src.rdata, tsx->last_tx, &tdata)) {
2764                                                 /* Send authed version of the method */
2765                                                 ast_sip_session_send_request_with_cb(session, tdata, cb);
2766                                                 return;
2767                                         }
2768                                 }
2769                         }
2770                 }
2771                 if (cb) {
2772                         cb(session, e->body.tsx_state.src.rdata);
2773                 }
2774                 break;
2775         case PJSIP_EVENT_TRANSPORT_ERROR:
2776                 if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2777                         /*
2778                          * Clear the module data now to block session_inv_on_state_changed()
2779                          * from calling session_end() if it hasn't already done so.
2780                          */
2781                         inv->mod_data[id] = NULL;
2782
2783                         /*
2784                          * Pass the session ref held by session->inv_session to
2785                          * session_end_completion().
2786                          */
2787                         session_end_completion(session);
2788                         return;
2789                 }
2790                 break;
2791         case PJSIP_EVENT_TIMER:
2792                 /*
2793                  * The timer event is run by the pjsip monitor thread and not
2794                  * by the session serializer.
2795                  */
2796                 if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
2797                         /*
2798                          * We are locking because ast_sip_dialog_get_session() needs
2799                          * the dialog locked to get the session by other threads.
2800                          */
2801                         pjsip_dlg_inc_lock(inv->dlg);
2802                         session = inv->mod_data[id];
2803                         inv->mod_data[id] = NULL;
2804                         pjsip_dlg_dec_lock(inv->dlg);
2805
2806                         /*
2807                          * Pass the session ref held by session->inv_session to
2808                          * session_end_completion().
2809                          */
2810                         if (session
2811                                 && ast_sip_push_task(session->serializer, session_end_completion, session)) {
2812                                 /* Do it anyway even though this is not the right thread. */
2813                                 session_end_completion(session);
2814                         }
2815                         return;
2816                 }
2817                 break;
2818         case PJSIP_EVENT_USER:
2819         case PJSIP_EVENT_UNKNOWN:
2820         case PJSIP_EVENT_TSX_STATE:
2821                 /* Inception? */
2822                 break;
2823         }
2824
2825         if (AST_LIST_EMPTY(&session->delayed_requests)) {
2826                 /* No delayed request pending, so just return */
2827                 return;
2828         }
2829
2830         if (tsx->method.id == PJSIP_INVITE_METHOD) {
2831                 if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
2832                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2833                                 ast_sorcery_object_get_id(session->endpoint),
2834                                 session->channel ? ast_channel_name(session->channel) : "",
2835                                 pjsip_tsx_state_str(tsx->state));
2836                         check_delayed_requests(session, invite_proceeding);
2837                 } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
2838                         /*
2839                          * Terminated INVITE transactions always should result in
2840                          * queuing delayed requests, no matter what event caused
2841                          * the transaction to terminate.
2842                          */
2843                         ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
2844                                 ast_sorcery_object_get_id(session->endpoint),
2845                                 session->channel ? ast_channel_name(session->channel) : "",
2846                                 pjsip_tsx_state_str(tsx->state));
2847                         check_delayed_requests(session, invite_terminated);
2848                 }
2849         } else if (tsx->role == PJSIP_ROLE_UAC
2850                 && tsx->state == PJSIP_TSX_STATE_COMPLETED
2851                 && !pj_strcmp2(&tsx->method.name, "UPDATE")) {
2852                 ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",
2853                         ast_sorcery_object_get_id(session->endpoint),
2854                         session->channel ? ast_channel_name(session->channel) : "",
2855                         pjsip_tsx_state_str(tsx->state));
2856                 check_delayed_requests(session, update_completed);
2857         }
2858 }
2859
2860 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
2861 {
2862         struct ast_sip_session_media *session_media = obj;
2863         pjmedia_sdp_session *answer = arg;
2864         struct ast_sip_session *session = data;
2865         struct ast_sip_session_sdp_handler *handler = session_media->handler;
2866         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
2867         int res;
2868
2869         if (handler) {
2870                 /* if an already assigned handler reports a catastrophic error, fail */
2871                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2872                 if (res < 0) {
2873                         return 0;
2874                 }
2875                 return CMP_MATCH;
2876         }
2877
2878         handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
2879         if (!handler_list) {
2880                 return CMP_MATCH;
2881         }
2882
2883         /* no handler for this stream type and we have a list to search */
2884         AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
2885                 if (handler == session_media->handler) {
2886                         continue;
2887                 }
2888                 res = handler->create_outgoing_sdp_stream(session, session_media, answer);
2889                 if (res < 0) {
2890                         /* catastrophic error */
2891                         return 0;
2892                 }
2893                 if (res > 0) {
2894                         /* Handled by this handler. Move to the next stream */
2895                         session_media_set_handler(session_media, handler);
2896                         return CMP_MATCH;
2897                 }
2898         }
2899
2900         /* streams that weren't handled won't be included in generated outbound SDP */
2901         return CMP_MATCH;
2902 }
2903
2904 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
2905 {
2906         RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
2907         static const pj_str_t STR_IN = { "IN", 2 };
2908         static const pj_str_t STR_IP4 = { "IP4", 3 };
2909         static const pj_str_t STR_IP6 = { "IP6", 3 };
2910         pjmedia_sdp_session *local;
2911
2912         if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
2913                 return NULL;
2914         }
2915
2916         if (!offer) {
2917                 local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
2918         } else {
2919                 local->origin.version = offer->origin.version + 1;
2920                 local->origin.id = offer->origin.id;
2921         }
2922
2923         pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
2924         pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
2925
2926         /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
2927         successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
2928         if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
2929                 /* Something experienced a catastrophic failure */
2930                 return NULL;
2931         }
2932
2933         /* Use the connection details of the first media stream if possible for SDP level */
2934         if (local->media_count) {
2935                 int stream;
2936
2937                 /* Since we are using the first media stream as the SDP level we can get rid of it
2938                  * from the stream itself
2939                  */
2940                 local->conn = local->media[0]->conn;
2941                 local->media[0]->conn = NULL;
2942                 pj_strassign(&local->origin.net_type, &local->conn->net_type);
2943                 pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
2944                 pj_strassign(&local->origin.addr, &local->conn->addr);
2945
2946                 /* Go through each media stream seeing if the connection details actually differ,
2947                  * if not just use SDP level and reduce the SDP size
2948                  */
2949                 for (stream = 1; stream < local->media_count; stream++) {
2950                         if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
2951                                 !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
2952                                 !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
2953                                 local->media[stream]->conn = NULL;
2954                         }
2955                 }
2956         } else {
2957                 local->origin.net_type = STR_IN;
2958                 local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
2959
2960                 if (!ast_strlen_zero(session->endpoint->media.address)) {
2961                         pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
2962                 } else {
2963                         pj_strdup2(inv->pool_prov, &local->origin.addr, ast_sip_get_host_ip_string(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET()));
2964                 }
2965         }
2966
2967         return local;
2968 }
2969
2970 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
2971 {
2972         struct ast_sip_session *session = inv->mod_data[session_module.id];
2973         pjmedia_sdp_session *answer;
2974
2975         if (handle_incoming_sdp(session, offer)) {
2976                 return;
2977         }
2978
2979         if ((answer = create_local_sdp(inv, session, offer))) {
2980                 pjsip_inv_set_sdp_answer(inv, answer);
2981         }
2982 }
2983
2984 #if 0
2985 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
2986 {
2987         /* XXX STUB */
2988 }
2989 #endif
2990
2991 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
2992 {
2993         struct ast_sip_session *session = inv->mod_data[session_module.id];
2994         const pjmedia_sdp_session *local, *remote;
2995
2996         if (!session || !session->channel) {
2997                 /*
2998                  * If we don't have a session or channel then we really
2999                  * don't care about media updates.
3000                  * Just ignore
3001                  */
3002                 return;
3003         }
3004
3005         if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
3006                 (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
3007                 ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
3008                 ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
3009                 ast_queue_hangup(session->channel);
3010                 return;
3011         }
3012
3013         handle_negotiated_sdp(session, local, remote);
3014 }
3015
3016 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
3017 {
3018         struct ast_sip_session *session = inv->mod_data[session_module.id];
3019         const pjsip_sip_uri *uri;
3020
3021         if (!session->channel) {
3022                 return PJSIP_REDIRECT_STOP;
3023         }
3024
3025         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
3026                 return PJSIP_REDIRECT_ACCEPT;
3027         }
3028
3029         if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
3030                 return PJSIP_REDIRECT_STOP;
3031         }
3032
3033         handle_incoming(session, e->body.rx_msg.rdata, AST_SIP_SESSION_BEFORE_REDIRECTING);
3034
3035         uri = pjsip_uri_get_uri(target);
3036
3037         if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
3038                 char exten[AST_MAX_EXTENSION];
3039
3040                 ast_copy_pj_str(exten, &uri->user, sizeof(exten));
3041                 ast_channel_call_forward_set(session->channel, exten);
3042         } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
3043                 char target_uri[PJSIP_MAX_URL_SIZE];
3044                 /* PJSIP/ + endpoint length + / + max URL size */
3045                 char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
3046
3047                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
3048                 sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
3049                 ast_channel_call_forward_set(session->channel, forward);
3050         }
3051
3052         return PJSIP_REDIRECT_STOP;
3053 }
3054
3055 static pjsip_inv_callback inv_callback = {
3056         .on_state_changed = session_inv_on_state_changed,
3057         .on_new_session = session_inv_on_new_session,
3058         .on_tsx_state_changed = session_inv_on_tsx_state_changed,
3059         .on_rx_offer = session_inv_on_rx_offer,
3060         .on_media_update = session_inv_on_media_update,
3061         .on_redirected = session_inv_on_redirected,
3062 };
3063
3064 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
3065 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
3066 {
3067         RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);
3068         struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
3069                 tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
3070         struct pjmedia_sdp_session *sdp;
3071         int stream;
3072
3073         /* SDP produced by us directly will never be multipart */
3074         if (!transport_state || hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
3075                 pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
3076                 return;
3077         }
3078
3079         sdp = tdata->msg->body->data;
3080
3081         if (sdp->conn) {
3082                 char host[NI_MAXHOST];
3083                 struct ast_sockaddr addr = { { 0, } };
3084
3085                 ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
3086                 ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
3087
3088                 if (ast_apply_ha(transport_state->localnet, &addr) != AST_SENSE_ALLOW) {
3089                         pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
3090                 }
3091         }
3092
3093         for (stream = 0; stream < sdp->media_count; ++stream) {
3094                 /* See if there are registered handlers for this media stream type */
3095                 char media[20];
3096                 struct ast_sip_session_sdp_handler *handler;
3097                 RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
3098
3099                 /* We need a null-terminated version of the media string */
3100                 ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
3101
3102                 handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
3103                 if (!handler_list) {
3104                         ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
3105                         continue;
3106                 }
3107                 AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
3108                         if (handler->change_outgoing_sdp_stream_media_address) {
3109                                 handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
3110                         }
3111                 }
3112         }
3113
3114         /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
3115         ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
3116 }
3117
3118 static int load_module(void)
3119 {
3120         pjsip_endpoint *endpt;
3121
3122         CHECK_PJSIP_MODULE_LOADED();
3123
3124         if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
3125                 return AST_MODULE_LOAD_DECLINE;
3126         }
3127         if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
3128                 return AST_MODULE_LOAD_DECLINE;
3129         }
3130         nat_hook->outgoing_external_message = session_outgoing_nat_hook;
3131         ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
3132         sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
3133                         sdp_handler_list_hash, sdp_handler_list_cmp);
3134         if (!sdp_handlers) {
3135                 return AST_MODULE_LOAD_DECLINE;
3136         }
3137         endpt = ast_sip_get_pjsip_endpoint();
3138         pjsip_inv_usage_init(endpt, &inv_callback);
3139         pjsip_100rel_init_module(endpt);
3140         pjsip_timer_init_module(endpt);
3141         if (ast_sip_register_service(&session_module)) {
3142                 return AST_MODULE_LOAD_DECLINE;
3143         }
3144         ast_sip_register_service(&session_reinvite_module);
3145         ast_sip_register_service(&outbound_invite_auth_module);
3146
3147         ast_module_shutdown_ref(ast_module_info->self);
3148
3149         return AST_MODULE_LOAD_SUCCESS;
3150 }
3151
3152 static int unload_module(void)
3153 {
3154         ast_sip_unregister_service(&outbound_invite_auth_module);
3155         ast_sip_unregister_service(&session_reinvite_module);
3156         ast_sip_unregister_service(&session_module);
3157         ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
3158         ao2_cleanup(nat_hook);
3159         ao2_cleanup(sdp_handlers);
3160         return 0;
3161 }
3162
3163 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
3164         .support_level = AST_MODULE_SUPPORT_CORE,
3165         .load = load_module,
3166         .unload = unload_module,
3167         .load_pri = AST_MODPRI_APP_DEPEND,
3168 );