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