res_pjsip_session.c

Go to the documentation of this file.
00001 /*
00002 * Asterisk -- An open source telephony toolkit.
00003 *
00004 * Copyright (C) 2013, Digium, Inc.
00005 *
00006 * Mark Michelson <mmichelson@digium.com>
00007 *
00008 * See http://www.asterisk.org for more information about
00009 * the Asterisk project. Please do not directly contact
00010 * any of the maintainers of this project for assistance;
00011 * the project provides a web site, mailing lists and IRC
00012 * channels for your use.
00013 *
00014 * This program is free software, distributed under the terms of
00015 * the GNU General Public License Version 2. See the LICENSE file
00016 * at the top of the source tree.
00017 */
00018 
00019 /*** MODULEINFO
00020    <depend>pjproject</depend>
00021    <depend>res_pjsip</depend>
00022    <support_level>core</support_level>
00023  ***/
00024 
00025 #include "asterisk.h"
00026 
00027 #include <pjsip.h>
00028 #include <pjsip_ua.h>
00029 #include <pjlib.h>
00030 
00031 #include "asterisk/res_pjsip.h"
00032 #include "asterisk/res_pjsip_session.h"
00033 #include "asterisk/datastore.h"
00034 #include "asterisk/module.h"
00035 #include "asterisk/logger.h"
00036 #include "asterisk/res_pjsip.h"
00037 #include "asterisk/astobj2.h"
00038 #include "asterisk/lock.h"
00039 #include "asterisk/uuid.h"
00040 #include "asterisk/pbx.h"
00041 #include "asterisk/taskprocessor.h"
00042 #include "asterisk/causes.h"
00043 #include "asterisk/sdp_srtp.h"
00044 #include "asterisk/dsp.h"
00045 #include "asterisk/acl.h"
00046 #include "asterisk/features_config.h"
00047 #include "asterisk/pickup.h"
00048 
00049 #define SDP_HANDLER_BUCKETS 11
00050 
00051 #define MOD_DATA_ON_RESPONSE "on_response"
00052 #define MOD_DATA_NAT_HOOK "nat_hook"
00053 
00054 /* Some forward declarations */
00055 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type);
00056 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
00057       enum ast_sip_session_response_priority response_priority);
00058 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
00059       enum ast_sip_session_response_priority response_priority);
00060 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata);
00061 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata);
00062 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata);
00063 
00064 /*! \brief NAT hook for modifying outgoing messages with SDP */
00065 static struct ast_sip_nat_hook *nat_hook;
00066 
00067 /*!
00068  * \brief Registered SDP stream handlers
00069  *
00070  * This container is keyed on stream types. Each
00071  * object in the container is a linked list of
00072  * handlers for the stream type.
00073  */
00074 static struct ao2_container *sdp_handlers;
00075 
00076 /*!
00077  * These are the objects in the sdp_handlers container
00078  */
00079 struct sdp_handler_list {
00080    /* The list of handlers to visit */
00081    AST_LIST_HEAD_NOLOCK(, ast_sip_session_sdp_handler) list;
00082    /* The handlers in this list handle streams of this type */
00083    char stream_type[1];
00084 };
00085 
00086 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer);
00087 
00088 static int sdp_handler_list_hash(const void *obj, int flags)
00089 {
00090    const struct sdp_handler_list *handler_list = obj;
00091    const char *stream_type = flags & OBJ_KEY ? obj : handler_list->stream_type;
00092 
00093    return ast_str_hash(stream_type);
00094 }
00095 
00096 static int sdp_handler_list_cmp(void *obj, void *arg, int flags)
00097 {
00098    struct sdp_handler_list *handler_list1 = obj;
00099    struct sdp_handler_list *handler_list2 = arg;
00100    const char *stream_type2 = flags & OBJ_KEY ? arg : handler_list2->stream_type;
00101 
00102    return strcmp(handler_list1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
00103 }
00104 
00105 static int session_media_hash(const void *obj, int flags)
00106 {
00107    const struct ast_sip_session_media *session_media = obj;
00108    const char *stream_type = flags & OBJ_KEY ? obj : session_media->stream_type;
00109 
00110    return ast_str_hash(stream_type);
00111 }
00112 
00113 static int session_media_cmp(void *obj, void *arg, int flags)
00114 {
00115    struct ast_sip_session_media *session_media1 = obj;
00116    struct ast_sip_session_media *session_media2 = arg;
00117    const char *stream_type2 = flags & OBJ_KEY ? arg : session_media2->stream_type;
00118 
00119    return strcmp(session_media1->stream_type, stream_type2) ? 0 : CMP_MATCH | CMP_STOP;
00120 }
00121 
00122 int ast_sip_session_register_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
00123 {
00124    RAII_VAR(struct sdp_handler_list *, handler_list,
00125          ao2_find(sdp_handlers, stream_type, OBJ_KEY), ao2_cleanup);
00126    SCOPED_AO2LOCK(lock, sdp_handlers);
00127 
00128    if (handler_list) {
00129       struct ast_sip_session_sdp_handler *iter;
00130       /* Check if this handler is already registered for this stream type */
00131       AST_LIST_TRAVERSE(&handler_list->list, iter, next) {
00132          if (!strcmp(iter->id, handler->id)) {
00133             ast_log(LOG_WARNING, "Handler '%s' already registered for stream type '%s'.\n", handler->id, stream_type);
00134             return -1;
00135          }
00136       }
00137       AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
00138       ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
00139       ast_module_ref(ast_module_info->self);
00140       return 0;
00141    }
00142 
00143    /* No stream of this type has been registered yet, so we need to create a new list */
00144    handler_list = ao2_alloc(sizeof(*handler_list) + strlen(stream_type), NULL);
00145    if (!handler_list) {
00146       return -1;
00147    }
00148    /* Safe use of strcpy */
00149    strcpy(handler_list->stream_type, stream_type);
00150    AST_LIST_HEAD_INIT_NOLOCK(&handler_list->list);
00151    AST_LIST_INSERT_TAIL(&handler_list->list, handler, next);
00152    if (!ao2_link(sdp_handlers, handler_list)) {
00153       return -1;
00154    }
00155    ast_debug(1, "Registered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
00156    ast_module_ref(ast_module_info->self);
00157    return 0;
00158 }
00159 
00160 static int remove_handler(void *obj, void *arg, void *data, int flags)
00161 {
00162    struct sdp_handler_list *handler_list = obj;
00163    struct ast_sip_session_sdp_handler *handler = data;
00164    struct ast_sip_session_sdp_handler *iter;
00165    const char *stream_type = arg;
00166 
00167    AST_LIST_TRAVERSE_SAFE_BEGIN(&handler_list->list, iter, next) {
00168       if (!strcmp(iter->id, handler->id)) {
00169          AST_LIST_REMOVE_CURRENT(next);
00170          ast_debug(1, "Unregistered SDP stream handler '%s' for stream type '%s'\n", handler->id, stream_type);
00171          ast_module_unref(ast_module_info->self);
00172       }
00173    }
00174    AST_LIST_TRAVERSE_SAFE_END;
00175 
00176    if (AST_LIST_EMPTY(&handler_list->list)) {
00177       ast_debug(3, "No more handlers exist for stream type '%s'\n", stream_type);
00178       return CMP_MATCH;
00179    } else {
00180       return CMP_STOP;
00181    }
00182 }
00183 
00184 void ast_sip_session_unregister_sdp_handler(struct ast_sip_session_sdp_handler *handler, const char *stream_type)
00185 {
00186    ao2_callback_data(sdp_handlers, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, remove_handler, (void *)stream_type, handler);
00187 }
00188 
00189 /*!
00190  * \brief Set an SDP stream handler for a corresponding session media.
00191  *
00192  * \note Always use this function to set the SDP handler for a session media.
00193  *
00194  * This function will properly free resources on the SDP handler currently being
00195  * used by the session media, then set the session media to use the new SDP
00196  * handler.
00197  */
00198 static void session_media_set_handler(struct ast_sip_session_media *session_media,
00199       struct ast_sip_session_sdp_handler *handler)
00200 {
00201    ast_assert(session_media->handler != handler);
00202 
00203    if (session_media->handler) {
00204       session_media->handler->stream_destroy(session_media);
00205    }
00206    session_media->handler = handler;
00207 }
00208 
00209 static int handle_incoming_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
00210 {
00211    int i;
00212    int handled = 0;
00213 
00214    for (i = 0; i < sdp->media_count; ++i) {
00215       /* See if there are registered handlers for this media stream type */
00216       char media[20];
00217       struct ast_sip_session_sdp_handler *handler;
00218       RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
00219       RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
00220       int res;
00221 
00222       /* We need a null-terminated version of the media string */
00223       ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
00224 
00225       session_media = ao2_find(session->media, media, OBJ_KEY);
00226       if (!session_media) {
00227          /* if the session_media doesn't exist, there weren't
00228           * any handlers at the time of its creation */
00229          continue;
00230       }
00231 
00232       if (session_media->handler) {
00233          handler = session_media->handler;
00234          ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
00235             session_media->stream_type,
00236             session_media->handler->id);
00237          res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
00238             sdp->media[i]);
00239          if (res < 0) {
00240             /* Catastrophic failure. Abort! */
00241             return -1;
00242          } else if (res > 0) {
00243             ast_debug(1, "Media stream '%s' handled by %s\n",
00244                session_media->stream_type,
00245                session_media->handler->id);
00246             /* Handled by this handler. Move to the next stream */
00247             handled = 1;
00248             continue;
00249          }
00250       }
00251 
00252       handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
00253       if (!handler_list) {
00254          ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
00255          continue;
00256       }
00257       AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
00258          if (handler == session_media->handler) {
00259             continue;
00260          }
00261          ast_debug(1, "Negotiating incoming SDP media stream '%s' using %s SDP handler\n",
00262             session_media->stream_type,
00263             handler->id);
00264          res = handler->negotiate_incoming_sdp_stream(session, session_media, sdp,
00265             sdp->media[i]);
00266          if (res < 0) {
00267             /* Catastrophic failure. Abort! */
00268             return -1;
00269          }
00270          if (res > 0) {
00271             ast_debug(1, "Media stream '%s' handled by %s\n",
00272                session_media->stream_type,
00273                handler->id);
00274             /* Handled by this handler. Move to the next stream */
00275             session_media_set_handler(session_media, handler);
00276             handled = 1;
00277             break;
00278          }
00279       }
00280    }
00281    if (!handled) {
00282       return -1;
00283    }
00284    return 0;
00285 }
00286 
00287 struct handle_negotiated_sdp_cb {
00288    struct ast_sip_session *session;
00289    const pjmedia_sdp_session *local;
00290    const pjmedia_sdp_session *remote;
00291 };
00292 
00293 static int handle_negotiated_sdp_session_media(void *obj, void *arg, int flags)
00294 {
00295    struct ast_sip_session_media *session_media = obj;
00296    struct handle_negotiated_sdp_cb *callback_data = arg;
00297    struct ast_sip_session *session = callback_data->session;
00298    const pjmedia_sdp_session *local = callback_data->local;
00299    const pjmedia_sdp_session *remote = callback_data->remote;
00300    int i;
00301 
00302    for (i = 0; i < local->media_count; ++i) {
00303       /* See if there are registered handlers for this media stream type */
00304       char media[20];
00305       struct ast_sip_session_sdp_handler *handler;
00306       RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
00307       int res;
00308 
00309       if (!remote->media[i]) {
00310          continue;
00311       }
00312 
00313       /* We need a null-terminated version of the media string */
00314       ast_copy_pj_str(media, &local->media[i]->desc.media, sizeof(media));
00315 
00316       /* stream type doesn't match the one we're looking to fill */
00317       if (strcasecmp(session_media->stream_type, media)) {
00318          continue;
00319       }
00320 
00321       handler = session_media->handler;
00322       if (handler) {
00323          ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
00324             session_media->stream_type,
00325             handler->id);
00326          res = handler->apply_negotiated_sdp_stream(session, session_media, local,
00327             local->media[i], remote, remote->media[i]);
00328          if (res >= 0) {
00329             ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
00330                session_media->stream_type,
00331                handler->id);
00332             return CMP_MATCH;
00333          }
00334          return 0;
00335       }
00336 
00337       handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
00338       if (!handler_list) {
00339          ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
00340          continue;
00341       }
00342       AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
00343          if (handler == session_media->handler) {
00344             continue;
00345          }
00346          ast_debug(1, "Applying negotiated SDP media stream '%s' using %s SDP handler\n",
00347             session_media->stream_type,
00348             handler->id);
00349          res = handler->apply_negotiated_sdp_stream(session, session_media, local,
00350             local->media[i], remote, remote->media[i]);
00351          if (res < 0) {
00352             /* Catastrophic failure. Abort! */
00353             return 0;
00354          }
00355          if (res > 0) {
00356             ast_debug(1, "Applied negotiated SDP media stream '%s' using %s SDP handler\n",
00357                session_media->stream_type,
00358                handler->id);
00359             /* Handled by this handler. Move to the next stream */
00360             session_media_set_handler(session_media, handler);
00361             return CMP_MATCH;
00362          }
00363       }
00364    }
00365    return CMP_MATCH;
00366 }
00367 
00368 static int handle_negotiated_sdp(struct ast_sip_session *session, const pjmedia_sdp_session *local, const pjmedia_sdp_session *remote)
00369 {
00370    RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
00371    struct handle_negotiated_sdp_cb callback_data = {
00372       .session = session,
00373       .local = local,
00374       .remote = remote,
00375    };
00376 
00377    successful = ao2_callback(session->media, OBJ_MULTIPLE, handle_negotiated_sdp_session_media, &callback_data);
00378    if (successful && ao2_iterator_count(successful) == ao2_container_count(session->media)) {
00379       /* Nothing experienced a catastrophic failure */
00380       ast_queue_frame(session->channel, &ast_null_frame);
00381       return 0;
00382    }
00383    return -1;
00384 }
00385 
00386 AST_RWLIST_HEAD_STATIC(session_supplements, ast_sip_session_supplement);
00387 
00388 int ast_sip_session_register_supplement(struct ast_sip_session_supplement *supplement)
00389 {
00390    struct ast_sip_session_supplement *iter;
00391    int inserted = 0;
00392    SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
00393 
00394    if (!supplement->response_priority) {
00395       supplement->response_priority = AST_SIP_SESSION_BEFORE_MEDIA;
00396    }
00397 
00398    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
00399       if (iter->priority > supplement->priority) {
00400          AST_RWLIST_INSERT_BEFORE_CURRENT(supplement, next);
00401          inserted = 1;
00402          break;
00403       }
00404    }
00405    AST_RWLIST_TRAVERSE_SAFE_END;
00406 
00407    if (!inserted) {
00408       AST_RWLIST_INSERT_TAIL(&session_supplements, supplement, next);
00409    }
00410    ast_module_ref(ast_module_info->self);
00411    return 0;
00412 }
00413 
00414 void ast_sip_session_unregister_supplement(struct ast_sip_session_supplement *supplement)
00415 {
00416    struct ast_sip_session_supplement *iter;
00417    SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_WRLOCK, AST_RWLIST_UNLOCK);
00418    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&session_supplements, iter, next) {
00419       if (supplement == iter) {
00420          AST_RWLIST_REMOVE_CURRENT(next);
00421          ast_module_unref(ast_module_info->self);
00422          break;
00423       }
00424    }
00425    AST_RWLIST_TRAVERSE_SAFE_END;
00426 }
00427 
00428 static struct ast_sip_session_supplement *supplement_dup(const struct ast_sip_session_supplement *src)
00429 {
00430    struct ast_sip_session_supplement *dst = ast_calloc(1, sizeof(*dst));
00431    if (!dst) {
00432       return NULL;
00433    }
00434    /* Will need to revisit if shallow copy becomes an issue */
00435    *dst = *src;
00436    return dst;
00437 }
00438 
00439 #define DATASTORE_BUCKETS 53
00440 #define MEDIA_BUCKETS 7
00441 
00442 static void session_datastore_destroy(void *obj)
00443 {
00444    struct ast_datastore *datastore = obj;
00445 
00446    /* Using the destroy function (if present) destroy the data */
00447    if (datastore->info->destroy != NULL && datastore->data != NULL) {
00448       datastore->info->destroy(datastore->data);
00449       datastore->data = NULL;
00450    }
00451 
00452    ast_free((void *) datastore->uid);
00453    datastore->uid = NULL;
00454 }
00455 
00456 struct ast_datastore *ast_sip_session_alloc_datastore(const struct ast_datastore_info *info, const char *uid)
00457 {
00458    RAII_VAR(struct ast_datastore *, datastore, NULL, ao2_cleanup);
00459    char uuid_buf[AST_UUID_STR_LEN];
00460    const char *uid_ptr = uid;
00461 
00462    if (!info) {
00463       return NULL;
00464    }
00465 
00466    datastore = ao2_alloc(sizeof(*datastore), session_datastore_destroy);
00467    if (!datastore) {
00468       return NULL;
00469    }
00470 
00471    datastore->info = info;
00472    if (ast_strlen_zero(uid)) {
00473       /* They didn't provide an ID so we'll provide one ourself */
00474       uid_ptr = ast_uuid_generate_str(uuid_buf, sizeof(uuid_buf));
00475    }
00476 
00477    datastore->uid = ast_strdup(uid_ptr);
00478    if (!datastore->uid) {
00479       return NULL;
00480    }
00481 
00482    ao2_ref(datastore, +1);
00483    return datastore;
00484 }
00485 
00486 int ast_sip_session_add_datastore(struct ast_sip_session *session, struct ast_datastore *datastore)
00487 {
00488    ast_assert(datastore != NULL);
00489    ast_assert(datastore->info != NULL);
00490    ast_assert(ast_strlen_zero(datastore->uid) == 0);
00491 
00492    if (!ao2_link(session->datastores, datastore)) {
00493       return -1;
00494    }
00495    return 0;
00496 }
00497 
00498 struct ast_datastore *ast_sip_session_get_datastore(struct ast_sip_session *session, const char *name)
00499 {
00500    return ao2_find(session->datastores, name, OBJ_KEY);
00501 }
00502 
00503 void ast_sip_session_remove_datastore(struct ast_sip_session *session, const char *name)
00504 {
00505    ao2_callback(session->datastores, OBJ_KEY | OBJ_UNLINK | OBJ_NODATA, NULL, (void *) name);
00506 }
00507 
00508 enum delayed_method {
00509    DELAYED_METHOD_INVITE,
00510    DELAYED_METHOD_UPDATE,
00511    DELAYED_METHOD_BYE,
00512 };
00513 
00514 /*!
00515  * \internal
00516  * \brief Convert delayed method enum value to to a string.
00517  * \since 13.3.0
00518  *
00519  * \param method Delayed method enum value to convert to a string.
00520  *
00521  * \return String value of delayed method.
00522  */
00523 static const char *delayed_method2str(enum delayed_method method)
00524 {
00525    const char *str = "<unknown>";
00526 
00527    switch (method) {
00528    case DELAYED_METHOD_INVITE:
00529       str = "INVITE";
00530       break;
00531    case DELAYED_METHOD_UPDATE:
00532       str = "UPDATE";
00533       break;
00534    case DELAYED_METHOD_BYE:
00535       str = "BYE";
00536       break;
00537    }
00538 
00539    return str;
00540 }
00541 
00542 /*!
00543  * \brief Structure used for sending delayed requests
00544  *
00545  * Requests are typically delayed because the current transaction
00546  * state of an INVITE. Once the pending INVITE transaction terminates,
00547  * the delayed request will be sent
00548  */
00549 struct ast_sip_session_delayed_request {
00550    /*! Method of the request */
00551    enum delayed_method method;
00552    /*! Callback to call when the delayed request is created. */
00553    ast_sip_session_request_creation_cb on_request_creation;
00554    /*! Callback to call when the delayed request SDP is created */
00555    ast_sip_session_sdp_creation_cb on_sdp_creation;
00556    /*! Callback to call when the delayed request receives a response */
00557    ast_sip_session_response_cb on_response;
00558    /*! Whether to generate new SDP */
00559    int generate_new_sdp;
00560    AST_LIST_ENTRY(ast_sip_session_delayed_request) next;
00561 };
00562 
00563 static struct ast_sip_session_delayed_request *delayed_request_alloc(
00564    enum delayed_method method,
00565    ast_sip_session_request_creation_cb on_request_creation,
00566    ast_sip_session_sdp_creation_cb on_sdp_creation,
00567    ast_sip_session_response_cb on_response,
00568    int generate_new_sdp)
00569 {
00570    struct ast_sip_session_delayed_request *delay = ast_calloc(1, sizeof(*delay));
00571 
00572    if (!delay) {
00573       return NULL;
00574    }
00575    delay->method = method;
00576    delay->on_request_creation = on_request_creation;
00577    delay->on_sdp_creation = on_sdp_creation;
00578    delay->on_response = on_response;
00579    delay->generate_new_sdp = generate_new_sdp;
00580    return delay;
00581 }
00582 
00583 static int send_delayed_request(struct ast_sip_session *session, struct ast_sip_session_delayed_request *delay)
00584 {
00585    ast_debug(3, "Endpoint '%s(%s)' sending delayed %s request.\n",
00586       ast_sorcery_object_get_id(session->endpoint),
00587       session->channel ? ast_channel_name(session->channel) : "",
00588       delayed_method2str(delay->method));
00589 
00590    switch (delay->method) {
00591    case DELAYED_METHOD_INVITE:
00592       ast_sip_session_refresh(session, delay->on_request_creation,
00593          delay->on_sdp_creation, delay->on_response,
00594          AST_SIP_SESSION_REFRESH_METHOD_INVITE, delay->generate_new_sdp);
00595       return 0;
00596    case DELAYED_METHOD_UPDATE:
00597       ast_sip_session_refresh(session, delay->on_request_creation,
00598          delay->on_sdp_creation, delay->on_response,
00599          AST_SIP_SESSION_REFRESH_METHOD_UPDATE, delay->generate_new_sdp);
00600       return 0;
00601    case DELAYED_METHOD_BYE:
00602       ast_sip_session_terminate(session, 0);
00603       return 0;
00604    }
00605    ast_log(LOG_WARNING, "Don't know how to send delayed %s(%d) request.\n",
00606       delayed_method2str(delay->method), delay->method);
00607    return -1;
00608 }
00609 
00610 /*!
00611  * \internal
00612  * \brief The current INVITE transaction is in the PROCEEDING state.
00613  * \since 13.3.0
00614  *
00615  * \param vsession Session object.
00616  *
00617  * \retval 0 on success.
00618  * \retval -1 on error.
00619  */
00620 static int invite_proceeding(void *vsession)
00621 {
00622    struct ast_sip_session *session = vsession;
00623    struct ast_sip_session_delayed_request *delay;
00624    int found = 0;
00625    int res = 0;
00626 
00627    AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
00628       switch (delay->method) {
00629       case DELAYED_METHOD_INVITE:
00630          break;
00631       case DELAYED_METHOD_UPDATE:
00632          AST_LIST_REMOVE_CURRENT(next);
00633          res = send_delayed_request(session, delay);
00634          ast_free(delay);
00635          found = 1;
00636          break;
00637       case DELAYED_METHOD_BYE:
00638          /* A BYE is pending so don't bother anymore. */
00639          found = 1;
00640          break;
00641       }
00642       if (found) {
00643          break;
00644       }
00645    }
00646    AST_LIST_TRAVERSE_SAFE_END;
00647 
00648    ao2_ref(session, -1);
00649    return res;
00650 }
00651 
00652 /*!
00653  * \internal
00654  * \brief The current INVITE transaction is in the TERMINATED state.
00655  * \since 13.3.0
00656  *
00657  * \param vsession Session object.
00658  *
00659  * \retval 0 on success.
00660  * \retval -1 on error.
00661  */
00662 static int invite_terminated(void *vsession)
00663 {
00664    struct ast_sip_session *session = vsession;
00665    struct ast_sip_session_delayed_request *delay;
00666    int found = 0;
00667    int res = 0;
00668    int timer_running;
00669 
00670    /* re-INVITE collision timer running? */
00671    timer_running = pj_timer_entry_running(&session->rescheduled_reinvite);
00672 
00673    AST_LIST_TRAVERSE_SAFE_BEGIN(&session->delayed_requests, delay, next) {
00674       switch (delay->method) {
00675       case DELAYED_METHOD_INVITE:
00676          if (!timer_running) {
00677             found = 1;
00678          }
00679          break;
00680       case DELAYED_METHOD_UPDATE:
00681       case DELAYED_METHOD_BYE:
00682          found = 1;
00683          break;
00684       }
00685       if (found) {
00686          AST_LIST_REMOVE_CURRENT(next);
00687          res = send_delayed_request(session, delay);
00688          ast_free(delay);
00689          break;
00690       }
00691    }
00692    AST_LIST_TRAVERSE_SAFE_END;
00693 
00694    ao2_ref(session, -1);
00695    return res;
00696 }
00697 
00698 /*!
00699  * \internal
00700  * \brief INVITE collision timeout.
00701  * \since 13.3.0
00702  *
00703  * \param vsession Session object.
00704  *
00705  * \retval 0 on success.
00706  * \retval -1 on error.
00707  */
00708 static int invite_collision_timeout(void *vsession)
00709 {
00710    struct ast_sip_session *session = vsession;
00711    int res;
00712 
00713    if (session->inv_session->invite_tsx) {
00714       /*
00715        * INVITE transaction still active.  Let it send
00716        * the collision re-INVITE when it terminates.
00717        */
00718       ao2_ref(session, -1);
00719       res = 0;
00720    } else {
00721       res = invite_terminated(session);
00722    }
00723 
00724    return res;
00725 }
00726 
00727 /*!
00728  * \internal
00729  * \brief The current UPDATE transaction is in the COMPLETED state.
00730  * \since 13.3.0
00731  *
00732  * \param vsession Session object.
00733  *
00734  * \retval 0 on success.
00735  * \retval -1 on error.
00736  */
00737 static int update_completed(void *vsession)
00738 {
00739    struct ast_sip_session *session = vsession;
00740    int res;
00741 
00742    if (session->inv_session->invite_tsx) {
00743       res = invite_proceeding(session);
00744    } else {
00745       res = invite_terminated(session);
00746    }
00747 
00748    return res;
00749 }
00750 
00751 static void check_delayed_requests(struct ast_sip_session *session,
00752    int (*cb)(void *vsession))
00753 {
00754    ao2_ref(session, +1);
00755    if (ast_sip_push_task(session->serializer, cb, session)) {
00756       ao2_ref(session, -1);
00757    }
00758 }
00759 
00760 static int delay_request(struct ast_sip_session *session,
00761    ast_sip_session_request_creation_cb on_request,
00762    ast_sip_session_sdp_creation_cb on_sdp_creation,
00763    ast_sip_session_response_cb on_response,
00764    int generate_new_sdp,
00765    enum delayed_method method)
00766 {
00767    struct ast_sip_session_delayed_request *delay = delayed_request_alloc(method,
00768          on_request, on_sdp_creation, on_response, generate_new_sdp);
00769 
00770    if (!delay) {
00771       return -1;
00772    }
00773 
00774    if (method == DELAYED_METHOD_BYE) {
00775       /* Send BYE as early as possible */
00776       AST_LIST_INSERT_HEAD(&session->delayed_requests, delay, next);
00777    } else {
00778       AST_LIST_INSERT_TAIL(&session->delayed_requests, delay, next);
00779    }
00780    return 0;
00781 }
00782 
00783 static pjmedia_sdp_session *generate_session_refresh_sdp(struct ast_sip_session *session)
00784 {
00785    pjsip_inv_session *inv_session = session->inv_session;
00786    const pjmedia_sdp_session *previous_sdp;
00787 
00788    if (pjmedia_sdp_neg_was_answer_remote(inv_session->neg)) {
00789       pjmedia_sdp_neg_get_active_remote(inv_session->neg, &previous_sdp);
00790    } else {
00791       pjmedia_sdp_neg_get_active_local(inv_session->neg, &previous_sdp);
00792    }
00793    return create_local_sdp(inv_session, session, previous_sdp);
00794 }
00795 
00796 int ast_sip_session_refresh(struct ast_sip_session *session,
00797       ast_sip_session_request_creation_cb on_request_creation,
00798       ast_sip_session_sdp_creation_cb on_sdp_creation,
00799       ast_sip_session_response_cb on_response,
00800       enum ast_sip_session_refresh_method method, int generate_new_sdp)
00801 {
00802    pjsip_inv_session *inv_session = session->inv_session;
00803    pjmedia_sdp_session *new_sdp = NULL;
00804    pjsip_tx_data *tdata;
00805 
00806    if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
00807       /* Don't try to do anything with a hung-up call */
00808       ast_debug(3, "Not sending reinvite to %s because of disconnected state...\n",
00809             ast_sorcery_object_get_id(session->endpoint));
00810       return 0;
00811    }
00812 
00813    /* If the dialog has not yet been established we have to defer until it has */
00814    if (inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
00815       ast_debug(3, "Delay sending request to %s because dialog has not been established...\n",
00816          ast_sorcery_object_get_id(session->endpoint));
00817       return delay_request(session, on_request_creation, on_sdp_creation, on_response,
00818          generate_new_sdp,
00819          method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
00820             ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
00821    }
00822 
00823    if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
00824       if (inv_session->invite_tsx) {
00825          /* We can't send a reinvite yet, so delay it */
00826          ast_debug(3, "Delay sending reinvite to %s because of outstanding transaction...\n",
00827                ast_sorcery_object_get_id(session->endpoint));
00828          return delay_request(session, on_request_creation, on_sdp_creation,
00829             on_response, generate_new_sdp, DELAYED_METHOD_INVITE);
00830       } else if (inv_session->state != PJSIP_INV_STATE_CONFIRMED) {
00831          /* Initial INVITE transaction failed to progress us to a confirmed state
00832           * which means re-invites are not possible
00833           */
00834          ast_debug(3, "Not sending reinvite to %s because not in confirmed state...\n",
00835                ast_sorcery_object_get_id(session->endpoint));
00836          return 0;
00837       }
00838    }
00839 
00840    if (generate_new_sdp) {
00841       /* SDP can only be generated if current negotiation has already completed */
00842       if (pjmedia_sdp_neg_get_state(inv_session->neg) != PJMEDIA_SDP_NEG_STATE_DONE) {
00843          ast_debug(3, "Delay session refresh with new SDP to %s because SDP negotiation is not yet done...\n",
00844             ast_sorcery_object_get_id(session->endpoint));
00845          return delay_request(session, on_request_creation, on_sdp_creation,
00846             on_response, generate_new_sdp,
00847             method == AST_SIP_SESSION_REFRESH_METHOD_INVITE
00848                ? DELAYED_METHOD_INVITE : DELAYED_METHOD_UPDATE);
00849       }
00850 
00851       new_sdp = generate_session_refresh_sdp(session);
00852       if (!new_sdp) {
00853          ast_log(LOG_ERROR, "Failed to generate session refresh SDP. Not sending session refresh\n");
00854          return -1;
00855       }
00856       if (on_sdp_creation) {
00857          if (on_sdp_creation(session, new_sdp)) {
00858             return -1;
00859          }
00860       }
00861    }
00862 
00863    if (method == AST_SIP_SESSION_REFRESH_METHOD_INVITE) {
00864       if (pjsip_inv_reinvite(inv_session, NULL, new_sdp, &tdata)) {
00865          ast_log(LOG_WARNING, "Failed to create reinvite properly.\n");
00866          return -1;
00867       }
00868    } else if (pjsip_inv_update(inv_session, NULL, new_sdp, &tdata)) {
00869       ast_log(LOG_WARNING, "Failed to create UPDATE properly.\n");
00870       return -1;
00871    }
00872    if (on_request_creation) {
00873       if (on_request_creation(session, tdata)) {
00874          return -1;
00875       }
00876    }
00877    ast_debug(3, "Sending session refresh SDP via %s to %s\n",
00878       method == AST_SIP_SESSION_REFRESH_METHOD_INVITE ? "re-INVITE" : "UPDATE",
00879       ast_sorcery_object_get_id(session->endpoint));
00880    ast_sip_session_send_request_with_cb(session, tdata, on_response);
00881    return 0;
00882 }
00883 
00884 void ast_sip_session_send_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
00885 {
00886    handle_outgoing_response(session, tdata);
00887    pjsip_inv_send_msg(session->inv_session, tdata);
00888    return;
00889 }
00890 
00891 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata);
00892 
00893 static pjsip_module session_module = {
00894    .name = {"Session Module", 14},
00895    .priority = PJSIP_MOD_PRIORITY_APPLICATION,
00896    .on_rx_request = session_on_rx_request,
00897 };
00898 
00899 /*! \brief Determine whether the SDP provided requires deferral of negotiating or not
00900  *
00901  * \retval 1 re-invite should be deferred and resumed later
00902  * \retval 0 re-invite should not be deferred
00903  */
00904 static int sdp_requires_deferral(struct ast_sip_session *session, const pjmedia_sdp_session *sdp)
00905 {
00906    int i;
00907 
00908    for (i = 0; i < sdp->media_count; ++i) {
00909       /* See if there are registered handlers for this media stream type */
00910       char media[20];
00911       struct ast_sip_session_sdp_handler *handler;
00912       RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
00913       RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
00914       enum ast_sip_session_sdp_stream_defer res;
00915 
00916       /* We need a null-terminated version of the media string */
00917       ast_copy_pj_str(media, &sdp->media[i]->desc.media, sizeof(media));
00918 
00919       session_media = ao2_find(session->media, media, OBJ_KEY);
00920       if (!session_media) {
00921          /* if the session_media doesn't exist, there weren't
00922           * any handlers at the time of its creation */
00923          continue;
00924       }
00925 
00926       if (session_media->handler) {
00927          handler = session_media->handler;
00928          if (handler->defer_incoming_sdp_stream) {
00929             res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
00930                sdp->media[i]);
00931             switch (res) {
00932             case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
00933                break;
00934             case AST_SIP_SESSION_SDP_DEFER_ERROR:
00935                return 0;
00936             case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
00937                break;
00938             case AST_SIP_SESSION_SDP_DEFER_NEEDED:
00939                return 1;
00940             }
00941          }
00942          /* Handled by this handler. Move to the next stream */
00943          continue;
00944       }
00945 
00946       handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
00947       if (!handler_list) {
00948          ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
00949          continue;
00950       }
00951       AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
00952          if (handler == session_media->handler) {
00953             continue;
00954          }
00955          if (!handler->defer_incoming_sdp_stream) {
00956             continue;
00957          }
00958          res = handler->defer_incoming_sdp_stream(session, session_media, sdp,
00959             sdp->media[i]);
00960          switch (res) {
00961          case AST_SIP_SESSION_SDP_DEFER_NOT_HANDLED:
00962             continue;
00963          case AST_SIP_SESSION_SDP_DEFER_ERROR:
00964             session_media_set_handler(session_media, handler);
00965             return 0;
00966          case AST_SIP_SESSION_SDP_DEFER_NOT_NEEDED:
00967             /* Handled by this handler. */
00968             session_media_set_handler(session_media, handler);
00969             break;
00970          case AST_SIP_SESSION_SDP_DEFER_NEEDED:
00971             /* Handled by this handler. */
00972             session_media_set_handler(session_media, handler);
00973             return 1;
00974          }
00975          /* Move to the next stream */
00976          break;
00977       }
00978    }
00979    return 0;
00980 }
00981 
00982 static pj_bool_t session_reinvite_on_rx_request(pjsip_rx_data *rdata)
00983 {
00984    pjsip_dialog *dlg;
00985    RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
00986    pjsip_rdata_sdp_info *sdp_info;
00987 
00988    if (rdata->msg_info.msg->line.req.method.id != PJSIP_INVITE_METHOD ||
00989       !(dlg = pjsip_ua_find_dialog(&rdata->msg_info.cid->id, &rdata->msg_info.to->tag, &rdata->msg_info.from->tag, PJ_FALSE)) ||
00990       !(session = ast_sip_dialog_get_session(dlg)) ||
00991       !session->channel) {
00992       return PJ_FALSE;
00993    }
00994 
00995    if (session->deferred_reinvite) {
00996       pj_str_t key, deferred_key;
00997       pjsip_tx_data *tdata;
00998 
00999       /* We use memory from the new request on purpose so the deferred reinvite pool does not grow uncontrollably */
01000       pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, &rdata->msg_info.cseq->method, rdata);
01001       pjsip_tsx_create_key(rdata->tp_info.pool, &deferred_key, PJSIP_ROLE_UAS, &session->deferred_reinvite->msg_info.cseq->method,
01002          session->deferred_reinvite);
01003 
01004       /* If this is a retransmission ignore it */
01005       if (!pj_strcmp(&key, &deferred_key)) {
01006          return PJ_TRUE;
01007       }
01008 
01009       /* Otherwise this is a new re-invite, so reject it */
01010       if (pjsip_dlg_create_response(dlg, rdata, 491, NULL, &tdata) == PJ_SUCCESS) {
01011          pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
01012       }
01013 
01014       return PJ_TRUE;
01015    }
01016 
01017    if (!(sdp_info = pjsip_rdata_get_sdp_info(rdata)) ||
01018       (sdp_info->sdp_err != PJ_SUCCESS)) {
01019       return PJ_FALSE;
01020    }
01021 
01022    if (!sdp_info->sdp) {
01023       ast_queue_unhold(session->channel);
01024       return PJ_FALSE;
01025    }
01026 
01027    if (!sdp_requires_deferral(session, sdp_info->sdp)) {
01028       return PJ_FALSE;
01029    }
01030 
01031    pjsip_rx_data_clone(rdata, 0, &session->deferred_reinvite);
01032 
01033    return PJ_TRUE;
01034 }
01035 
01036 void ast_sip_session_resume_reinvite(struct ast_sip_session *session)
01037 {
01038    if (!session->deferred_reinvite) {
01039       return;
01040    }
01041 
01042    pjsip_endpt_process_rx_data(ast_sip_get_pjsip_endpoint(), session->deferred_reinvite, NULL, NULL);
01043    pjsip_rx_data_free_cloned(session->deferred_reinvite);
01044    session->deferred_reinvite = NULL;
01045 }
01046 
01047 static pjsip_module session_reinvite_module = {
01048    .name = { "Session Re-Invite Module", 24 },
01049    .priority = PJSIP_MOD_PRIORITY_UA_PROXY_LAYER - 1,
01050    .on_rx_request = session_reinvite_on_rx_request,
01051 };
01052 
01053 void ast_sip_session_send_request_with_cb(struct ast_sip_session *session, pjsip_tx_data *tdata,
01054       ast_sip_session_response_cb on_response)
01055 {
01056    pjsip_inv_session *inv_session = session->inv_session;
01057 
01058    if (inv_session->state == PJSIP_INV_STATE_DISCONNECTED) {
01059       /* Don't try to do anything with a hung-up call */
01060       return;
01061    }
01062 
01063    ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id,
01064               MOD_DATA_ON_RESPONSE, on_response);
01065 
01066    if (!ast_strlen_zero(session->endpoint->fromuser) ||
01067       !ast_strlen_zero(session->endpoint->fromdomain)) {
01068       pjsip_fromto_hdr *from = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_FROM, tdata->msg->hdr.next);
01069       pjsip_sip_uri *uri = pjsip_uri_get_uri(from->uri);
01070 
01071       if (!ast_strlen_zero(session->endpoint->fromuser)) {
01072          pj_strdup2(tdata->pool, &uri->user, session->endpoint->fromuser);
01073       }
01074       if (!ast_strlen_zero(session->endpoint->fromdomain)) {
01075          pj_strdup2(tdata->pool, &uri->host, session->endpoint->fromdomain);
01076       }
01077    }
01078 
01079    handle_outgoing_request(session, tdata);
01080    pjsip_inv_send_msg(session->inv_session, tdata);
01081    return;
01082 }
01083 
01084 void ast_sip_session_send_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
01085 {
01086    ast_sip_session_send_request_with_cb(session, tdata, NULL);
01087 }
01088 
01089 int ast_sip_session_create_invite(struct ast_sip_session *session, pjsip_tx_data **tdata)
01090 {
01091    pjmedia_sdp_session *offer;
01092 
01093    if (!(offer = create_local_sdp(session->inv_session, session, NULL))) {
01094       pjsip_inv_terminate(session->inv_session, 500, PJ_FALSE);
01095       return -1;
01096    }
01097 
01098    pjsip_inv_set_local_sdp(session->inv_session, offer);
01099    pjmedia_sdp_neg_set_prefer_remote_codec_order(session->inv_session->neg, PJ_FALSE);
01100 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
01101    pjmedia_sdp_neg_set_answer_multiple_codecs(session->inv_session->neg, PJ_TRUE);
01102 #endif
01103    if (pjsip_inv_invite(session->inv_session, tdata) != PJ_SUCCESS) {
01104       return -1;
01105    }
01106    return 0;
01107 }
01108 
01109 static int datastore_hash(const void *obj, int flags)
01110 {
01111    const struct ast_datastore *datastore = obj;
01112    const char *uid = flags & OBJ_KEY ? obj : datastore->uid;
01113 
01114    ast_assert(uid != NULL);
01115 
01116    return ast_str_hash(uid);
01117 }
01118 
01119 static int datastore_cmp(void *obj, void *arg, int flags)
01120 {
01121    const struct ast_datastore *datastore1 = obj;
01122    const struct ast_datastore *datastore2 = arg;
01123    const char *uid2 = flags & OBJ_KEY ? arg : datastore2->uid;
01124 
01125    ast_assert(datastore1->uid != NULL);
01126    ast_assert(uid2 != NULL);
01127 
01128    return strcmp(datastore1->uid, uid2) ? 0 : CMP_MATCH | CMP_STOP;
01129 }
01130 
01131 static void session_media_dtor(void *obj)
01132 {
01133    struct ast_sip_session_media *session_media = obj;
01134    struct sdp_handler_list *handler_list;
01135    /* It is possible for SDP handlers to allocate memory on a session_media but
01136     * not end up getting set as the handler for this session_media. This traversal
01137     * ensures that all memory allocated by SDP handlers on the session_media is
01138     * cleared (as well as file descriptors, etc.).
01139     */
01140    handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
01141    if (handler_list) {
01142       struct ast_sip_session_sdp_handler *handler;
01143 
01144       AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
01145          handler->stream_destroy(session_media);
01146       }
01147    }
01148    ao2_cleanup(handler_list);
01149    if (session_media->srtp) {
01150       ast_sdp_srtp_destroy(session_media->srtp);
01151    }
01152 }
01153 
01154 static void session_destructor(void *obj)
01155 {
01156    struct ast_sip_session *session = obj;
01157    struct ast_sip_session_supplement *supplement;
01158    struct ast_sip_session_delayed_request *delay;
01159 
01160    ast_debug(3, "Destroying SIP session with endpoint %s\n",
01161          ast_sorcery_object_get_id(session->endpoint));
01162 
01163    while ((supplement = AST_LIST_REMOVE_HEAD(&session->supplements, next))) {
01164       if (supplement->session_destroy) {
01165          supplement->session_destroy(session);
01166       }
01167       ast_free(supplement);
01168    }
01169 
01170    ast_taskprocessor_unreference(session->serializer);
01171    ao2_cleanup(session->datastores);
01172    ao2_cleanup(session->media);
01173 
01174    AST_LIST_HEAD_DESTROY(&session->supplements);
01175    while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
01176       ast_free(delay);
01177    }
01178    ast_party_id_free(&session->id);
01179    ao2_cleanup(session->endpoint);
01180    ao2_cleanup(session->aor);
01181    ao2_cleanup(session->contact);
01182    ao2_cleanup(session->req_caps);
01183    ao2_cleanup(session->direct_media_cap);
01184 
01185    if (session->dsp) {
01186       ast_dsp_free(session->dsp);
01187    }
01188 
01189    if (session->inv_session) {
01190       pjsip_dlg_dec_session(session->inv_session->dlg, &session_module);
01191    }
01192 }
01193 
01194 static int add_supplements(struct ast_sip_session *session)
01195 {
01196    struct ast_sip_session_supplement *iter;
01197    SCOPED_LOCK(lock, &session_supplements, AST_RWLIST_RDLOCK, AST_RWLIST_UNLOCK);
01198 
01199    AST_RWLIST_TRAVERSE(&session_supplements, iter, next) {
01200       struct ast_sip_session_supplement *copy = supplement_dup(iter);
01201       if (!copy) {
01202          return -1;
01203       }
01204       AST_LIST_INSERT_TAIL(&session->supplements, copy, next);
01205    }
01206    return 0;
01207 }
01208 
01209 static int add_session_media(void *obj, void *arg, int flags)
01210 {
01211    struct sdp_handler_list *handler_list = obj;
01212    struct ast_sip_session * session = arg;
01213    RAII_VAR(struct ast_sip_session_media *, session_media, NULL, ao2_cleanup);
01214    session_media = ao2_alloc(sizeof(*session_media) + strlen(handler_list->stream_type), session_media_dtor);
01215    if (!session_media) {
01216       return CMP_STOP;
01217    }
01218    session_media->encryption = session->endpoint->media.rtp.encryption;
01219    /* Safe use of strcpy */
01220    strcpy(session_media->stream_type, handler_list->stream_type);
01221    ao2_link(session->media, session_media);
01222    return 0;
01223 }
01224 
01225 /*! \brief Destructor for SIP channel */
01226 static void sip_channel_destroy(void *obj)
01227 {
01228    struct ast_sip_channel_pvt *channel = obj;
01229 
01230    ao2_cleanup(channel->pvt);
01231    ao2_cleanup(channel->session);
01232 }
01233 
01234 struct ast_sip_channel_pvt *ast_sip_channel_pvt_alloc(void *pvt, struct ast_sip_session *session)
01235 {
01236    struct ast_sip_channel_pvt *channel = ao2_alloc(sizeof(*channel), sip_channel_destroy);
01237 
01238    if (!channel) {
01239       return NULL;
01240    }
01241 
01242    ao2_ref(pvt, +1);
01243    channel->pvt = pvt;
01244    ao2_ref(session, +1);
01245    channel->session = session;
01246 
01247    return channel;
01248 }
01249 
01250 struct ast_sip_session *ast_sip_session_alloc(struct ast_sip_endpoint *endpoint,
01251    struct ast_sip_contact *contact, pjsip_inv_session *inv_session)
01252 {
01253    RAII_VAR(struct ast_sip_session *, session, ao2_alloc(sizeof(*session), session_destructor), ao2_cleanup);
01254    struct ast_sip_session_supplement *iter;
01255    int dsp_features = 0;
01256    if (!session) {
01257       return NULL;
01258    }
01259    AST_LIST_HEAD_INIT(&session->supplements);
01260    session->datastores = ao2_container_alloc(DATASTORE_BUCKETS, datastore_hash, datastore_cmp);
01261    if (!session->datastores) {
01262       return NULL;
01263    }
01264 
01265    session->endpoint = ao2_bump(endpoint);
01266 
01267    session->media = ao2_container_alloc(MEDIA_BUCKETS, session_media_hash, session_media_cmp);
01268    if (!session->media) {
01269       return NULL;
01270    }
01271    /* fill session->media with available types */
01272    ao2_callback(sdp_handlers, OBJ_NODATA, add_session_media, session);
01273 
01274    session->serializer = ast_sip_create_serializer();
01275    if (!session->serializer) {
01276       return NULL;
01277    }
01278    ast_sip_dialog_set_serializer(inv_session->dlg, session->serializer);
01279    ast_sip_dialog_set_endpoint(inv_session->dlg, endpoint);
01280    pjsip_dlg_inc_session(inv_session->dlg, &session_module);
01281    inv_session->mod_data[session_module.id] = ao2_bump(session);
01282    session->contact = ao2_bump(contact);
01283    session->inv_session = inv_session;
01284    session->req_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
01285 
01286    if ((endpoint->dtmf == AST_SIP_DTMF_INBAND) || (endpoint->dtmf == AST_SIP_DTMF_AUTO)) {
01287       dsp_features |= DSP_FEATURE_DIGIT_DETECT;
01288    }
01289 
01290    if (endpoint->faxdetect) {
01291       dsp_features |= DSP_FEATURE_FAX_DETECT;
01292    }
01293 
01294    if (dsp_features) {
01295       if (!(session->dsp = ast_dsp_new())) {
01296          ao2_ref(session, -1);
01297          return NULL;
01298       }
01299 
01300       ast_dsp_set_features(session->dsp, dsp_features);
01301    }
01302 
01303    if (add_supplements(session)) {
01304       ao2_ref(session, -1);
01305       return NULL;
01306    }
01307    AST_LIST_TRAVERSE(&session->supplements, iter, next) {
01308       if (iter->session_begin) {
01309          iter->session_begin(session);
01310       }
01311    }
01312    session->direct_media_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
01313    AST_LIST_HEAD_INIT_NOLOCK(&session->delayed_requests);
01314    ast_party_id_init(&session->id);
01315    ao2_ref(session, +1);
01316    return session;
01317 }
01318 
01319 /*! \brief struct controlling the suspension of the session's serializer. */
01320 struct ast_sip_session_suspender {
01321    ast_cond_t cond_suspended;
01322    ast_cond_t cond_complete;
01323    int suspended;
01324    int complete;
01325 };
01326 
01327 static void sip_session_suspender_dtor(void *vdoomed)
01328 {
01329    struct ast_sip_session_suspender *doomed = vdoomed;
01330 
01331    ast_cond_destroy(&doomed->cond_suspended);
01332    ast_cond_destroy(&doomed->cond_complete);
01333 }
01334 
01335 /*!
01336  * \internal
01337  * \brief Block the session serializer thread task.
01338  *
01339  * \param data Pushed serializer task data for suspension.
01340  *
01341  * \retval 0
01342  */
01343 static int sip_session_suspend_task(void *data)
01344 {
01345    struct ast_sip_session_suspender *suspender = data;
01346 
01347    ao2_lock(suspender);
01348 
01349    /* Signal that the serializer task is now suspended. */
01350    suspender->suspended = 1;
01351    ast_cond_signal(&suspender->cond_suspended);
01352 
01353    /* Wait for the the serializer suspension to be completed. */
01354    while (!suspender->complete) {
01355       ast_cond_wait(&suspender->cond_complete, ao2_object_get_lockaddr(suspender));
01356    }
01357 
01358    ao2_unlock(suspender);
01359    ao2_ref(suspender, -1);
01360 
01361    return 0;
01362 }
01363 
01364 void ast_sip_session_suspend(struct ast_sip_session *session)
01365 {
01366    struct ast_sip_session_suspender *suspender;
01367    int res;
01368 
01369    ast_assert(session->suspended == NULL);
01370 
01371    if (ast_taskprocessor_is_task(session->serializer)) {
01372       /* I am the session's serializer thread so I cannot suspend. */
01373       return;
01374    }
01375 
01376    suspender = ao2_alloc(sizeof(*suspender), sip_session_suspender_dtor);
01377    if (!suspender) {
01378       /* We will just have to hope that the system does not deadlock */
01379       return;
01380    }
01381    ast_cond_init(&suspender->cond_suspended, NULL);
01382    ast_cond_init(&suspender->cond_complete, NULL);
01383 
01384    ao2_ref(suspender, +1);
01385    res = ast_sip_push_task(session->serializer, sip_session_suspend_task, suspender);
01386    if (res) {
01387       /* We will just have to hope that the system does not deadlock */
01388       ao2_ref(suspender, -2);
01389       return;
01390    }
01391 
01392    session->suspended = suspender;
01393 
01394    /* Wait for the serializer to get suspended. */
01395    ao2_lock(suspender);
01396    while (!suspender->suspended) {
01397       ast_cond_wait(&suspender->cond_suspended, ao2_object_get_lockaddr(suspender));
01398    }
01399    ao2_unlock(suspender);
01400 }
01401 
01402 void ast_sip_session_unsuspend(struct ast_sip_session *session)
01403 {
01404    struct ast_sip_session_suspender *suspender = session->suspended;
01405 
01406    if (!suspender) {
01407       /* Nothing to do */
01408       return;
01409    }
01410    session->suspended = NULL;
01411 
01412    /* Signal that the serializer task suspension is now complete. */
01413    ao2_lock(suspender);
01414    suspender->complete = 1;
01415    ast_cond_signal(&suspender->cond_complete);
01416    ao2_unlock(suspender);
01417 
01418    ao2_ref(suspender, -1);
01419 }
01420 
01421 static int session_outbound_auth(pjsip_dialog *dlg, pjsip_tx_data *tdata, void *user_data)
01422 {
01423    pjsip_inv_session *inv = pjsip_dlg_get_inv_session(dlg);
01424    struct ast_sip_session *session = inv->mod_data[session_module.id];
01425 
01426    if (inv->state < PJSIP_INV_STATE_CONFIRMED && tdata->msg->line.req.method.id == PJSIP_INVITE_METHOD) {
01427       pjsip_inv_uac_restart(inv, PJ_FALSE);
01428    }
01429    ast_sip_session_send_request(session, tdata);
01430    return 0;
01431 }
01432 
01433 struct ast_sip_session *ast_sip_session_create_outgoing(struct ast_sip_endpoint *endpoint,
01434    struct ast_sip_contact *contact, const char *location, const char *request_user,
01435    struct ast_format_cap *req_caps)
01436 {
01437    const char *uri = NULL;
01438    RAII_VAR(struct ast_sip_aor *, found_aor, NULL, ao2_cleanup);
01439    RAII_VAR(struct ast_sip_contact *, found_contact, NULL, ao2_cleanup);
01440    pjsip_timer_setting timer;
01441    pjsip_dialog *dlg;
01442    struct pjsip_inv_session *inv_session;
01443    RAII_VAR(struct ast_sip_session *, session, NULL, ao2_cleanup);
01444 
01445    /* If no location has been provided use the AOR list from the endpoint itself */
01446    if (location || !contact) {
01447       location = S_OR(location, endpoint->aors);
01448 
01449       ast_sip_location_retrieve_contact_and_aor_from_list(location, &found_aor, &found_contact);
01450       if (!found_contact || ast_strlen_zero(found_contact->uri)) {
01451          uri = location;
01452       } else {
01453          uri = found_contact->uri;
01454       }
01455    } else {
01456       uri = contact->uri;
01457    }
01458 
01459    /* If we still have no URI to dial fail to create the session */
01460    if (ast_strlen_zero(uri)) {
01461       return NULL;
01462    }
01463 
01464    if (!(dlg = ast_sip_create_dialog_uac(endpoint, uri, request_user))) {
01465       return NULL;
01466    }
01467 
01468    if (ast_sip_dialog_setup_outbound_authentication(dlg, endpoint, session_outbound_auth, NULL)) {
01469       pjsip_dlg_terminate(dlg);
01470       return NULL;
01471    }
01472 
01473    if (pjsip_inv_create_uac(dlg, NULL, endpoint->extensions.flags, &inv_session) != PJ_SUCCESS) {
01474       pjsip_dlg_terminate(dlg);
01475       return NULL;
01476    }
01477 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
01478    inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
01479 #endif
01480 
01481    pjsip_timer_setting_default(&timer);
01482    timer.min_se = endpoint->extensions.timer.min_se;
01483    timer.sess_expires = endpoint->extensions.timer.sess_expires;
01484    pjsip_timer_init_session(inv_session, &timer);
01485 
01486    if (!(session = ast_sip_session_alloc(endpoint, found_contact ? found_contact : contact, inv_session))) {
01487       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
01488       return NULL;
01489    }
01490    session->aor = ao2_bump(found_aor);
01491    ast_party_id_copy(&session->id, &endpoint->id.self);
01492 
01493    if (ast_format_cap_count(req_caps)) {
01494       /* get joint caps between req_caps and endpoint caps */
01495       struct ast_format_cap *joint_caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
01496       ast_format_cap_get_compatible(req_caps, session->endpoint->media.codecs, joint_caps);
01497 
01498       /* if joint caps */
01499       if (ast_format_cap_count(joint_caps)) {
01500          /* copy endpoint caps into session->req_caps */
01501          ast_format_cap_append_from_cap(session->req_caps, session->endpoint->media.codecs, AST_MEDIA_TYPE_UNKNOWN);
01502          /* replace instances of joint caps equivalents in session->req_caps */
01503          ast_format_cap_replace_from_cap(session->req_caps, joint_caps, AST_MEDIA_TYPE_UNKNOWN);
01504       }
01505       ao2_cleanup(joint_caps);
01506    }
01507 
01508    if ((pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS)) {
01509       pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
01510       /* Since we are not notifying ourselves that the INVITE session is being terminated
01511        * we need to manually drop its reference to session
01512        */
01513       ao2_ref(session, -1);
01514       return NULL;
01515    }
01516 
01517    ao2_ref(session, +1);
01518    return session;
01519 }
01520 
01521 void ast_sip_session_terminate(struct ast_sip_session *session, int response)
01522 {
01523    pj_status_t status;
01524    pjsip_tx_data *packet = NULL;
01525 
01526    if (session->defer_terminate) {
01527       session->terminate_while_deferred = 1;
01528       return;
01529    }
01530 
01531    if (!response) {
01532       response = 603;
01533    }
01534 
01535    if ((session->inv_session->state == PJSIP_INV_STATE_CONFIRMED) && session->inv_session->invite_tsx) {
01536       ast_debug(3, "Delay sending BYE to %s because of outstanding transaction...\n",
01537             ast_sorcery_object_get_id(session->endpoint));
01538       /* If this is delayed the only thing that will happen is a BYE request so we don't
01539        * actually need to store the response code for when it happens.
01540        */
01541       delay_request(session, NULL, NULL, NULL, 0, DELAYED_METHOD_BYE);
01542    } else if (session->inv_session->state == PJSIP_INV_STATE_NULL) {
01543       pjsip_inv_terminate(session->inv_session, response, PJ_TRUE);
01544    } else if (((status = pjsip_inv_end_session(session->inv_session, response, NULL, &packet)) == PJ_SUCCESS)
01545       && packet) {
01546       struct ast_sip_session_delayed_request *delay;
01547 
01548       /* Flush any delayed requests so they cannot overlap this transaction. */
01549       while ((delay = AST_LIST_REMOVE_HEAD(&session->delayed_requests, next))) {
01550          ast_free(delay);
01551       }
01552 
01553       if (packet->msg->type == PJSIP_RESPONSE_MSG) {
01554          ast_sip_session_send_response(session, packet);
01555       } else {
01556          ast_sip_session_send_request(session, packet);
01557       }
01558    }
01559 }
01560 
01561 static int session_termination_task(void *data)
01562 {
01563    struct ast_sip_session *session = data;
01564 
01565    if (session->defer_terminate) {
01566       session->defer_terminate = 0;
01567       if (session->inv_session) {
01568          ast_sip_session_terminate(session, 0);
01569       }
01570    }
01571 
01572    ao2_ref(session, -1);
01573    return 0;
01574 }
01575 
01576 static void session_termination_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry)
01577 {
01578    struct ast_sip_session *session = entry->user_data;
01579 
01580    if (ast_sip_push_task(session->serializer, session_termination_task, session)) {
01581       ao2_cleanup(session);
01582    }
01583 }
01584 
01585 int ast_sip_session_defer_termination(struct ast_sip_session *session)
01586 {
01587    pj_time_val delay = { .sec = 60, };
01588    int res;
01589 
01590    /* The session should not have an active deferred termination request. */
01591    ast_assert(!session->defer_terminate);
01592 
01593    session->defer_terminate = 1;
01594 
01595    session->scheduled_termination.id = 0;
01596    ao2_ref(session, +1);
01597    session->scheduled_termination.user_data = session;
01598    session->scheduled_termination.cb = session_termination_cb;
01599 
01600    res = (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
01601       &session->scheduled_termination, &delay) != PJ_SUCCESS) ? -1 : 0;
01602    if (res) {
01603       session->defer_terminate = 0;
01604       ao2_ref(session, -1);
01605    }
01606    return res;
01607 }
01608 
01609 void ast_sip_session_defer_termination_cancel(struct ast_sip_session *session)
01610 {
01611    if (!session->defer_terminate) {
01612       /* Already canceled or timer fired. */
01613       return;
01614    }
01615    session->defer_terminate = 0;
01616 
01617    if (session->terminate_while_deferred) {
01618       /* Complete the termination started by the upper layer. */
01619       ast_sip_session_terminate(session, 0);
01620    }
01621 
01622    /* Stop the termination timer if it is still running. */
01623    if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()),
01624       &session->scheduled_termination)) {
01625       ao2_ref(session, -1);
01626    }
01627 }
01628 
01629 struct ast_sip_session *ast_sip_dialog_get_session(pjsip_dialog *dlg)
01630 {
01631    pjsip_inv_session *inv_session = pjsip_dlg_get_inv_session(dlg);
01632    struct ast_sip_session *session;
01633 
01634    if (!inv_session ||
01635       !(session = inv_session->mod_data[session_module.id])) {
01636       return NULL;
01637    }
01638 
01639    ao2_ref(session, +1);
01640 
01641    return session;
01642 }
01643 
01644 enum sip_get_destination_result {
01645    /*! The extension was successfully found */
01646    SIP_GET_DEST_EXTEN_FOUND,
01647    /*! The extension specified in the RURI was not found */
01648    SIP_GET_DEST_EXTEN_NOT_FOUND,
01649    /*! The extension specified in the RURI was a partial match */
01650    SIP_GET_DEST_EXTEN_PARTIAL,
01651    /*! The RURI is of an unsupported scheme */
01652    SIP_GET_DEST_UNSUPPORTED_URI,
01653 };
01654 
01655 /*!
01656  * \brief Determine where in the dialplan a call should go
01657  *
01658  * This uses the username in the request URI to try to match
01659  * an extension in the endpoint's configured context in order
01660  * to route the call.
01661  *
01662  * \param session The inbound SIP session
01663  * \param rdata The SIP INVITE
01664  */
01665 static enum sip_get_destination_result get_destination(struct ast_sip_session *session, pjsip_rx_data *rdata)
01666 {
01667    pjsip_uri *ruri = rdata->msg_info.msg->line.req.uri;
01668    pjsip_sip_uri *sip_ruri;
01669    struct ast_features_pickup_config *pickup_cfg;
01670    const char *pickupexten;
01671 
01672    if (!PJSIP_URI_SCHEME_IS_SIP(ruri) && !PJSIP_URI_SCHEME_IS_SIPS(ruri)) {
01673       return SIP_GET_DEST_UNSUPPORTED_URI;
01674    }
01675 
01676    sip_ruri = pjsip_uri_get_uri(ruri);
01677    ast_copy_pj_str(session->exten, &sip_ruri->user, sizeof(session->exten));
01678 
01679    pickup_cfg = ast_get_chan_features_pickup_config(session->channel);
01680    if (!pickup_cfg) {
01681       ast_log(LOG_ERROR, "Unable to retrieve pickup configuration options. Unable to detect call pickup extension\n");
01682       pickupexten = "";
01683    } else {
01684       pickupexten = ast_strdupa(pickup_cfg->pickupexten);
01685       ao2_ref(pickup_cfg, -1);
01686    }
01687 
01688    if (!strcmp(session->exten, pickupexten) ||
01689       ast_exists_extension(NULL, session->endpoint->context, session->exten, 1, NULL)) {
01690       return SIP_GET_DEST_EXTEN_FOUND;
01691    }
01692    /* XXX In reality, we'll likely have further options so that partial matches
01693     * can be indicated here, but for getting something up and running, we're going
01694     * to return a "not exists" error here.
01695     */
01696    return SIP_GET_DEST_EXTEN_NOT_FOUND;
01697 }
01698 
01699 static pjsip_inv_session *pre_session_setup(pjsip_rx_data *rdata, const struct ast_sip_endpoint *endpoint)
01700 {
01701    pjsip_tx_data *tdata;
01702    pjsip_dialog *dlg;
01703    pjsip_inv_session *inv_session;
01704    unsigned int options = endpoint->extensions.flags;
01705    pj_status_t dlg_status;
01706 
01707    if (pjsip_inv_verify_request(rdata, &options, NULL, NULL, ast_sip_get_pjsip_endpoint(), &tdata) != PJ_SUCCESS) {
01708       if (tdata) {
01709          pjsip_endpt_send_response2(ast_sip_get_pjsip_endpoint(), rdata, tdata, NULL, NULL);
01710       } else {
01711          pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
01712       }
01713       return NULL;
01714    }
01715    dlg = ast_sip_create_dialog_uas(endpoint, rdata, &dlg_status);
01716    if (!dlg) {
01717       if (dlg_status != PJ_EEXISTS) {
01718          pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
01719       }
01720       return NULL;
01721    }
01722    if (pjsip_inv_create_uas(dlg, rdata, NULL, options, &inv_session) != PJ_SUCCESS) {
01723       pjsip_endpt_respond_stateless(ast_sip_get_pjsip_endpoint(), rdata, 500, NULL, NULL, NULL);
01724       pjsip_dlg_terminate(dlg);
01725       return NULL;
01726    }
01727 
01728 #if defined(HAVE_PJSIP_REPLACE_MEDIA_STREAM) || defined(PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE)
01729    inv_session->sdp_neg_flags = PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE;
01730 #endif
01731    if (pjsip_dlg_add_usage(dlg, &session_module, NULL) != PJ_SUCCESS) {
01732       if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) != PJ_SUCCESS) {
01733          pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
01734       }
01735       pjsip_inv_send_msg(inv_session, tdata);
01736       return NULL;
01737    }
01738    return inv_session;
01739 }
01740 
01741 struct new_invite {
01742    /*! \brief Session created for the new INVITE */
01743    struct ast_sip_session *session;
01744 
01745    /*! \brief INVITE request itself */
01746    pjsip_rx_data *rdata;
01747 };
01748 
01749 static void new_invite_destroy(void *obj)
01750 {
01751    struct new_invite *invite = obj;
01752 
01753    ao2_cleanup(invite->session);
01754 
01755    if (invite->rdata) {
01756       pjsip_rx_data_free_cloned(invite->rdata);
01757    }
01758 }
01759 
01760 static struct new_invite *new_invite_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata)
01761 {
01762    struct new_invite *invite = ao2_alloc(sizeof(*invite), new_invite_destroy);
01763 
01764    if (!invite) {
01765       return NULL;
01766    }
01767 
01768    ao2_ref(session, +1);
01769    invite->session = session;
01770 
01771    if (pjsip_rx_data_clone(rdata, 0, &invite->rdata) != PJ_SUCCESS) {
01772       ao2_ref(invite, -1);
01773       return NULL;
01774    }
01775 
01776    return invite;
01777 }
01778 
01779 static int new_invite(void *data)
01780 {
01781    RAII_VAR(struct new_invite *, invite, data, ao2_cleanup);
01782    pjsip_tx_data *tdata = NULL;
01783    pjsip_timer_setting timer;
01784    pjsip_rdata_sdp_info *sdp_info;
01785    pjmedia_sdp_session *local = NULL;
01786 
01787    /* From this point on, any calls to pjsip_inv_terminate have the last argument as PJ_TRUE
01788     * so that we will be notified so we can destroy the session properly
01789     */
01790 
01791    switch (get_destination(invite->session, invite->rdata)) {
01792    case SIP_GET_DEST_EXTEN_FOUND:
01793       /* Things worked. Keep going */
01794       break;
01795    case SIP_GET_DEST_UNSUPPORTED_URI:
01796       if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 416, NULL, NULL, &tdata) == PJ_SUCCESS) {
01797          ast_sip_session_send_response(invite->session, tdata);
01798       } else  {
01799          pjsip_inv_terminate(invite->session->inv_session, 416, PJ_TRUE);
01800       }
01801       return 0;
01802    case SIP_GET_DEST_EXTEN_NOT_FOUND:
01803    case SIP_GET_DEST_EXTEN_PARTIAL:
01804    default:
01805       ast_log(LOG_NOTICE, "Call from '%s' (%s:%s:%d) to extension '%s' rejected because extension not found in context '%s'.\n",
01806          ast_sorcery_object_get_id(invite->session->endpoint), invite->rdata->tp_info.transport->type_name, invite->rdata->pkt_info.src_name,
01807          invite->rdata->pkt_info.src_port, invite->session->exten, invite->session->endpoint->context);
01808 
01809       if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 404, NULL, NULL, &tdata) == PJ_SUCCESS) {
01810          ast_sip_session_send_response(invite->session, tdata);
01811       } else  {
01812          pjsip_inv_terminate(invite->session->inv_session, 404, PJ_TRUE);
01813       }
01814       return 0;
01815    };
01816 
01817    if ((sdp_info = pjsip_rdata_get_sdp_info(invite->rdata)) && (sdp_info->sdp_err == PJ_SUCCESS) && sdp_info->sdp) {
01818       if (handle_incoming_sdp(invite->session, sdp_info->sdp)) {
01819          if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 488, NULL, NULL, &tdata) == PJ_SUCCESS) {
01820             ast_sip_session_send_response(invite->session, tdata);
01821          } else  {
01822             pjsip_inv_terminate(invite->session->inv_session, 488, PJ_TRUE);
01823          }
01824          return 0;
01825       }
01826       /* We are creating a local SDP which is an answer to their offer */
01827       local = create_local_sdp(invite->session->inv_session, invite->session, sdp_info->sdp);
01828    } else {
01829       /* We are creating a local SDP which is an offer */
01830       local = create_local_sdp(invite->session->inv_session, invite->session, NULL);
01831    }
01832 
01833    /* If we were unable to create a local SDP terminate the session early, it won't go anywhere */
01834    if (!local) {
01835       if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
01836          ast_sip_session_send_response(invite->session, tdata);
01837       } else  {
01838          pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
01839       }
01840       return 0;
01841    } else {
01842       pjsip_inv_set_local_sdp(invite->session->inv_session, local);
01843       pjmedia_sdp_neg_set_prefer_remote_codec_order(invite->session->inv_session->neg, PJ_FALSE);
01844 #ifdef PJMEDIA_SDP_NEG_ANSWER_MULTIPLE_CODECS
01845       pjmedia_sdp_neg_set_answer_multiple_codecs(invite->session->inv_session->neg, PJ_TRUE);
01846 #endif
01847    }
01848 
01849    pjsip_timer_setting_default(&timer);
01850    timer.min_se = invite->session->endpoint->extensions.timer.min_se;
01851    timer.sess_expires = invite->session->endpoint->extensions.timer.sess_expires;
01852    pjsip_timer_init_session(invite->session->inv_session, &timer);
01853 
01854    /* At this point, we've verified what we can, so let's go ahead and send a 100 Trying out */
01855    if (pjsip_inv_initial_answer(invite->session->inv_session, invite->rdata, 100, NULL, NULL, &tdata) != PJ_SUCCESS) {
01856       pjsip_inv_terminate(invite->session->inv_session, 500, PJ_TRUE);
01857       return 0;
01858    }
01859    ast_sip_session_send_response(invite->session, tdata);
01860 
01861    handle_incoming_request(invite->session, invite->rdata, PJSIP_EVENT_RX_MSG);
01862 
01863    return 0;
01864 }
01865 
01866 static void handle_new_invite_request(pjsip_rx_data *rdata)
01867 {
01868    RAII_VAR(struct ast_sip_endpoint *, endpoint,
01869          ast_pjsip_rdata_get_endpoint(rdata), ao2_cleanup);
01870    pjsip_tx_data *tdata = NULL;
01871    pjsip_inv_session *inv_session = NULL;
01872    struct ast_sip_session *session;
01873    struct new_invite *invite;
01874 
01875    ast_assert(endpoint != NULL);
01876 
01877    inv_session = pre_session_setup(rdata, endpoint);
01878    if (!inv_session) {
01879       /* pre_session_setup() returns a response on failure */
01880       return;
01881    }
01882 
01883    session = ast_sip_session_alloc(endpoint, NULL, inv_session);
01884    if (!session) {
01885       if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
01886          pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
01887       } else {
01888          pjsip_inv_send_msg(inv_session, tdata);
01889       }
01890       return;
01891    }
01892 
01893    invite = new_invite_alloc(session, rdata);
01894    if (!invite || ast_sip_push_task(session->serializer, new_invite, invite)) {
01895       if (pjsip_inv_initial_answer(inv_session, rdata, 500, NULL, NULL, &tdata) == PJ_SUCCESS) {
01896          pjsip_inv_terminate(inv_session, 500, PJ_FALSE);
01897       } else {
01898          pjsip_inv_send_msg(inv_session, tdata);
01899       }
01900       ao2_cleanup(invite);
01901    }
01902    ao2_ref(session, -1);
01903 }
01904 
01905 static pj_bool_t does_method_match(const pj_str_t *message_method, const char *supplement_method)
01906 {
01907    pj_str_t method;
01908 
01909    if (ast_strlen_zero(supplement_method)) {
01910       return PJ_TRUE;
01911    }
01912 
01913    pj_cstr(&method, supplement_method);
01914 
01915    return pj_stristr(&method, message_method) ? PJ_TRUE : PJ_FALSE;
01916 }
01917 
01918 static pj_bool_t has_supplement(const struct ast_sip_session *session, const pjsip_rx_data *rdata)
01919 {
01920    struct ast_sip_session_supplement *supplement;
01921    struct pjsip_method *method = &rdata->msg_info.msg->line.req.method;
01922 
01923    if (!session) {
01924       return PJ_FALSE;
01925    }
01926 
01927    AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
01928       if (does_method_match(&method->name, supplement->method)) {
01929          return PJ_TRUE;
01930       }
01931    }
01932    return PJ_FALSE;
01933 }
01934 /*!
01935  * \brief Called when a new SIP request comes into PJSIP
01936  *
01937  * This function is called under two circumstances
01938  * 1) An out-of-dialog request is received by PJSIP
01939  * 2) An in-dialog request that the inv_session layer does not
01940  *    handle is received (such as an in-dialog INFO)
01941  *
01942  * In all cases, there is very little we actually do in this function
01943  * 1) For requests we don't handle, we return PJ_FALSE
01944  * 2) For new INVITEs, throw the work into the SIP threadpool to be done
01945  *    there to free up the thread(s) handling incoming requests
01946  * 3) For in-dialog requests we handle, we defer handling them until the
01947  *    on_inv_state_change() callback instead (where we will end up putting
01948  *    them into the threadpool).
01949  */
01950 static pj_bool_t session_on_rx_request(pjsip_rx_data *rdata)
01951 {
01952    pj_status_t handled = PJ_FALSE;
01953    pjsip_dialog *dlg = pjsip_rdata_get_dlg(rdata);
01954    pjsip_inv_session *inv_session;
01955 
01956    switch (rdata->msg_info.msg->line.req.method.id) {
01957    case PJSIP_INVITE_METHOD:
01958       if (dlg) {
01959          ast_log(LOG_WARNING, "on_rx_request called for INVITE in mid-dialog?\n");
01960          break;
01961       }
01962       handled = PJ_TRUE;
01963       handle_new_invite_request(rdata);
01964       break;
01965    default:
01966       /* Handle other in-dialog methods if their supplements have been registered */
01967       handled = dlg && (inv_session = pjsip_dlg_get_inv_session(dlg)) &&
01968          has_supplement(inv_session->mod_data[session_module.id], rdata);
01969       break;
01970    }
01971 
01972    return handled;
01973 }
01974 
01975 static void resend_reinvite(pj_timer_heap_t *timer, pj_timer_entry *entry)
01976 {
01977    struct ast_sip_session *session = entry->user_data;
01978 
01979    ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision timer expired.\n",
01980       ast_sorcery_object_get_id(session->endpoint),
01981       session->channel ? ast_channel_name(session->channel) : "");
01982 
01983    if (AST_LIST_EMPTY(&session->delayed_requests)) {
01984       /* No delayed request pending, so just return */
01985       ao2_ref(session, -1);
01986       return;
01987    }
01988    if (ast_sip_push_task(session->serializer, invite_collision_timeout, session)) {
01989       /*
01990        * Uh oh.  We now have nothing in the foreseeable future
01991        * to trigger sending the delayed requests.
01992        */
01993       ao2_ref(session, -1);
01994    }
01995 }
01996 
01997 static void reschedule_reinvite(struct ast_sip_session *session, ast_sip_session_response_cb on_response)
01998 {
01999    pjsip_inv_session *inv = session->inv_session;
02000    pj_time_val tv;
02001 
02002    ast_debug(3, "Endpoint '%s(%s)' re-INVITE collision.\n",
02003       ast_sorcery_object_get_id(session->endpoint),
02004       session->channel ? ast_channel_name(session->channel) : "");
02005    if (delay_request(session, NULL, NULL, on_response, 1, DELAYED_METHOD_INVITE)) {
02006       return;
02007    }
02008    if (pj_timer_entry_running(&session->rescheduled_reinvite)) {
02009       /* Timer already running.  Something weird is going on. */
02010       ast_debug(1, "Endpoint '%s(%s)' re-INVITE collision while timer running!!!\n",
02011          ast_sorcery_object_get_id(session->endpoint),
02012          session->channel ? ast_channel_name(session->channel) : "");
02013       return;
02014    }
02015 
02016    tv.sec = 0;
02017    if (inv->role == PJSIP_ROLE_UAC) {
02018       tv.msec = 2100 + ast_random() % 2000;
02019    } else {
02020       tv.msec = ast_random() % 2000;
02021    }
02022    pj_timer_entry_init(&session->rescheduled_reinvite, 0, session, resend_reinvite);
02023 
02024    ao2_ref(session, +1);
02025    if (pjsip_endpt_schedule_timer(ast_sip_get_pjsip_endpoint(),
02026       &session->rescheduled_reinvite, &tv) != PJ_SUCCESS) {
02027       ao2_ref(session, -1);
02028    }
02029 }
02030 
02031 static void __print_debug_details(const char *function, pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
02032 {
02033    struct ast_sip_session *session;
02034 
02035    if (!DEBUG_ATLEAST(5)) {
02036       /* Debug not spamy enough */
02037       return;
02038    }
02039 
02040    ast_log(LOG_DEBUG, "Function %s called on event %s\n",
02041       function, pjsip_event_str(e->type));
02042    if (!inv) {
02043       ast_log(LOG_DEBUG, "Transaction %p does not belong to an inv_session?\n", tsx);
02044       ast_log(LOG_DEBUG, "The transaction state is %s\n",
02045          pjsip_tsx_state_str(tsx->state));
02046       return;
02047    }
02048    session = inv->mod_data[session_module.id];
02049    if (!session) {
02050       ast_log(LOG_DEBUG, "inv_session %p has no ast session\n", inv);
02051    } else {
02052       ast_log(LOG_DEBUG, "The state change pertains to the endpoint '%s(%s)'\n",
02053          ast_sorcery_object_get_id(session->endpoint),
02054          session->channel ? ast_channel_name(session->channel) : "");
02055    }
02056    if (inv->invite_tsx) {
02057       ast_log(LOG_DEBUG, "The inv session still has an invite_tsx (%p)\n",
02058          inv->invite_tsx);
02059    } else {
02060       ast_log(LOG_DEBUG, "The inv session does NOT have an invite_tsx\n");
02061    }
02062    if (tsx) {
02063       ast_log(LOG_DEBUG, "The %s %.*s transaction involved in this state change is %p\n",
02064          pjsip_role_name(tsx->role),
02065          (int) pj_strlen(&tsx->method.name), pj_strbuf(&tsx->method.name),
02066          tsx);
02067       ast_log(LOG_DEBUG, "The current transaction state is %s\n",
02068          pjsip_tsx_state_str(tsx->state));
02069       ast_log(LOG_DEBUG, "The transaction state change event is %s\n",
02070          pjsip_event_str(e->body.tsx_state.type));
02071    } else {
02072       ast_log(LOG_DEBUG, "There is no transaction involved in this state change\n");
02073    }
02074    ast_log(LOG_DEBUG, "The current inv state is %s\n", pjsip_inv_state_name(inv->state));
02075 }
02076 
02077 #define print_debug_details(inv, tsx, e) __print_debug_details(__PRETTY_FUNCTION__, (inv), (tsx), (e))
02078 
02079 static void handle_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type)
02080 {
02081    struct ast_sip_session_supplement *supplement;
02082    struct pjsip_request_line req = rdata->msg_info.msg->line.req;
02083 
02084    ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
02085    AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
02086       if (supplement->incoming_request && does_method_match(&req.method.name, supplement->method)) {
02087          if (supplement->incoming_request(session, rdata)) {
02088             break;
02089          }
02090       }
02091    }
02092 }
02093 
02094 static void handle_incoming_response(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
02095       enum ast_sip_session_response_priority response_priority)
02096 {
02097    struct ast_sip_session_supplement *supplement;
02098    struct pjsip_status_line status = rdata->msg_info.msg->line.status;
02099 
02100    ast_debug(3, "Response is %d %.*s\n", status.code, (int) pj_strlen(&status.reason),
02101          pj_strbuf(&status.reason));
02102 
02103    AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
02104       if (!(supplement->response_priority & response_priority)) {
02105          continue;
02106       }
02107       if (supplement->incoming_response && does_method_match(&rdata->msg_info.cseq->method.name, supplement->method)) {
02108          supplement->incoming_response(session, rdata);
02109       }
02110    }
02111 }
02112 
02113 static int handle_incoming(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_event_id_e type,
02114       enum ast_sip_session_response_priority response_priority)
02115 {
02116    ast_debug(3, "Received %s\n", rdata->msg_info.msg->type == PJSIP_REQUEST_MSG ?
02117          "request" : "response");
02118 
02119    if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG) {
02120       handle_incoming_request(session, rdata, type);
02121    } else {
02122       handle_incoming_response(session, rdata, type, response_priority);
02123    }
02124 
02125    return 0;
02126 }
02127 
02128 static void handle_outgoing_request(struct ast_sip_session *session, pjsip_tx_data *tdata)
02129 {
02130    struct ast_sip_session_supplement *supplement;
02131    struct pjsip_request_line req = tdata->msg->line.req;
02132 
02133    ast_debug(3, "Method is %.*s\n", (int) pj_strlen(&req.method.name), pj_strbuf(&req.method.name));
02134    AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
02135       if (supplement->outgoing_request && does_method_match(&req.method.name, supplement->method)) {
02136          supplement->outgoing_request(session, tdata);
02137       }
02138    }
02139 }
02140 
02141 static void handle_outgoing_response(struct ast_sip_session *session, pjsip_tx_data *tdata)
02142 {
02143    struct ast_sip_session_supplement *supplement;
02144    struct pjsip_status_line status = tdata->msg->line.status;
02145    pjsip_cseq_hdr *cseq = pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL);
02146    ast_debug(3, "Method is %.*s, Response is %d %.*s\n", (int) pj_strlen(&cseq->method.name),
02147       pj_strbuf(&cseq->method.name), status.code, (int) pj_strlen(&status.reason),
02148       pj_strbuf(&status.reason));
02149 
02150    AST_LIST_TRAVERSE(&session->supplements, supplement, next) {
02151       if (supplement->outgoing_response && does_method_match(&cseq->method.name, supplement->method)) {
02152          supplement->outgoing_response(session, tdata);
02153       }
02154    }
02155 }
02156 
02157 static void handle_outgoing(struct ast_sip_session *session, pjsip_tx_data *tdata)
02158 {
02159    ast_debug(3, "Sending %s\n", tdata->msg->type == PJSIP_REQUEST_MSG ?
02160          "request" : "response");
02161    if (tdata->msg->type == PJSIP_REQUEST_MSG) {
02162       handle_outgoing_request(session, tdata);
02163    } else {
02164       handle_outgoing_response(session, tdata);
02165    }
02166 }
02167 
02168 static int session_end(struct ast_sip_session *session)
02169 {
02170    struct ast_sip_session_supplement *iter;
02171 
02172    /* Stop the scheduled termination */
02173    if (pj_timer_heap_cancel(pjsip_endpt_get_timer_heap(ast_sip_get_pjsip_endpoint()), &session->scheduled_termination)) {
02174       ao2_ref(session, -1);
02175    }
02176 
02177    /* Session is dead. Let's get rid of the reference to the session */
02178    AST_LIST_TRAVERSE(&session->supplements, iter, next) {
02179       if (iter->session_end) {
02180          iter->session_end(session);
02181       }
02182    }
02183 
02184    session->inv_session->mod_data[session_module.id] = NULL;
02185    ast_sip_dialog_set_serializer(session->inv_session->dlg, NULL);
02186    ast_sip_dialog_set_endpoint(session->inv_session->dlg, NULL);
02187    ao2_cleanup(session);
02188    return 0;
02189 }
02190 
02191 static void session_inv_on_state_changed(pjsip_inv_session *inv, pjsip_event *e)
02192 {
02193    struct ast_sip_session *session = inv->mod_data[session_module.id];
02194    pjsip_event_id_e type;
02195 
02196    if (e) {
02197       print_debug_details(inv, NULL, e);
02198       type = e->type;
02199    } else {
02200       type = PJSIP_EVENT_UNKNOWN;
02201    }
02202 
02203    if (!session) {
02204       return;
02205    }
02206 
02207    switch(type) {
02208    case PJSIP_EVENT_TX_MSG:
02209       handle_outgoing(session, e->body.tx_msg.tdata);
02210       break;
02211    case PJSIP_EVENT_RX_MSG:
02212       handle_incoming(session, e->body.rx_msg.rdata, type,
02213             AST_SIP_SESSION_BEFORE_MEDIA);
02214       break;
02215    case PJSIP_EVENT_TSX_STATE:
02216       ast_debug(3, "Source of transaction state change is %s\n", pjsip_event_str(e->body.tsx_state.type));
02217       /* Transaction state changes are prompted by some other underlying event. */
02218       switch(e->body.tsx_state.type) {
02219       case PJSIP_EVENT_TX_MSG:
02220          handle_outgoing(session, e->body.tsx_state.src.tdata);
02221          break;
02222       case PJSIP_EVENT_RX_MSG:
02223          handle_incoming(session, e->body.tsx_state.src.rdata, type,
02224                AST_SIP_SESSION_BEFORE_MEDIA);
02225          break;
02226       case PJSIP_EVENT_TRANSPORT_ERROR:
02227       case PJSIP_EVENT_TIMER:
02228       case PJSIP_EVENT_USER:
02229       case PJSIP_EVENT_UNKNOWN:
02230       case PJSIP_EVENT_TSX_STATE:
02231          /* Inception? */
02232          break;
02233       }
02234       break;
02235    case PJSIP_EVENT_TRANSPORT_ERROR:
02236    case PJSIP_EVENT_TIMER:
02237    case PJSIP_EVENT_UNKNOWN:
02238    case PJSIP_EVENT_USER:
02239    default:
02240       break;
02241    }
02242 
02243    if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
02244       session_end(session);
02245    }
02246 }
02247 
02248 static void session_inv_on_new_session(pjsip_inv_session *inv, pjsip_event *e)
02249 {
02250    /* XXX STUB */
02251 }
02252 
02253 static void session_inv_on_tsx_state_changed(pjsip_inv_session *inv, pjsip_transaction *tsx, pjsip_event *e)
02254 {
02255    ast_sip_session_response_cb cb;
02256    struct ast_sip_session *session = inv->mod_data[session_module.id];
02257 
02258    print_debug_details(inv, tsx, e);
02259    if (!session) {
02260       /* Transaction likely timed out after the call was hung up. Just
02261        * ignore such transaction changes
02262        */
02263       return;
02264    }
02265    switch (e->body.tsx_state.type) {
02266    case PJSIP_EVENT_TX_MSG:
02267       handle_outgoing(session, e->body.tsx_state.src.tdata);
02268       /* When we create an outgoing request, we do not have access to the transaction that
02269        * is created. Instead, We have to place transaction-specific data in the tdata. Here,
02270        * we transfer the data into the transaction. This way, when we receive a response, we
02271        * can dig this data out again
02272        */
02273       tsx->mod_data[session_module.id] = e->body.tsx_state.src.tdata->mod_data[session_module.id];
02274       break;
02275    case PJSIP_EVENT_RX_MSG:
02276       cb = ast_sip_mod_data_get(tsx->mod_data, session_module.id, MOD_DATA_ON_RESPONSE);
02277       handle_incoming(session, e->body.tsx_state.src.rdata, e->type,
02278             AST_SIP_SESSION_AFTER_MEDIA);
02279       if (tsx->method.id == PJSIP_INVITE_METHOD) {
02280          if (tsx->role == PJSIP_ROLE_UAC) {
02281             if (tsx->state == PJSIP_TSX_STATE_COMPLETED) {
02282                /* This means we got a non 2XX final response to our outgoing INVITE */
02283                if (tsx->status_code == PJSIP_SC_REQUEST_PENDING) {
02284                   reschedule_reinvite(session, cb);
02285                   return;
02286                } else if (inv->state == PJSIP_INV_STATE_CONFIRMED &&
02287                      tsx->status_code != 488) {
02288                   /* Other reinvite failures (except 488) result in destroying the session. */
02289                   pjsip_tx_data *tdata;
02290                   if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
02291                      ast_sip_session_send_request(session, tdata);
02292                   }
02293                }
02294             } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
02295                if (inv->cancelling && tsx->status_code == PJSIP_SC_OK) {
02296                   /* This is a race condition detailed in RFC 5407 section 3.1.2.
02297                    * We sent a CANCEL at the same time that the UAS sent us a 200 OK for
02298                    * the original INVITE. As a result, we have now received a 200 OK for
02299                    * a cancelled call. Our role is to immediately send a BYE to end the
02300                    * dialog.
02301                    */
02302                   pjsip_tx_data *tdata;
02303 
02304                   if (pjsip_inv_end_session(inv, 500, NULL, &tdata) == PJ_SUCCESS) {
02305                      ast_sip_session_send_request(session, tdata);
02306                   }
02307                }
02308             }
02309          }
02310       }
02311       if (cb) {
02312          cb(session, e->body.tsx_state.src.rdata);
02313       }
02314       break;
02315    case PJSIP_EVENT_TRANSPORT_ERROR:
02316    case PJSIP_EVENT_TIMER:
02317    case PJSIP_EVENT_USER:
02318    case PJSIP_EVENT_UNKNOWN:
02319    case PJSIP_EVENT_TSX_STATE:
02320       /* Inception? */
02321       break;
02322    }
02323 
02324    if (AST_LIST_EMPTY(&session->delayed_requests)) {
02325       /* No delayed request pending, so just return */
02326       return;
02327    }
02328 
02329    if (tsx->method.id == PJSIP_INVITE_METHOD) {
02330       if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
02331          ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
02332             ast_sorcery_object_get_id(session->endpoint),
02333             session->channel ? ast_channel_name(session->channel) : "",
02334             pjsip_tsx_state_str(tsx->state));
02335          check_delayed_requests(session, invite_proceeding);
02336       } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED) {
02337          /*
02338           * Terminated INVITE transactions always should result in
02339           * queuing delayed requests, no matter what event caused
02340           * the transaction to terminate.
02341           */
02342          ast_debug(3, "Endpoint '%s(%s)' INVITE delay check. tsx-state:%s\n",
02343             ast_sorcery_object_get_id(session->endpoint),
02344             session->channel ? ast_channel_name(session->channel) : "",
02345             pjsip_tsx_state_str(tsx->state));
02346          check_delayed_requests(session, invite_terminated);
02347       }
02348    } else if (tsx->role == PJSIP_ROLE_UAC
02349       && tsx->state == PJSIP_TSX_STATE_COMPLETED
02350       && !pj_strcmp2(&tsx->method.name, "UPDATE")) {
02351       ast_debug(3, "Endpoint '%s(%s)' UPDATE delay check. tsx-state:%s\n",
02352          ast_sorcery_object_get_id(session->endpoint),
02353          session->channel ? ast_channel_name(session->channel) : "",
02354          pjsip_tsx_state_str(tsx->state));
02355       check_delayed_requests(session, update_completed);
02356    }
02357 }
02358 
02359 static int add_sdp_streams(void *obj, void *arg, void *data, int flags)
02360 {
02361    struct ast_sip_session_media *session_media = obj;
02362    pjmedia_sdp_session *answer = arg;
02363    struct ast_sip_session *session = data;
02364    struct ast_sip_session_sdp_handler *handler = session_media->handler;
02365    RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
02366    int res;
02367 
02368    if (handler) {
02369       /* if an already assigned handler reports a catastrophic error, fail */
02370       res = handler->create_outgoing_sdp_stream(session, session_media, answer);
02371       if (res < 0) {
02372          return 0;
02373       }
02374       return CMP_MATCH;
02375    }
02376 
02377    handler_list = ao2_find(sdp_handlers, session_media->stream_type, OBJ_KEY);
02378    if (!handler_list) {
02379       return CMP_MATCH;
02380    }
02381 
02382    /* no handler for this stream type and we have a list to search */
02383    AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
02384       if (handler == session_media->handler) {
02385          continue;
02386       }
02387       res = handler->create_outgoing_sdp_stream(session, session_media, answer);
02388       if (res < 0) {
02389          /* catastrophic error */
02390          return 0;
02391       }
02392       if (res > 0) {
02393          /* Handled by this handler. Move to the next stream */
02394          session_media_set_handler(session_media, handler);
02395          return CMP_MATCH;
02396       }
02397    }
02398 
02399    /* streams that weren't handled won't be included in generated outbound SDP */
02400    return CMP_MATCH;
02401 }
02402 
02403 static struct pjmedia_sdp_session *create_local_sdp(pjsip_inv_session *inv, struct ast_sip_session *session, const pjmedia_sdp_session *offer)
02404 {
02405    RAII_VAR(struct ao2_iterator *, successful, NULL, ao2_iterator_cleanup);
02406    static const pj_str_t STR_IN = { "IN", 2 };
02407    static const pj_str_t STR_IP4 = { "IP4", 3 };
02408    static const pj_str_t STR_IP6 = { "IP6", 3 };
02409    pjmedia_sdp_session *local;
02410 
02411    if (!(local = PJ_POOL_ZALLOC_T(inv->pool_prov, pjmedia_sdp_session))) {
02412       return NULL;
02413    }
02414 
02415    if (!offer) {
02416       local->origin.version = local->origin.id = (pj_uint32_t)(ast_random());
02417    } else {
02418       local->origin.version = offer->origin.version + 1;
02419       local->origin.id = offer->origin.id;
02420    }
02421 
02422    pj_strdup2(inv->pool_prov, &local->origin.user, session->endpoint->media.sdpowner);
02423    pj_strdup2(inv->pool_prov, &local->name, session->endpoint->media.sdpsession);
02424 
02425    /* Now let the handlers add streams of various types, pjmedia will automatically reorder the media streams for us */
02426    successful = ao2_callback_data(session->media, OBJ_MULTIPLE, add_sdp_streams, local, session);
02427    if (!successful || ao2_iterator_count(successful) != ao2_container_count(session->media)) {
02428       /* Something experienced a catastrophic failure */
02429       return NULL;
02430    }
02431 
02432    /* Use the connection details of the first media stream if possible for SDP level */
02433    if (local->media_count) {
02434       int stream;
02435 
02436       /* Since we are using the first media stream as the SDP level we can get rid of it
02437        * from the stream itself
02438        */
02439       local->conn = local->media[0]->conn;
02440       local->media[0]->conn = NULL;
02441       pj_strassign(&local->origin.net_type, &local->conn->net_type);
02442       pj_strassign(&local->origin.addr_type, &local->conn->addr_type);
02443       pj_strassign(&local->origin.addr, &local->conn->addr);
02444 
02445       /* Go through each media stream seeing if the connection details actually differ,
02446        * if not just use SDP level and reduce the SDP size
02447        */
02448       for (stream = 1; stream < local->media_count; stream++) {
02449          if (!pj_strcmp(&local->conn->net_type, &local->media[stream]->conn->net_type) &&
02450             !pj_strcmp(&local->conn->addr_type, &local->media[stream]->conn->addr_type) &&
02451             !pj_strcmp(&local->conn->addr, &local->media[stream]->conn->addr)) {
02452             local->media[stream]->conn = NULL;
02453          }
02454       }
02455    } else {
02456       local->origin.net_type = STR_IN;
02457       local->origin.addr_type = session->endpoint->media.rtp.ipv6 ? STR_IP6 : STR_IP4;
02458 
02459       if (!ast_strlen_zero(session->endpoint->media.address)) {
02460          pj_strdup2(inv->pool_prov, &local->origin.addr, session->endpoint->media.address);
02461       } else {
02462          pj_sockaddr localaddr;
02463          char our_ip[PJ_INET6_ADDRSTRLEN];
02464 
02465          pj_gethostip(session->endpoint->media.rtp.ipv6 ? pj_AF_INET6() : pj_AF_INET(), &localaddr);
02466          pj_sockaddr_print(&localaddr, our_ip, sizeof(our_ip), 0);
02467          pj_strdup2(inv->pool_prov, &local->origin.addr, our_ip);
02468       }
02469    }
02470 
02471    return local;
02472 }
02473 
02474 static void session_inv_on_rx_offer(pjsip_inv_session *inv, const pjmedia_sdp_session *offer)
02475 {
02476    struct ast_sip_session *session = inv->mod_data[session_module.id];
02477    pjmedia_sdp_session *answer;
02478 
02479    if (handle_incoming_sdp(session, offer)) {
02480       return;
02481    }
02482 
02483    if ((answer = create_local_sdp(inv, session, offer))) {
02484       pjsip_inv_set_sdp_answer(inv, answer);
02485    }
02486 }
02487 
02488 #if 0
02489 static void session_inv_on_create_offer(pjsip_inv_session *inv, pjmedia_sdp_session **p_offer)
02490 {
02491    /* XXX STUB */
02492 }
02493 #endif
02494 
02495 static void session_inv_on_media_update(pjsip_inv_session *inv, pj_status_t status)
02496 {
02497    struct ast_sip_session *session = inv->mod_data[session_module.id];
02498    const pjmedia_sdp_session *local, *remote;
02499 
02500    if (!session->channel) {
02501       /* If we don't have a channel. We really don't care about media updates.
02502        * Just ignore
02503        */
02504       return;
02505    }
02506 
02507    if ((status != PJ_SUCCESS) || (pjmedia_sdp_neg_get_active_local(inv->neg, &local) != PJ_SUCCESS) ||
02508       (pjmedia_sdp_neg_get_active_remote(inv->neg, &remote) != PJ_SUCCESS)) {
02509       ast_channel_hangupcause_set(session->channel, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
02510       ast_set_hangupsource(session->channel, ast_channel_name(session->channel), 0);
02511       ast_queue_hangup(session->channel);
02512       return;
02513    }
02514 
02515    handle_negotiated_sdp(session, local, remote);
02516 }
02517 
02518 static pjsip_redirect_op session_inv_on_redirected(pjsip_inv_session *inv, const pjsip_uri *target, const pjsip_event *e)
02519 {
02520    struct ast_sip_session *session = inv->mod_data[session_module.id];
02521    const pjsip_sip_uri *uri;
02522 
02523    if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_PJSIP) {
02524       return PJSIP_REDIRECT_ACCEPT;
02525    }
02526 
02527    if (!PJSIP_URI_SCHEME_IS_SIP(target) && !PJSIP_URI_SCHEME_IS_SIPS(target)) {
02528       return PJSIP_REDIRECT_STOP;
02529    }
02530 
02531    handle_incoming(session, e->body.rx_msg.rdata, PJSIP_EVENT_RX_MSG,
02532          AST_SIP_SESSION_BEFORE_REDIRECTING);
02533 
02534    uri = pjsip_uri_get_uri(target);
02535 
02536    if (session->endpoint->redirect_method == AST_SIP_REDIRECT_USER) {
02537       char exten[AST_MAX_EXTENSION];
02538 
02539       ast_copy_pj_str(exten, &uri->user, sizeof(exten));
02540       ast_channel_call_forward_set(session->channel, exten);
02541    } else if (session->endpoint->redirect_method == AST_SIP_REDIRECT_URI_CORE) {
02542       char target_uri[PJSIP_MAX_URL_SIZE];
02543       /* PJSIP/ + endpoint length + / + max URL size */
02544       char forward[8 + strlen(ast_sorcery_object_get_id(session->endpoint)) + PJSIP_MAX_URL_SIZE];
02545 
02546       pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, target_uri, sizeof(target_uri));
02547       sprintf(forward, "PJSIP/%s/%s", ast_sorcery_object_get_id(session->endpoint), target_uri);
02548       ast_channel_call_forward_set(session->channel, forward);
02549    }
02550 
02551    return PJSIP_REDIRECT_STOP;
02552 }
02553 
02554 static pjsip_inv_callback inv_callback = {
02555    .on_state_changed = session_inv_on_state_changed,
02556    .on_new_session = session_inv_on_new_session,
02557    .on_tsx_state_changed = session_inv_on_tsx_state_changed,
02558    .on_rx_offer = session_inv_on_rx_offer,
02559    .on_media_update = session_inv_on_media_update,
02560    .on_redirected = session_inv_on_redirected,
02561 };
02562 
02563 /*! \brief Hook for modifying outgoing messages with SDP to contain the proper address information */
02564 static void session_outgoing_nat_hook(pjsip_tx_data *tdata, struct ast_sip_transport *transport)
02565 {
02566    struct ast_sip_nat_hook *hook = ast_sip_mod_data_get(
02567       tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK);
02568    struct pjmedia_sdp_session *sdp;
02569    int stream;
02570 
02571    /* SDP produced by us directly will never be multipart */
02572    if (hook || !tdata->msg->body || pj_stricmp2(&tdata->msg->body->content_type.type, "application") ||
02573       pj_stricmp2(&tdata->msg->body->content_type.subtype, "sdp") || ast_strlen_zero(transport->external_media_address)) {
02574       return;
02575    }
02576 
02577    sdp = tdata->msg->body->data;
02578 
02579    if (sdp->conn) {
02580       char host[NI_MAXHOST];
02581       struct ast_sockaddr addr = { { 0, } };
02582 
02583       ast_copy_pj_str(host, &sdp->conn->addr, sizeof(host));
02584       ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID);
02585 
02586       if (ast_apply_ha(transport->localnet, &addr) != AST_SENSE_ALLOW) {
02587          pj_strdup2(tdata->pool, &sdp->conn->addr, transport->external_media_address);
02588       }
02589    }
02590 
02591    for (stream = 0; stream < sdp->media_count; ++stream) {
02592       /* See if there are registered handlers for this media stream type */
02593       char media[20];
02594       struct ast_sip_session_sdp_handler *handler;
02595       RAII_VAR(struct sdp_handler_list *, handler_list, NULL, ao2_cleanup);
02596 
02597       /* We need a null-terminated version of the media string */
02598       ast_copy_pj_str(media, &sdp->media[stream]->desc.media, sizeof(media));
02599 
02600       handler_list = ao2_find(sdp_handlers, media, OBJ_KEY);
02601       if (!handler_list) {
02602          ast_debug(1, "No registered SDP handlers for media type '%s'\n", media);
02603          continue;
02604       }
02605       AST_LIST_TRAVERSE(&handler_list->list, handler, next) {
02606          if (handler->change_outgoing_sdp_stream_media_address) {
02607             handler->change_outgoing_sdp_stream_media_address(tdata, sdp->media[stream], transport);
02608          }
02609       }
02610    }
02611 
02612    /* We purposely do this so that the hook will not be invoked multiple times, ie: if a retransmit occurs */
02613    ast_sip_mod_data_set(tdata->pool, tdata->mod_data, session_module.id, MOD_DATA_NAT_HOOK, nat_hook);
02614 }
02615 
02616 static int load_module(void)
02617 {
02618    pjsip_endpoint *endpt;
02619 
02620    CHECK_PJSIP_MODULE_LOADED();
02621 
02622    if (!ast_sip_get_sorcery() || !ast_sip_get_pjsip_endpoint()) {
02623       return AST_MODULE_LOAD_DECLINE;
02624    }
02625    if (!(nat_hook = ast_sorcery_alloc(ast_sip_get_sorcery(), "nat_hook", NULL))) {
02626       return AST_MODULE_LOAD_DECLINE;
02627    }
02628    nat_hook->outgoing_external_message = session_outgoing_nat_hook;
02629    ast_sorcery_create(ast_sip_get_sorcery(), nat_hook);
02630    sdp_handlers = ao2_container_alloc(SDP_HANDLER_BUCKETS,
02631          sdp_handler_list_hash, sdp_handler_list_cmp);
02632    if (!sdp_handlers) {
02633       return AST_MODULE_LOAD_DECLINE;
02634    }
02635    endpt = ast_sip_get_pjsip_endpoint();
02636    pjsip_inv_usage_init(endpt, &inv_callback);
02637    pjsip_100rel_init_module(endpt);
02638    pjsip_timer_init_module(endpt);
02639    if (ast_sip_register_service(&session_module)) {
02640       return AST_MODULE_LOAD_DECLINE;
02641    }
02642    ast_sip_register_service(&session_reinvite_module);
02643 
02644    ast_module_shutdown_ref(ast_module_info->self);
02645 
02646    return AST_MODULE_LOAD_SUCCESS;
02647 }
02648 
02649 static int unload_module(void)
02650 {
02651    ast_sip_unregister_service(&session_reinvite_module);
02652    ast_sip_unregister_service(&session_module);
02653    ast_sorcery_delete(ast_sip_get_sorcery(), nat_hook);
02654    ao2_cleanup(nat_hook);
02655    ao2_cleanup(sdp_handlers);
02656    return 0;
02657 }
02658 
02659 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "PJSIP Session resource",
02660       .support_level = AST_MODULE_SUPPORT_CORE,
02661       .load = load_module,
02662       .unload = unload_module,
02663       .load_pri = AST_MODPRI_APP_DEPEND,
02664           );

Generated on Thu Apr 16 06:27:50 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6