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