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