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