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