<p>Corey Farrell has uploaded this change for <strong>review</strong>.</p><p><a href="https://gerrit.asterisk.org/7925">View Change</a></p><pre style="font-family: monospace,monospace; white-space: pre-wrap;">res_pjsip_session: Move implementation to res_pjsip.so.<br><br>This reduces the changes of a crash during shutdown.  It is still<br>possible to have a crash between the calls to res_pjsip_unload and<br>pj_shutdown, though the time between those calls is now much shorter.<br><br>ASTERISK~27571<br><br>Change-Id: Ib76e156ec123477943153d903091406620a9c6ab<br>---<br>M res/res_pjsip.c<br>M res/res_pjsip.exports.in<br>M res/res_pjsip/include/res_pjsip_private.h<br>M res/res_pjsip/pjsip_session.c<br>M res/res_pjsip_session.c<br>5 files changed, 3,213 insertions(+), 3,185 deletions(-)<br><br></pre><pre style="font-family: monospace,monospace; white-space: pre-wrap;">git pull ssh://gerrit.asterisk.org:29418/asterisk refs/changes/25/7925/1</pre><pre style="font-family: monospace,monospace; white-space: pre-wrap;">diff --git a/res/res_pjsip.c b/res/res_pjsip.c<br>index 842cc20..8e948df 100644<br>--- a/res/res_pjsip.c<br>+++ b/res/res_pjsip.c<br>@@ -4654,6 +4654,7 @@<br>          * If they're not set, then there's nothing to clean up anyway.<br>        */<br>   if (ast_pjsip_endpoint && serializer_pool[0]) {<br>+              pjsip_session_unload();<br>               ast_res_pjsip_cleanup_options_handling();<br>             internal_sip_destroy_outbound_authentication();<br>               ast_res_pjsip_cleanup_message_filter();<br>diff --git a/res/res_pjsip.exports.in b/res/res_pjsip.exports.in<br>index 8b62abb..bb1205e 100644<br>--- a/res/res_pjsip.exports.in<br>+++ b/res/res_pjsip.exports.in<br>@@ -3,6 +3,7 @@<br>             LINKER_SYMBOL_PREFIXast_sip_*;<br>                LINKER_SYMBOL_PREFIXast_copy_pj_str;<br>          LINKER_SYMBOL_PREFIXast_pjsip_rdata_get_endpoint;<br>+            LINKER_SYMBOL_PREFIXres_pjsip_session_load*;<br>  local:<br>                *;<br> };<br>diff --git a/res/res_pjsip/include/res_pjsip_private.h b/res/res_pjsip/include/res_pjsip_private.h<br>index 151f598..0884cc4 100644<br>--- a/res/res_pjsip/include/res_pjsip_private.h<br>+++ b/res/res_pjsip/include/res_pjsip_private.h<br>@@ -419,4 +419,16 @@<br>  */<br> void internal_res_pjsip_unref(void);<br> <br>+/*!<br>+ * \internal<br>+ * \brief This is called by the res_pjsip_session load_module stub.<br>+ */<br>+int res_pjsip_session_load(void);<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Perform cleanup on res_pjsip/pjsip_session.c.<br>+ */<br>+int pjsip_session_unload(void);<br>+<br> #endif /* RES_PJSIP_PRIVATE_H_ */<br>diff --git a/res/res_pjsip/pjsip_session.c b/res/res_pjsip/pjsip_session.c<br>index 074ec4e..c1bf95c 100644<br>--- a/res/res_pjsip/pjsip_session.c<br>+++ b/res/res_pjsip/pjsip_session.c<br>@@ -25,10 +25,63 @@<br> #include "asterisk/res_pjsip.h"<br> #include "asterisk/res_pjsip_session.h"<br> #include "include/res_pjsip_private.h"<br>-#include "asterisk/linkedlists.h"<br>-#include "asterisk/lock.h"<br>+#include "asterisk/callerid.h"<br>+#include "asterisk/datastore.h"<br> #include "asterisk/module.h"<br>+#include "asterisk/linkedlists.h"<br>+#include "asterisk/logger.h"<br>+#include "asterisk/astobj2.h"<br>+#include "asterisk/lock.h"<br>+#include "asterisk/uuid.h"<br>+#include "asterisk/pbx.h"<br>+#include "asterisk/taskprocessor.h"<br>+#include "asterisk/causes.h"<br>+#include "asterisk/sdp_srtp.h"<br>+#include "asterisk/dsp.h"<br>+#include "asterisk/acl.h"<br>+#include "asterisk/features_config.h"<br>+#include "asterisk/pickup.h"<br>+#include "asterisk/test.h"<br> <br>+#define SDP_HANDLER_BUCKETS 11<br>+<br>+#define MOD_DATA_ON_RESPONSE "on_response"<br>+#define MOD_DATA_NAT_HOOK "nat_hook"<br>+<br>+<br>+/* Some forward declarations */<br>+static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata);<br>+static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>+         enum ast_sip_session_response_priority response_priority);<br>+static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>+               enum ast_sip_session_response_priority response_priority);<br>+static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);<br>+static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);<br>+<br>+/*! \brief NAT hook for modifying outgoing messages with SDP */<br>+static struct ast_sip_nat_hook *nat_hook;<br>+<br>+/*!<br>+ * \brief Registered SDP stream handlers<br>+ *<br>+ * This container is keyed on stream types. Each<br>+ * object in the container is a linked list of<br>+ * handlers for the stream type.<br>+ */<br>+static struct ao2_container *sdp_handlers;<br>+<br>+/*!<br>+ * These are the objects in the sdp_handlers container<br>+ */<br>+struct sdp_handler_list {<br>+      /* The list of handlers to visit */<br>+  AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;<br>+    /* The handlers in this list handle streams of this type */<br>+  char stream_type[1];<br>+};<br>+<br>+static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv,<br>+   struct ast_sip_session *session, const pjmedia_sdp_session *offer);<br> <br> AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);<br> <br>@@ -118,3 +171,3141 @@<br> <br>       return 0;<br> }<br>+<br>+static int sdp_handler_list_hash(const void *obj, int flags)<br>+{<br>+  const struct sdp_handler_list *handler_list = obj;<br>+   const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;<br>+<br>+       return ast_str_hash(stream_type);<br>+}<br>+<br>+static int sdp_handler_list_cmp(void *obj, void *arg, int flags)<br>+{<br>+      struct sdp_handler_list *handler_list1 = obj;<br>+        struct sdp_handler_list *handler_list2 = arg;<br>+        const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;<br>+<br>+     return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;<br>+}<br>+<br>+static int session_media_hash(const void *obj, int flags)<br>+{<br>+        const struct ast_sip_session_media *session_media = obj;<br>+     const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;<br>+<br>+      return ast_str_hash(stream_type);<br>+}<br>+<br>+static int session_media_cmp(void *obj, void *arg, int flags)<br>+{<br>+ struct ast_sip_session_media *session_media1 = obj;<br>+  struct ast_sip_session_media *session_media2 = arg;<br>+  const char *stream_type2 = flags & OBJ_KEY ? arg : session_media2->stream_type;<br>+<br>+    return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;<br>+}<br>+<br>+int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)<br>+{<br>+  RAII_VAR(struct sdp_handler_list *, handler_list,<br>+                    ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);<br>+  SCOPED_AO2LOCK(lock, sdp_handlers);<br>+<br>+       if (handler_list) {<br>+          struct ast_sip_session_sdp_handler *iter;<br>+            /* Check if this handler is already registered for this stream type */<br>+               AST_LIST_TRAVERSE(&handler_list->list, iter, next) {<br>+                  if (!strcmp(iter->id, handler->id)) {<br>+                          ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);<br>+                              return -1;<br>+                   }<br>+            }<br>+            AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);<br>+             ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>+            internal_res_pjsip_ref();<br>+            return 0;<br>+    }<br>+<br>+ /* No stream of this type has been registered yet, so we need to create a new list */<br>+        handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);<br>+ if (!handler_list) {<br>+         return -1;<br>+   }<br>+    /* Safe use of strcpy */<br>+     strcpy(handler_list->stream_type, stream_type);<br>+   AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);<br>+       AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);<br>+     if (!ao2_link(sdp_handlers, handler_list)) {<br>+         return -1;<br>+   }<br>+    ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>+    internal_res_pjsip_ref();<br>+    return 0;<br>+}<br>+<br>+static int remove_handler(void *obj, void *arg, void *data, int flags)<br>+{<br>+        struct sdp_handler_list *handler_list = obj;<br>+ struct ast_sip_session_sdp_handler *handler = data;<br>+  struct ast_sip_session_sdp_handler *iter;<br>+    const char *stream_type = arg;<br>+<br>+    AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {<br>+               if (!strcmp(iter->id, handler->id)) {<br>+                  AST_LIST_REMOVE_CURRENT(next);<br>+                       ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>+                  internal_res_pjsip_unref();<br>+          }<br>+    }<br>+    AST_LIST_TRAVERSE_SAFE_END;<br>+<br>+       if (AST_LIST_EMPTY(&handler_list->list)) {<br>+            ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);<br>+                return CMP_MATCH;<br>+    } else {<br>+             return CMP_STOP;<br>+     }<br>+}<br>+<br>+void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)<br>+{<br>+     ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);<br>+}<br>+<br>+/*!<br>+ * \brief Set an SDP stream handler for a corresponding session media.<br>+ *<br>+ * \note Always use this function to set the SDP handler for a session media.<br>+ *<br>+ * This function will properly free resources on the SDP handler currently being<br>+ * used by the session media, then set the session media to use the new SDP<br>+ * handler.<br>+ */<br>+static void session_media_set_handler(struct ast_sip_session_media *session_media,<br>+          struct ast_sip_session_sdp_handler *handler)<br>+{<br>+     ast_assert(session_media->handler != handler);<br>+<br>+ if (session_media->handler) {<br>+             session_media->handler->stream_destroy(session_media);<br>+ }<br>+    session_media->handler = handler;<br>+}<br>+<br>+static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)<br>+{<br>+    int i;<br>+       int handled = 0;<br>+<br>+  if (session->inv_session && session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>+          ast_log(LOG_ERROR, "Failed to handle incoming SDP. Session has been already disconnected\n");<br>+              return -1;<br>+   }<br>+<br>+ for (i = 0; i < sdp->media_count; ++i) {<br>+               /* See if there are registered handlers for this media stream type */<br>+                char media[20];<br>+              struct ast_sip_session_sdp_handler *handler;<br>+         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>+                RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>+          int res;<br>+<br>+          /* We need a null-terminated version of the media string */<br>+          ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));<br>+<br>+              session_media = ao2_find(session->media, media, OBJ_KEY);<br>+         if (!session_media) {<br>+                        /* if the session_media doesn't exist, there weren't<br>+                  * any handlers at the time of its creation */<br>+                       continue;<br>+            }<br>+<br>+         if (session_media->handler) {<br>+                     handler = session_media->handler;<br>+                 ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",<br>+                          session_media->stream_type,<br>+                               session_media->handler->id);<br>+                   res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,<br>+                         sdp->media[i]);<br>+                   if (res < 0) {<br>+                            /* Catastrophic failure. Abort! */<br>+                           return -1;<br>+                   } else if (res > 0) {<br>+                             ast_debug(1, "Media stream '%s' handled by %s\n",<br>+                                  session_media->stream_type,<br>+                                       session_media->handler->id);<br>+                           /* Handled by this handler. Move to the next stream */<br>+                               handled = 1;<br>+                         continue;<br>+                    }<br>+            }<br>+<br>+         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>+               if (!handler_list) {<br>+                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>+                   continue;<br>+            }<br>+            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+                       if (handler == session_media->handler) {<br>+                          continue;<br>+                    }<br>+                    ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",<br>+                          session_media->stream_type,<br>+                               handler->id);<br>+                     res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,<br>+                         sdp->media[i]);<br>+                   if (res < 0) {<br>+                            /* Catastrophic failure. Abort! */<br>+                           return -1;<br>+                   }<br>+                    if (res > 0) {<br>+                            ast_debug(1, "Media stream '%s' handled by %s\n",<br>+                                  session_media->stream_type,<br>+                                       handler->id);<br>+                             /* Handled by this handler. Move to the next stream */<br>+                               session_media_set_handler(session_media, handler);<br>+                           handled = 1;<br>+                         break;<br>+                       }<br>+            }<br>+    }<br>+    if (!handled) {<br>+              return -1;<br>+   }<br>+    return 0;<br>+}<br>+<br>+struct handle_negotiated_sdp_cb {<br>+ struct ast_sip_session *session;<br>+     const pjmedia_sdp_session *local;<br>+    const pjmedia_sdp_session *remote;<br>+};<br>+<br>+static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)<br>+{<br>+     struct ast_sip_session_media *session_media = obj;<br>+   struct handle_negotiated_sdp_cb *callback_data = arg;<br>+        struct ast_sip_session *session = callback_data->session;<br>+ const pjmedia_sdp_session *local = callback_data->local;<br>+  const pjmedia_sdp_session *remote = callback_data->remote;<br>+        int i;<br>+<br>+    for (i = 0; i < local->media_count; ++i) {<br>+             /* See if there are registered handlers for this media stream type */<br>+                char media[20];<br>+              struct ast_sip_session_sdp_handler *handler;<br>+         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>+                int res;<br>+<br>+          if (!remote->media[i]) {<br>+                  continue;<br>+            }<br>+<br>+         /* We need a null-terminated version of the media string */<br>+          ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));<br>+<br>+            /* stream type doesn't match the one we're looking to fill */<br>+                if (strcasecmp(session_media->stream_type, media)) {<br>+                      continue;<br>+            }<br>+<br>+         handler = session_media->handler;<br>+         if (handler) {<br>+                       ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",<br>+                           session_media->stream_type,<br>+                               handler->id);<br>+                     res = handler->apply_negotiated_sdp_stream(session, session_media, local,<br>+                         local->media[i], remote, remote->media[i]);<br>+                    if (res >= 0) {<br>+                           ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",<br>+                                    session_media->stream_type,<br>+                                       handler->id);<br>+                             return CMP_MATCH;<br>+                    }<br>+                    return 0;<br>+            }<br>+<br>+         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>+               if (!handler_list) {<br>+                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>+                   continue;<br>+            }<br>+            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+                       if (handler == session_media->handler) {<br>+                          continue;<br>+                    }<br>+                    ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",<br>+                           session_media->stream_type,<br>+                               handler->id);<br>+                     res = handler->apply_negotiated_sdp_stream(session, session_media, local,<br>+                         local->media[i], remote, remote->media[i]);<br>+                    if (res < 0) {<br>+                            /* Catastrophic failure. Abort! */<br>+                           return 0;<br>+                    }<br>+                    if (res > 0) {<br>+                            ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",<br>+                                    session_media->stream_type,<br>+                                       handler->id);<br>+                             /* Handled by this handler. Move to the next stream */<br>+                               session_media_set_handler(session_media, handler);<br>+                           return CMP_MATCH;<br>+                    }<br>+            }<br>+    }<br>+<br>+ if (session_media->handler && session_media->handler->stream_stop) {<br>+                ast_debug(1, "Stopping SDP media stream '%s' as it is not currently negotiated\n",<br>+                 session_media->stream_type);<br>+              session_media->handler->stream_stop(session_media);<br>+    }<br>+<br>+ return CMP_MATCH;<br>+}<br>+<br>+static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)<br>+{<br>+        RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);<br>+     struct handle_negotiated_sdp_cb callback_data = {<br>+            .session = session,<br>+          .local = local,<br>+              .remote = remote,<br>+    };<br>+<br>+        successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);<br>+ if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {<br>+                /* Nothing experienced a catastrophic failure */<br>+             ast_queue_frame(session->channel, &ast_null_frame);<br>+           return 0;<br>+    }<br>+    return -1;<br>+}<br>+<br>+#define DATASTORE_BUCKETS 53<br>+#define MEDIA_BUCKETS 7<br>+<br>+static void session_datastore_destroy(void *obj)<br>+{<br>+ struct ast_datastore *datastore = obj;<br>+<br>+    /* Using the destroy function (if present) destroy the data */<br>+       if (datastore->info->destroy != NULL && datastore->data != NULL) {<br>+          datastore->info->destroy(datastore->data);<br>+          datastore->data = NULL;<br>+   }<br>+<br>+ ast_free((void *) datastore->uid);<br>+        datastore->uid = NULL;<br>+}<br>+<br>+struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)<br>+{<br>+ RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);<br>+      char uuid_buf[AST_UUID_STR_LEN];<br>+     const char *uid_ptr = uid;<br>+<br>+        if (!info) {<br>+         return NULL;<br>+ }<br>+<br>+ datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);<br>+        if (!datastore) {<br>+            return NULL;<br>+ }<br>+<br>+ datastore->info = info;<br>+   if (ast_strlen_zero(uid)) {<br>+          /* They didn't provide an ID so we'll provide one ourself */<br>+         uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));<br>+ }<br>+<br>+ datastore->uid = ast_strdup(uid_ptr);<br>+     if (!datastore->uid) {<br>+            return NULL;<br>+ }<br>+<br>+ ao2_ref(datastore, +1);<br>+      return datastore;<br>+}<br>+<br>+int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)<br>+{<br>+   ast_assert(datastore != NULL);<br>+       ast_assert(datastore->info != NULL);<br>+      ast_assert(ast_strlen_zero(datastore->uid) == 0);<br>+<br>+      if (!ao2_link(session->datastores, datastore)) {<br>+          return -1;<br>+   }<br>+    return 0;<br>+}<br>+<br>+struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)<br>+{<br>+        return ao2_find(session->datastores, name, OBJ_KEY);<br>+}<br>+<br>+void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)<br>+{<br>+        ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);<br>+}<br>+<br>+enum delayed_method {<br>+ DELAYED_METHOD_INVITE,<br>+       DELAYED_METHOD_UPDATE,<br>+       DELAYED_METHOD_BYE,<br>+};<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Convert delayed method enum value to a string.<br>+ * \since 13.3.0<br>+ *<br>+ * \param method Delayed method enum value to convert to a string.<br>+ *<br>+ * \return String value of delayed method.<br>+ */<br>+static const char *delayed_method2str(enum delayed_method method)<br>+{<br>+     const char *str = "<unknown>";<br>+<br>+    switch (method) {<br>+    case DELAYED_METHOD_INVITE:<br>+          str = "INVITE";<br>+            break;<br>+       case DELAYED_METHOD_UPDATE:<br>+          str = "UPDATE";<br>+            break;<br>+       case DELAYED_METHOD_BYE:<br>+             str = "BYE";<br>+               break;<br>+       }<br>+<br>+ return str;<br>+}<br>+<br>+/*!<br>+ * \brief Structure used for sending delayed requests<br>+ *<br>+ * Requests are typically delayed because the current transaction<br>+ * state of an INVITE. Once the pending INVITE transaction terminates,<br>+ * the delayed request will be sent<br>+ */<br>+struct ast_sip_session_delayed_request {<br>+    /*! Method of the request */<br>+ enum delayed_method method;<br>+  /*! Callback to call when the delayed request is created. */<br>+ ast_sip_session_request_creation_cb on_request_creation;<br>+     /*! Callback to call when the delayed request SDP is created */<br>+      ast_sip_session_sdp_creation_cb on_sdp_creation;<br>+     /*! Callback to call when the delayed request receives a response */<br>+ ast_sip_session_response_cb on_response;<br>+     /*! Whether to generate new SDP */<br>+   int generate_new_sdp;<br>+        AST_LIST_ENTRY(ast_sip_session_delayed_request) next;<br>+};<br>+<br>+static struct ast_sip_session_delayed_request *delayed_request_alloc(<br>+        enum delayed_method method,<br>+  ast_sip_session_request_creation_cb on_request_creation,<br>+     ast_sip_session_sdp_creation_cb on_sdp_creation,<br>+     ast_sip_session_response_cb on_response,<br>+     int generate_new_sdp)<br>+{<br>+    struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));<br>+<br>+    if (!delay) {<br>+                return NULL;<br>+ }<br>+    delay->method = method;<br>+   delay->on_request_creation = on_request_creation;<br>+ delay->on_sdp_creation = on_sdp_creation;<br>+ delay->on_response = on_response;<br>+ delay->generate_new_sdp = generate_new_sdp;<br>+       return delay;<br>+}<br>+<br>+static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)<br>+{<br>+   ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",<br>+            ast_sorcery_object_get_id(session->endpoint),<br>+             session->channel ? ast_channel_name(session->channel) : "",<br>+          delayed_method2str(delay->method));<br>+<br>+    switch (delay->method) {<br>+  case DELAYED_METHOD_INVITE:<br>+          ast_sip_session_refresh(session, delay->on_request_creation,<br>+                      delay->on_sdp_creation, delay->on_response,<br>+                    AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);<br>+          return 0;<br>+    case DELAYED_METHOD_UPDATE:<br>+          ast_sip_session_refresh(session, delay->on_request_creation,<br>+                      delay->on_sdp_creation, delay->on_response,<br>+                    AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);<br>+          return 0;<br>+    case DELAYED_METHOD_BYE:<br>+             ast_sip_session_terminate(session, 0);<br>+               return 0;<br>+    }<br>+    ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",<br>+               delayed_method2str(delay->method), delay->method);<br>+     return -1;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief The current INVITE transaction is in the PROCEEDING state.<br>+ * \since 13.3.0<br>+ *<br>+ * \param vsession Session object.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int invite_proceeding(void *vsession)<br>+{<br>+        struct ast_sip_session *session = vsession;<br>+  struct ast_sip_session_delayed_request *delay;<br>+       int found = 0;<br>+       int res = 0;<br>+<br>+      AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {<br>+               switch (delay->method) {<br>+          case DELAYED_METHOD_INVITE:<br>+                  break;<br>+               case DELAYED_METHOD_UPDATE:<br>+                  AST_LIST_REMOVE_CURRENT(next);<br>+                       res = send_delayed_request(session, delay);<br>+                  ast_free(delay);<br>+                     found = 1;<br>+                   break;<br>+               case DELAYED_METHOD_BYE:<br>+                     /* A BYE is pending so don't bother anymore. */<br>+                  found = 1;<br>+                   break;<br>+               }<br>+            if (found) {<br>+                 break;<br>+               }<br>+    }<br>+    AST_LIST_TRAVERSE_SAFE_END;<br>+<br>+       ao2_ref(session, -1);<br>+        return res;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief The current INVITE transaction is in the TERMINATED state.<br>+ * \since 13.3.0<br>+ *<br>+ * \param vsession Session object.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int invite_terminated(void *vsession)<br>+{<br>+       struct ast_sip_session *session = vsession;<br>+  struct ast_sip_session_delayed_request *delay;<br>+       int found = 0;<br>+       int res = 0;<br>+ int timer_running;<br>+<br>+        /* re-INVITE collision timer running? */<br>+     timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);<br>+<br>+    AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {<br>+               switch (delay->method) {<br>+          case DELAYED_METHOD_INVITE:<br>+                  if (!timer_running) {<br>+                                found = 1;<br>+                   }<br>+                    break;<br>+               case DELAYED_METHOD_UPDATE:<br>+          case DELAYED_METHOD_BYE:<br>+                     found = 1;<br>+                   break;<br>+               }<br>+            if (found) {<br>+                 AST_LIST_REMOVE_CURRENT(next);<br>+                       res = send_delayed_request(session, delay);<br>+                  ast_free(delay);<br>+                     break;<br>+               }<br>+    }<br>+    AST_LIST_TRAVERSE_SAFE_END;<br>+<br>+       ao2_ref(session, -1);<br>+        return res;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief INVITE collision timeout.<br>+ * \since 13.3.0<br>+ *<br>+ * \param vsession Session object.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int invite_collision_timeout(void *vsession)<br>+{<br>+ struct ast_sip_session *session = vsession;<br>+  int res;<br>+<br>+  if (session->inv_session->invite_tsx) {<br>+                /*<br>+            * INVITE transaction still active.  Let it send<br>+              * the collision re-INVITE when it terminates.<br>+                */<br>+          ao2_ref(session, -1);<br>+                res = 0;<br>+     } else {<br>+             res = invite_terminated(session);<br>+    }<br>+<br>+ return res;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief The current UPDATE transaction is in the COMPLETED state.<br>+ * \since 13.3.0<br>+ *<br>+ * \param vsession Session object.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int update_completed(void *vsession)<br>+{<br>+ struct ast_sip_session *session = vsession;<br>+  int res;<br>+<br>+  if (session->inv_session->invite_tsx) {<br>+                res = invite_proceeding(session);<br>+    } else {<br>+             res = invite_terminated(session);<br>+    }<br>+<br>+ return res;<br>+}<br>+<br>+static void check_delayed_requests(struct ast_sip_session *session,<br>+     int (*cb)(void *vsession))<br>+{<br>+       ao2_ref(session, +1);<br>+        if (ast_sip_push_task(session->serializer, cb, session)) {<br>+                ao2_ref(session, -1);<br>+        }<br>+}<br>+<br>+static int delay_request(struct ast_sip_session *session,<br>+ ast_sip_session_request_creation_cb on_request,<br>+      ast_sip_session_sdp_creation_cb on_sdp_creation,<br>+     ast_sip_session_response_cb on_response,<br>+     int generate_new_sdp,<br>+        enum delayed_method method)<br>+{<br>+      struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,<br>+                        on_request, on_sdp_creation, on_response, generate_new_sdp);<br>+<br>+      if (!delay) {<br>+                return -1;<br>+   }<br>+<br>+ if (method == DELAYED_METHOD_BYE) {<br>+          /* Send BYE as early as possible */<br>+          AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);<br>+        } else {<br>+             AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);<br>+        }<br>+    return 0;<br>+}<br>+<br>+static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)<br>+{<br>+     pjsip_inv_session *inv_session = session->inv_session;<br>+    const pjmedia_sdp_session *previous_sdp = NULL;<br>+<br>+   if (inv_session->neg) {<br>+           if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {<br>+                        pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);<br>+           } else {<br>+                     pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);<br>+            }<br>+    }<br>+    return create_local_sdp(inv_session, session, previous_sdp);<br>+}<br>+<br>+static void set_from_header(struct ast_sip_session *session)<br>+{<br>+       struct ast_party_id effective_id;<br>+    struct ast_party_id connected_id;<br>+    pj_pool_t *dlg_pool;<br>+ pjsip_fromto_hdr *dlg_info;<br>+  pjsip_name_addr *dlg_info_name_addr;<br>+ pjsip_sip_uri *dlg_info_uri;<br>+ int restricted;<br>+<br>+   if (!session->channel || session->saved_from_hdr) {<br>+            return;<br>+      }<br>+<br>+ /* We need to save off connected_id for RPID/PAI generation */<br>+       ast_party_id_init(&connected_id);<br>+        ast_channel_lock(session->channel);<br>+       effective_id = ast_channel_connected_effective_id(session->channel);<br>+      ast_party_id_copy(&connected_id, &effective_id);<br>+     ast_channel_unlock(session->channel);<br>+<br>+  restricted =<br>+         ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);<br>+<br>+  /* Now set up dlg->local.info so pjsip can correctly generate From */<br>+<br>+  dlg_pool = session->inv_session->dlg->pool;<br>+ dlg_info = session->inv_session->dlg->local.info;<br>+   dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;<br>+   dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);<br>+<br>+     if (session->endpoint->id.trust_outbound || !restricted) {<br>+             ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);<br>+     }<br>+<br>+ ast_party_id_free(&connected_id);<br>+<br>+     if (!ast_strlen_zero(session->endpoint->fromuser)) {<br>+           dlg_info_name_addr->display.ptr = NULL;<br>+           dlg_info_name_addr->display.slen = 0;<br>+             pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);<br>+ }<br>+<br>+ if (!ast_strlen_zero(session->endpoint->fromdomain)) {<br>+         pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);<br>+       }<br>+<br>+ /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */<br>+       session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);<br>+    ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);<br>+<br>+      /* In chan_sip, fromuser and fromdomain trump restricted so we only<br>+   * anonymize if they're not set.<br>+  */<br>+  if (restricted) {<br>+            /* fromuser doesn't provide a display name so we always set it */<br>+                pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");<br>+<br>+         if (ast_strlen_zero(session->endpoint->fromuser)) {<br>+                    pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");<br>+             }<br>+<br>+         if (ast_strlen_zero(session->endpoint->fromdomain)) {<br>+                  pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");<br>+             }<br>+    } else {<br>+             ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);<br>+    }<br>+}<br>+<br>+int ast_sip_session_refresh(struct ast_sip_session *session,<br>+             ast_sip_session_request_creation_cb on_request_creation,<br>+             ast_sip_session_sdp_creation_cb on_sdp_creation,<br>+             ast_sip_session_response_cb on_response,<br>+             enum ast_sip_session_refresh_method method, int generate_new_sdp)<br>+{<br>+        pjsip_inv_session *inv_session = session->inv_session;<br>+    pjmedia_sdp_session *new_sdp = NULL;<br>+ pjsip_tx_data *tdata;<br>+<br>+     if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>+         /* Don't try to do anything with a hung-up call */<br>+               ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",<br>+                              ast_sorcery_object_get_id(session->endpoint));<br>+            return 0;<br>+    }<br>+<br>+ /* If the dialog has not yet been established we have to defer until it has */<br>+       if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {<br>+               ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",<br>+                   ast_sorcery_object_get_id(session->endpoint));<br>+            return delay_request(session, on_request_creation, on_sdp_creation, on_response,<br>+                     generate_new_sdp,<br>+                    method == AST_SIP_SESSION_REFRESH_METHOD_INVITE<br>+                              ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);<br>+    }<br>+<br>+ if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {<br>+               if (inv_session->invite_tsx) {<br>+                    /* We can't send a reinvite yet, so delay it */<br>+                  ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",<br>+                                       ast_sorcery_object_get_id(session->endpoint));<br>+                    return delay_request(session, on_request_creation, on_sdp_creation,<br>+                          on_response, generate_new_sdp, DELAYED_METHOD_INVITE);<br>+               } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {<br>+                     /* Initial INVITE transaction failed to progress us to a confirmed state<br>+                      * which means re-invites are not possible<br>+                    */<br>+                  ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",<br>+                                     ast_sorcery_object_get_id(session->endpoint));<br>+                    return 0;<br>+            }<br>+    }<br>+<br>+ if (generate_new_sdp) {<br>+              /* SDP can only be generated if current negotiation has already completed */<br>+         if (inv_session->neg<br>+                      && pjmedia_sdp_neg_get_state(inv_session->neg)<br>+                            != PJMEDIA_SDP_NEG_STATE_DONE) {<br>+                     ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",<br>+                              ast_sorcery_object_get_id(session->endpoint));<br>+                    return delay_request(session, on_request_creation, on_sdp_creation,<br>+                          on_response, generate_new_sdp,<br>+                               method == AST_SIP_SESSION_REFRESH_METHOD_INVITE<br>+                                      ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);<br>+            }<br>+<br>+         new_sdp = generate_session_refresh_sdp(session);<br>+             if (!new_sdp) {<br>+                      ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");<br>+                       return -1;<br>+           }<br>+            if (on_sdp_creation) {<br>+                       if (on_sdp_creation(session, new_sdp)) {<br>+                             return -1;<br>+                   }<br>+            }<br>+    }<br>+<br>+<br>+      if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {<br>+               if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {<br>+                    ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");<br>+                     return -1;<br>+           }<br>+    } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {<br>+               ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");<br>+               return -1;<br>+   }<br>+    if (on_request_creation) {<br>+           if (on_request_creation(session, tdata)) {<br>+                   return -1;<br>+           }<br>+    }<br>+    ast_debug(3, "Sending session refresh SDP via %s to %s\n",<br>+         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",<br>+                ast_sorcery_object_get_id(session->endpoint));<br>+    ast_sip_session_send_request_with_cb(session, tdata, on_response);<br>+   return 0;<br>+}<br>+<br>+int ast_sip_session_regenerate_answer(struct ast_sip_session *session,<br>+            ast_sip_session_sdp_creation_cb on_sdp_creation)<br>+{<br>+ pjsip_inv_session *inv_session = session->inv_session;<br>+    pjmedia_sdp_session *new_answer = NULL;<br>+      const pjmedia_sdp_session *previous_offer = NULL;<br>+<br>+ /* The SDP answer can only be regenerated if it is still pending to be sent */<br>+       if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&<br>+         pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {<br>+                ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",<br>+                  ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));<br>+           return -1;<br>+   }<br>+<br>+ pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);<br>+    if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {<br>+             /* Transition the SDP negotiator back to when it received the remote offer */<br>+                pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);<br>+             pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);<br>+ }<br>+<br>+ new_answer = create_local_sdp(inv_session, session, previous_offer);<br>+ if (!new_answer) {<br>+           ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",<br>+                 ast_channel_name(session->channel));<br>+              return -1;<br>+   }<br>+<br>+ if (on_sdp_creation) {<br>+               if (on_sdp_creation(session, new_answer)) {<br>+                  return -1;<br>+           }<br>+    }<br>+<br>+ pjsip_inv_set_sdp_answer(inv_session, new_answer);<br>+<br>+        return 0;<br>+}<br>+<br>+void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>+{<br>+     handle_outgoing_response(session, tdata);<br>+    pjsip_inv_send_msg(session->inv_session, tdata);<br>+  return;<br>+}<br>+<br>+static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);<br>+<br>+static pjsip_module session_module = {<br>+   .name = {"Session Module", 14},<br>+    .priority = PJSIP_MOD_PRIORITY_APPLICATION,<br>+  .on_rx_request = session_on_rx_request,<br>+};<br>+<br>+/*! \brief Determine whether the SDP provided requires deferral of negotiating or not<br>+ *<br>+ * \retval 1 re-invite should be deferred and resumed later<br>+ * \retval 0 re-invite should not be deferred<br>+ */<br>+static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)<br>+{<br>+     int i;<br>+<br>+    for (i = 0; i < sdp->media_count; ++i) {<br>+               /* See if there are registered handlers for this media stream type */<br>+                char media[20];<br>+              struct ast_sip_session_sdp_handler *handler;<br>+         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>+                RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>+          enum ast_sip_session_sdp_stream_defer res;<br>+<br>+                /* We need a null-terminated version of the media string */<br>+          ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));<br>+<br>+              session_media = ao2_find(session->media, media, OBJ_KEY);<br>+         if (!session_media) {<br>+                        /* if the session_media doesn't exist, there weren't<br>+                  * any handlers at the time of its creation */<br>+                       continue;<br>+            }<br>+<br>+         if (session_media->handler) {<br>+                     handler = session_media->handler;<br>+                 if (handler->defer_incoming_sdp_stream) {<br>+                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,<br>+                                     sdp->media[i]);<br>+                           switch (res) {<br>+                               case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:<br>+                                  break;<br>+                               case AST_SIP_SESSION_SDP_DEFER_ERROR:<br>+                                        return 0;<br>+                            case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:<br>+                                   break;<br>+                               case AST_SIP_SESSION_SDP_DEFER_NEEDED:<br>+                                       return 1;<br>+                            }<br>+                    }<br>+                    /* Handled by this handler. Move to the next stream */<br>+                       continue;<br>+            }<br>+<br>+         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>+               if (!handler_list) {<br>+                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>+                   continue;<br>+            }<br>+            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+                       if (handler == session_media->handler) {<br>+                          continue;<br>+                    }<br>+                    if (!handler->defer_incoming_sdp_stream) {<br>+                                continue;<br>+                    }<br>+                    res = handler->defer_incoming_sdp_stream(session, session_media, sdp,<br>+                             sdp->media[i]);<br>+                   switch (res) {<br>+                       case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:<br>+                          continue;<br>+                    case AST_SIP_SESSION_SDP_DEFER_ERROR:<br>+                                session_media_set_handler(session_media, handler);<br>+                           return 0;<br>+                    case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:<br>+                           /* Handled by this handler. */<br>+                               session_media_set_handler(session_media, handler);<br>+                           break;<br>+                       case AST_SIP_SESSION_SDP_DEFER_NEEDED:<br>+                               /* Handled by this handler. */<br>+                               session_media_set_handler(session_media, handler);<br>+                           return 1;<br>+                    }<br>+                    /* Move to the next stream */<br>+                        break;<br>+               }<br>+    }<br>+    return 0;<br>+}<br>+<br>+static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)<br>+{<br>+ pjsip_dialog *dlg;<br>+   RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>+      pjsip_rdata_sdp_info *sdp_info;<br>+<br>+   if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||<br>+          !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||<br>+             !(session = ast_sip_dialog_get_session(dlg)) ||<br>+              !session->channel) {<br>+              return PJ_FALSE;<br>+     }<br>+<br>+ if (session->deferred_reinvite) {<br>+         pj_str_t key, deferred_key;<br>+          pjsip_tx_data *tdata;<br>+<br>+             /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */<br>+               pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);<br>+              pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,<br>+                     session->deferred_reinvite);<br>+<br>+           /* If this is a retransmission ignore it */<br>+          if (!pj_strcmp(&key, &deferred_key)) {<br>+                       return PJ_TRUE;<br>+              }<br>+<br>+         /* Otherwise this is a new re-invite, so reject it */<br>+                if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {<br>+                    pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);<br>+          }<br>+<br>+         return PJ_TRUE;<br>+      }<br>+<br>+ if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||<br>+         (sdp_info->sdp_err != PJ_SUCCESS)) {<br>+              return PJ_FALSE;<br>+     }<br>+<br>+ if (!sdp_info->sdp) {<br>+             const pjmedia_sdp_session *local;<br>+            int i;<br>+<br>+            ast_queue_unhold(session->channel);<br>+<br>+            pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);<br>+               if (!local) {<br>+                        return PJ_FALSE;<br>+             }<br>+<br>+         /*<br>+            * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).<br>+              * When hold is initially indicated, we<br>+               * - Receive an INVITE with no SDP<br>+            * - Send a 200 OK with SDP, indicating sendrecv in the media streams<br>+                 * - Receive an ACK with SDP, indicating sendonly in the media streams<br>+                *<br>+            * At this point, the pjmedia negotiator saves the state of the media direction so that<br>+               * if we are to send any offers, we'll offer recvonly in the media streams. This is<br>+               * problematic if the device is attempting to unhold, though. If the device unholds<br>+           * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.<br>+               * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond<br>+               * with sendonly or inactive. The result of this is that the stream is not off hold.<br>+          *<br>+            * Therefore, in this case, when we receive a reinvite while the stream is on hold, we<br>+                * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv<br>+                * in order to get the stream off hold. If this is actually a different purpose reinvite<br>+              * (like a session timer refresh), then the answerer can respond to our sendrecv with<br>+                 * sendonly, keeping the stream on hold.<br>+              */<br>+          for (i = 0; i < local->media_count; ++i) {<br>+                     pjmedia_sdp_media *m = local->media[i];<br>+                   pjmedia_sdp_attr *recvonly;<br>+                  pjmedia_sdp_attr *inactive;<br>+<br>+                       recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);<br>+                 inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);<br>+                 if (recvonly || inactive) {<br>+                          pjmedia_sdp_attr *to_remove = recvonly ?: inactive;<br>+                          pjmedia_sdp_attr *sendrecv;<br>+<br>+                               pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);<br>+<br>+                            sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);<br>+                            pjmedia_sdp_media_add_attr(m, sendrecv);<br>+                     }<br>+            }<br>+<br>+         return PJ_FALSE;<br>+     }<br>+<br>+ if (!sdp_requires_deferral(session, sdp_info->sdp)) {<br>+             return PJ_FALSE;<br>+     }<br>+<br>+ pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);<br>+<br>+        return PJ_TRUE;<br>+}<br>+<br>+void ast_sip_session_resume_reinvite(struct ast_sip_session *session)<br>+{<br>+   if (!session->deferred_reinvite) {<br>+                return;<br>+      }<br>+<br>+ if (session->channel) {<br>+           pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),<br>+                    session->deferred_reinvite, NULL, NULL);<br>+  }<br>+    pjsip_rx_data_free_cloned(session->deferred_reinvite);<br>+    session->deferred_reinvite = NULL;<br>+}<br>+<br>+static pjsip_module session_reinvite_module = {<br>+       .name = { "Session Re-Invite Module", 24 },<br>+        .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,<br>+   .on_rx_request = session_reinvite_on_rx_request,<br>+};<br>+<br>+<br>+void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,<br>+               ast_sip_session_response_cb on_response)<br>+{<br>+ pjsip_inv_session *inv_session = session->inv_session;<br>+<br>+ /* For every request except BYE we disallow sending of the message when<br>+       * the session has been disconnected. A BYE request is special though<br>+         * because it can be sent again after the session is disconnected except<br>+      * with credentials.<br>+  */<br>+  if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&<br>+         tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {<br>+          return;<br>+      }<br>+<br>+ ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,<br>+                       MOD_DATA_ON_RESPONSE, on_response);<br>+<br>+  handle_outgoing_request(session, tdata);<br>+     pjsip_inv_send_msg(session->inv_session, tdata);<br>+<br>+       return;<br>+}<br>+<br>+void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>+{<br>+        ast_sip_session_send_request_with_cb(session, tdata, NULL);<br>+}<br>+<br>+int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)<br>+{<br>+   pjmedia_sdp_session *offer;<br>+<br>+       if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {<br>+           pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);<br>+         return -1;<br>+   }<br>+<br>+ pjsip_inv_set_local_sdp(session->inv_session, offer);<br>+     pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);<br>+#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS<br>+    pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);<br>+#endif<br>+<br>+    /*<br>+    * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the<br>+      * From in the initial INVITE will be wrong but the rest of the messages will be OK.<br>+  */<br>+  set_from_header(session);<br>+<br>+ if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {<br>+                return -1;<br>+   }<br>+<br>+ return 0;<br>+}<br>+<br>+static int datastore_hash(const void *obj, int flags)<br>+{<br>+ const struct ast_datastore *datastore = obj;<br>+ const char *uid = flags & OBJ_KEY ? obj : datastore->uid;<br>+<br>+  ast_assert(uid != NULL);<br>+<br>+  return ast_str_hash(uid);<br>+}<br>+<br>+static int datastore_cmp(void *obj, void *arg, int flags)<br>+{<br>+     const struct ast_datastore *datastore1 = obj;<br>+        const struct ast_datastore *datastore2 = arg;<br>+        const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;<br>+<br>+        ast_assert(datastore1->uid != NULL);<br>+      ast_assert(uid2 != NULL);<br>+<br>+ return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;<br>+}<br>+<br>+static void session_media_dtor(void *obj)<br>+{<br>+   struct ast_sip_session_media *session_media = obj;<br>+   struct sdp_handler_list *handler_list;<br>+       /* It is possible for SDP handlers to allocate memory on a session_media but<br>+  * not end up getting set as the handler for this session_media. This traversal<br>+       * ensures that all memory allocated by SDP handlers on the session_media is<br>+  * cleared (as well as file descriptors, etc.).<br>+       */<br>+  handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);<br>+       if (handler_list) {<br>+          struct ast_sip_session_sdp_handler *handler;<br>+<br>+              AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+                       handler->stream_destroy(session_media);<br>+           }<br>+    }<br>+    ao2_cleanup(handler_list);<br>+   if (session_media->srtp) {<br>+                ast_sdp_srtp_destroy(session_media->srtp);<br>+        }<br>+}<br>+<br>+static void session_destructor(void *obj)<br>+{<br>+     struct ast_sip_session *session = obj;<br>+       struct ast_sip_session_supplement *supplement;<br>+       struct ast_sip_session_delayed_request *delay;<br>+       const char *endpoint_name = session->endpoint ?<br>+           ast_sorcery_object_get_id(session->endpoint) : "<none>";<br>+<br>+       ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);<br>+<br>+       ast_test_suite_event_notify("SESSION_DESTROYING",<br>+          "Endpoint: %s\r\n"<br>+         "AOR: %s\r\n"<br>+              "Contact: %s"<br>+              , endpoint_name<br>+              , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"<br>+            , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"<br>+            );<br>+<br>+        while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {<br>+            if (supplement->session_destroy) {<br>+                        supplement->session_destroy(session);<br>+             }<br>+            ast_free(supplement);<br>+        }<br>+<br>+ ast_taskprocessor_unreference(session->serializer);<br>+       ao2_cleanup(session->datastores);<br>+ ao2_cleanup(session->media);<br>+<br>+   AST_LIST_HEAD_DESTROY(&session->supplements);<br>+ while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {<br>+            ast_free(delay);<br>+     }<br>+    ast_party_id_free(&session->id);<br>+      ao2_cleanup(session->endpoint);<br>+   ao2_cleanup(session->aor);<br>+        ao2_cleanup(session->contact);<br>+    ao2_cleanup(session->req_caps);<br>+   ao2_cleanup(session->direct_media_cap);<br>+<br>+        ast_dsp_free(session->dsp);<br>+<br>+    if (session->inv_session) {<br>+               pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);<br>+ }<br>+<br>+ ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);<br>+}<br>+<br>+static int add_session_media(void *obj, void *arg, int flags)<br>+{<br>+      struct sdp_handler_list *handler_list = obj;<br>+ struct ast_sip_session *session = arg;<br>+       RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>+<br>+       session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);<br>+        if (!session_media) {<br>+                return CMP_STOP;<br>+     }<br>+    session_media->encryption = session->endpoint->media.rtp.encryption;<br>+        session_media->keepalive_sched_id = -1;<br>+   session_media->timeout_sched_id = -1;<br>+     /* Safe use of strcpy */<br>+     strcpy(session_media->stream_type, handler_list->stream_type);<br>+ ao2_link(session->media, session_media);<br>+  return 0;<br>+}<br>+<br>+/*! \brief Destructor for SIP channel */<br>+static void sip_channel_destroy(void *obj)<br>+{<br>+ struct ast_sip_channel_pvt *channel = obj;<br>+<br>+        ao2_cleanup(channel->pvt);<br>+        ao2_cleanup(channel->session);<br>+}<br>+<br>+struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)<br>+{<br>+     struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);<br>+<br>+   if (!channel) {<br>+              return NULL;<br>+ }<br>+<br>+ ao2_ref(pvt, +1);<br>+    channel->pvt = pvt;<br>+       ao2_ref(session, +1);<br>+        channel->session = session;<br>+<br>+    return channel;<br>+}<br>+<br>+struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,<br>+    struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)<br>+{<br>+   RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>+      struct ast_sip_session *ret_session;<br>+ struct ast_sip_session_supplement *iter;<br>+     int dsp_features = 0;<br>+<br>+     session = ao2_alloc(sizeof(*session), session_destructor);<br>+   if (!session) {<br>+              return NULL;<br>+ }<br>+<br>+ AST_LIST_HEAD_INIT(&session->supplements);<br>+    AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);<br>+        ast_party_id_init(&session->id);<br>+<br>+   session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>+    if (!session->direct_media_cap) {<br>+         return NULL;<br>+ }<br>+    session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>+    if (!session->req_caps) {<br>+         return NULL;<br>+ }<br>+    session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);<br>+      if (!session->datastores) {<br>+               return NULL;<br>+ }<br>+<br>+ if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {<br>+            dsp_features |= DSP_FEATURE_DIGIT_DETECT;<br>+    }<br>+    if (endpoint->faxdetect) {<br>+                dsp_features |= DSP_FEATURE_FAX_DETECT;<br>+      }<br>+    if (dsp_features) {<br>+          session->dsp = ast_dsp_new();<br>+             if (!session->dsp) {<br>+                      return NULL;<br>+         }<br>+<br>+         ast_dsp_set_features(session->dsp, dsp_features);<br>+ }<br>+<br>+ session->endpoint = ao2_bump(endpoint);<br>+<br>+        session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);<br>+       if (!session->media) {<br>+            return NULL;<br>+ }<br>+    /* fill session->media with available types */<br>+    ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);<br>+<br>+       if (rdata) {<br>+         /*<br>+            * We must continue using the serializer that the original<br>+            * INVITE came in on for the dialog.  There may be<br>+            * retransmissions already enqueued in the original<br>+           * serializer that can result in reentrancy and message<br>+               * sequencing problems.<br>+               */<br>+          session->serializer = ast_sip_get_distributor_serializer(rdata);<br>+  } else {<br>+             char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];<br>+<br>+            /* Create name with seq number appended. */<br>+          ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",<br>+                       ast_sorcery_object_get_id(endpoint));<br>+<br>+             session->serializer = ast_sip_create_serializer_named(tps_name);<br>+  }<br>+    if (!session->serializer) {<br>+               return NULL;<br>+ }<br>+    ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);<br>+  ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);<br>+  pjsip_dlg_inc_session(inv_session->dlg, &session_module);<br>+     inv_session->mod_data[session_module.id] = ao2_bump(session);<br>+     session->contact = ao2_bump(contact);<br>+     session->inv_session = inv_session;<br>+<br>+    session->dtmf = endpoint->dtmf;<br>+<br>+     if (ast_sip_session_add_supplements(session)) {<br>+              /* Release the ref held by session->inv_session */<br>+                ao2_ref(session, -1);<br>+                return NULL;<br>+ }<br>+    AST_LIST_TRAVERSE(&session->supplements, iter, next) {<br>+                if (iter->session_begin) {<br>+                        iter->session_begin(session);<br>+             }<br>+    }<br>+<br>+ /* Avoid unnecessary ref manipulation to return a session */<br>+ ret_session = session;<br>+       session = NULL;<br>+      return ret_session;<br>+}<br>+<br>+/*! \brief struct controlling the suspension of the session's serializer. */<br>+struct ast_sip_session_suspender {<br>+   ast_cond_t cond_suspended;<br>+   ast_cond_t cond_complete;<br>+    int suspended;<br>+       int complete;<br>+};<br>+<br>+static void sip_session_suspender_dtor(void *vdoomed)<br>+{<br>+    struct ast_sip_session_suspender *doomed = vdoomed;<br>+<br>+       ast_cond_destroy(&doomed->cond_suspended);<br>+    ast_cond_destroy(&doomed->cond_complete);<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Block the session serializer thread task.<br>+ *<br>+ * \param data Pushed serializer task data for suspension.<br>+ *<br>+ * \retval 0<br>+ */<br>+static int sip_session_suspend_task(void *data)<br>+{<br>+ struct ast_sip_session_suspender *suspender = data;<br>+<br>+       ao2_lock(suspender);<br>+<br>+      /* Signal that the serializer task is now suspended. */<br>+      suspender->suspended = 1;<br>+ ast_cond_signal(&suspender->cond_suspended);<br>+<br>+       /* Wait for the serializer suspension to be completed. */<br>+    while (!suspender->complete) {<br>+            ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));<br>+ }<br>+<br>+ ao2_unlock(suspender);<br>+       ao2_ref(suspender, -1);<br>+<br>+   return 0;<br>+}<br>+<br>+void ast_sip_session_suspend(struct ast_sip_session *session)<br>+{<br>+ struct ast_sip_session_suspender *suspender;<br>+ int res;<br>+<br>+  ast_assert(session->suspended == NULL);<br>+<br>+        if (ast_taskprocessor_is_task(session->serializer)) {<br>+             /* I am the session's serializer thread so I cannot suspend. */<br>+          return;<br>+      }<br>+<br>+ if (ast_taskprocessor_is_suspended(session->serializer)) {<br>+                /* The serializer already suspended. */<br>+              return;<br>+      }<br>+<br>+ suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);<br>+       if (!suspender) {<br>+            /* We will just have to hope that the system does not deadlock */<br>+            return;<br>+      }<br>+    ast_cond_init(&suspender->cond_suspended, NULL);<br>+      ast_cond_init(&suspender->cond_complete, NULL);<br>+<br>+    ao2_ref(suspender, +1);<br>+      res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);<br>+        if (res) {<br>+           /* We will just have to hope that the system does not deadlock */<br>+            ao2_ref(suspender, -2);<br>+              return;<br>+      }<br>+<br>+ session->suspended = suspender;<br>+<br>+        /* Wait for the serializer to get suspended. */<br>+      ao2_lock(suspender);<br>+ while (!suspender->suspended) {<br>+           ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));<br>+        }<br>+    ao2_unlock(suspender);<br>+<br>+    ast_taskprocessor_suspend(session->serializer);<br>+}<br>+<br>+void ast_sip_session_unsuspend(struct ast_sip_session *session)<br>+{<br>+      struct ast_sip_session_suspender *suspender = session->suspended;<br>+<br>+      if (!suspender) {<br>+            /* Nothing to do */<br>+          return;<br>+      }<br>+    session->suspended = NULL;<br>+<br>+     /* Signal that the serializer task suspension is now complete. */<br>+    ao2_lock(suspender);<br>+ suspender->complete = 1;<br>+  ast_cond_signal(&suspender->cond_complete);<br>+   ao2_unlock(suspender);<br>+<br>+    ao2_ref(suspender, -1);<br>+<br>+   ast_taskprocessor_unsuspend(session->serializer);<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Handle initial INVITE challenge response message.<br>+ * \since 13.5.0<br>+ *<br>+ * \param rdata PJSIP receive response message data.<br>+ *<br>+ * \retval PJ_FALSE Did not handle message.<br>+ * \retval PJ_TRUE Handled message.<br>+ */<br>+static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)<br>+{<br>+       pjsip_transaction *tsx;<br>+      pjsip_dialog *dlg;<br>+   pjsip_inv_session *inv;<br>+      pjsip_tx_data *tdata;<br>+        struct ast_sip_session *session;<br>+<br>+  if (rdata->msg_info.msg->line.status.code != 401<br>+               && rdata->msg_info.msg->line.status.code != 407) {<br>+             /* Doesn't pertain to us. Move on */<br>+             return PJ_FALSE;<br>+     }<br>+<br>+ tsx = pjsip_rdata_get_tsx(rdata);<br>+    dlg = pjsip_rdata_get_dlg(rdata);<br>+    if (!dlg || !tsx) {<br>+          return PJ_FALSE;<br>+     }<br>+<br>+ if (tsx->method.id != PJSIP_INVITE_METHOD) {<br>+              /* Not an INVITE that needs authentication */<br>+                return PJ_FALSE;<br>+     }<br>+<br>+ inv = pjsip_dlg_get_inv_session(dlg);<br>+        if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {<br>+         /*<br>+            * We cannot handle reINVITE authentication at this<br>+           * time because the reINVITE transaction is still in<br>+          * progress.<br>+          */<br>+          ast_debug(1, "A reINVITE is being challenged.\n");<br>+         return PJ_FALSE;<br>+     }<br>+    ast_debug(1, "Initial INVITE is being challenged.\n");<br>+<br>+  session = inv->mod_data[session_module.id];<br>+<br>+    if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata, tsx,<br>+               &tdata)) {<br>+               return PJ_FALSE;<br>+     }<br>+<br>+ /*<br>+    * Restart the outgoing initial INVITE transaction to deal<br>+    * with authentication.<br>+       */<br>+  pjsip_inv_uac_restart(inv, PJ_FALSE);<br>+<br>+     ast_sip_session_send_request(session, tdata);<br>+        return PJ_TRUE;<br>+}<br>+<br>+static pjsip_module outbound_invite_auth_module = {<br>+ .name = {"Outbound INVITE Auth", 20},<br>+      .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,<br>+ .on_rx_response = outbound_invite_auth,<br>+};<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Setup outbound initial INVITE authentication.<br>+ * \since 13.5.0<br>+ *<br>+ * \param dlg PJSIP dialog to attach outbound authentication.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int setup_outbound_invite_auth(pjsip_dialog *dlg)<br>+{<br>+        pj_status_t status;<br>+<br>+       ++dlg->sess_count;<br>+        status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);<br>+   --dlg->sess_count;<br>+<br>+     return status != PJ_SUCCESS ? -1 : 0;<br>+}<br>+<br>+struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,<br>+    struct ast_sip_contact *contact, const char *location, const char *request_user,<br>+     struct ast_format_cap *req_caps)<br>+{<br>+ const char *uri = NULL;<br>+      RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);<br>+        RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);<br>+        pjsip_timer_setting timer;<br>+   pjsip_dialog *dlg;<br>+   struct pjsip_inv_session *inv_session;<br>+       RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>+      struct ast_sip_session *ret_session;<br>+<br>+      /* If no location has been provided use the AOR list from the endpoint itself */<br>+     if (location || !contact) {<br>+          location = S_OR(location, endpoint->aors);<br>+<br>+             ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,<br>+                     &found_aor, &found_contact);<br>+         if (!found_contact || ast_strlen_zero(found_contact->uri)) {<br>+                      uri = location;<br>+              } else {<br>+                     uri = found_contact->uri;<br>+         }<br>+    } else {<br>+             uri = contact->uri;<br>+       }<br>+<br>+ /* If we still have no URI to dial fail to create the session */<br>+     if (ast_strlen_zero(uri)) {<br>+          ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",<br>+                  ast_sorcery_object_get_id(endpoint));<br>+                return NULL;<br>+ }<br>+<br>+ if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {<br>+               return NULL;<br>+ }<br>+<br>+ if (setup_outbound_invite_auth(dlg)) {<br>+               pjsip_dlg_terminate(dlg);<br>+            return NULL;<br>+ }<br>+<br>+ if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {<br>+                pjsip_dlg_terminate(dlg);<br>+            return NULL;<br>+ }<br>+#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)<br>+      inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;<br>+#endif<br>+<br>+      pjsip_timer_setting_default(&timer);<br>+     timer.min_se = endpoint->extensions.timer.min_se;<br>+ timer.sess_expires = endpoint->extensions.timer.sess_expires;<br>+     pjsip_timer_init_session(inv_session, &timer);<br>+<br>+        session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,<br>+           inv_session, NULL);<br>+  if (!session) {<br>+              pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>+             return NULL;<br>+ }<br>+    session->aor = ao2_bump(found_aor);<br>+       ast_party_id_copy(&session->id, &endpoint->id.self);<br>+<br>+        if (ast_format_cap_count(req_caps)) {<br>+                /* get joint caps between req_caps and endpoint caps */<br>+              struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>+<br>+            ast_format_cap_get_compatible(req_caps, endpoint->media.codecs, joint_caps);<br>+<br>+           /* if joint caps */<br>+          if (ast_format_cap_count(joint_caps)) {<br>+                      /* copy endpoint caps into session->req_caps */<br>+                   ast_format_cap_append_from_cap(session->req_caps,<br>+                         endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);<br>+                  /* replace instances of joint caps equivalents in session->req_caps */<br>+                    ast_format_cap_replace_from_cap(session->req_caps, joint_caps,<br>+                            AST_MEDIA_TYPE_UNKNOWN);<br>+             }<br>+            ao2_cleanup(joint_caps);<br>+     }<br>+<br>+ if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {<br>+             pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>+             /* Since we are not notifying ourselves that the INVITE session is being terminated<br>+           * we need to manually drop its reference to session<br>+          */<br>+          ao2_ref(session, -1);<br>+                return NULL;<br>+ }<br>+<br>+ /* Avoid unnecessary ref manipulation to return a session */<br>+ ret_session = session;<br>+       session = NULL;<br>+      return ret_session;<br>+}<br>+<br>+static int session_end(void *vsession);<br>+static int session_end_completion(void *vsession);<br>+<br>+void ast_sip_session_terminate(struct ast_sip_session *session, int response)<br>+{<br>+     pj_status_t status;<br>+  pjsip_tx_data *packet = NULL;<br>+<br>+     if (session->defer_terminate) {<br>+           session->terminate_while_deferred = 1;<br>+            return;<br>+      }<br>+<br>+ if (!response) {<br>+             response = 603;<br>+      }<br>+<br>+ switch (session->inv_session->state) {<br>+ case PJSIP_INV_STATE_NULL:<br>+           if (!session->inv_session->invite_tsx) {<br>+                       /*<br>+                    * Normally, it's pjproject's transaction cleanup that ultimately causes the<br>+                  * final session reference to be released but if both STATE and invite_tsx are NULL,<br>+                  * we never created a transaction in the first place.  In this case, we need to<br>+                       * do the cleanup ourselves.<br>+                  */<br>+                  /* Transfer the inv_session session reference to the session_end_task */<br>+                     session->inv_session->mod_data[session_module.id] = NULL;<br>+                      pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);<br>+                     session_end(session);<br>+                        /*<br>+                    * session_end_completion will cleanup the final session reference unless<br>+                     * ast_sip_session_terminate's caller is holding one.<br>+                     */<br>+                  session_end_completion(session);<br>+             } else {<br>+                     pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);<br>+             }<br>+            break;<br>+       case PJSIP_INV_STATE_CONFIRMED:<br>+              if (session->inv_session->invite_tsx) {<br>+                        ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",<br>+                                    ast_sorcery_object_get_id(session->endpoint));<br>+                    /* If this is delayed the only thing that will happen is a BYE request so we don't<br>+                        * actually need to store the response code for when it happens.<br>+                      */<br>+                  delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);<br>+                     break;<br>+               }<br>+            /* Fall through */<br>+   default:<br>+             status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);<br>+                if (status == PJ_SUCCESS && packet) {<br>+                        struct ast_sip_session_delayed_request *delay;<br>+<br>+                    /* Flush any delayed requests so they cannot overlap this transaction. */<br>+                    while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {<br>+                            ast_free(delay);<br>+                     }<br>+<br>+                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {<br>+                         ast_sip_session_send_response(session, packet);<br>+                      } else {<br>+                             ast_sip_session_send_request(session, packet);<br>+                       }<br>+            }<br>+            break;<br>+       }<br>+}<br>+<br>+static int session_termination_task(void *data)<br>+{<br>+       struct ast_sip_session *session = data;<br>+<br>+   if (session->defer_terminate) {<br>+           session->defer_terminate = 0;<br>+             if (session->inv_session) {<br>+                       ast_sip_session_terminate(session, 0);<br>+               }<br>+    }<br>+<br>+ ao2_ref(session, -1);<br>+        return 0;<br>+}<br>+<br>+static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)<br>+{<br>+ struct ast_sip_session *session = entry->user_data;<br>+<br>+    if (ast_sip_push_task(session->serializer, session_termination_task, session)) {<br>+          ao2_cleanup(session);<br>+        }<br>+}<br>+<br>+int ast_sip_session_defer_termination(struct ast_sip_session *session)<br>+{<br>+        pj_time_val delay = { .sec = 60, };<br>+  int res;<br>+<br>+  /* The session should not have an active deferred termination request. */<br>+    ast_assert(!session->defer_terminate);<br>+<br>+ session->defer_terminate = 1;<br>+<br>+  session->defer_end = 1;<br>+   session->ended_while_deferred = 0;<br>+<br>+     session->scheduled_termination.id = 0;<br>+    ao2_ref(session, +1);<br>+        session->scheduled_termination.user_data = session;<br>+       session->scheduled_termination.cb = session_termination_cb;<br>+<br>+    res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),<br>+              &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;<br>+ if (res) {<br>+           session->defer_terminate = 0;<br>+             ao2_ref(session, -1);<br>+        }<br>+    return res;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Stop the defer termination timer if it is still running.<br>+ * \since 13.5.0<br>+ *<br>+ * \param session Which session to stop the timer.<br>+ *<br>+ * \return Nothing<br>+ */<br>+static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)<br>+{<br>+        if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),<br>+           &session->scheduled_termination)) {<br>+           ao2_ref(session, -1);<br>+        }<br>+}<br>+<br>+void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)<br>+{<br>+        if (!session->defer_terminate) {<br>+          /* Already canceled or timer fired. */<br>+               return;<br>+      }<br>+<br>+ session->defer_terminate = 0;<br>+<br>+  if (session->terminate_while_deferred) {<br>+          /* Complete the termination started by the upper layer. */<br>+           ast_sip_session_terminate(session, 0);<br>+       }<br>+<br>+ /* Stop the termination timer if it is still running. */<br>+     sip_session_defer_termination_stop_timer(session);<br>+}<br>+<br>+void ast_sip_session_end_if_deferred(struct ast_sip_session *session)<br>+{<br>+        if (!session->defer_end) {<br>+                return;<br>+      }<br>+<br>+ session->defer_end = 0;<br>+<br>+        if (session->ended_while_deferred) {<br>+              /* Complete the session end started by the remote hangup. */<br>+         ast_debug(3, "Ending session (%p) after being deferred\n", session);<br>+               session->ended_while_deferred = 0;<br>+                session_end(session);<br>+        }<br>+}<br>+<br>+struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)<br>+{<br>+ pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);<br>+     struct ast_sip_session *session;<br>+<br>+  if (!inv_session ||<br>+          !(session = inv_session->mod_data[session_module.id])) {<br>+          return NULL;<br>+ }<br>+<br>+ ao2_ref(session, +1);<br>+<br>+     return session;<br>+}<br>+<br>+enum sip_get_destination_result {<br>+   /*! The extension was successfully found */<br>+  SIP_GET_DEST_EXTEN_FOUND,<br>+    /*! The extension specified in the RURI was not found */<br>+     SIP_GET_DEST_EXTEN_NOT_FOUND,<br>+        /*! The extension specified in the RURI was a partial match */<br>+       SIP_GET_DEST_EXTEN_PARTIAL,<br>+  /*! The RURI is of an unsupported scheme */<br>+  SIP_GET_DEST_UNSUPPORTED_URI,<br>+};<br>+<br>+/*!<br>+ * \brief Determine where in the dialplan a call should go<br>+ *<br>+ * This uses the username in the request URI to try to match<br>+ * an extension in the endpoint's configured context in order<br>+ * to route the call.<br>+ *<br>+ * \param session The inbound SIP session<br>+ * \param rdata The SIP INVITE<br>+ */<br>+static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)<br>+{<br>+ pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;<br>+   pjsip_sip_uri *sip_ruri;<br>+     struct ast_features_pickup_config *pickup_cfg;<br>+       const char *pickupexten;<br>+<br>+  if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {<br>+             return SIP_GET_DEST_UNSUPPORTED_URI;<br>+ }<br>+<br>+ sip_ruri = pjsip_uri_get_uri(ruri);<br>+  ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));<br>+<br>+    /*<br>+    * We may want to match in the dialplan without any user<br>+      * options getting in the way.<br>+        */<br>+  AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);<br>+<br>+   pickup_cfg = ast_get_chan_features_pickup_config(session->channel);<br>+       if (!pickup_cfg) {<br>+           ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");<br>+           pickupexten = "";<br>+  } else {<br>+             pickupexten = ast_strdupa(pickup_cfg->pickupexten);<br>+               ao2_ref(pickup_cfg, -1);<br>+     }<br>+<br>+ if (!strcmp(session->exten, pickupexten) ||<br>+               ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {<br>+          size_t size = pj_strlen(&sip_ruri->host) + 1;<br>+         char *domain = ast_alloca(size);<br>+<br>+          ast_copy_pj_str(domain, &sip_ruri->host, size);<br>+               pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);<br>+<br>+            /*<br>+            * Save off the INVITE Request-URI in case it is<br>+              * needed: CHANNEL(pjsip,request_uri)<br>+                 */<br>+          session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);<br>+<br>+                return SIP_GET_DEST_EXTEN_FOUND;<br>+     }<br>+<br>+ /*<br>+    * Check for partial match via overlap dialling (if enabled)<br>+  */<br>+  if (session->endpoint->allow_overlap && (<br>+              !strncmp(session->exten, pickupexten, strlen(session->exten)) ||<br>+               ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {<br>+               /* Overlap partial match */<br>+          return SIP_GET_DEST_EXTEN_PARTIAL;<br>+   }<br>+<br>+ return SIP_GET_DEST_EXTEN_NOT_FOUND;<br>+}<br>+<br>+static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)<br>+{<br>+ pjsip_tx_data *tdata;<br>+        pjsip_dialog *dlg;<br>+   pjsip_inv_session *inv_session;<br>+      unsigned int options = endpoint->extensions.flags;<br>+        pj_status_t dlg_status;<br>+<br>+   if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {<br>+             if (tdata) {<br>+                 pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);<br>+          } else {<br>+                     pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>+           }<br>+            return NULL;<br>+ }<br>+    dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);<br>+   if (!dlg) {<br>+          if (dlg_status != PJ_EEXISTS) {<br>+                      pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>+           }<br>+            return NULL;<br>+ }<br>+    if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {<br>+               pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>+           pjsip_dlg_terminate(dlg);<br>+            return NULL;<br>+ }<br>+<br>+#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)<br>+   inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;<br>+#endif<br>+ if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {<br>+             if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {<br>+                       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>+             }<br>+            pjsip_inv_send_msg(inv_session, tdata);<br>+              return NULL;<br>+ }<br>+    return inv_session;<br>+}<br>+<br>+struct new_invite {<br>+     /*! \brief Session created for the new INVITE */<br>+     struct ast_sip_session *session;<br>+<br>+  /*! \brief INVITE request itself */<br>+  pjsip_rx_data *rdata;<br>+};<br>+<br>+static int new_invite(struct new_invite *invite)<br>+{<br>+ pjsip_tx_data *tdata = NULL;<br>+ pjsip_timer_setting timer;<br>+   pjsip_rdata_sdp_info *sdp_info;<br>+      pjmedia_sdp_session *local = NULL;<br>+<br>+        /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE<br>+     * so that we will be notified so we can destroy the session properly<br>+         */<br>+<br>+       if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>+          ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",<br>+                      invite->session->inv_session->cause,<br>+                        pjsip_get_status_text(invite->session->inv_session->cause)->ptr);<br>+#ifdef HAVE_PJSIP_INV_SESSION_REF<br>+            pjsip_inv_dec_ref(invite->session->inv_session);<br>+#endif<br>+              return -1;<br>+   }<br>+<br>+ switch (get_destination(invite->session, invite->rdata)) {<br>+     case SIP_GET_DEST_EXTEN_FOUND:<br>+               /* Things worked. Keep going */<br>+              break;<br>+       case SIP_GET_DEST_UNSUPPORTED_URI:<br>+           if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>+                     ast_sip_session_send_response(invite->session, tdata);<br>+            } else  {<br>+                    pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);<br>+               }<br>+            goto end;<br>+    case SIP_GET_DEST_EXTEN_PARTIAL:<br>+             ast_debug(1, "Call from '%s' (%s:%s:%d) to extension '%s' - partial match\n", ast_sorcery_object_get_id(invite->session->endpoint),<br>+                  invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name, invite->rdata->pkt_info.src_port, invite->session->exten);<br>+<br>+              if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>+                     ast_sip_session_send_response(invite->session, tdata);<br>+            } else  {<br>+                    pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);<br>+               }<br>+            goto end;<br>+    case SIP_GET_DEST_EXTEN_NOT_FOUND:<br>+   default:<br>+             ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",<br>+                 ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,<br>+                    invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);<br>+<br>+               if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>+                     ast_sip_session_send_response(invite->session, tdata);<br>+            } else  {<br>+                    pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);<br>+               }<br>+            goto end;<br>+    };<br>+<br>+        pjsip_timer_setting_default(&timer);<br>+     timer.min_se = invite->session->endpoint->extensions.timer.min_se;<br>+  timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;<br>+      pjsip_timer_init_session(invite->session->inv_session, &timer);<br>+<br>+ /*<br>+    * At this point, we've verified what we can that won't take awhile,<br>+  * so let's go ahead and send a 100 Trying out to stop any<br>+        * retransmissions.<br>+   */<br>+  if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {<br>+             pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);<br>+               goto end;<br>+    }<br>+    ast_sip_session_send_response(invite->session, tdata);<br>+<br>+ sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);<br>+       if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {<br>+          if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {<br>+                     tdata = NULL;<br>+                        if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS<br>+                           && tdata) {<br>+                          ast_sip_session_send_response(invite->session, tdata);<br>+                    }<br>+                    goto end;<br>+            }<br>+            /* We are creating a local SDP which is an answer to their offer */<br>+          local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);<br>+  } else {<br>+             /* We are creating a local SDP which is an offer */<br>+          local = create_local_sdp(invite->session->inv_session, invite->session, NULL);<br>+      }<br>+<br>+ /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */<br>+  if (!local) {<br>+                tdata = NULL;<br>+                if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS<br>+                   && tdata) {<br>+                  ast_sip_session_send_response(invite->session, tdata);<br>+            }<br>+            goto end;<br>+    }<br>+<br>+ pjsip_inv_set_local_sdp(invite->session->inv_session, local);<br>+  pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);<br>+#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS<br>+ pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);<br>+#endif<br>+<br>+ handle_incoming_request(invite->session, invite->rdata);<br>+<br>+end:<br>+#ifdef HAVE_PJSIP_INV_SESSION_REF<br>+ pjsip_inv_dec_ref(invite->session->inv_session);<br>+#endif<br>+      return 0;<br>+}<br>+<br>+static void handle_new_invite_request(pjsip_rx_data *rdata)<br>+{<br>+   RAII_VAR(struct ast_sip_endpoint *, endpoint,<br>+                        ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);<br>+   pjsip_tx_data *tdata = NULL;<br>+ pjsip_inv_session *inv_session = NULL;<br>+       struct ast_sip_session *session;<br>+     struct new_invite invite;<br>+<br>+ ast_assert(endpoint != NULL);<br>+<br>+     inv_session = pre_session_setup(rdata, endpoint);<br>+    if (!inv_session) {<br>+          /* pre_session_setup() returns a response on failure */<br>+              return;<br>+      }<br>+<br>+#ifdef HAVE_PJSIP_INV_SESSION_REF<br>+     if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {<br>+          ast_log(LOG_ERROR, "Can't increase the session reference counter\n");<br>+          if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {<br>+                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>+                               pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>+                     } else {<br>+                             pjsip_inv_send_msg(inv_session, tdata);<br>+                      }<br>+            }<br>+            return;<br>+      }<br>+#endif<br>+<br>+        session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);<br>+ if (!session) {<br>+              if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>+                       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>+             } else {<br>+                     pjsip_inv_send_msg(inv_session, tdata);<br>+              }<br>+#ifdef HAVE_PJSIP_INV_SESSION_REF<br>+                pjsip_inv_dec_ref(inv_session);<br>+#endif<br>+             return;<br>+      }<br>+<br>+ /*<br>+    * The current thread is supposed be the session serializer to prevent<br>+        * any initial INVITE retransmissions from trying to setup the same<br>+   * call again.<br>+        */<br>+  ast_assert(ast_taskprocessor_is_task(session->serializer));<br>+<br>+    invite.session = session;<br>+    invite.rdata = rdata;<br>+        new_invite(&invite);<br>+<br>+  ao2_ref(session, -1);<br>+}<br>+<br>+static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)<br>+{<br>+ pj_str_t method;<br>+<br>+  if (ast_strlen_zero(supplement_method)) {<br>+            return PJ_TRUE;<br>+      }<br>+<br>+ pj_cstr(&method, supplement_method);<br>+<br>+  return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;<br>+}<br>+<br>+static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)<br>+{<br>+ struct ast_sip_session_supplement *supplement;<br>+       struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;<br>+<br>+    if (!session) {<br>+              return PJ_FALSE;<br>+     }<br>+<br>+ AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>+          if (does_method_match(&method->name, supplement->method)) {<br>+                        return PJ_TRUE;<br>+              }<br>+    }<br>+    return PJ_FALSE;<br>+}<br>+/*!<br>+ * \brief Called when a new SIP request comes into PJSIP<br>+ *<br>+ * This function is called under two circumstances<br>+ * 1) An out-of-dialog request is received by PJSIP<br>+ * 2) An in-dialog request that the inv_session layer does not<br>+ *    handle is received (such as an in-dialog INFO)<br>+ *<br>+ * Except for INVITEs, there is very little we actually do in this function<br>+ * 1) For requests we don't handle, we return PJ_FALSE<br>+ * 2) For new INVITEs, handle them now to prevent retransmissions from<br>+ *    trying to setup the same call again.<br>+ * 3) For in-dialog requests we handle, we process them in the<br>+ *    .on_state_changed = session_inv_on_state_changed or<br>+ *    .on_tsx_state_changed = session_inv_on_tsx_state_changed<br>+ *    callbacks instead.<br>+ */<br>+static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)<br>+{<br>+        pj_status_t handled = PJ_FALSE;<br>+      pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);<br>+      pjsip_inv_session *inv_session;<br>+<br>+   switch (rdata->msg_info.msg->line.req.method.id) {<br>+     case PJSIP_INVITE_METHOD:<br>+            if (dlg) {<br>+                   ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");<br>+                  break;<br>+               }<br>+            handled = PJ_TRUE;<br>+           handle_new_invite_request(rdata);<br>+            break;<br>+       default:<br>+             /* Handle other in-dialog methods if their supplements have been registered */<br>+               handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&<br>+                   has_supplement(inv_session->mod_data[session_module.id], rdata);<br>+          break;<br>+       }<br>+<br>+ return handled;<br>+}<br>+<br>+static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)<br>+{<br>+      struct ast_sip_session *session = entry->user_data;<br>+<br>+    ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",<br>+             ast_sorcery_object_get_id(session->endpoint),<br>+             session->channel ? ast_channel_name(session->channel) : "");<br>+<br>+      if (AST_LIST_EMPTY(&session->delayed_requests)) {<br>+             /* No delayed request pending, so just return */<br>+             ao2_ref(session, -1);<br>+                return;<br>+      }<br>+    if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {<br>+          /*<br>+            * Uh oh.  We now have nothing in the foreseeable future<br>+              * to trigger sending the delayed requests.<br>+           */<br>+          ao2_ref(session, -1);<br>+        }<br>+}<br>+<br>+static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)<br>+{<br>+     pjsip_inv_session *inv = session->inv_session;<br>+    pj_time_val tv;<br>+<br>+   ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",<br>+           ast_sorcery_object_get_id(session->endpoint),<br>+             session->channel ? ast_channel_name(session->channel) : "");<br>+ if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {<br>+             return;<br>+      }<br>+    if (pj_timer_entry_running(&session->rescheduled_reinvite)) {<br>+         /* Timer already running.  Something weird is going on. */<br>+           ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",<br>+                     ast_sorcery_object_get_id(session->endpoint),<br>+                     session->channel ? ast_channel_name(session->channel) : "");<br>+         return;<br>+      }<br>+<br>+ tv.sec = 0;<br>+  if (inv->role == PJSIP_ROLE_UAC) {<br>+                tv.msec = 2100 + ast_random() % 2000;<br>+        } else {<br>+             tv.msec = ast_random() % 2000;<br>+       }<br>+    pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);<br>+<br>+  ao2_ref(session, +1);<br>+        if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),<br>+         &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {<br>+             ao2_ref(session, -1);<br>+        }<br>+}<br>+<br>+static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)<br>+{<br>+       int id = session_module.id;<br>+  struct ast_sip_session *session = NULL;<br>+<br>+   if (!DEBUG_ATLEAST(5)) {<br>+             /* Debug not spamy enough */<br>+         return;<br>+      }<br>+<br>+ ast_log(LOG_DEBUG, "Function %s called on event %s\n",<br>+             function, pjsip_event_str(e->type));<br>+      if (!inv) {<br>+          ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);<br>+            ast_log(LOG_DEBUG, "The transaction state is %s\n",<br>+                        pjsip_tsx_state_str(tsx->state));<br>+         return;<br>+      }<br>+    if (id > -1) {<br>+            session = inv->mod_data[session_module.id];<br>+       }<br>+    if (!session) {<br>+              ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);<br>+    } else {<br>+             ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",<br>+                 ast_sorcery_object_get_id(session->endpoint),<br>+                     session->channel ? ast_channel_name(session->channel) : "");<br>+ }<br>+    if (inv->invite_tsx) {<br>+            ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",<br>+                       inv->invite_tsx);<br>+ } else {<br>+             ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");<br>+       }<br>+    if (tsx) {<br>+           ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",<br>+                        pjsip_role_name(tsx->role),<br>+                       (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),<br>+                      tsx);<br>+                ast_log(LOG_DEBUG, "The current transaction state is %s\n",<br>+                        pjsip_tsx_state_str(tsx->state));<br>+         ast_log(LOG_DEBUG, "The transaction state change event is %s\n",<br>+                   pjsip_event_str(e->body.tsx_state.type));<br>+ } else {<br>+             ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");<br>+     }<br>+    ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));<br>+}<br>+<br>+#define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))<br>+<br>+static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)<br>+{<br>+      struct ast_sip_session_supplement *supplement;<br>+       struct pjsip_request_line req = rdata->msg_info.msg->line.req;<br>+<br>+      ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));<br>+  AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>+          if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {<br>+                     if (supplement->incoming_request(session, rdata)) {<br>+                               break;<br>+                       }<br>+            }<br>+    }<br>+}<br>+<br>+static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>+               enum ast_sip_session_response_priority response_priority)<br>+{<br>+        struct ast_sip_session_supplement *supplement;<br>+       struct pjsip_status_line status = rdata->msg_info.msg->line.status;<br>+<br>+ ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),<br>+                    pj_strbuf(&status.reason));<br>+<br>+   AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>+          if (!(supplement->response_priority & response_priority)) {<br>+                   continue;<br>+            }<br>+            if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {<br>+                    supplement->incoming_response(session, rdata);<br>+            }<br>+    }<br>+}<br>+<br>+static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>+         enum ast_sip_session_response_priority response_priority)<br>+{<br>+        ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?<br>+                       "request" : "response");<br>+<br>+      if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {<br>+          handle_incoming_request(session, rdata);<br>+     } else {<br>+             handle_incoming_response(session, rdata, response_priority);<br>+ }<br>+<br>+ return 0;<br>+}<br>+<br>+static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>+{<br>+    struct ast_sip_session_supplement *supplement;<br>+       struct pjsip_request_line req = tdata->msg->line.req;<br>+<br>+       ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));<br>+  AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>+          if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {<br>+                     supplement->outgoing_request(session, tdata);<br>+             }<br>+    }<br>+}<br>+<br>+static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>+{<br>+   struct ast_sip_session_supplement *supplement;<br>+       struct pjsip_status_line status = tdata->msg->line.status;<br>+     pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);<br>+<br>+     if (!cseq) {<br>+         ast_log(LOG_ERROR, "Cannot send response due to missing sequence header");<br>+         return;<br>+      }<br>+<br>+ ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),<br>+          pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),<br>+              pj_strbuf(&status.reason));<br>+<br>+   AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>+          if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {<br>+                       supplement->outgoing_response(session, tdata);<br>+            }<br>+    }<br>+}<br>+<br>+static int session_end(void *vsession)<br>+{<br>+        struct ast_sip_session *session = vsession;<br>+  struct ast_sip_session_supplement *iter;<br>+<br>+  /* Stop the scheduled termination */<br>+ sip_session_defer_termination_stop_timer(session);<br>+<br>+        /* Session is dead.  Notify the supplements. */<br>+      AST_LIST_TRAVERSE(&session->supplements, iter, next) {<br>+                if (iter->session_end) {<br>+                  iter->session_end(session);<br>+               }<br>+    }<br>+<br>+ /* Release any media resources. */<br>+   ao2_cleanup(session->media);<br>+      session->media = NULL;<br>+<br>+ return 0;<br>+}<br>+<br>+/*!<br>+ * \internal<br>+ * \brief Complete ending session activities.<br>+ * \since 13.5.0<br>+ *<br>+ * \param vsession Which session to complete stopping.<br>+ *<br>+ * \retval 0 on success.<br>+ * \retval -1 on error.<br>+ */<br>+static int session_end_completion(void *vsession)<br>+{<br>+       struct ast_sip_session *session = vsession;<br>+<br>+       ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);<br>+        ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);<br>+<br>+       /* Now we can release the ref that was held by session->inv_session */<br>+    ao2_cleanup(session);<br>+        return 0;<br>+}<br>+<br>+static void handle_incoming_before_media(pjsip_inv_session *inv,<br>+  struct ast_sip_session *session, pjsip_rx_data *rdata)<br>+{<br>+   pjsip_msg *msg;<br>+<br>+   handle_incoming(session, rdata, AST_SIP_SESSION_BEFORE_MEDIA);<br>+       msg = rdata->msg_info.msg;<br>+        if (msg->type == PJSIP_REQUEST_MSG<br>+                && msg->line.req.method.id == PJSIP_ACK_METHOD<br>+            && pjmedia_sdp_neg_get_state(inv->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {<br>+           pjsip_tx_data *tdata;<br>+<br>+             /*<br>+            * SDP negotiation failed on an incoming call that delayed<br>+            * negotiation and then gave us an invalid SDP answer.  We<br>+            * need to send a BYE to end the call because of the invalid<br>+          * SDP answer.<br>+                */<br>+          ast_debug(1,<br>+                 "Endpoint '%s(%s)': Ending session due to incomplete SDP negotiation.  %s\n",<br>+                      ast_sorcery_object_get_id(session->endpoint),<br>+                     session->channel ? ast_channel_name(session->channel) : "",<br>+                  pjsip_rx_data_get_info(rdata));<br>+              if (pjsip_inv_end_session(inv, 400, NULL, &tdata) == PJ_SUCCESS<br>+                  && tdata) {<br>+                  ast_sip_session_send_request(session, tdata);<br>+                }<br>+    }<br>+}<br>+<br>+static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)<br>+{<br>+      struct ast_sip_session *session = inv->mod_data[session_module.id];<br>+       pjsip_event_id_e type;<br>+<br>+    if (e) {<br>+             print_debug_details(inv, NULL, e);<br>+           type = e->type;<br>+   } else {<br>+             type = PJSIP_EVENT_UNKNOWN;<br>+  }<br>+<br>+ if (!session) {<br>+              return;<br>+      }<br>+<br>+ switch(type) {<br>+       case PJSIP_EVENT_TX_MSG:<br>+             break;<br>+       case PJSIP_EVENT_RX_MSG:<br>+             handle_incoming_before_media(inv, session, e->body.rx_msg.rdata);<br>+         break;<br>+       case PJSIP_EVENT_TSX_STATE:<br>+          ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));<br>+            /* Transaction state changes are prompted by some other underlying event. */<br>+         switch(e->body.tsx_state.type) {<br>+          case PJSIP_EVENT_TX_MSG:<br>+                     break;<br>+               case PJSIP_EVENT_RX_MSG:<br>+                     handle_incoming_before_media(inv, session, e->body.tsx_state.src.rdata);<br>+                  break;<br>+               case PJSIP_EVENT_TRANSPORT_ERROR:<br>+            case PJSIP_EVENT_TIMER:<br>+              case PJSIP_EVENT_USER:<br>+               case PJSIP_EVENT_UNKNOWN:<br>+            case PJSIP_EVENT_TSX_STATE:<br>+                  /* Inception? */<br>+                     break;<br>+               }<br>+            break;<br>+       case PJSIP_EVENT_TRANSPORT_ERROR:<br>+    case PJSIP_EVENT_TIMER:<br>+      case PJSIP_EVENT_UNKNOWN:<br>+    case PJSIP_EVENT_USER:<br>+       default:<br>+             break;<br>+       }<br>+<br>+ if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {<br>+         if (session->defer_end) {<br>+                 ast_debug(3, "Deferring session (%p) end\n", session);<br>+                     session->ended_while_deferred = 1;<br>+                        return;<br>+              }<br>+<br>+         if (ast_sip_push_task(session->serializer, session_end, session)) {<br>+                       /* Do it anyway even though this is not the right thread. */<br>+                 session_end(session);<br>+                }<br>+    }<br>+}<br>+<br>+static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)<br>+{<br>+        /* XXX STUB */<br>+}<br>+<br>+static int session_end_if_disconnected(int id, pjsip_inv_session *inv)<br>+{<br>+   struct ast_sip_session *session;<br>+<br>+  if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {<br>+         return 0;<br>+    }<br>+<br>+ /*<br>+    * We are locking because ast_sip_dialog_get_session() needs<br>+  * the dialog locked to get the session by other threads.<br>+     */<br>+  pjsip_dlg_inc_lock(inv->dlg);<br>+     session = inv->mod_data[id];<br>+      inv->mod_data[id] = NULL;<br>+ pjsip_dlg_dec_lock(inv->dlg);<br>+<br>+  /*<br>+    * Pass the session ref held by session->inv_session to<br>+    * session_end_completion().<br>+  */<br>+  if (session<br>+          && ast_sip_push_task(session->serializer, session_end_completion, session)) {<br>+             /* Do it anyway even though this is not the right thread. */<br>+         session_end_completion(session);<br>+     }<br>+<br>+ return 1;<br>+}<br>+<br>+static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)<br>+{<br>+  ast_sip_session_response_cb cb;<br>+      int id = session_module.id;<br>+  struct ast_sip_session *session;<br>+     pjsip_tx_data *tdata;<br>+<br>+     /*<br>+    * A race condition exists at shutdown where the res_pjsip_session can be<br>+     * unloaded but this callback may still get called afterwards. In this case<br>+   * the id may end up being -1 which is useless to us. To work around this<br>+     * we store the current value and check/use it.<br>+       */<br>+  if (id < 0) {<br>+             return;<br>+      }<br>+<br>+ session = inv->mod_data[id];<br>+<br>+   print_debug_details(inv, tsx, e);<br>+    if (!session) {<br>+              /* The session has ended.  Ignore the transaction change. */<br>+         return;<br>+      }<br>+<br>+ /*<br>+    * If the session is disconnected really nothing else to do unless currently transacting<br>+      * a BYE. If a BYE then hold off destruction until the transaction timeout occurs. This<br>+       * has to be done for BYEs because sometimes the dialog can be in a disconnected<br>+      * state but the BYE request transaction has not yet completed.<br>+       */<br>+  if (tsx->method.id != PJSIP_BYE_METHOD && session_end_if_disconnected(id, inv)) {<br>+         return;<br>+      }<br>+<br>+ switch (e->body.tsx_state.type) {<br>+ case PJSIP_EVENT_TX_MSG:<br>+             /* When we create an outgoing request, we do not have access to the transaction that<br>+          * is created. Instead, We have to place transaction-specific data in the tdata. Here,<br>+                * we transfer the data into the transaction. This way, when we receive a response, we<br>+                * can dig this data out again<br>+                */<br>+          tsx->mod_data[id] = e->body.tsx_state.src.tdata->mod_data[id];<br>+              break;<br>+       case PJSIP_EVENT_RX_MSG:<br>+             cb = ast_sip_mod_data_get(tsx->mod_data, id, MOD_DATA_ON_RESPONSE);<br>+               /* As the PJSIP invite session implementation responds with a 200 OK before we have a<br>+                 * chance to be invoked session supplements for BYE requests actually end up executing<br>+                * in the invite session state callback as well. To prevent session supplements from<br>+          * running on the BYE request again we explicitly squash invocation of them here.<br>+             */<br>+          if ((e->body.tsx_state.src.rdata->msg_info.msg->type != PJSIP_REQUEST_MSG) ||<br>+                       (tsx->method.id != PJSIP_BYE_METHOD)) {<br>+                   handle_incoming(session, e->body.tsx_state.src.rdata,<br>+                             AST_SIP_SESSION_AFTER_MEDIA);<br>+                }<br>+            if (tsx->method.id == PJSIP_INVITE_METHOD) {<br>+                      if (tsx->role == PJSIP_ROLE_UAC) {<br>+                                if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {<br>+                                    /* This means we got a non 2XX final response to our outgoing INVITE */<br>+                                      if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {<br>+                                               reschedule_reinvite(session, cb);<br>+                                            return;<br>+                                      }<br>+                                    if (inv->state == PJSIP_INV_STATE_CONFIRMED) {<br>+                                            ast_debug(1, "reINVITE received final response code %d\n",<br>+                                                 tsx->status_code);<br>+                                                if ((tsx->status_code == 401 || tsx->status_code == 407)<br>+                                                       && !ast_sip_create_request_with_auth(<br>+                                                                &session->endpoint->outbound_auths,<br>+                                                                e->body.tsx_state.src.rdata, tsx, &tdata)) {<br>+                                                  /* Send authed reINVITE */<br>+                                                   ast_sip_session_send_request_with_cb(session, tdata, cb);<br>+                                                    return;<br>+                                              }<br>+                                            if (tsx->status_code != 488) {<br>+                                                    /* Other reinvite failures (except 488) result in destroying the session. */<br>+                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS<br>+                                                          && tdata) {<br>+                                                          ast_sip_session_send_request(session, tdata);<br>+                                                        }<br>+                                            }<br>+                                    }<br>+                            } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {<br>+                                    if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {<br>+                                              int sdp_negotiation_done =<br>+                                                   pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE;<br>+<br>+                                             /*<br>+                                            * We can get here for the following reasons.<br>+                                                 *<br>+                                            * 1) The race condition detailed in RFC5407 section 3.1.2.<br>+                                           * We sent a CANCEL at the same time that the UAS sent us a<br>+                                           * 200 OK with a valid SDP for the original INVITE.  As a<br>+                                             * result, we have now received a 200 OK for a cancelled<br>+                                              * call and the SDP negotiation is complete.  We need to<br>+                                              * immediately send a BYE to end the dialog.<br>+                                          *<br>+                                            * 2) We sent a CANCEL and hit the race condition but the<br>+                                             * UAS sent us an invalid SDP with the 200 OK.  In this case<br>+                                          * the SDP negotiation is incomplete and PJPROJECT has<br>+                                                * already sent the BYE for us because of the invalid SDP.<br>+                                            *<br>+                                            * 3) We didn't send a CANCEL but the UAS sent us an invalid<br>+                                              * SDP with the 200 OK.  In this case the SDP negotiation is<br>+                                          * incomplete and PJPROJECT has already sent the BYE for us<br>+                                           * because of the invalid SDP.<br>+                                                */<br>+                                          ast_test_suite_event_notify("PJSIP_SESSION_CANCELED",<br>+                                                      "Endpoint: %s\r\n"<br>+                                                 "Channel: %s\r\n"<br>+                                                  "Message: %s\r\n"<br>+                                                  "SDP: %s",<br>+                                                 ast_sorcery_object_get_id(session->endpoint),<br>+                                                     session->channel ? ast_channel_name(session->channel) : "",<br>+                                                  pjsip_rx_data_get_info(e->body.tsx_state.src.rdata),<br>+                                                      sdp_negotiation_done ? "complete" : "incomplete");<br>+                                               if (!sdp_negotiation_done) {<br>+                                                 ast_debug(1, "Endpoint '%s(%s)': Incomplete SDP negotiation cancelled session.  %s\n",<br>+                                                             ast_sorcery_object_get_id(session->endpoint),<br>+                                                             session->channel ? ast_channel_name(session->channel) : "",<br>+                                                          pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));<br>+                                             } else if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS<br>+                                                   && tdata) {<br>+                                                  ast_debug(1, "Endpoint '%s(%s)': Ending session due to RFC5407 race condition.  %s\n",<br>+                                                             ast_sorcery_object_get_id(session->endpoint),<br>+                                                             session->channel ? ast_channel_name(session->channel) : "",<br>+                                                          pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));<br>+                                                     ast_sip_session_send_request(session, tdata);<br>+                                                }<br>+                                    }<br>+                            }<br>+                    }<br>+            } else {<br>+                     /* All other methods */<br>+                      if (tsx->role == PJSIP_ROLE_UAC) {<br>+                                if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {<br>+                                    /* This means we got a final response to our outgoing method */<br>+                                      ast_debug(1, "%.*s received final response code %d\n",<br>+                                             (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),<br>+                                              tsx->status_code);<br>+                                        if ((tsx->status_code == 401 || tsx->status_code == 407)<br>+                                               && !ast_sip_create_request_with_auth(<br>+                                                        &session->endpoint->outbound_auths,<br>+                                                        e->body.tsx_state.src.rdata, tsx, &tdata)) {<br>+                                          /* Send authed version of the method */<br>+                                              ast_sip_session_send_request_with_cb(session, tdata, cb);<br>+                                            return;<br>+                                      }<br>+                            }<br>+                    }<br>+            }<br>+            if (cb) {<br>+                    cb(session, e->body.tsx_state.src.rdata);<br>+         }<br>+            break;<br>+       case PJSIP_EVENT_TRANSPORT_ERROR:<br>+    case PJSIP_EVENT_TIMER:<br>+              /*<br>+            * The timer event is run by the pjsip monitor thread and not<br>+                 * by the session serializer.<br>+                 */<br>+          if (session_end_if_disconnected(id, inv)) {<br>+                  return;<br>+              }<br>+            break;<br>+       case PJSIP_EVENT_USER:<br>+       case PJSIP_EVENT_UNKNOWN:<br>+    case PJSIP_EVENT_TSX_STATE:<br>+          /* Inception? */<br>+             break;<br>+       }<br>+<br>+ if (AST_LIST_EMPTY(&session->delayed_requests)) {<br>+             /* No delayed request pending, so just return */<br>+             return;<br>+      }<br>+<br>+ if (tsx->method.id == PJSIP_INVITE_METHOD) {<br>+              if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {<br>+                   ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",<br>+                               ast_sorcery_object_get_id(session->endpoint),<br>+                             session->channel ? ast_channel_name(session->channel) : "",<br>+                          pjsip_tsx_state_str(tsx->state));<br>+                 check_delayed_requests(session, invite_proceeding);<br>+          } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {<br>+                    /*<br>+                    * Terminated INVITE transactions always should result in<br>+                     * queuing delayed requests, no matter what event caused<br>+                      * the transaction to terminate.<br>+                      */<br>+                  ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",<br>+                               ast_sorcery_object_get_id(session->endpoint),<br>+                             session->channel ? ast_channel_name(session->channel) : "",<br>+                          pjsip_tsx_state_str(tsx->state));<br>+                 check_delayed_requests(session, invite_terminated);<br>+          }<br>+    } else if (tsx->role == PJSIP_ROLE_UAC<br>+            && tsx->state == PJSIP_TSX_STATE_COMPLETED<br>+                && !pj_strcmp2(&tsx->method.name, "UPDATE")) {<br>+              ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",<br>+                       ast_sorcery_object_get_id(session->endpoint),<br>+                     session->channel ? ast_channel_name(session->channel) : "",<br>+                  pjsip_tsx_state_str(tsx->state));<br>+         check_delayed_requests(session, update_completed);<br>+   }<br>+}<br>+<br>+static int add_sdp_streams(void *obj, void *arg, void *data, int flags)<br>+{<br>+       struct ast_sip_session_media *session_media = obj;<br>+   pjmedia_sdp_session *answer = arg;<br>+   struct ast_sip_session *session = data;<br>+      struct ast_sip_session_sdp_handler *handler = session_media->handler;<br>+     RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>+        int res;<br>+<br>+  if (handler) {<br>+               /* if an already assigned handler reports a catastrophic error, fail */<br>+              res = handler->create_outgoing_sdp_stream(session, session_media, answer);<br>+                if (res < 0) {<br>+                    return 0;<br>+            }<br>+            return CMP_MATCH;<br>+    }<br>+<br>+ handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);<br>+       if (!handler_list) {<br>+         return CMP_MATCH;<br>+    }<br>+<br>+ /* no handler for this stream type and we have a list to search */<br>+   AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+               if (handler == session_media->handler) {<br>+                  continue;<br>+            }<br>+            res = handler->create_outgoing_sdp_stream(session, session_media, answer);<br>+                if (res < 0) {<br>+                    /* catastrophic error */<br>+                     return 0;<br>+            }<br>+            if (res > 0) {<br>+                    /* Handled by this handler. Move to the next stream */<br>+                       session_media_set_handler(session_media, handler);<br>+                   return CMP_MATCH;<br>+            }<br>+    }<br>+<br>+ /* streams that weren't handled won't be included in generated outbound SDP */<br>+       return CMP_MATCH;<br>+}<br>+<br>+static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)<br>+{<br>+        RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);<br>+     static const pj_str_t STR_IN = { "IN", 2 };<br>+        static const pj_str_t STR_IP4 = { "IP4", 3 };<br>+      static const pj_str_t STR_IP6 = { "IP6", 3 };<br>+      pjmedia_sdp_session *local;<br>+<br>+       if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {<br>+         ast_log(LOG_ERROR, "Failed to create session SDP. Session has been already disconnected\n");<br>+               return NULL;<br>+ }<br>+<br>+ if (!inv->pool_prov || !(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {<br>+             return NULL;<br>+ }<br>+<br>+ if (!offer) {<br>+                local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());<br>+        } else {<br>+             local->origin.version = offer->origin.version + 1;<br>+             local->origin.id = offer->origin.id;<br>+   }<br>+<br>+ pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);<br>+  pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);<br>+<br>+    /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */<br>+ successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);<br>+    if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {<br>+               /* Something experienced a catastrophic failure */<br>+           return NULL;<br>+ }<br>+<br>+ /* Use the connection details of the first media stream if possible for SDP level */<br>+ if (local->media_count) {<br>+         int stream;<br>+<br>+               /* Since we are using the first media stream as the SDP level we can get rid of it<br>+            * from the stream itself<br>+             */<br>+          local->conn = local->media[0]->conn;<br>+                local->media[0]->conn = NULL;<br>+          pj_strassign(&local->origin.net_type, &local->conn->net_type);<br>+              pj_strassign(&local->origin.addr_type, &local->conn->addr_type);<br>+            pj_strassign(&local->origin.addr, &local->conn->addr);<br>+<br>+           /* Go through each media stream seeing if the connection details actually differ,<br>+             * if not just use SDP level and reduce the SDP size<br>+          */<br>+          for (stream = 1; stream < local->media_count; stream++) {<br>+                      if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&<br>+                              !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&<br>+                                !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {<br>+                          local->media[stream]->conn = NULL;<br>+                     }<br>+            }<br>+    } else {<br>+             local->origin.net_type = STR_IN;<br>+          local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;<br>+<br>+         if (!ast_strlen_zero(session->endpoint->media.address)) {<br>+                      pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);<br>+           } else {<br>+                     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()));<br>+               }<br>+    }<br>+<br>+ return local;<br>+}<br>+<br>+static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)<br>+{<br>+     struct ast_sip_session *session = inv->mod_data[session_module.id];<br>+       pjmedia_sdp_session *answer;<br>+<br>+      if (handle_incoming_sdp(session, offer)) {<br>+           return;<br>+      }<br>+<br>+ if ((answer = create_local_sdp(inv, session, offer))) {<br>+              pjsip_inv_set_sdp_answer(inv, answer);<br>+       }<br>+}<br>+<br>+#if 0<br>+static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)<br>+{<br>+        /* XXX STUB */<br>+}<br>+#endif<br>+<br>+static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)<br>+{<br>+     struct ast_sip_session *session = inv->mod_data[session_module.id];<br>+       const pjmedia_sdp_session *local, *remote;<br>+<br>+        if (!session || !session->channel) {<br>+              /*<br>+            * If we don't have a session or channel then we really<br>+           * don't care about media updates.<br>+                * Just ignore<br>+                */<br>+          return;<br>+      }<br>+<br>+ if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||<br>+           (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {<br>+               ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);<br>+               ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);<br>+         ast_queue_hangup(session->channel);<br>+               return;<br>+      }<br>+<br>+ handle_negotiated_sdp(session, local, remote);<br>+}<br>+<br>+static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)<br>+{<br>+        struct ast_sip_session *session = inv->mod_data[session_module.id];<br>+       const pjsip_sip_uri *uri;<br>+<br>+ if (!session->channel) {<br>+          return PJSIP_REDIRECT_STOP;<br>+  }<br>+<br>+ if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {<br>+                return PJSIP_REDIRECT_ACCEPT;<br>+        }<br>+<br>+ if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {<br>+         return PJSIP_REDIRECT_STOP;<br>+  }<br>+<br>+ handle_incoming(session, e->body.rx_msg.rdata, AST_SIP_SESSION_BEFORE_REDIRECTING);<br>+<br>+    uri = pjsip_uri_get_uri(target);<br>+<br>+  if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {<br>+             char exten[AST_MAX_EXTENSION];<br>+<br>+            ast_copy_pj_str(exten, &uri->user, sizeof(exten));<br>+<br>+         /*<br>+            * We may want to match in the dialplan without any user<br>+              * options getting in the way.<br>+                */<br>+          AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(exten);<br>+<br>+               ast_channel_call_forward_set(session->channel, exten);<br>+    } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {<br>+          char target_uri[PJSIP_MAX_URL_SIZE];<br>+         /* PJSIP/ + endpoint length + / + max URL size */<br>+            char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];<br>+<br>+           pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));<br>+          sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);<br>+              ast_channel_call_forward_set(session->channel, forward);<br>+  }<br>+<br>+ return PJSIP_REDIRECT_STOP;<br>+}<br>+<br>+static pjsip_inv_callback inv_callback = {<br>+      .on_state_changed = session_inv_on_state_changed,<br>+    .on_new_session = session_inv_on_new_session,<br>+        .on_tsx_state_changed = session_inv_on_tsx_state_changed,<br>+    .on_rx_offer = session_inv_on_rx_offer,<br>+      .on_media_update = session_inv_on_media_update,<br>+      .on_redirected = session_inv_on_redirected,<br>+};<br>+<br>+/*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */<br>+static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)<br>+{<br>+   RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);<br>+ struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(<br>+                tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);<br>+   struct pjmedia_sdp_session *sdp;<br>+     int stream;<br>+<br>+       /* SDP produced by us directly will never be multipart */<br>+    if (!transport_state || hook || !tdata->msg->body ||<br>+           !ast_sip_is_content_type(&tdata->msg->body->content_type, "application", "sdp") ||<br>+          ast_strlen_zero(transport->external_media_address)) {<br>+             return;<br>+      }<br>+<br>+ sdp = tdata->msg->body->data;<br>+<br>+    if (sdp->conn) {<br>+          char host[NI_MAXHOST];<br>+               struct ast_sockaddr our_sdp_addr = { { 0, } };<br>+<br>+            ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));<br>+             ast_sockaddr_parse(&our_sdp_addr, host, PARSE_PORT_FORBID);<br>+<br>+           /* Reversed check here. We don't check the remote<br>+                 * endpoint being in our local net, but whether our<br>+           * outgoing session IP is local. If it is, we'll do<br>+               * rewriting. No localnet configured? Always rewrite. */<br>+             if (ast_sip_transport_is_local(transport_state, &our_sdp_addr) || !transport_state->localnet) {<br>+                       ast_debug(5, "Setting external media address to %s\n", ast_sockaddr_stringify_host(&transport_state->external_media_address));<br>+                      pj_strdup2(tdata->pool, &sdp->conn->addr, ast_sockaddr_stringify_host(&transport_state->external_media_address));<br>+                        pj_strdup2(tdata->pool, &sdp->origin.addr, transport->external_media_address);<br>+          }<br>+    }<br>+<br>+ for (stream = 0; stream < sdp->media_count; ++stream) {<br>+                /* See if there are registered handlers for this media stream type */<br>+                char media[20];<br>+              struct ast_sip_session_sdp_handler *handler;<br>+         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>+<br>+             /* We need a null-terminated version of the media string */<br>+          ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));<br>+<br>+         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>+               if (!handler_list) {<br>+                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>+                   continue;<br>+            }<br>+            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>+                       if (handler->change_outgoing_sdp_stream_media_address) {<br>+                          handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);<br>+                       }<br>+            }<br>+    }<br>+<br>+ /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */<br>+   ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);<br>+}<br>+<br>+int res_pjsip_session_load(void)<br>+{<br>+      pjsip_endpoint *endpt;<br>+<br>+    if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {<br>+               return -1;<br>+   }<br>+    if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {<br>+            return -1;<br>+   }<br>+    nat_hook->outgoing_external_message = session_outgoing_nat_hook;<br>+  ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);<br>+ sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,<br>+                      sdp_handler_list_hash, sdp_handler_list_cmp);<br>+        if (!sdp_handlers) {<br>+         return -1;<br>+   }<br>+    endpt = ast_sip_get_pjsip_endpoint();<br>+        pjsip_inv_usage_init(endpt, &inv_callback);<br>+      pjsip_100rel_init_module(endpt);<br>+     pjsip_timer_init_module(endpt);<br>+      if (internal_sip_register_service(&session_module)) {<br>+            return -1;<br>+   }<br>+<br>+ internal_sip_register_service(&session_reinvite_module);<br>+ internal_sip_register_service(&outbound_invite_auth_module);<br>+<br>+  return 0;<br>+}<br>+<br>+int pjsip_session_unload(void)<br>+{<br>+        internal_sip_unregister_service(&outbound_invite_auth_module);<br>+   internal_sip_unregister_service(&session_reinvite_module);<br>+       internal_sip_unregister_service(&session_module);<br>+        ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);<br>+ ao2_cleanup(nat_hook);<br>+       ao2_cleanup(sdp_handlers);<br>+<br>+        return 0;<br>+}<br>diff --git a/res/res_pjsip_session.c b/res/res_pjsip_session.c<br>index b4fe0be..c1807d9 100644<br>--- a/res/res_pjsip_session.c<br>+++ b/res/res_pjsip_session.c<br>@@ -24,3192 +24,18 @@<br> <br> #include "asterisk.h"<br> <br>-#include <pjsip.h><br>-#include <pjsip_ua.h><br>-#include <pjlib.h><br>-<br> #include "asterisk/res_pjsip.h"<br>-#include "asterisk/res_pjsip_session.h"<br>-#include "asterisk/callerid.h"<br>-#include "asterisk/datastore.h"<br>-#include "asterisk/module.h"<br>-#include "asterisk/logger.h"<br>-#include "asterisk/res_pjsip.h"<br>-#include "asterisk/astobj2.h"<br>-#include "asterisk/lock.h"<br>-#include "asterisk/uuid.h"<br>-#include "asterisk/pbx.h"<br>-#include "asterisk/taskprocessor.h"<br>-#include "asterisk/causes.h"<br>-#include "asterisk/sdp_srtp.h"<br>-#include "asterisk/dsp.h"<br>-#include "asterisk/acl.h"<br>-#include "asterisk/features_config.h"<br>-#include "asterisk/pickup.h"<br>-#include "asterisk/test.h"<br>-<br>-#define SDP_HANDLER_BUCKETS 11<br>-<br>-#define MOD_DATA_ON_RESPONSE "on_response"<br>-#define MOD_DATA_NAT_HOOK "nat_hook"<br>-<br>-/* Some forward declarations */<br>-static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata);<br>-static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>-                enum ast_sip_session_response_priority response_priority);<br>-static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>-               enum ast_sip_session_response_priority response_priority);<br>-static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);<br>-static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);<br>-<br>-/*! \brief NAT hook for modifying outgoing messages with SDP */<br>-static struct ast_sip_nat_hook *nat_hook;<br>-<br>-/*!<br>- * \brief Registered SDP stream handlers<br>- *<br>- * This container is keyed on stream types. Each<br>- * object in the container is a linked list of<br>- * handlers for the stream type.<br>- */<br>-static struct ao2_container *sdp_handlers;<br>-<br>-/*!<br>- * These are the objects in the sdp_handlers container<br>- */<br>-struct sdp_handler_list {<br>-      /* The list of handlers to visit */<br>-  AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;<br>-    /* The handlers in this list handle streams of this type */<br>-  char stream_type[1];<br>-};<br>-<br>-static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);<br>-<br>-static int sdp_handler_list_hash(const void *obj, int flags)<br>-{<br>- const struct sdp_handler_list *handler_list = obj;<br>-   const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;<br>-<br>-       return ast_str_hash(stream_type);<br>-}<br>-<br>-static int sdp_handler_list_cmp(void *obj, void *arg, int flags)<br>-{<br>-      struct sdp_handler_list *handler_list1 = obj;<br>-        struct sdp_handler_list *handler_list2 = arg;<br>-        const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;<br>-<br>-     return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;<br>-}<br>-<br>-static int session_media_hash(const void *obj, int flags)<br>-{<br>-        const struct ast_sip_session_media *session_media = obj;<br>-     const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;<br>-<br>-      return ast_str_hash(stream_type);<br>-}<br>-<br>-static int session_media_cmp(void *obj, void *arg, int flags)<br>-{<br>- struct ast_sip_session_media *session_media1 = obj;<br>-  struct ast_sip_session_media *session_media2 = arg;<br>-  const char *stream_type2 = flags & OBJ_KEY ? arg : session_media2->stream_type;<br>-<br>-    return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;<br>-}<br>-<br>-int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)<br>-{<br>-  RAII_VAR(struct sdp_handler_list *, handler_list,<br>-                    ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);<br>-  SCOPED_AO2LOCK(lock, sdp_handlers);<br>-<br>-       if (handler_list) {<br>-          struct ast_sip_session_sdp_handler *iter;<br>-            /* Check if this handler is already registered for this stream type */<br>-               AST_LIST_TRAVERSE(&handler_list->list, iter, next) {<br>-                  if (!strcmp(iter->id, handler->id)) {<br>-                          ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);<br>-                              return -1;<br>-                   }<br>-            }<br>-            AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);<br>-             ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>-            ast_module_ref(ast_module_info->self);<br>-            return 0;<br>-    }<br>-<br>- /* No stream of this type has been registered yet, so we need to create a new list */<br>-        handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);<br>- if (!handler_list) {<br>-         return -1;<br>-   }<br>-    /* Safe use of strcpy */<br>-     strcpy(handler_list->stream_type, stream_type);<br>-   AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);<br>-       AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);<br>-     if (!ao2_link(sdp_handlers, handler_list)) {<br>-         return -1;<br>-   }<br>-    ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>-    ast_module_ref(ast_module_info->self);<br>-    return 0;<br>-}<br>-<br>-static int remove_handler(void *obj, void *arg, void *data, int flags)<br>-{<br>-        struct sdp_handler_list *handler_list = obj;<br>- struct ast_sip_session_sdp_handler *handler = data;<br>-  struct ast_sip_session_sdp_handler *iter;<br>-    const char *stream_type = arg;<br>-<br>-    AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {<br>-               if (!strcmp(iter->id, handler->id)) {<br>-                  AST_LIST_REMOVE_CURRENT(next);<br>-                       ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);<br>-                  ast_module_unref(ast_module_info->self);<br>-          }<br>-    }<br>-    AST_LIST_TRAVERSE_SAFE_END;<br>-<br>-       if (AST_LIST_EMPTY(&handler_list->list)) {<br>-            ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);<br>-                return CMP_MATCH;<br>-    } else {<br>-             return CMP_STOP;<br>-     }<br>-}<br>-<br>-void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)<br>-{<br>-     ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);<br>-}<br>-<br>-/*!<br>- * \brief Set an SDP stream handler for a corresponding session media.<br>- *<br>- * \note Always use this function to set the SDP handler for a session media.<br>- *<br>- * This function will properly free resources on the SDP handler currently being<br>- * used by the session media, then set the session media to use the new SDP<br>- * handler.<br>- */<br>-static void session_media_set_handler(struct ast_sip_session_media *session_media,<br>-          struct ast_sip_session_sdp_handler *handler)<br>-{<br>-     ast_assert(session_media->handler != handler);<br>-<br>- if (session_media->handler) {<br>-             session_media->handler->stream_destroy(session_media);<br>- }<br>-    session_media->handler = handler;<br>-}<br>-<br>-static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)<br>-{<br>-    int i;<br>-       int handled = 0;<br>-<br>-  if (session->inv_session && session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>-          ast_log(LOG_ERROR, "Failed to handle incoming SDP. Session has been already disconnected\n");<br>-              return -1;<br>-   }<br>-<br>- for (i = 0; i < sdp->media_count; ++i) {<br>-               /* See if there are registered handlers for this media stream type */<br>-                char media[20];<br>-              struct ast_sip_session_sdp_handler *handler;<br>-         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>-                RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>-          int res;<br>-<br>-          /* We need a null-terminated version of the media string */<br>-          ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));<br>-<br>-              session_media = ao2_find(session->media, media, OBJ_KEY);<br>-         if (!session_media) {<br>-                        /* if the session_media doesn't exist, there weren't<br>-                  * any handlers at the time of its creation */<br>-                       continue;<br>-            }<br>-<br>-         if (session_media->handler) {<br>-                     handler = session_media->handler;<br>-                 ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",<br>-                          session_media->stream_type,<br>-                               session_media->handler->id);<br>-                   res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,<br>-                         sdp->media[i]);<br>-                   if (res < 0) {<br>-                            /* Catastrophic failure. Abort! */<br>-                           return -1;<br>-                   } else if (res > 0) {<br>-                             ast_debug(1, "Media stream '%s' handled by %s\n",<br>-                                  session_media->stream_type,<br>-                                       session_media->handler->id);<br>-                           /* Handled by this handler. Move to the next stream */<br>-                               handled = 1;<br>-                         continue;<br>-                    }<br>-            }<br>-<br>-         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>-               if (!handler_list) {<br>-                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>-                   continue;<br>-            }<br>-            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-                       if (handler == session_media->handler) {<br>-                          continue;<br>-                    }<br>-                    ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",<br>-                          session_media->stream_type,<br>-                               handler->id);<br>-                     res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,<br>-                         sdp->media[i]);<br>-                   if (res < 0) {<br>-                            /* Catastrophic failure. Abort! */<br>-                           return -1;<br>-                   }<br>-                    if (res > 0) {<br>-                            ast_debug(1, "Media stream '%s' handled by %s\n",<br>-                                  session_media->stream_type,<br>-                                       handler->id);<br>-                             /* Handled by this handler. Move to the next stream */<br>-                               session_media_set_handler(session_media, handler);<br>-                           handled = 1;<br>-                         break;<br>-                       }<br>-            }<br>-    }<br>-    if (!handled) {<br>-              return -1;<br>-   }<br>-    return 0;<br>-}<br>-<br>-struct handle_negotiated_sdp_cb {<br>- struct ast_sip_session *session;<br>-     const pjmedia_sdp_session *local;<br>-    const pjmedia_sdp_session *remote;<br>-};<br>-<br>-static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)<br>-{<br>-     struct ast_sip_session_media *session_media = obj;<br>-   struct handle_negotiated_sdp_cb *callback_data = arg;<br>-        struct ast_sip_session *session = callback_data->session;<br>- const pjmedia_sdp_session *local = callback_data->local;<br>-  const pjmedia_sdp_session *remote = callback_data->remote;<br>-        int i;<br>-<br>-    for (i = 0; i < local->media_count; ++i) {<br>-             /* See if there are registered handlers for this media stream type */<br>-                char media[20];<br>-              struct ast_sip_session_sdp_handler *handler;<br>-         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>-                int res;<br>-<br>-          if (!remote->media[i]) {<br>-                  continue;<br>-            }<br>-<br>-         /* We need a null-terminated version of the media string */<br>-          ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));<br>-<br>-            /* stream type doesn't match the one we're looking to fill */<br>-                if (strcasecmp(session_media->stream_type, media)) {<br>-                      continue;<br>-            }<br>-<br>-         handler = session_media->handler;<br>-         if (handler) {<br>-                       ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",<br>-                           session_media->stream_type,<br>-                               handler->id);<br>-                     res = handler->apply_negotiated_sdp_stream(session, session_media, local,<br>-                         local->media[i], remote, remote->media[i]);<br>-                    if (res >= 0) {<br>-                           ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",<br>-                                    session_media->stream_type,<br>-                                       handler->id);<br>-                             return CMP_MATCH;<br>-                    }<br>-                    return 0;<br>-            }<br>-<br>-         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>-               if (!handler_list) {<br>-                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>-                   continue;<br>-            }<br>-            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-                       if (handler == session_media->handler) {<br>-                          continue;<br>-                    }<br>-                    ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",<br>-                           session_media->stream_type,<br>-                               handler->id);<br>-                     res = handler->apply_negotiated_sdp_stream(session, session_media, local,<br>-                         local->media[i], remote, remote->media[i]);<br>-                    if (res < 0) {<br>-                            /* Catastrophic failure. Abort! */<br>-                           return 0;<br>-                    }<br>-                    if (res > 0) {<br>-                            ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",<br>-                                    session_media->stream_type,<br>-                                       handler->id);<br>-                             /* Handled by this handler. Move to the next stream */<br>-                               session_media_set_handler(session_media, handler);<br>-                           return CMP_MATCH;<br>-                    }<br>-            }<br>-    }<br>-<br>- if (session_media->handler && session_media->handler->stream_stop) {<br>-                ast_debug(1, "Stopping SDP media stream '%s' as it is not currently negotiated\n",<br>-                 session_media->stream_type);<br>-              session_media->handler->stream_stop(session_media);<br>-    }<br>-<br>- return CMP_MATCH;<br>-}<br>-<br>-static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)<br>-{<br>-        RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);<br>-     struct handle_negotiated_sdp_cb callback_data = {<br>-            .session = session,<br>-          .local = local,<br>-              .remote = remote,<br>-    };<br>-<br>-        successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);<br>- if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {<br>-                /* Nothing experienced a catastrophic failure */<br>-             ast_queue_frame(session->channel, &ast_null_frame);<br>-           return 0;<br>-    }<br>-    return -1;<br>-}<br>-<br>-#define DATASTORE_BUCKETS 53<br>-#define MEDIA_BUCKETS 7<br>-<br>-static void session_datastore_destroy(void *obj)<br>-{<br>- struct ast_datastore *datastore = obj;<br>-<br>-    /* Using the destroy function (if present) destroy the data */<br>-       if (datastore->info->destroy != NULL && datastore->data != NULL) {<br>-          datastore->info->destroy(datastore->data);<br>-          datastore->data = NULL;<br>-   }<br>-<br>- ast_free((void *) datastore->uid);<br>-        datastore->uid = NULL;<br>-}<br>-<br>-struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)<br>-{<br>- RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);<br>-      char uuid_buf[AST_UUID_STR_LEN];<br>-     const char *uid_ptr = uid;<br>-<br>-        if (!info) {<br>-         return NULL;<br>- }<br>-<br>- datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);<br>-        if (!datastore) {<br>-            return NULL;<br>- }<br>-<br>- datastore->info = info;<br>-   if (ast_strlen_zero(uid)) {<br>-          /* They didn't provide an ID so we'll provide one ourself */<br>-         uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));<br>- }<br>-<br>- datastore->uid = ast_strdup(uid_ptr);<br>-     if (!datastore->uid) {<br>-            return NULL;<br>- }<br>-<br>- ao2_ref(datastore, +1);<br>-      return datastore;<br>-}<br>-<br>-int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)<br>-{<br>-   ast_assert(datastore != NULL);<br>-       ast_assert(datastore->info != NULL);<br>-      ast_assert(ast_strlen_zero(datastore->uid) == 0);<br>-<br>-      if (!ao2_link(session->datastores, datastore)) {<br>-          return -1;<br>-   }<br>-    return 0;<br>-}<br>-<br>-struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)<br>-{<br>-        return ao2_find(session->datastores, name, OBJ_KEY);<br>-}<br>-<br>-void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)<br>-{<br>-        ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);<br>-}<br>-<br>-enum delayed_method {<br>- DELAYED_METHOD_INVITE,<br>-       DELAYED_METHOD_UPDATE,<br>-       DELAYED_METHOD_BYE,<br>-};<br>-<br>-/*!<br>- * \internal<br>- * \brief Convert delayed method enum value to a string.<br>- * \since 13.3.0<br>- *<br>- * \param method Delayed method enum value to convert to a string.<br>- *<br>- * \return String value of delayed method.<br>- */<br>-static const char *delayed_method2str(enum delayed_method method)<br>-{<br>-     const char *str = "<unknown>";<br>-<br>-    switch (method) {<br>-    case DELAYED_METHOD_INVITE:<br>-          str = "INVITE";<br>-            break;<br>-       case DELAYED_METHOD_UPDATE:<br>-          str = "UPDATE";<br>-            break;<br>-       case DELAYED_METHOD_BYE:<br>-             str = "BYE";<br>-               break;<br>-       }<br>-<br>- return str;<br>-}<br>-<br>-/*!<br>- * \brief Structure used for sending delayed requests<br>- *<br>- * Requests are typically delayed because the current transaction<br>- * state of an INVITE. Once the pending INVITE transaction terminates,<br>- * the delayed request will be sent<br>- */<br>-struct ast_sip_session_delayed_request {<br>-    /*! Method of the request */<br>- enum delayed_method method;<br>-  /*! Callback to call when the delayed request is created. */<br>- ast_sip_session_request_creation_cb on_request_creation;<br>-     /*! Callback to call when the delayed request SDP is created */<br>-      ast_sip_session_sdp_creation_cb on_sdp_creation;<br>-     /*! Callback to call when the delayed request receives a response */<br>- ast_sip_session_response_cb on_response;<br>-     /*! Whether to generate new SDP */<br>-   int generate_new_sdp;<br>-        AST_LIST_ENTRY(ast_sip_session_delayed_request) next;<br>-};<br>-<br>-static struct ast_sip_session_delayed_request *delayed_request_alloc(<br>-        enum delayed_method method,<br>-  ast_sip_session_request_creation_cb on_request_creation,<br>-     ast_sip_session_sdp_creation_cb on_sdp_creation,<br>-     ast_sip_session_response_cb on_response,<br>-     int generate_new_sdp)<br>-{<br>-    struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));<br>-<br>-    if (!delay) {<br>-                return NULL;<br>- }<br>-    delay->method = method;<br>-   delay->on_request_creation = on_request_creation;<br>- delay->on_sdp_creation = on_sdp_creation;<br>- delay->on_response = on_response;<br>- delay->generate_new_sdp = generate_new_sdp;<br>-       return delay;<br>-}<br>-<br>-static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)<br>-{<br>-   ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",<br>-            ast_sorcery_object_get_id(session->endpoint),<br>-             session->channel ? ast_channel_name(session->channel) : "",<br>-          delayed_method2str(delay->method));<br>-<br>-    switch (delay->method) {<br>-  case DELAYED_METHOD_INVITE:<br>-          ast_sip_session_refresh(session, delay->on_request_creation,<br>-                      delay->on_sdp_creation, delay->on_response,<br>-                    AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);<br>-          return 0;<br>-    case DELAYED_METHOD_UPDATE:<br>-          ast_sip_session_refresh(session, delay->on_request_creation,<br>-                      delay->on_sdp_creation, delay->on_response,<br>-                    AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);<br>-          return 0;<br>-    case DELAYED_METHOD_BYE:<br>-             ast_sip_session_terminate(session, 0);<br>-               return 0;<br>-    }<br>-    ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",<br>-               delayed_method2str(delay->method), delay->method);<br>-     return -1;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief The current INVITE transaction is in the PROCEEDING state.<br>- * \since 13.3.0<br>- *<br>- * \param vsession Session object.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int invite_proceeding(void *vsession)<br>-{<br>-        struct ast_sip_session *session = vsession;<br>-  struct ast_sip_session_delayed_request *delay;<br>-       int found = 0;<br>-       int res = 0;<br>-<br>-      AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {<br>-               switch (delay->method) {<br>-          case DELAYED_METHOD_INVITE:<br>-                  break;<br>-               case DELAYED_METHOD_UPDATE:<br>-                  AST_LIST_REMOVE_CURRENT(next);<br>-                       res = send_delayed_request(session, delay);<br>-                  ast_free(delay);<br>-                     found = 1;<br>-                   break;<br>-               case DELAYED_METHOD_BYE:<br>-                     /* A BYE is pending so don't bother anymore. */<br>-                  found = 1;<br>-                   break;<br>-               }<br>-            if (found) {<br>-                 break;<br>-               }<br>-    }<br>-    AST_LIST_TRAVERSE_SAFE_END;<br>-<br>-       ao2_ref(session, -1);<br>-        return res;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief The current INVITE transaction is in the TERMINATED state.<br>- * \since 13.3.0<br>- *<br>- * \param vsession Session object.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int invite_terminated(void *vsession)<br>-{<br>-       struct ast_sip_session *session = vsession;<br>-  struct ast_sip_session_delayed_request *delay;<br>-       int found = 0;<br>-       int res = 0;<br>- int timer_running;<br>-<br>-        /* re-INVITE collision timer running? */<br>-     timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);<br>-<br>-    AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {<br>-               switch (delay->method) {<br>-          case DELAYED_METHOD_INVITE:<br>-                  if (!timer_running) {<br>-                                found = 1;<br>-                   }<br>-                    break;<br>-               case DELAYED_METHOD_UPDATE:<br>-          case DELAYED_METHOD_BYE:<br>-                     found = 1;<br>-                   break;<br>-               }<br>-            if (found) {<br>-                 AST_LIST_REMOVE_CURRENT(next);<br>-                       res = send_delayed_request(session, delay);<br>-                  ast_free(delay);<br>-                     break;<br>-               }<br>-    }<br>-    AST_LIST_TRAVERSE_SAFE_END;<br>-<br>-       ao2_ref(session, -1);<br>-        return res;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief INVITE collision timeout.<br>- * \since 13.3.0<br>- *<br>- * \param vsession Session object.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int invite_collision_timeout(void *vsession)<br>-{<br>- struct ast_sip_session *session = vsession;<br>-  int res;<br>-<br>-  if (session->inv_session->invite_tsx) {<br>-                /*<br>-            * INVITE transaction still active.  Let it send<br>-              * the collision re-INVITE when it terminates.<br>-                */<br>-          ao2_ref(session, -1);<br>-                res = 0;<br>-     } else {<br>-             res = invite_terminated(session);<br>-    }<br>-<br>- return res;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief The current UPDATE transaction is in the COMPLETED state.<br>- * \since 13.3.0<br>- *<br>- * \param vsession Session object.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int update_completed(void *vsession)<br>-{<br>- struct ast_sip_session *session = vsession;<br>-  int res;<br>-<br>-  if (session->inv_session->invite_tsx) {<br>-                res = invite_proceeding(session);<br>-    } else {<br>-             res = invite_terminated(session);<br>-    }<br>-<br>- return res;<br>-}<br>-<br>-static void check_delayed_requests(struct ast_sip_session *session,<br>-     int (*cb)(void *vsession))<br>-{<br>-       ao2_ref(session, +1);<br>-        if (ast_sip_push_task(session->serializer, cb, session)) {<br>-                ao2_ref(session, -1);<br>-        }<br>-}<br>-<br>-static int delay_request(struct ast_sip_session *session,<br>- ast_sip_session_request_creation_cb on_request,<br>-      ast_sip_session_sdp_creation_cb on_sdp_creation,<br>-     ast_sip_session_response_cb on_response,<br>-     int generate_new_sdp,<br>-        enum delayed_method method)<br>-{<br>-      struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,<br>-                        on_request, on_sdp_creation, on_response, generate_new_sdp);<br>-<br>-      if (!delay) {<br>-                return -1;<br>-   }<br>-<br>- if (method == DELAYED_METHOD_BYE) {<br>-          /* Send BYE as early as possible */<br>-          AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);<br>-        } else {<br>-             AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);<br>-        }<br>-    return 0;<br>-}<br>-<br>-static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)<br>-{<br>-     pjsip_inv_session *inv_session = session->inv_session;<br>-    const pjmedia_sdp_session *previous_sdp = NULL;<br>-<br>-   if (inv_session->neg) {<br>-           if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {<br>-                        pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);<br>-           } else {<br>-                     pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);<br>-            }<br>-    }<br>-    return create_local_sdp(inv_session, session, previous_sdp);<br>-}<br>-<br>-static void set_from_header(struct ast_sip_session *session)<br>-{<br>-       struct ast_party_id effective_id;<br>-    struct ast_party_id connected_id;<br>-    pj_pool_t *dlg_pool;<br>- pjsip_fromto_hdr *dlg_info;<br>-  pjsip_name_addr *dlg_info_name_addr;<br>- pjsip_sip_uri *dlg_info_uri;<br>- int restricted;<br>-<br>-   if (!session->channel || session->saved_from_hdr) {<br>-            return;<br>-      }<br>-<br>- /* We need to save off connected_id for RPID/PAI generation */<br>-       ast_party_id_init(&connected_id);<br>-        ast_channel_lock(session->channel);<br>-       effective_id = ast_channel_connected_effective_id(session->channel);<br>-      ast_party_id_copy(&connected_id, &effective_id);<br>-     ast_channel_unlock(session->channel);<br>-<br>-  restricted =<br>-         ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED);<br>-<br>-  /* Now set up dlg->local.info so pjsip can correctly generate From */<br>-<br>-  dlg_pool = session->inv_session->dlg->pool;<br>- dlg_info = session->inv_session->dlg->local.info;<br>-   dlg_info_name_addr = (pjsip_name_addr *) dlg_info->uri;<br>-   dlg_info_uri = pjsip_uri_get_uri(dlg_info_name_addr);<br>-<br>-     if (session->endpoint->id.trust_outbound || !restricted) {<br>-             ast_sip_modify_id_header(dlg_pool, dlg_info, &connected_id);<br>-     }<br>-<br>- ast_party_id_free(&connected_id);<br>-<br>-     if (!ast_strlen_zero(session->endpoint->fromuser)) {<br>-           dlg_info_name_addr->display.ptr = NULL;<br>-           dlg_info_name_addr->display.slen = 0;<br>-             pj_strdup2(dlg_pool, &dlg_info_uri->user, session->endpoint->fromuser);<br>- }<br>-<br>- if (!ast_strlen_zero(session->endpoint->fromdomain)) {<br>-         pj_strdup2(dlg_pool, &dlg_info_uri->host, session->endpoint->fromdomain);<br>-       }<br>-<br>- /* We need to save off the non-anonymized From for RPID/PAI generation (for domain) */<br>-       session->saved_from_hdr = pjsip_hdr_clone(dlg_pool, dlg_info);<br>-    ast_sip_add_usereqphone(session->endpoint, dlg_pool, session->saved_from_hdr->uri);<br>-<br>-      /* In chan_sip, fromuser and fromdomain trump restricted so we only<br>-   * anonymize if they're not set.<br>-  */<br>-  if (restricted) {<br>-            /* fromuser doesn't provide a display name so we always set it */<br>-                pj_strdup2(dlg_pool, &dlg_info_name_addr->display, "Anonymous");<br>-<br>-         if (ast_strlen_zero(session->endpoint->fromuser)) {<br>-                    pj_strdup2(dlg_pool, &dlg_info_uri->user, "anonymous");<br>-             }<br>-<br>-         if (ast_strlen_zero(session->endpoint->fromdomain)) {<br>-                  pj_strdup2(dlg_pool, &dlg_info_uri->host, "anonymous.invalid");<br>-             }<br>-    } else {<br>-             ast_sip_add_usereqphone(session->endpoint, dlg_pool, dlg_info->uri);<br>-    }<br>-}<br>-<br>-int ast_sip_session_refresh(struct ast_sip_session *session,<br>-             ast_sip_session_request_creation_cb on_request_creation,<br>-             ast_sip_session_sdp_creation_cb on_sdp_creation,<br>-             ast_sip_session_response_cb on_response,<br>-             enum ast_sip_session_refresh_method method, int generate_new_sdp)<br>-{<br>-        pjsip_inv_session *inv_session = session->inv_session;<br>-    pjmedia_sdp_session *new_sdp = NULL;<br>- pjsip_tx_data *tdata;<br>-<br>-     if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>-         /* Don't try to do anything with a hung-up call */<br>-               ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",<br>-                              ast_sorcery_object_get_id(session->endpoint));<br>-            return 0;<br>-    }<br>-<br>- /* If the dialog has not yet been established we have to defer until it has */<br>-       if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {<br>-               ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",<br>-                   ast_sorcery_object_get_id(session->endpoint));<br>-            return delay_request(session, on_request_creation, on_sdp_creation, on_response,<br>-                     generate_new_sdp,<br>-                    method == AST_SIP_SESSION_REFRESH_METHOD_INVITE<br>-                              ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);<br>-    }<br>-<br>- if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {<br>-               if (inv_session->invite_tsx) {<br>-                    /* We can't send a reinvite yet, so delay it */<br>-                  ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",<br>-                                       ast_sorcery_object_get_id(session->endpoint));<br>-                    return delay_request(session, on_request_creation, on_sdp_creation,<br>-                          on_response, generate_new_sdp, DELAYED_METHOD_INVITE);<br>-               } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {<br>-                     /* Initial INVITE transaction failed to progress us to a confirmed state<br>-                      * which means re-invites are not possible<br>-                    */<br>-                  ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",<br>-                                     ast_sorcery_object_get_id(session->endpoint));<br>-                    return 0;<br>-            }<br>-    }<br>-<br>- if (generate_new_sdp) {<br>-              /* SDP can only be generated if current negotiation has already completed */<br>-         if (inv_session->neg<br>-                      && pjmedia_sdp_neg_get_state(inv_session->neg)<br>-                            != PJMEDIA_SDP_NEG_STATE_DONE) {<br>-                     ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",<br>-                              ast_sorcery_object_get_id(session->endpoint));<br>-                    return delay_request(session, on_request_creation, on_sdp_creation,<br>-                          on_response, generate_new_sdp,<br>-                               method == AST_SIP_SESSION_REFRESH_METHOD_INVITE<br>-                                      ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);<br>-            }<br>-<br>-         new_sdp = generate_session_refresh_sdp(session);<br>-             if (!new_sdp) {<br>-                      ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");<br>-                       return -1;<br>-           }<br>-            if (on_sdp_creation) {<br>-                       if (on_sdp_creation(session, new_sdp)) {<br>-                             return -1;<br>-                   }<br>-            }<br>-    }<br>-<br>-<br>-      if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {<br>-               if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {<br>-                    ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");<br>-                     return -1;<br>-           }<br>-    } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {<br>-               ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");<br>-               return -1;<br>-   }<br>-    if (on_request_creation) {<br>-           if (on_request_creation(session, tdata)) {<br>-                   return -1;<br>-           }<br>-    }<br>-    ast_debug(3, "Sending session refresh SDP via %s to %s\n",<br>-         method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",<br>-                ast_sorcery_object_get_id(session->endpoint));<br>-    ast_sip_session_send_request_with_cb(session, tdata, on_response);<br>-   return 0;<br>-}<br>-<br>-int ast_sip_session_regenerate_answer(struct ast_sip_session *session,<br>-            ast_sip_session_sdp_creation_cb on_sdp_creation)<br>-{<br>- pjsip_inv_session *inv_session = session->inv_session;<br>-    pjmedia_sdp_session *new_answer = NULL;<br>-      const pjmedia_sdp_session *previous_offer = NULL;<br>-<br>- /* The SDP answer can only be regenerated if it is still pending to be sent */<br>-       if (!inv_session->neg || (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER &&<br>-         pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)) {<br>-                ast_log(LOG_WARNING, "Requested to regenerate local SDP answer for channel '%s' but negotiation in state '%s'\n",<br>-                  ast_channel_name(session->channel), pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv_session->neg)));<br>-           return -1;<br>-   }<br>-<br>- pjmedia_sdp_neg_get_neg_remote(inv_session->neg, &previous_offer);<br>-    if (pjmedia_sdp_neg_get_state(inv_session->neg) == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) {<br>-             /* Transition the SDP negotiator back to when it received the remote offer */<br>-                pjmedia_sdp_neg_negotiate(inv_session->pool, inv_session->neg, 0);<br>-             pjmedia_sdp_neg_set_remote_offer(inv_session->pool, inv_session->neg, previous_offer);<br>- }<br>-<br>- new_answer = create_local_sdp(inv_session, session, previous_offer);<br>- if (!new_answer) {<br>-           ast_log(LOG_WARNING, "Could not create a new local SDP answer for channel '%s'\n",<br>-                 ast_channel_name(session->channel));<br>-              return -1;<br>-   }<br>-<br>- if (on_sdp_creation) {<br>-               if (on_sdp_creation(session, new_answer)) {<br>-                  return -1;<br>-           }<br>-    }<br>-<br>- pjsip_inv_set_sdp_answer(inv_session, new_answer);<br>-<br>-        return 0;<br>-}<br>-<br>-void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>-{<br>-     handle_outgoing_response(session, tdata);<br>-    pjsip_inv_send_msg(session->inv_session, tdata);<br>-  return;<br>-}<br>-<br>-static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);<br>-<br>-static pjsip_module session_module = {<br>-   .name = {"Session Module", 14},<br>-    .priority = PJSIP_MOD_PRIORITY_APPLICATION,<br>-  .on_rx_request = session_on_rx_request,<br>-};<br>-<br>-/*! \brief Determine whether the SDP provided requires deferral of negotiating or not<br>- *<br>- * \retval 1 re-invite should be deferred and resumed later<br>- * \retval 0 re-invite should not be deferred<br>- */<br>-static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)<br>-{<br>-     int i;<br>-<br>-    for (i = 0; i < sdp->media_count; ++i) {<br>-               /* See if there are registered handlers for this media stream type */<br>-                char media[20];<br>-              struct ast_sip_session_sdp_handler *handler;<br>-         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>-                RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>-          enum ast_sip_session_sdp_stream_defer res;<br>-<br>-                /* We need a null-terminated version of the media string */<br>-          ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));<br>-<br>-              session_media = ao2_find(session->media, media, OBJ_KEY);<br>-         if (!session_media) {<br>-                        /* if the session_media doesn't exist, there weren't<br>-                  * any handlers at the time of its creation */<br>-                       continue;<br>-            }<br>-<br>-         if (session_media->handler) {<br>-                     handler = session_media->handler;<br>-                 if (handler->defer_incoming_sdp_stream) {<br>-                         res = handler->defer_incoming_sdp_stream(session, session_media, sdp,<br>-                                     sdp->media[i]);<br>-                           switch (res) {<br>-                               case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:<br>-                                  break;<br>-                               case AST_SIP_SESSION_SDP_DEFER_ERROR:<br>-                                        return 0;<br>-                            case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:<br>-                                   break;<br>-                               case AST_SIP_SESSION_SDP_DEFER_NEEDED:<br>-                                       return 1;<br>-                            }<br>-                    }<br>-                    /* Handled by this handler. Move to the next stream */<br>-                       continue;<br>-            }<br>-<br>-         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>-               if (!handler_list) {<br>-                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>-                   continue;<br>-            }<br>-            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-                       if (handler == session_media->handler) {<br>-                          continue;<br>-                    }<br>-                    if (!handler->defer_incoming_sdp_stream) {<br>-                                continue;<br>-                    }<br>-                    res = handler->defer_incoming_sdp_stream(session, session_media, sdp,<br>-                             sdp->media[i]);<br>-                   switch (res) {<br>-                       case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:<br>-                          continue;<br>-                    case AST_SIP_SESSION_SDP_DEFER_ERROR:<br>-                                session_media_set_handler(session_media, handler);<br>-                           return 0;<br>-                    case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:<br>-                           /* Handled by this handler. */<br>-                               session_media_set_handler(session_media, handler);<br>-                           break;<br>-                       case AST_SIP_SESSION_SDP_DEFER_NEEDED:<br>-                               /* Handled by this handler. */<br>-                               session_media_set_handler(session_media, handler);<br>-                           return 1;<br>-                    }<br>-                    /* Move to the next stream */<br>-                        break;<br>-               }<br>-    }<br>-    return 0;<br>-}<br>-<br>-static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)<br>-{<br>- pjsip_dialog *dlg;<br>-   RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>-      pjsip_rdata_sdp_info *sdp_info;<br>-<br>-   if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||<br>-          !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||<br>-             !(session = ast_sip_dialog_get_session(dlg)) ||<br>-              !session->channel) {<br>-              return PJ_FALSE;<br>-     }<br>-<br>- if (session->deferred_reinvite) {<br>-         pj_str_t key, deferred_key;<br>-          pjsip_tx_data *tdata;<br>-<br>-             /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */<br>-               pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);<br>-              pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,<br>-                     session->deferred_reinvite);<br>-<br>-           /* If this is a retransmission ignore it */<br>-          if (!pj_strcmp(&key, &deferred_key)) {<br>-                       return PJ_TRUE;<br>-              }<br>-<br>-         /* Otherwise this is a new re-invite, so reject it */<br>-                if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {<br>-                    pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);<br>-          }<br>-<br>-         return PJ_TRUE;<br>-      }<br>-<br>- if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||<br>-         (sdp_info->sdp_err != PJ_SUCCESS)) {<br>-              return PJ_FALSE;<br>-     }<br>-<br>- if (!sdp_info->sdp) {<br>-             const pjmedia_sdp_session *local;<br>-            int i;<br>-<br>-            ast_queue_unhold(session->channel);<br>-<br>-            pjmedia_sdp_neg_get_active_local(session->inv_session->neg, &local);<br>-               if (!local) {<br>-                        return PJ_FALSE;<br>-             }<br>-<br>-         /*<br>-            * Some devices indicate hold with deferred SDP reinvites (i.e. no SDP in the reinvite).<br>-              * When hold is initially indicated, we<br>-               * - Receive an INVITE with no SDP<br>-            * - Send a 200 OK with SDP, indicating sendrecv in the media streams<br>-                 * - Receive an ACK with SDP, indicating sendonly in the media streams<br>-                *<br>-            * At this point, the pjmedia negotiator saves the state of the media direction so that<br>-               * if we are to send any offers, we'll offer recvonly in the media streams. This is<br>-               * problematic if the device is attempting to unhold, though. If the device unholds<br>-           * by sending a reinvite with no SDP, then we will respond with a 200 OK with recvonly.<br>-               * According to RFC 3264, if an offerer offers recvonly, then the answerer MUST respond<br>-               * with sendonly or inactive. The result of this is that the stream is not off hold.<br>-          *<br>-            * Therefore, in this case, when we receive a reinvite while the stream is on hold, we<br>-                * need to be sure to offer sendrecv. This way, the answerer can respond with sendrecv<br>-                * in order to get the stream off hold. If this is actually a different purpose reinvite<br>-              * (like a session timer refresh), then the answerer can respond to our sendrecv with<br>-                 * sendonly, keeping the stream on hold.<br>-              */<br>-          for (i = 0; i < local->media_count; ++i) {<br>-                     pjmedia_sdp_media *m = local->media[i];<br>-                   pjmedia_sdp_attr *recvonly;<br>-                  pjmedia_sdp_attr *inactive;<br>-<br>-                       recvonly = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "recvonly", NULL);<br>-                 inactive = pjmedia_sdp_attr_find2(m->attr_count, m->attr, "inactive", NULL);<br>-                 if (recvonly || inactive) {<br>-                          pjmedia_sdp_attr *to_remove = recvonly ?: inactive;<br>-                          pjmedia_sdp_attr *sendrecv;<br>-<br>-                               pjmedia_sdp_attr_remove(&m->attr_count, m->attr, to_remove);<br>-<br>-                            sendrecv = pjmedia_sdp_attr_create(session->inv_session->pool, "sendrecv", NULL);<br>-                            pjmedia_sdp_media_add_attr(m, sendrecv);<br>-                     }<br>-            }<br>-<br>-         return PJ_FALSE;<br>-     }<br>-<br>- if (!sdp_requires_deferral(session, sdp_info->sdp)) {<br>-             return PJ_FALSE;<br>-     }<br>-<br>- pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);<br>-<br>-        return PJ_TRUE;<br>-}<br>-<br>-void ast_sip_session_resume_reinvite(struct ast_sip_session *session)<br>-{<br>-   if (!session->deferred_reinvite) {<br>-                return;<br>-      }<br>-<br>- if (session->channel) {<br>-           pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(),<br>-                    session->deferred_reinvite, NULL, NULL);<br>-  }<br>-    pjsip_rx_data_free_cloned(session->deferred_reinvite);<br>-    session->deferred_reinvite = NULL;<br>-}<br>-<br>-static pjsip_module session_reinvite_module = {<br>-       .name = { "Session Re-Invite Module", 24 },<br>-        .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,<br>-   .on_rx_request = session_reinvite_on_rx_request,<br>-};<br>-<br>-<br>-void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,<br>-               ast_sip_session_response_cb on_response)<br>-{<br>- pjsip_inv_session *inv_session = session->inv_session;<br>-<br>- /* For every request except BYE we disallow sending of the message when<br>-       * the session has been disconnected. A BYE request is special though<br>-         * because it can be sent again after the session is disconnected except<br>-      * with credentials.<br>-  */<br>-  if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED &&<br>-         tdata->msg->line.req.method.id != PJSIP_BYE_METHOD) {<br>-          return;<br>-      }<br>-<br>- ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,<br>-                       MOD_DATA_ON_RESPONSE, on_response);<br>-<br>-  handle_outgoing_request(session, tdata);<br>-     pjsip_inv_send_msg(session->inv_session, tdata);<br>-<br>-       return;<br>-}<br>-<br>-void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>-{<br>-        ast_sip_session_send_request_with_cb(session, tdata, NULL);<br>-}<br>-<br>-int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)<br>-{<br>-   pjmedia_sdp_session *offer;<br>-<br>-       if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {<br>-           pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);<br>-         return -1;<br>-   }<br>-<br>- pjsip_inv_set_local_sdp(session->inv_session, offer);<br>-     pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);<br>-#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS<br>-    pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);<br>-#endif<br>-<br>-    /*<br>-    * We MUST call set_from_header() before pjsip_inv_invite.  If we don't, the<br>-      * From in the initial INVITE will be wrong but the rest of the messages will be OK.<br>-  */<br>-  set_from_header(session);<br>-<br>- if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {<br>-                return -1;<br>-   }<br>-<br>- return 0;<br>-}<br>-<br>-static int datastore_hash(const void *obj, int flags)<br>-{<br>- const struct ast_datastore *datastore = obj;<br>- const char *uid = flags & OBJ_KEY ? obj : datastore->uid;<br>-<br>-  ast_assert(uid != NULL);<br>-<br>-  return ast_str_hash(uid);<br>-}<br>-<br>-static int datastore_cmp(void *obj, void *arg, int flags)<br>-{<br>-     const struct ast_datastore *datastore1 = obj;<br>-        const struct ast_datastore *datastore2 = arg;<br>-        const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;<br>-<br>-        ast_assert(datastore1->uid != NULL);<br>-      ast_assert(uid2 != NULL);<br>-<br>- return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;<br>-}<br>-<br>-static void session_media_dtor(void *obj)<br>-{<br>-   struct ast_sip_session_media *session_media = obj;<br>-   struct sdp_handler_list *handler_list;<br>-       /* It is possible for SDP handlers to allocate memory on a session_media but<br>-  * not end up getting set as the handler for this session_media. This traversal<br>-       * ensures that all memory allocated by SDP handlers on the session_media is<br>-  * cleared (as well as file descriptors, etc.).<br>-       */<br>-  handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);<br>-       if (handler_list) {<br>-          struct ast_sip_session_sdp_handler *handler;<br>-<br>-              AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-                       handler->stream_destroy(session_media);<br>-           }<br>-    }<br>-    ao2_cleanup(handler_list);<br>-   if (session_media->srtp) {<br>-                ast_sdp_srtp_destroy(session_media->srtp);<br>-        }<br>-}<br>-<br>-static void session_destructor(void *obj)<br>-{<br>-     struct ast_sip_session *session = obj;<br>-       struct ast_sip_session_supplement *supplement;<br>-       struct ast_sip_session_delayed_request *delay;<br>-       const char *endpoint_name = session->endpoint ?<br>-           ast_sorcery_object_get_id(session->endpoint) : "<none>";<br>-<br>-       ast_debug(3, "Destroying SIP session with endpoint %s\n", endpoint_name);<br>-<br>-       ast_test_suite_event_notify("SESSION_DESTROYING",<br>-          "Endpoint: %s\r\n"<br>-         "AOR: %s\r\n"<br>-              "Contact: %s"<br>-              , endpoint_name<br>-              , session->aor ? ast_sorcery_object_get_id(session->aor) : "<none>"<br>-            , session->contact ? ast_sorcery_object_get_id(session->contact) : "<none>"<br>-            );<br>-<br>-        while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {<br>-            if (supplement->session_destroy) {<br>-                        supplement->session_destroy(session);<br>-             }<br>-            ast_free(supplement);<br>-        }<br>-<br>- ast_taskprocessor_unreference(session->serializer);<br>-       ao2_cleanup(session->datastores);<br>- ao2_cleanup(session->media);<br>-<br>-   AST_LIST_HEAD_DESTROY(&session->supplements);<br>- while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {<br>-            ast_free(delay);<br>-     }<br>-    ast_party_id_free(&session->id);<br>-      ao2_cleanup(session->endpoint);<br>-   ao2_cleanup(session->aor);<br>-        ao2_cleanup(session->contact);<br>-    ao2_cleanup(session->req_caps);<br>-   ao2_cleanup(session->direct_media_cap);<br>-<br>-        ast_dsp_free(session->dsp);<br>-<br>-    if (session->inv_session) {<br>-               pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);<br>- }<br>-<br>- ast_test_suite_event_notify("SESSION_DESTROYED", "Endpoint: %s", endpoint_name);<br>-}<br>-<br>-static int add_session_media(void *obj, void *arg, int flags)<br>-{<br>-      struct sdp_handler_list *handler_list = obj;<br>- struct ast_sip_session *session = arg;<br>-       RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);<br>-<br>-       session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);<br>-        if (!session_media) {<br>-                return CMP_STOP;<br>-     }<br>-    session_media->encryption = session->endpoint->media.rtp.encryption;<br>-        session_media->keepalive_sched_id = -1;<br>-   session_media->timeout_sched_id = -1;<br>-     /* Safe use of strcpy */<br>-     strcpy(session_media->stream_type, handler_list->stream_type);<br>- ao2_link(session->media, session_media);<br>-  return 0;<br>-}<br>-<br>-/*! \brief Destructor for SIP channel */<br>-static void sip_channel_destroy(void *obj)<br>-{<br>- struct ast_sip_channel_pvt *channel = obj;<br>-<br>-        ao2_cleanup(channel->pvt);<br>-        ao2_cleanup(channel->session);<br>-}<br>-<br>-struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)<br>-{<br>-     struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);<br>-<br>-   if (!channel) {<br>-              return NULL;<br>- }<br>-<br>- ao2_ref(pvt, +1);<br>-    channel->pvt = pvt;<br>-       ao2_ref(session, +1);<br>-        channel->session = session;<br>-<br>-    return channel;<br>-}<br>-<br>-struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,<br>-    struct ast_sip_contact *contact, pjsip_inv_session *inv_session, pjsip_rx_data *rdata)<br>-{<br>-   RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>-      struct ast_sip_session *ret_session;<br>- struct ast_sip_session_supplement *iter;<br>-     int dsp_features = 0;<br>-<br>-     session = ao2_alloc(sizeof(*session), session_destructor);<br>-   if (!session) {<br>-              return NULL;<br>- }<br>-<br>- AST_LIST_HEAD_INIT(&session->supplements);<br>-    AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);<br>-        ast_party_id_init(&session->id);<br>-<br>-   session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>-    if (!session->direct_media_cap) {<br>-         return NULL;<br>- }<br>-    session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>-    if (!session->req_caps) {<br>-         return NULL;<br>- }<br>-    session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);<br>-      if (!session->datastores) {<br>-               return NULL;<br>- }<br>-<br>- if (endpoint->dtmf == AST_SIP_DTMF_INBAND || endpoint->dtmf == AST_SIP_DTMF_AUTO) {<br>-            dsp_features |= DSP_FEATURE_DIGIT_DETECT;<br>-    }<br>-    if (endpoint->faxdetect) {<br>-                dsp_features |= DSP_FEATURE_FAX_DETECT;<br>-      }<br>-    if (dsp_features) {<br>-          session->dsp = ast_dsp_new();<br>-             if (!session->dsp) {<br>-                      return NULL;<br>-         }<br>-<br>-         ast_dsp_set_features(session->dsp, dsp_features);<br>- }<br>-<br>- session->endpoint = ao2_bump(endpoint);<br>-<br>-        session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);<br>-       if (!session->media) {<br>-            return NULL;<br>- }<br>-    /* fill session->media with available types */<br>-    ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);<br>-<br>-       if (rdata) {<br>-         /*<br>-            * We must continue using the serializer that the original<br>-            * INVITE came in on for the dialog.  There may be<br>-            * retransmissions already enqueued in the original<br>-           * serializer that can result in reentrancy and message<br>-               * sequencing problems.<br>-               */<br>-          session->serializer = ast_sip_get_distributor_serializer(rdata);<br>-  } else {<br>-             char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];<br>-<br>-            /* Create name with seq number appended. */<br>-          ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/outsess/%s",<br>-                       ast_sorcery_object_get_id(endpoint));<br>-<br>-             session->serializer = ast_sip_create_serializer_named(tps_name);<br>-  }<br>-    if (!session->serializer) {<br>-               return NULL;<br>- }<br>-    ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);<br>-  ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);<br>-  pjsip_dlg_inc_session(inv_session->dlg, &session_module);<br>-     inv_session->mod_data[session_module.id] = ao2_bump(session);<br>-     session->contact = ao2_bump(contact);<br>-     session->inv_session = inv_session;<br>-<br>-    session->dtmf = endpoint->dtmf;<br>-<br>-     if (ast_sip_session_add_supplements(session)) {<br>-              /* Release the ref held by session->inv_session */<br>-                ao2_ref(session, -1);<br>-                return NULL;<br>- }<br>-    AST_LIST_TRAVERSE(&session->supplements, iter, next) {<br>-                if (iter->session_begin) {<br>-                        iter->session_begin(session);<br>-             }<br>-    }<br>-<br>- /* Avoid unnecessary ref manipulation to return a session */<br>- ret_session = session;<br>-       session = NULL;<br>-      return ret_session;<br>-}<br>-<br>-/*! \brief struct controlling the suspension of the session's serializer. */<br>-struct ast_sip_session_suspender {<br>-   ast_cond_t cond_suspended;<br>-   ast_cond_t cond_complete;<br>-    int suspended;<br>-       int complete;<br>-};<br>-<br>-static void sip_session_suspender_dtor(void *vdoomed)<br>-{<br>-    struct ast_sip_session_suspender *doomed = vdoomed;<br>-<br>-       ast_cond_destroy(&doomed->cond_suspended);<br>-    ast_cond_destroy(&doomed->cond_complete);<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief Block the session serializer thread task.<br>- *<br>- * \param data Pushed serializer task data for suspension.<br>- *<br>- * \retval 0<br>- */<br>-static int sip_session_suspend_task(void *data)<br>-{<br>- struct ast_sip_session_suspender *suspender = data;<br>-<br>-       ao2_lock(suspender);<br>-<br>-      /* Signal that the serializer task is now suspended. */<br>-      suspender->suspended = 1;<br>- ast_cond_signal(&suspender->cond_suspended);<br>-<br>-       /* Wait for the serializer suspension to be completed. */<br>-    while (!suspender->complete) {<br>-            ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));<br>- }<br>-<br>- ao2_unlock(suspender);<br>-       ao2_ref(suspender, -1);<br>-<br>-   return 0;<br>-}<br>-<br>-void ast_sip_session_suspend(struct ast_sip_session *session)<br>-{<br>- struct ast_sip_session_suspender *suspender;<br>- int res;<br>-<br>-  ast_assert(session->suspended == NULL);<br>-<br>-        if (ast_taskprocessor_is_task(session->serializer)) {<br>-             /* I am the session's serializer thread so I cannot suspend. */<br>-          return;<br>-      }<br>-<br>- if (ast_taskprocessor_is_suspended(session->serializer)) {<br>-                /* The serializer already suspended. */<br>-              return;<br>-      }<br>-<br>- suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);<br>-       if (!suspender) {<br>-            /* We will just have to hope that the system does not deadlock */<br>-            return;<br>-      }<br>-    ast_cond_init(&suspender->cond_suspended, NULL);<br>-      ast_cond_init(&suspender->cond_complete, NULL);<br>-<br>-    ao2_ref(suspender, +1);<br>-      res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);<br>-        if (res) {<br>-           /* We will just have to hope that the system does not deadlock */<br>-            ao2_ref(suspender, -2);<br>-              return;<br>-      }<br>-<br>- session->suspended = suspender;<br>-<br>-        /* Wait for the serializer to get suspended. */<br>-      ao2_lock(suspender);<br>- while (!suspender->suspended) {<br>-           ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));<br>-        }<br>-    ao2_unlock(suspender);<br>-<br>-    ast_taskprocessor_suspend(session->serializer);<br>-}<br>-<br>-void ast_sip_session_unsuspend(struct ast_sip_session *session)<br>-{<br>-      struct ast_sip_session_suspender *suspender = session->suspended;<br>-<br>-      if (!suspender) {<br>-            /* Nothing to do */<br>-          return;<br>-      }<br>-    session->suspended = NULL;<br>-<br>-     /* Signal that the serializer task suspension is now complete. */<br>-    ao2_lock(suspender);<br>- suspender->complete = 1;<br>-  ast_cond_signal(&suspender->cond_complete);<br>-   ao2_unlock(suspender);<br>-<br>-    ao2_ref(suspender, -1);<br>-<br>-   ast_taskprocessor_unsuspend(session->serializer);<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief Handle initial INVITE challenge response message.<br>- * \since 13.5.0<br>- *<br>- * \param rdata PJSIP receive response message data.<br>- *<br>- * \retval PJ_FALSE Did not handle message.<br>- * \retval PJ_TRUE Handled message.<br>- */<br>-static pj_bool_t outbound_invite_auth(pjsip_rx_data *rdata)<br>-{<br>-       pjsip_transaction *tsx;<br>-      pjsip_dialog *dlg;<br>-   pjsip_inv_session *inv;<br>-      pjsip_tx_data *tdata;<br>-        struct ast_sip_session *session;<br>-<br>-  if (rdata->msg_info.msg->line.status.code != 401<br>-               && rdata->msg_info.msg->line.status.code != 407) {<br>-             /* Doesn't pertain to us. Move on */<br>-             return PJ_FALSE;<br>-     }<br>-<br>- tsx = pjsip_rdata_get_tsx(rdata);<br>-    dlg = pjsip_rdata_get_dlg(rdata);<br>-    if (!dlg || !tsx) {<br>-          return PJ_FALSE;<br>-     }<br>-<br>- if (tsx->method.id != PJSIP_INVITE_METHOD) {<br>-              /* Not an INVITE that needs authentication */<br>-                return PJ_FALSE;<br>-     }<br>-<br>- inv = pjsip_dlg_get_inv_session(dlg);<br>-        if (PJSIP_INV_STATE_CONFIRMED <= inv->state) {<br>-         /*<br>-            * We cannot handle reINVITE authentication at this<br>-           * time because the reINVITE transaction is still in<br>-          * progress.<br>-          */<br>-          ast_debug(1, "A reINVITE is being challenged.\n");<br>-         return PJ_FALSE;<br>-     }<br>-    ast_debug(1, "Initial INVITE is being challenged.\n");<br>-<br>-  session = inv->mod_data[session_module.id];<br>-<br>-    if (ast_sip_create_request_with_auth(&session->endpoint->outbound_auths, rdata, tsx,<br>-               &tdata)) {<br>-               return PJ_FALSE;<br>-     }<br>-<br>- /*<br>-    * Restart the outgoing initial INVITE transaction to deal<br>-    * with authentication.<br>-       */<br>-  pjsip_inv_uac_restart(inv, PJ_FALSE);<br>-<br>-     ast_sip_session_send_request(session, tdata);<br>-        return PJ_TRUE;<br>-}<br>-<br>-static pjsip_module outbound_invite_auth_module = {<br>- .name = {"Outbound INVITE Auth", 20},<br>-      .priority = PJSIP_MOD_PRIORITY_DIALOG_USAGE,<br>- .on_rx_response = outbound_invite_auth,<br>-};<br>-<br>-/*!<br>- * \internal<br>- * \brief Setup outbound initial INVITE authentication.<br>- * \since 13.5.0<br>- *<br>- * \param dlg PJSIP dialog to attach outbound authentication.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int setup_outbound_invite_auth(pjsip_dialog *dlg)<br>-{<br>-        pj_status_t status;<br>-<br>-       ++dlg->sess_count;<br>-        status = pjsip_dlg_add_usage(dlg, &outbound_invite_auth_module, NULL);<br>-   --dlg->sess_count;<br>-<br>-     return status != PJ_SUCCESS ? -1 : 0;<br>-}<br>-<br>-struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,<br>-    struct ast_sip_contact *contact, const char *location, const char *request_user,<br>-     struct ast_format_cap *req_caps)<br>-{<br>- const char *uri = NULL;<br>-      RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);<br>-        RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);<br>-        pjsip_timer_setting timer;<br>-   pjsip_dialog *dlg;<br>-   struct pjsip_inv_session *inv_session;<br>-       RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);<br>-      struct ast_sip_session *ret_session;<br>-<br>-      /* If no location has been provided use the AOR list from the endpoint itself */<br>-     if (location || !contact) {<br>-          location = S_OR(location, endpoint->aors);<br>-<br>-             ast_sip_location_retrieve_contact_and_aor_from_list_filtered(location, AST_SIP_CONTACT_FILTER_REACHABLE,<br>-                     &found_aor, &found_contact);<br>-         if (!found_contact || ast_strlen_zero(found_contact->uri)) {<br>-                      uri = location;<br>-              } else {<br>-                     uri = found_contact->uri;<br>-         }<br>-    } else {<br>-             uri = contact->uri;<br>-       }<br>-<br>- /* If we still have no URI to dial fail to create the session */<br>-     if (ast_strlen_zero(uri)) {<br>-          ast_log(LOG_ERROR, "Endpoint '%s': No URI available.  Is endpoint registered?\n",<br>-                  ast_sorcery_object_get_id(endpoint));<br>-                return NULL;<br>- }<br>-<br>- if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {<br>-               return NULL;<br>- }<br>-<br>- if (setup_outbound_invite_auth(dlg)) {<br>-               pjsip_dlg_terminate(dlg);<br>-            return NULL;<br>- }<br>-<br>- if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {<br>-                pjsip_dlg_terminate(dlg);<br>-            return NULL;<br>- }<br>-#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)<br>-      inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;<br>-#endif<br>-<br>-      pjsip_timer_setting_default(&timer);<br>-     timer.min_se = endpoint->extensions.timer.min_se;<br>- timer.sess_expires = endpoint->extensions.timer.sess_expires;<br>-     pjsip_timer_init_session(inv_session, &timer);<br>-<br>-        session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact,<br>-           inv_session, NULL);<br>-  if (!session) {<br>-              pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>-             return NULL;<br>- }<br>-    session->aor = ao2_bump(found_aor);<br>-       ast_party_id_copy(&session->id, &endpoint->id.self);<br>-<br>-        if (ast_format_cap_count(req_caps)) {<br>-                /* get joint caps between req_caps and endpoint caps */<br>-              struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);<br>-<br>-            ast_format_cap_get_compatible(req_caps, endpoint->media.codecs, joint_caps);<br>-<br>-           /* if joint caps */<br>-          if (ast_format_cap_count(joint_caps)) {<br>-                      /* copy endpoint caps into session->req_caps */<br>-                   ast_format_cap_append_from_cap(session->req_caps,<br>-                         endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);<br>-                  /* replace instances of joint caps equivalents in session->req_caps */<br>-                    ast_format_cap_replace_from_cap(session->req_caps, joint_caps,<br>-                            AST_MEDIA_TYPE_UNKNOWN);<br>-             }<br>-            ao2_cleanup(joint_caps);<br>-     }<br>-<br>- if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {<br>-             pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>-             /* Since we are not notifying ourselves that the INVITE session is being terminated<br>-           * we need to manually drop its reference to session<br>-          */<br>-          ao2_ref(session, -1);<br>-                return NULL;<br>- }<br>-<br>- /* Avoid unnecessary ref manipulation to return a session */<br>- ret_session = session;<br>-       session = NULL;<br>-      return ret_session;<br>-}<br>-<br>-static int session_end(void *vsession);<br>-static int session_end_completion(void *vsession);<br>-<br>-void ast_sip_session_terminate(struct ast_sip_session *session, int response)<br>-{<br>-     pj_status_t status;<br>-  pjsip_tx_data *packet = NULL;<br>-<br>-     if (session->defer_terminate) {<br>-           session->terminate_while_deferred = 1;<br>-            return;<br>-      }<br>-<br>- if (!response) {<br>-             response = 603;<br>-      }<br>-<br>- switch (session->inv_session->state) {<br>- case PJSIP_INV_STATE_NULL:<br>-           if (!session->inv_session->invite_tsx) {<br>-                       /*<br>-                    * Normally, it's pjproject's transaction cleanup that ultimately causes the<br>-                  * final session reference to be released but if both STATE and invite_tsx are NULL,<br>-                  * we never created a transaction in the first place.  In this case, we need to<br>-                       * do the cleanup ourselves.<br>-                  */<br>-                  /* Transfer the inv_session session reference to the session_end_task */<br>-                     session->inv_session->mod_data[session_module.id] = NULL;<br>-                      pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);<br>-                     session_end(session);<br>-                        /*<br>-                    * session_end_completion will cleanup the final session reference unless<br>-                     * ast_sip_session_terminate's caller is holding one.<br>-                     */<br>-                  session_end_completion(session);<br>-             } else {<br>-                     pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);<br>-             }<br>-            break;<br>-       case PJSIP_INV_STATE_CONFIRMED:<br>-              if (session->inv_session->invite_tsx) {<br>-                        ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",<br>-                                    ast_sorcery_object_get_id(session->endpoint));<br>-                    /* If this is delayed the only thing that will happen is a BYE request so we don't<br>-                        * actually need to store the response code for when it happens.<br>-                      */<br>-                  delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);<br>-                     break;<br>-               }<br>-            /* Fall through */<br>-   default:<br>-             status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet);<br>-                if (status == PJ_SUCCESS && packet) {<br>-                        struct ast_sip_session_delayed_request *delay;<br>-<br>-                    /* Flush any delayed requests so they cannot overlap this transaction. */<br>-                    while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {<br>-                            ast_free(delay);<br>-                     }<br>-<br>-                 if (packet->msg->type == PJSIP_RESPONSE_MSG) {<br>-                         ast_sip_session_send_response(session, packet);<br>-                      } else {<br>-                             ast_sip_session_send_request(session, packet);<br>-                       }<br>-            }<br>-            break;<br>-       }<br>-}<br>-<br>-static int session_termination_task(void *data)<br>-{<br>-       struct ast_sip_session *session = data;<br>-<br>-   if (session->defer_terminate) {<br>-           session->defer_terminate = 0;<br>-             if (session->inv_session) {<br>-                       ast_sip_session_terminate(session, 0);<br>-               }<br>-    }<br>-<br>- ao2_ref(session, -1);<br>-        return 0;<br>-}<br>-<br>-static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)<br>-{<br>- struct ast_sip_session *session = entry->user_data;<br>-<br>-    if (ast_sip_push_task(session->serializer, session_termination_task, session)) {<br>-          ao2_cleanup(session);<br>-        }<br>-}<br>-<br>-int ast_sip_session_defer_termination(struct ast_sip_session *session)<br>-{<br>-        pj_time_val delay = { .sec = 60, };<br>-  int res;<br>-<br>-  /* The session should not have an active deferred termination request. */<br>-    ast_assert(!session->defer_terminate);<br>-<br>- session->defer_terminate = 1;<br>-<br>-  session->defer_end = 1;<br>-   session->ended_while_deferred = 0;<br>-<br>-     session->scheduled_termination.id = 0;<br>-    ao2_ref(session, +1);<br>-        session->scheduled_termination.user_data = session;<br>-       session->scheduled_termination.cb = session_termination_cb;<br>-<br>-    res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),<br>-              &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;<br>- if (res) {<br>-           session->defer_terminate = 0;<br>-             ao2_ref(session, -1);<br>-        }<br>-    return res;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief Stop the defer termination timer if it is still running.<br>- * \since 13.5.0<br>- *<br>- * \param session Which session to stop the timer.<br>- *<br>- * \return Nothing<br>- */<br>-static void sip_session_defer_termination_stop_timer(struct ast_sip_session *session)<br>-{<br>-        if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),<br>-           &session->scheduled_termination)) {<br>-           ao2_ref(session, -1);<br>-        }<br>-}<br>-<br>-void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)<br>-{<br>-        if (!session->defer_terminate) {<br>-          /* Already canceled or timer fired. */<br>-               return;<br>-      }<br>-<br>- session->defer_terminate = 0;<br>-<br>-  if (session->terminate_while_deferred) {<br>-          /* Complete the termination started by the upper layer. */<br>-           ast_sip_session_terminate(session, 0);<br>-       }<br>-<br>- /* Stop the termination timer if it is still running. */<br>-     sip_session_defer_termination_stop_timer(session);<br>-}<br>-<br>-void ast_sip_session_end_if_deferred(struct ast_sip_session *session)<br>-{<br>-        if (!session->defer_end) {<br>-                return;<br>-      }<br>-<br>- session->defer_end = 0;<br>-<br>-        if (session->ended_while_deferred) {<br>-              /* Complete the session end started by the remote hangup. */<br>-         ast_debug(3, "Ending session (%p) after being deferred\n", session);<br>-               session->ended_while_deferred = 0;<br>-                session_end(session);<br>-        }<br>-}<br>-<br>-struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)<br>-{<br>- pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);<br>-     struct ast_sip_session *session;<br>-<br>-  if (!inv_session ||<br>-          !(session = inv_session->mod_data[session_module.id])) {<br>-          return NULL;<br>- }<br>-<br>- ao2_ref(session, +1);<br>-<br>-     return session;<br>-}<br>-<br>-enum sip_get_destination_result {<br>-   /*! The extension was successfully found */<br>-  SIP_GET_DEST_EXTEN_FOUND,<br>-    /*! The extension specified in the RURI was not found */<br>-     SIP_GET_DEST_EXTEN_NOT_FOUND,<br>-        /*! The extension specified in the RURI was a partial match */<br>-       SIP_GET_DEST_EXTEN_PARTIAL,<br>-  /*! The RURI is of an unsupported scheme */<br>-  SIP_GET_DEST_UNSUPPORTED_URI,<br>-};<br>-<br>-/*!<br>- * \brief Determine where in the dialplan a call should go<br>- *<br>- * This uses the username in the request URI to try to match<br>- * an extension in the endpoint's configured context in order<br>- * to route the call.<br>- *<br>- * \param session The inbound SIP session<br>- * \param rdata The SIP INVITE<br>- */<br>-static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)<br>-{<br>- pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;<br>-   pjsip_sip_uri *sip_ruri;<br>-     struct ast_features_pickup_config *pickup_cfg;<br>-       const char *pickupexten;<br>-<br>-  if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {<br>-             return SIP_GET_DEST_UNSUPPORTED_URI;<br>- }<br>-<br>- sip_ruri = pjsip_uri_get_uri(ruri);<br>-  ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));<br>-<br>-    /*<br>-    * We may want to match in the dialplan without any user<br>-      * options getting in the way.<br>-        */<br>-  AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(session->exten);<br>-<br>-   pickup_cfg = ast_get_chan_features_pickup_config(session->channel);<br>-       if (!pickup_cfg) {<br>-           ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");<br>-           pickupexten = "";<br>-  } else {<br>-             pickupexten = ast_strdupa(pickup_cfg->pickupexten);<br>-               ao2_ref(pickup_cfg, -1);<br>-     }<br>-<br>- if (!strcmp(session->exten, pickupexten) ||<br>-               ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {<br>-          size_t size = pj_strlen(&sip_ruri->host) + 1;<br>-         char *domain = ast_alloca(size);<br>-<br>-          ast_copy_pj_str(domain, &sip_ruri->host, size);<br>-               pbx_builtin_setvar_helper(session->channel, "SIPDOMAIN", domain);<br>-<br>-            /*<br>-            * Save off the INVITE Request-URI in case it is<br>-              * needed: CHANNEL(pjsip,request_uri)<br>-                 */<br>-          session->request_uri = pjsip_uri_clone(session->inv_session->pool, ruri);<br>-<br>-                return SIP_GET_DEST_EXTEN_FOUND;<br>-     }<br>-<br>- /*<br>-    * Check for partial match via overlap dialling (if enabled)<br>-  */<br>-  if (session->endpoint->allow_overlap && (<br>-              !strncmp(session->exten, pickupexten, strlen(session->exten)) ||<br>-               ast_canmatch_extension(NULL, session->endpoint->context, session->exten, 1, NULL))) {<br>-               /* Overlap partial match */<br>-          return SIP_GET_DEST_EXTEN_PARTIAL;<br>-   }<br>-<br>- return SIP_GET_DEST_EXTEN_NOT_FOUND;<br>-}<br>-<br>-static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)<br>-{<br>- pjsip_tx_data *tdata;<br>-        pjsip_dialog *dlg;<br>-   pjsip_inv_session *inv_session;<br>-      unsigned int options = endpoint->extensions.flags;<br>-        pj_status_t dlg_status;<br>-<br>-   if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {<br>-             if (tdata) {<br>-                 pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);<br>-          } else {<br>-                     pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>-           }<br>-            return NULL;<br>- }<br>-    dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);<br>-   if (!dlg) {<br>-          if (dlg_status != PJ_EEXISTS) {<br>-                      pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>-           }<br>-            return NULL;<br>- }<br>-    if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {<br>-               pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);<br>-           pjsip_dlg_terminate(dlg);<br>-            return NULL;<br>- }<br>-<br>-#if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)<br>-   inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;<br>-#endif<br>- if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {<br>-             if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {<br>-                       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>-             }<br>-            pjsip_inv_send_msg(inv_session, tdata);<br>-              return NULL;<br>- }<br>-    return inv_session;<br>-}<br>-<br>-struct new_invite {<br>-     /*! \brief Session created for the new INVITE */<br>-     struct ast_sip_session *session;<br>-<br>-  /*! \brief INVITE request itself */<br>-  pjsip_rx_data *rdata;<br>-};<br>-<br>-static int new_invite(struct new_invite *invite)<br>-{<br>- pjsip_tx_data *tdata = NULL;<br>- pjsip_timer_setting timer;<br>-   pjsip_rdata_sdp_info *sdp_info;<br>-      pjmedia_sdp_session *local = NULL;<br>-<br>-        /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE<br>-     * so that we will be notified so we can destroy the session properly<br>-         */<br>-<br>-       if (invite->session->inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {<br>-          ast_log(LOG_ERROR, "Session already DISCONNECTED [reason=%d (%s)]\n",<br>-                      invite->session->inv_session->cause,<br>-                        pjsip_get_status_text(invite->session->inv_session->cause)->ptr);<br>-#ifdef HAVE_PJSIP_INV_SESSION_REF<br>-            pjsip_inv_dec_ref(invite->session->inv_session);<br>-#endif<br>-              return -1;<br>-   }<br>-<br>- switch (get_destination(invite->session, invite->rdata)) {<br>-     case SIP_GET_DEST_EXTEN_FOUND:<br>-               /* Things worked. Keep going */<br>-              break;<br>-       case SIP_GET_DEST_UNSUPPORTED_URI:<br>-           if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>-                     ast_sip_session_send_response(invite->session, tdata);<br>-            } else  {<br>-                    pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);<br>-               }<br>-            goto end;<br>-    case SIP_GET_DEST_EXTEN_PARTIAL:<br>-             ast_debug(1, "Call from '%s' (%s:%s:%d) to extension '%s' - partial match\n", ast_sorcery_object_get_id(invite->session->endpoint),<br>-                  invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name, invite->rdata->pkt_info.src_port, invite->session->exten);<br>-<br>-              if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 484, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>-                     ast_sip_session_send_response(invite->session, tdata);<br>-            } else  {<br>-                    pjsip_inv_terminate(invite->session->inv_session, 484, PJ_TRUE);<br>-               }<br>-            goto end;<br>-    case SIP_GET_DEST_EXTEN_NOT_FOUND:<br>-   default:<br>-             ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",<br>-                 ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,<br>-                    invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);<br>-<br>-               if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>-                     ast_sip_session_send_response(invite->session, tdata);<br>-            } else  {<br>-                    pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);<br>-               }<br>-            goto end;<br>-    };<br>-<br>-        pjsip_timer_setting_default(&timer);<br>-     timer.min_se = invite->session->endpoint->extensions.timer.min_se;<br>-  timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;<br>-      pjsip_timer_init_session(invite->session->inv_session, &timer);<br>-<br>- /*<br>-    * At this point, we've verified what we can that won't take awhile,<br>-  * so let's go ahead and send a 100 Trying out to stop any<br>-        * retransmissions.<br>-   */<br>-  if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {<br>-             pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);<br>-               goto end;<br>-    }<br>-    ast_sip_session_send_response(invite->session, tdata);<br>-<br>- sdp_info = pjsip_rdata_get_sdp_info(invite->rdata);<br>-       if (sdp_info && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {<br>-          if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {<br>-                     tdata = NULL;<br>-                        if (pjsip_inv_end_session(invite->session->inv_session, 488, NULL, &tdata) == PJ_SUCCESS<br>-                           && tdata) {<br>-                          ast_sip_session_send_response(invite->session, tdata);<br>-                    }<br>-                    goto end;<br>-            }<br>-            /* We are creating a local SDP which is an answer to their offer */<br>-          local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);<br>-  } else {<br>-             /* We are creating a local SDP which is an offer */<br>-          local = create_local_sdp(invite->session->inv_session, invite->session, NULL);<br>-      }<br>-<br>- /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */<br>-  if (!local) {<br>-                tdata = NULL;<br>-                if (pjsip_inv_end_session(invite->session->inv_session, 500, NULL, &tdata) == PJ_SUCCESS<br>-                   && tdata) {<br>-                  ast_sip_session_send_response(invite->session, tdata);<br>-            }<br>-            goto end;<br>-    }<br>-<br>- pjsip_inv_set_local_sdp(invite->session->inv_session, local);<br>-  pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);<br>-#ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS<br>- pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);<br>-#endif<br>-<br>- handle_incoming_request(invite->session, invite->rdata);<br>-<br>-end:<br>-#ifdef HAVE_PJSIP_INV_SESSION_REF<br>- pjsip_inv_dec_ref(invite->session->inv_session);<br>-#endif<br>-      return 0;<br>-}<br>-<br>-static void handle_new_invite_request(pjsip_rx_data *rdata)<br>-{<br>-   RAII_VAR(struct ast_sip_endpoint *, endpoint,<br>-                        ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);<br>-   pjsip_tx_data *tdata = NULL;<br>- pjsip_inv_session *inv_session = NULL;<br>-       struct ast_sip_session *session;<br>-     struct new_invite invite;<br>-<br>- ast_assert(endpoint != NULL);<br>-<br>-     inv_session = pre_session_setup(rdata, endpoint);<br>-    if (!inv_session) {<br>-          /* pre_session_setup() returns a response on failure */<br>-              return;<br>-      }<br>-<br>-#ifdef HAVE_PJSIP_INV_SESSION_REF<br>-     if (pjsip_inv_add_ref(inv_session) != PJ_SUCCESS) {<br>-          ast_log(LOG_ERROR, "Can't increase the session reference counter\n");<br>-          if (inv_session->state != PJSIP_INV_STATE_DISCONNECTED) {<br>-                 if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>-                               pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>-                     } else {<br>-                             pjsip_inv_send_msg(inv_session, tdata);<br>-                      }<br>-            }<br>-            return;<br>-      }<br>-#endif<br>-<br>-        session = ast_sip_session_alloc(endpoint, NULL, inv_session, rdata);<br>- if (!session) {<br>-              if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {<br>-                       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);<br>-             } else {<br>-                     pjsip_inv_send_msg(inv_session, tdata);<br>-              }<br>-#ifdef HAVE_PJSIP_INV_SESSION_REF<br>-                pjsip_inv_dec_ref(inv_session);<br>-#endif<br>-             return;<br>-      }<br>-<br>- /*<br>-    * The current thread is supposed be the session serializer to prevent<br>-        * any initial INVITE retransmissions from trying to setup the same<br>-   * call again.<br>-        */<br>-  ast_assert(ast_taskprocessor_is_task(session->serializer));<br>-<br>-    invite.session = session;<br>-    invite.rdata = rdata;<br>-        new_invite(&invite);<br>-<br>-  ao2_ref(session, -1);<br>-}<br>-<br>-static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)<br>-{<br>- pj_str_t method;<br>-<br>-  if (ast_strlen_zero(supplement_method)) {<br>-            return PJ_TRUE;<br>-      }<br>-<br>- pj_cstr(&method, supplement_method);<br>-<br>-  return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;<br>-}<br>-<br>-static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)<br>-{<br>- struct ast_sip_session_supplement *supplement;<br>-       struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;<br>-<br>-    if (!session) {<br>-              return PJ_FALSE;<br>-     }<br>-<br>- AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>-          if (does_method_match(&method->name, supplement->method)) {<br>-                        return PJ_TRUE;<br>-              }<br>-    }<br>-    return PJ_FALSE;<br>-}<br>-/*!<br>- * \brief Called when a new SIP request comes into PJSIP<br>- *<br>- * This function is called under two circumstances<br>- * 1) An out-of-dialog request is received by PJSIP<br>- * 2) An in-dialog request that the inv_session layer does not<br>- *    handle is received (such as an in-dialog INFO)<br>- *<br>- * Except for INVITEs, there is very little we actually do in this function<br>- * 1) For requests we don't handle, we return PJ_FALSE<br>- * 2) For new INVITEs, handle them now to prevent retransmissions from<br>- *    trying to setup the same call again.<br>- * 3) For in-dialog requests we handle, we process them in the<br>- *    .on_state_changed = session_inv_on_state_changed or<br>- *    .on_tsx_state_changed = session_inv_on_tsx_state_changed<br>- *    callbacks instead.<br>- */<br>-static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)<br>-{<br>-        pj_status_t handled = PJ_FALSE;<br>-      pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);<br>-      pjsip_inv_session *inv_session;<br>-<br>-   switch (rdata->msg_info.msg->line.req.method.id) {<br>-     case PJSIP_INVITE_METHOD:<br>-            if (dlg) {<br>-                   ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");<br>-                  break;<br>-               }<br>-            handled = PJ_TRUE;<br>-           handle_new_invite_request(rdata);<br>-            break;<br>-       default:<br>-             /* Handle other in-dialog methods if their supplements have been registered */<br>-               handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&<br>-                   has_supplement(inv_session->mod_data[session_module.id], rdata);<br>-          break;<br>-       }<br>-<br>- return handled;<br>-}<br>-<br>-static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)<br>-{<br>-      struct ast_sip_session *session = entry->user_data;<br>-<br>-    ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",<br>-             ast_sorcery_object_get_id(session->endpoint),<br>-             session->channel ? ast_channel_name(session->channel) : "");<br>-<br>-      if (AST_LIST_EMPTY(&session->delayed_requests)) {<br>-             /* No delayed request pending, so just return */<br>-             ao2_ref(session, -1);<br>-                return;<br>-      }<br>-    if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {<br>-          /*<br>-            * Uh oh.  We now have nothing in the foreseeable future<br>-              * to trigger sending the delayed requests.<br>-           */<br>-          ao2_ref(session, -1);<br>-        }<br>-}<br>-<br>-static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)<br>-{<br>-     pjsip_inv_session *inv = session->inv_session;<br>-    pj_time_val tv;<br>-<br>-   ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",<br>-           ast_sorcery_object_get_id(session->endpoint),<br>-             session->channel ? ast_channel_name(session->channel) : "");<br>- if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {<br>-             return;<br>-      }<br>-    if (pj_timer_entry_running(&session->rescheduled_reinvite)) {<br>-         /* Timer already running.  Something weird is going on. */<br>-           ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",<br>-                     ast_sorcery_object_get_id(session->endpoint),<br>-                     session->channel ? ast_channel_name(session->channel) : "");<br>-         return;<br>-      }<br>-<br>- tv.sec = 0;<br>-  if (inv->role == PJSIP_ROLE_UAC) {<br>-                tv.msec = 2100 + ast_random() % 2000;<br>-        } else {<br>-             tv.msec = ast_random() % 2000;<br>-       }<br>-    pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);<br>-<br>-  ao2_ref(session, +1);<br>-        if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),<br>-         &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {<br>-             ao2_ref(session, -1);<br>-        }<br>-}<br>-<br>-static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)<br>-{<br>-       int id = session_module.id;<br>-  struct ast_sip_session *session = NULL;<br>-<br>-   if (!DEBUG_ATLEAST(5)) {<br>-             /* Debug not spamy enough */<br>-         return;<br>-      }<br>-<br>- ast_log(LOG_DEBUG, "Function %s called on event %s\n",<br>-             function, pjsip_event_str(e->type));<br>-      if (!inv) {<br>-          ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);<br>-            ast_log(LOG_DEBUG, "The transaction state is %s\n",<br>-                        pjsip_tsx_state_str(tsx->state));<br>-         return;<br>-      }<br>-    if (id > -1) {<br>-            session = inv->mod_data[session_module.id];<br>-       }<br>-    if (!session) {<br>-              ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);<br>-    } else {<br>-             ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",<br>-                 ast_sorcery_object_get_id(session->endpoint),<br>-                     session->channel ? ast_channel_name(session->channel) : "");<br>- }<br>-    if (inv->invite_tsx) {<br>-            ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",<br>-                       inv->invite_tsx);<br>- } else {<br>-             ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");<br>-       }<br>-    if (tsx) {<br>-           ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",<br>-                        pjsip_role_name(tsx->role),<br>-                       (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),<br>-                      tsx);<br>-                ast_log(LOG_DEBUG, "The current transaction state is %s\n",<br>-                        pjsip_tsx_state_str(tsx->state));<br>-         ast_log(LOG_DEBUG, "The transaction state change event is %s\n",<br>-                   pjsip_event_str(e->body.tsx_state.type));<br>- } else {<br>-             ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");<br>-     }<br>-    ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));<br>-}<br>-<br>-#define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))<br>-<br>-static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)<br>-{<br>-      struct ast_sip_session_supplement *supplement;<br>-       struct pjsip_request_line req = rdata->msg_info.msg->line.req;<br>-<br>-      ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));<br>-  AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>-          if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {<br>-                     if (supplement->incoming_request(session, rdata)) {<br>-                               break;<br>-                       }<br>-            }<br>-    }<br>-}<br>-<br>-static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>-               enum ast_sip_session_response_priority response_priority)<br>-{<br>-        struct ast_sip_session_supplement *supplement;<br>-       struct pjsip_status_line status = rdata->msg_info.msg->line.status;<br>-<br>- ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),<br>-                    pj_strbuf(&status.reason));<br>-<br>-   AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>-          if (!(supplement->response_priority & response_priority)) {<br>-                   continue;<br>-            }<br>-            if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {<br>-                    supplement->incoming_response(session, rdata);<br>-            }<br>-    }<br>-}<br>-<br>-static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata,<br>-         enum ast_sip_session_response_priority response_priority)<br>-{<br>-        ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?<br>-                       "request" : "response");<br>-<br>-      if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {<br>-          handle_incoming_request(session, rdata);<br>-     } else {<br>-             handle_incoming_response(session, rdata, response_priority);<br>- }<br>-<br>- return 0;<br>-}<br>-<br>-static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>-{<br>-    struct ast_sip_session_supplement *supplement;<br>-       struct pjsip_request_line req = tdata->msg->line.req;<br>-<br>-       ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));<br>-  AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>-          if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {<br>-                     supplement->outgoing_request(session, tdata);<br>-             }<br>-    }<br>-}<br>-<br>-static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)<br>-{<br>-   struct ast_sip_session_supplement *supplement;<br>-       struct pjsip_status_line status = tdata->msg->line.status;<br>-     pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);<br>-<br>-     if (!cseq) {<br>-         ast_log(LOG_ERROR, "Cannot send response due to missing sequence header");<br>-         return;<br>-      }<br>-<br>- ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),<br>-          pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),<br>-              pj_strbuf(&status.reason));<br>-<br>-   AST_LIST_TRAVERSE(&session->supplements, supplement, next) {<br>-          if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {<br>-                       supplement->outgoing_response(session, tdata);<br>-            }<br>-    }<br>-}<br>-<br>-static int session_end(void *vsession)<br>-{<br>-        struct ast_sip_session *session = vsession;<br>-  struct ast_sip_session_supplement *iter;<br>-<br>-  /* Stop the scheduled termination */<br>- sip_session_defer_termination_stop_timer(session);<br>-<br>-        /* Session is dead.  Notify the supplements. */<br>-      AST_LIST_TRAVERSE(&session->supplements, iter, next) {<br>-                if (iter->session_end) {<br>-                  iter->session_end(session);<br>-               }<br>-    }<br>-<br>- /* Release any media resources. */<br>-   ao2_cleanup(session->media);<br>-      session->media = NULL;<br>-<br>- return 0;<br>-}<br>-<br>-/*!<br>- * \internal<br>- * \brief Complete ending session activities.<br>- * \since 13.5.0<br>- *<br>- * \param vsession Which session to complete stopping.<br>- *<br>- * \retval 0 on success.<br>- * \retval -1 on error.<br>- */<br>-static int session_end_completion(void *vsession)<br>-{<br>-       struct ast_sip_session *session = vsession;<br>-<br>-       ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);<br>-        ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);<br>-<br>-       /* Now we can release the ref that was held by session->inv_session */<br>-    ao2_cleanup(session);<br>-        return 0;<br>-}<br>-<br>-static void handle_incoming_before_media(pjsip_inv_session *inv,<br>-  struct ast_sip_session *session, pjsip_rx_data *rdata)<br>-{<br>-   pjsip_msg *msg;<br>-<br>-   handle_incoming(session, rdata, AST_SIP_SESSION_BEFORE_MEDIA);<br>-       msg = rdata->msg_info.msg;<br>-        if (msg->type == PJSIP_REQUEST_MSG<br>-                && msg->line.req.method.id == PJSIP_ACK_METHOD<br>-            && pjmedia_sdp_neg_get_state(inv->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {<br>-           pjsip_tx_data *tdata;<br>-<br>-             /*<br>-            * SDP negotiation failed on an incoming call that delayed<br>-            * negotiation and then gave us an invalid SDP answer.  We<br>-            * need to send a BYE to end the call because of the invalid<br>-          * SDP answer.<br>-                */<br>-          ast_debug(1,<br>-                 "Endpoint '%s(%s)': Ending session due to incomplete SDP negotiation.  %s\n",<br>-                      ast_sorcery_object_get_id(session->endpoint),<br>-                     session->channel ? ast_channel_name(session->channel) : "",<br>-                  pjsip_rx_data_get_info(rdata));<br>-              if (pjsip_inv_end_session(inv, 400, NULL, &tdata) == PJ_SUCCESS<br>-                  && tdata) {<br>-                  ast_sip_session_send_request(session, tdata);<br>-                }<br>-    }<br>-}<br>-<br>-static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)<br>-{<br>-      struct ast_sip_session *session = inv->mod_data[session_module.id];<br>-       pjsip_event_id_e type;<br>-<br>-    if (e) {<br>-             print_debug_details(inv, NULL, e);<br>-           type = e->type;<br>-   } else {<br>-             type = PJSIP_EVENT_UNKNOWN;<br>-  }<br>-<br>- if (!session) {<br>-              return;<br>-      }<br>-<br>- switch(type) {<br>-       case PJSIP_EVENT_TX_MSG:<br>-             break;<br>-       case PJSIP_EVENT_RX_MSG:<br>-             handle_incoming_before_media(inv, session, e->body.rx_msg.rdata);<br>-         break;<br>-       case PJSIP_EVENT_TSX_STATE:<br>-          ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));<br>-            /* Transaction state changes are prompted by some other underlying event. */<br>-         switch(e->body.tsx_state.type) {<br>-          case PJSIP_EVENT_TX_MSG:<br>-                     break;<br>-               case PJSIP_EVENT_RX_MSG:<br>-                     handle_incoming_before_media(inv, session, e->body.tsx_state.src.rdata);<br>-                  break;<br>-               case PJSIP_EVENT_TRANSPORT_ERROR:<br>-            case PJSIP_EVENT_TIMER:<br>-              case PJSIP_EVENT_USER:<br>-               case PJSIP_EVENT_UNKNOWN:<br>-            case PJSIP_EVENT_TSX_STATE:<br>-                  /* Inception? */<br>-                     break;<br>-               }<br>-            break;<br>-       case PJSIP_EVENT_TRANSPORT_ERROR:<br>-    case PJSIP_EVENT_TIMER:<br>-      case PJSIP_EVENT_UNKNOWN:<br>-    case PJSIP_EVENT_USER:<br>-       default:<br>-             break;<br>-       }<br>-<br>- if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {<br>-         if (session->defer_end) {<br>-                 ast_debug(3, "Deferring session (%p) end\n", session);<br>-                     session->ended_while_deferred = 1;<br>-                        return;<br>-              }<br>-<br>-         if (ast_sip_push_task(session->serializer, session_end, session)) {<br>-                       /* Do it anyway even though this is not the right thread. */<br>-                 session_end(session);<br>-                }<br>-    }<br>-}<br>-<br>-static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)<br>-{<br>-        /* XXX STUB */<br>-}<br>-<br>-static int session_end_if_disconnected(int id, pjsip_inv_session *inv)<br>-{<br>-   struct ast_sip_session *session;<br>-<br>-  if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {<br>-         return 0;<br>-    }<br>-<br>- /*<br>-    * We are locking because ast_sip_dialog_get_session() needs<br>-  * the dialog locked to get the session by other threads.<br>-     */<br>-  pjsip_dlg_inc_lock(inv->dlg);<br>-     session = inv->mod_data[id];<br>-      inv->mod_data[id] = NULL;<br>- pjsip_dlg_dec_lock(inv->dlg);<br>-<br>-  /*<br>-    * Pass the session ref held by session->inv_session to<br>-    * session_end_completion().<br>-  */<br>-  if (session<br>-          && ast_sip_push_task(session->serializer, session_end_completion, session)) {<br>-             /* Do it anyway even though this is not the right thread. */<br>-         session_end_completion(session);<br>-     }<br>-<br>- return 1;<br>-}<br>-<br>-static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)<br>-{<br>-  ast_sip_session_response_cb cb;<br>-      int id = session_module.id;<br>-  struct ast_sip_session *session;<br>-     pjsip_tx_data *tdata;<br>-<br>-     /*<br>-    * A race condition exists at shutdown where the res_pjsip_session can be<br>-     * unloaded but this callback may still get called afterwards. In this case<br>-   * the id may end up being -1 which is useless to us. To work around this<br>-     * we store the current value and check/use it.<br>-       */<br>-  if (id < 0) {<br>-             return;<br>-      }<br>-<br>- session = inv->mod_data[id];<br>-<br>-   print_debug_details(inv, tsx, e);<br>-    if (!session) {<br>-              /* The session has ended.  Ignore the transaction change. */<br>-         return;<br>-      }<br>-<br>- /*<br>-    * If the session is disconnected really nothing else to do unless currently transacting<br>-      * a BYE. If a BYE then hold off destruction until the transaction timeout occurs. This<br>-       * has to be done for BYEs because sometimes the dialog can be in a disconnected<br>-      * state but the BYE request transaction has not yet completed.<br>-       */<br>-  if (tsx->method.id != PJSIP_BYE_METHOD && session_end_if_disconnected(id, inv)) {<br>-         return;<br>-      }<br>-<br>- switch (e->body.tsx_state.type) {<br>- case PJSIP_EVENT_TX_MSG:<br>-             /* When we create an outgoing request, we do not have access to the transaction that<br>-          * is created. Instead, We have to place transaction-specific data in the tdata. Here,<br>-                * we transfer the data into the transaction. This way, when we receive a response, we<br>-                * can dig this data out again<br>-                */<br>-          tsx->mod_data[id] = e->body.tsx_state.src.tdata->mod_data[id];<br>-              break;<br>-       case PJSIP_EVENT_RX_MSG:<br>-             cb = ast_sip_mod_data_get(tsx->mod_data, id, MOD_DATA_ON_RESPONSE);<br>-               /* As the PJSIP invite session implementation responds with a 200 OK before we have a<br>-                 * chance to be invoked session supplements for BYE requests actually end up executing<br>-                * in the invite session state callback as well. To prevent session supplements from<br>-          * running on the BYE request again we explicitly squash invocation of them here.<br>-             */<br>-          if ((e->body.tsx_state.src.rdata->msg_info.msg->type != PJSIP_REQUEST_MSG) ||<br>-                       (tsx->method.id != PJSIP_BYE_METHOD)) {<br>-                   handle_incoming(session, e->body.tsx_state.src.rdata,<br>-                             AST_SIP_SESSION_AFTER_MEDIA);<br>-                }<br>-            if (tsx->method.id == PJSIP_INVITE_METHOD) {<br>-                      if (tsx->role == PJSIP_ROLE_UAC) {<br>-                                if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {<br>-                                    /* This means we got a non 2XX final response to our outgoing INVITE */<br>-                                      if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {<br>-                                               reschedule_reinvite(session, cb);<br>-                                            return;<br>-                                      }<br>-                                    if (inv->state == PJSIP_INV_STATE_CONFIRMED) {<br>-                                            ast_debug(1, "reINVITE received final response code %d\n",<br>-                                                 tsx->status_code);<br>-                                                if ((tsx->status_code == 401 || tsx->status_code == 407)<br>-                                                       && !ast_sip_create_request_with_auth(<br>-                                                                &session->endpoint->outbound_auths,<br>-                                                                e->body.tsx_state.src.rdata, tsx, &tdata)) {<br>-                                                  /* Send authed reINVITE */<br>-                                                   ast_sip_session_send_request_with_cb(session, tdata, cb);<br>-                                                    return;<br>-                                              }<br>-                                            if (tsx->status_code != 488) {<br>-                                                    /* Other reinvite failures (except 488) result in destroying the session. */<br>-                                                 if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS<br>-                                                          && tdata) {<br>-                                                          ast_sip_session_send_request(session, tdata);<br>-                                                        }<br>-                                            }<br>-                                    }<br>-                            } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {<br>-                                    if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {<br>-                                              int sdp_negotiation_done =<br>-                                                   pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE;<br>-<br>-                                             /*<br>-                                            * We can get here for the following reasons.<br>-                                                 *<br>-                                            * 1) The race condition detailed in RFC5407 section 3.1.2.<br>-                                           * We sent a CANCEL at the same time that the UAS sent us a<br>-                                           * 200 OK with a valid SDP for the original INVITE.  As a<br>-                                             * result, we have now received a 200 OK for a cancelled<br>-                                              * call and the SDP negotiation is complete.  We need to<br>-                                              * immediately send a BYE to end the dialog.<br>-                                          *<br>-                                            * 2) We sent a CANCEL and hit the race condition but the<br>-                                             * UAS sent us an invalid SDP with the 200 OK.  In this case<br>-                                          * the SDP negotiation is incomplete and PJPROJECT has<br>-                                                * already sent the BYE for us because of the invalid SDP.<br>-                                            *<br>-                                            * 3) We didn't send a CANCEL but the UAS sent us an invalid<br>-                                              * SDP with the 200 OK.  In this case the SDP negotiation is<br>-                                          * incomplete and PJPROJECT has already sent the BYE for us<br>-                                           * because of the invalid SDP.<br>-                                                */<br>-                                          ast_test_suite_event_notify("PJSIP_SESSION_CANCELED",<br>-                                                      "Endpoint: %s\r\n"<br>-                                                 "Channel: %s\r\n"<br>-                                                  "Message: %s\r\n"<br>-                                                  "SDP: %s",<br>-                                                 ast_sorcery_object_get_id(session->endpoint),<br>-                                                     session->channel ? ast_channel_name(session->channel) : "",<br>-                                                  pjsip_rx_data_get_info(e->body.tsx_state.src.rdata),<br>-                                                      sdp_negotiation_done ? "complete" : "incomplete");<br>-                                               if (!sdp_negotiation_done) {<br>-                                                 ast_debug(1, "Endpoint '%s(%s)': Incomplete SDP negotiation cancelled session.  %s\n",<br>-                                                             ast_sorcery_object_get_id(session->endpoint),<br>-                                                             session->channel ? ast_channel_name(session->channel) : "",<br>-                                                          pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));<br>-                                             } else if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS<br>-                                                   && tdata) {<br>-                                                  ast_debug(1, "Endpoint '%s(%s)': Ending session due to RFC5407 race condition.  %s\n",<br>-                                                             ast_sorcery_object_get_id(session->endpoint),<br>-                                                             session->channel ? ast_channel_name(session->channel) : "",<br>-                                                          pjsip_rx_data_get_info(e->body.tsx_state.src.rdata));<br>-                                                     ast_sip_session_send_request(session, tdata);<br>-                                                }<br>-                                    }<br>-                            }<br>-                    }<br>-            } else {<br>-                     /* All other methods */<br>-                      if (tsx->role == PJSIP_ROLE_UAC) {<br>-                                if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {<br>-                                    /* This means we got a final response to our outgoing method */<br>-                                      ast_debug(1, "%.*s received final response code %d\n",<br>-                                             (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),<br>-                                              tsx->status_code);<br>-                                        if ((tsx->status_code == 401 || tsx->status_code == 407)<br>-                                               && !ast_sip_create_request_with_auth(<br>-                                                        &session->endpoint->outbound_auths,<br>-                                                        e->body.tsx_state.src.rdata, tsx, &tdata)) {<br>-                                          /* Send authed version of the method */<br>-                                              ast_sip_session_send_request_with_cb(session, tdata, cb);<br>-                                            return;<br>-                                      }<br>-                            }<br>-                    }<br>-            }<br>-            if (cb) {<br>-                    cb(session, e->body.tsx_state.src.rdata);<br>-         }<br>-            break;<br>-       case PJSIP_EVENT_TRANSPORT_ERROR:<br>-    case PJSIP_EVENT_TIMER:<br>-              /*<br>-            * The timer event is run by the pjsip monitor thread and not<br>-                 * by the session serializer.<br>-                 */<br>-          if (session_end_if_disconnected(id, inv)) {<br>-                  return;<br>-              }<br>-            break;<br>-       case PJSIP_EVENT_USER:<br>-       case PJSIP_EVENT_UNKNOWN:<br>-    case PJSIP_EVENT_TSX_STATE:<br>-          /* Inception? */<br>-             break;<br>-       }<br>-<br>- if (AST_LIST_EMPTY(&session->delayed_requests)) {<br>-             /* No delayed request pending, so just return */<br>-             return;<br>-      }<br>-<br>- if (tsx->method.id == PJSIP_INVITE_METHOD) {<br>-              if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {<br>-                   ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",<br>-                               ast_sorcery_object_get_id(session->endpoint),<br>-                             session->channel ? ast_channel_name(session->channel) : "",<br>-                          pjsip_tsx_state_str(tsx->state));<br>-                 check_delayed_requests(session, invite_proceeding);<br>-          } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {<br>-                    /*<br>-                    * Terminated INVITE transactions always should result in<br>-                     * queuing delayed requests, no matter what event caused<br>-                      * the transaction to terminate.<br>-                      */<br>-                  ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",<br>-                               ast_sorcery_object_get_id(session->endpoint),<br>-                             session->channel ? ast_channel_name(session->channel) : "",<br>-                          pjsip_tsx_state_str(tsx->state));<br>-                 check_delayed_requests(session, invite_terminated);<br>-          }<br>-    } else if (tsx->role == PJSIP_ROLE_UAC<br>-            && tsx->state == PJSIP_TSX_STATE_COMPLETED<br>-                && !pj_strcmp2(&tsx->method.name, "UPDATE")) {<br>-              ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",<br>-                       ast_sorcery_object_get_id(session->endpoint),<br>-                     session->channel ? ast_channel_name(session->channel) : "",<br>-                  pjsip_tsx_state_str(tsx->state));<br>-         check_delayed_requests(session, update_completed);<br>-   }<br>-}<br>-<br>-static int add_sdp_streams(void *obj, void *arg, void *data, int flags)<br>-{<br>-       struct ast_sip_session_media *session_media = obj;<br>-   pjmedia_sdp_session *answer = arg;<br>-   struct ast_sip_session *session = data;<br>-      struct ast_sip_session_sdp_handler *handler = session_media->handler;<br>-     RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>-        int res;<br>-<br>-  if (handler) {<br>-               /* if an already assigned handler reports a catastrophic error, fail */<br>-              res = handler->create_outgoing_sdp_stream(session, session_media, answer);<br>-                if (res < 0) {<br>-                    return 0;<br>-            }<br>-            return CMP_MATCH;<br>-    }<br>-<br>- handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);<br>-       if (!handler_list) {<br>-         return CMP_MATCH;<br>-    }<br>-<br>- /* no handler for this stream type and we have a list to search */<br>-   AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-               if (handler == session_media->handler) {<br>-                  continue;<br>-            }<br>-            res = handler->create_outgoing_sdp_stream(session, session_media, answer);<br>-                if (res < 0) {<br>-                    /* catastrophic error */<br>-                     return 0;<br>-            }<br>-            if (res > 0) {<br>-                    /* Handled by this handler. Move to the next stream */<br>-                       session_media_set_handler(session_media, handler);<br>-                   return CMP_MATCH;<br>-            }<br>-    }<br>-<br>- /* streams that weren't handled won't be included in generated outbound SDP */<br>-       return CMP_MATCH;<br>-}<br>-<br>-static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)<br>-{<br>-        RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);<br>-     static const pj_str_t STR_IN = { "IN", 2 };<br>-        static const pj_str_t STR_IP4 = { "IP4", 3 };<br>-      static const pj_str_t STR_IP6 = { "IP6", 3 };<br>-      pjmedia_sdp_session *local;<br>-<br>-       if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {<br>-         ast_log(LOG_ERROR, "Failed to create session SDP. Session has been already disconnected\n");<br>-               return NULL;<br>- }<br>-<br>- if (!inv->pool_prov || !(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {<br>-             return NULL;<br>- }<br>-<br>- if (!offer) {<br>-                local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());<br>-        } else {<br>-             local->origin.version = offer->origin.version + 1;<br>-             local->origin.id = offer->origin.id;<br>-   }<br>-<br>- pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);<br>-  pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);<br>-<br>-    /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */<br>- successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);<br>-    if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {<br>-               /* Something experienced a catastrophic failure */<br>-           return NULL;<br>- }<br>-<br>- /* Use the connection details of the first media stream if possible for SDP level */<br>- if (local->media_count) {<br>-         int stream;<br>-<br>-               /* Since we are using the first media stream as the SDP level we can get rid of it<br>-            * from the stream itself<br>-             */<br>-          local->conn = local->media[0]->conn;<br>-                local->media[0]->conn = NULL;<br>-          pj_strassign(&local->origin.net_type, &local->conn->net_type);<br>-              pj_strassign(&local->origin.addr_type, &local->conn->addr_type);<br>-            pj_strassign(&local->origin.addr, &local->conn->addr);<br>-<br>-           /* Go through each media stream seeing if the connection details actually differ,<br>-             * if not just use SDP level and reduce the SDP size<br>-          */<br>-          for (stream = 1; stream < local->media_count; stream++) {<br>-                      if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&<br>-                              !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&<br>-                                !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {<br>-                          local->media[stream]->conn = NULL;<br>-                     }<br>-            }<br>-    } else {<br>-             local->origin.net_type = STR_IN;<br>-          local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;<br>-<br>-         if (!ast_strlen_zero(session->endpoint->media.address)) {<br>-                      pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);<br>-           } else {<br>-                     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()));<br>-               }<br>-    }<br>-<br>- return local;<br>-}<br>-<br>-static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)<br>-{<br>-     struct ast_sip_session *session = inv->mod_data[session_module.id];<br>-       pjmedia_sdp_session *answer;<br>-<br>-      if (handle_incoming_sdp(session, offer)) {<br>-           return;<br>-      }<br>-<br>- if ((answer = create_local_sdp(inv, session, offer))) {<br>-              pjsip_inv_set_sdp_answer(inv, answer);<br>-       }<br>-}<br>-<br>-#if 0<br>-static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)<br>-{<br>-        /* XXX STUB */<br>-}<br>-#endif<br>-<br>-static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)<br>-{<br>-     struct ast_sip_session *session = inv->mod_data[session_module.id];<br>-       const pjmedia_sdp_session *local, *remote;<br>-<br>-        if (!session || !session->channel) {<br>-              /*<br>-            * If we don't have a session or channel then we really<br>-           * don't care about media updates.<br>-                * Just ignore<br>-                */<br>-          return;<br>-      }<br>-<br>- if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||<br>-           (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {<br>-               ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);<br>-               ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);<br>-         ast_queue_hangup(session->channel);<br>-               return;<br>-      }<br>-<br>- handle_negotiated_sdp(session, local, remote);<br>-}<br>-<br>-static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)<br>-{<br>-        struct ast_sip_session *session = inv->mod_data[session_module.id];<br>-       const pjsip_sip_uri *uri;<br>-<br>- if (!session->channel) {<br>-          return PJSIP_REDIRECT_STOP;<br>-  }<br>-<br>- if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {<br>-                return PJSIP_REDIRECT_ACCEPT;<br>-        }<br>-<br>- if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {<br>-         return PJSIP_REDIRECT_STOP;<br>-  }<br>-<br>- handle_incoming(session, e->body.rx_msg.rdata, AST_SIP_SESSION_BEFORE_REDIRECTING);<br>-<br>-    uri = pjsip_uri_get_uri(target);<br>-<br>-  if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {<br>-             char exten[AST_MAX_EXTENSION];<br>-<br>-            ast_copy_pj_str(exten, &uri->user, sizeof(exten));<br>-<br>-         /*<br>-            * We may want to match in the dialplan without any user<br>-              * options getting in the way.<br>-                */<br>-          AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(exten);<br>-<br>-               ast_channel_call_forward_set(session->channel, exten);<br>-    } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {<br>-          char target_uri[PJSIP_MAX_URL_SIZE];<br>-         /* PJSIP/ + endpoint length + / + max URL size */<br>-            char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];<br>-<br>-           pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));<br>-          sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);<br>-              ast_channel_call_forward_set(session->channel, forward);<br>-  }<br>-<br>- return PJSIP_REDIRECT_STOP;<br>-}<br>-<br>-static pjsip_inv_callback inv_callback = {<br>-      .on_state_changed = session_inv_on_state_changed,<br>-    .on_new_session = session_inv_on_new_session,<br>-        .on_tsx_state_changed = session_inv_on_tsx_state_changed,<br>-    .on_rx_offer = session_inv_on_rx_offer,<br>-      .on_media_update = session_inv_on_media_update,<br>-      .on_redirected = session_inv_on_redirected,<br>-};<br>-<br>-/*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */<br>-static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)<br>-{<br>-   RAII_VAR(struct ast_sip_transport_state *, transport_state, ast_sip_get_transport_state(ast_sorcery_object_get_id(transport)), ao2_cleanup);<br>- struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(<br>-                tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);<br>-   struct pjmedia_sdp_session *sdp;<br>-     int stream;<br>-<br>-       /* SDP produced by us directly will never be multipart */<br>-    if (!transport_state || hook || !tdata->msg->body ||<br>-           !ast_sip_is_content_type(&tdata->msg->body->content_type, "application", "sdp") ||<br>-          ast_strlen_zero(transport->external_media_address)) {<br>-             return;<br>-      }<br>-<br>- sdp = tdata->msg->body->data;<br>-<br>-    if (sdp->conn) {<br>-          char host[NI_MAXHOST];<br>-               struct ast_sockaddr our_sdp_addr = { { 0, } };<br>-<br>-            ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));<br>-             ast_sockaddr_parse(&our_sdp_addr, host, PARSE_PORT_FORBID);<br>-<br>-           /* Reversed check here. We don't check the remote<br>-                 * endpoint being in our local net, but whether our<br>-           * outgoing session IP is local. If it is, we'll do<br>-               * rewriting. No localnet configured? Always rewrite. */<br>-             if (ast_sip_transport_is_local(transport_state, &our_sdp_addr) || !transport_state->localnet) {<br>-                       ast_debug(5, "Setting external media address to %s\n", ast_sockaddr_stringify_host(&transport_state->external_media_address));<br>-                      pj_strdup2(tdata->pool, &sdp->conn->addr, ast_sockaddr_stringify_host(&transport_state->external_media_address));<br>-                        pj_strdup2(tdata->pool, &sdp->origin.addr, transport->external_media_address);<br>-          }<br>-    }<br>-<br>- for (stream = 0; stream < sdp->media_count; ++stream) {<br>-                /* See if there are registered handlers for this media stream type */<br>-                char media[20];<br>-              struct ast_sip_session_sdp_handler *handler;<br>-         RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);<br>-<br>-             /* We need a null-terminated version of the media string */<br>-          ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));<br>-<br>-         handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);<br>-               if (!handler_list) {<br>-                 ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);<br>-                   continue;<br>-            }<br>-            AST_LIST_TRAVERSE(&handler_list->list, handler, next) {<br>-                       if (handler->change_outgoing_sdp_stream_media_address) {<br>-                          handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);<br>-                       }<br>-            }<br>-    }<br>-<br>- /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */<br>-   ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);<br>-}<br>+#include "res_pjsip/include/res_pjsip_private.h"<br> <br> static int load_module(void)<br> {<br>-     pjsip_endpoint *endpt;<br>-<br>     CHECK_PJSIP_MODULE_LOADED();<br> <br>-      if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {<br>+       if (res_pjsip_session_load()) {<br>               return AST_MODULE_LOAD_DECLINE;<br>       }<br>-    if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {<br>-            return AST_MODULE_LOAD_DECLINE;<br>-      }<br>-    nat_hook->outgoing_external_message = session_outgoing_nat_hook;<br>-  ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);<br>- sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,<br>-                      sdp_handler_list_hash, sdp_handler_list_cmp);<br>-        if (!sdp_handlers) {<br>-         return AST_MODULE_LOAD_DECLINE;<br>-      }<br>-    endpt = ast_sip_get_pjsip_endpoint();<br>-        pjsip_inv_usage_init(endpt, &inv_callback);<br>-      pjsip_100rel_init_module(endpt);<br>-     pjsip_timer_init_module(endpt);<br>-      if (ast_sip_register_service(&session_module)) {<br>-         return AST_MODULE_LOAD_DECLINE;<br>-      }<br>-    ast_sip_register_service(&session_reinvite_module);<br>-      ast_sip_register_service(&outbound_invite_auth_module);<br> <br>+       /* This module is cleaned up by res_pjsip which can only happen during startup. */<br>    ast_module_shutdown_ref(ast_module_info->self);<br> <br>         return AST_MODULE_LOAD_SUCCESS;<br>@@ -3217,15 +43,12 @@<br> <br> static int unload_module(void)<br> {<br>-       ast_sip_unregister_service(&outbound_invite_auth_module);<br>-        ast_sip_unregister_service(&session_reinvite_module);<br>-    ast_sip_unregister_service(&session_module);<br>-     ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);<br>- ao2_cleanup(nat_hook);<br>-       ao2_cleanup(sdp_handlers);<br>+   /* Nothing to do here, res_pjsip will handle the cleanup on it's own. */<br>  return 0;<br> }<br> <br>+/* This module does not actually export any symbols but keep the flag in place as <br>+ * it is needed to keep this initialization early. */<br> AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",<br>            .support_level = AST_MODULE_SUPPORT_CORE,<br>             .load = load_module,<br></pre><p>To view, visit <a href="https://gerrit.asterisk.org/7925">change 7925</a>. To unsubscribe, visit <a href="https://gerrit.asterisk.org/settings">settings</a>.</p><div itemscope itemtype="http://schema.org/EmailMessage"><div itemscope itemprop="action" itemtype="http://schema.org/ViewAction"><link itemprop="url" href="https://gerrit.asterisk.org/7925"/><meta itemprop="name" content="View Change"/></div></div>

<div style="display:none"> Gerrit-Project: asterisk </div>
<div style="display:none"> Gerrit-Branch: 13 </div>
<div style="display:none"> Gerrit-MessageType: newchange </div>
<div style="display:none"> Gerrit-Change-Id: Ib76e156ec123477943153d903091406620a9c6ab </div>
<div style="display:none"> Gerrit-Change-Number: 7925 </div>
<div style="display:none"> Gerrit-PatchSet: 1 </div>
<div style="display:none"> Gerrit-Owner: Corey Farrell <git@cfware.com> </div>