LCOV - code coverage report
Current view: top level - xmpp - xmpp_server.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 323 499 64.7 %
Date: 2026-11-16 02:06:09 Functions: 47 66 71.2 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
       3             :  * Copyright Contributors to the OpenSDN project
       4             :  */
       5             : 
       6             : #include "xmpp/xmpp_server.h"
       7             : 
       8             : #include <boost/foreach.hpp>
       9             : #include <boost/tuple/tuple.hpp>
      10             : 
      11             : #include "base/task_annotations.h"
      12             : #include "xmpp/xmpp_connection.h"
      13             : #include "xmpp/xmpp_factory.h"
      14             : #include "xmpp/xmpp_lifetime.h"
      15             : #include "xmpp/xmpp_log.h"
      16             : #include "xmpp/xmpp_sandesh.h"
      17             : #include "xmpp/xmpp_session.h"
      18             : 
      19             : #include "sandesh/request_pipeline.h"
      20             : #include "sandesh/common/vns_types.h"
      21             : #include "sandesh/common/vns_constants.h"
      22             : #include "sandesh/xmpp_server_types.h"
      23             : #include "sandesh/xmpp_trace_sandesh_types.h"
      24             : #include "sandesh/xmpp_client_server_sandesh_types.h"
      25             : 
      26             : using namespace std;
      27             : using namespace boost::asio;
      28             : using boost::tie;
      29             : 
      30             : #define DEFAULT_XMPP_HOLD_TIME 90
      31             : class XmppServer::DeleteActor : public LifetimeActor {
      32             : public:
      33         100 :     DeleteActor(XmppServer *server)
      34         100 :         : LifetimeActor(server->lifetime_manager()), server_(server) {
      35         100 :     }
      36          98 :     virtual bool MayDelete() const {
      37          98 :         CHECK_CONCURRENCY("bgp::Config");
      38          98 :         return server_->MayDelete();
      39             :     }
      40          98 :     virtual void Shutdown() {
      41          98 :         CHECK_CONCURRENCY("bgp::Config");
      42          98 :         server_->SessionShutdown();
      43          98 :     }
      44          98 :     virtual void Destroy() {
      45          98 :         CHECK_CONCURRENCY("bgp::Config");
      46          98 :         server_->Terminate();
      47          98 :     }
      48             : 
      49             : private:
      50             :     XmppServer *server_;
      51             : };
      52             : 
      53             : 
      54          54 : XmppServer::XmppServer(EventManager *evm, const string &server_addr,
      55          54 :                        const XmppChannelConfig *config)
      56             :     : XmppConnectionManager(
      57          54 :           evm, ssl::context::sslv23_server, config->auth_enabled, true),
      58          54 :       max_connections_(0),
      59          54 :       lifetime_manager_(XmppStaticObjectFactory::Create<XmppLifetimeManager>(
      60             :           TaskScheduler::GetInstance()->GetTaskId("bgp::Config"))),
      61          54 :       deleter_(new DeleteActor(this)),
      62          54 :       server_addr_(server_addr),
      63          54 :       log_uve_(false),
      64          54 :       auth_enabled_(config->auth_enabled),
      65          54 :       tcp_hold_time_(config->tcp_hold_time),
      66          54 :       gr_helper_disable_(config->gr_helper_disable),
      67          54 :       dscp_value_(0),
      68          54 :       connection_queue_(TaskScheduler::GetInstance()->GetTaskId("bgp::Config"),
      69         162 :           0, boost::bind(&XmppServer::DequeueConnection, this, _1)) {
      70             : 
      71          54 :     if (config->auth_enabled) {
      72             : 
      73             :         // Get SSL context from base class and update
      74          44 :         boost::asio::ssl::context *ctx = context();
      75          44 :         boost::system::error_code ec;
      76             : 
      77             :         // set mode
      78          44 :         ctx->set_options(ssl::context::default_workarounds |
      79             :                          ssl::context::no_sslv3 | ssl::context::no_sslv2, ec);
      80          44 :         if (ec.value() != 0) {
      81           0 :             LOG(ERROR, "Error : " << ec.message() << ", setting ssl options");
      82           0 :             exit(EINVAL);
      83             :         }
      84             : 
      85             :         // CA certificate, used to verify if the peer certificate
      86             :         // is signed by a trusted CA
      87          44 :         std::string ca_cert_filename = config->path_to_ca_cert;
      88          44 :         if (!ca_cert_filename.empty()) {
      89             : 
      90             :             // Verify peer has CA signed certificate
      91           0 :             ctx->set_verify_mode(boost::asio::ssl::verify_peer, ec);
      92           0 :             if (ec.value() != 0) {
      93           0 :                 LOG(ERROR, "Error : " << ec.message()
      94             :                     << ", while setting ssl verification mode");
      95           0 :                 exit(EINVAL);
      96             :             }
      97             : 
      98           0 :             ctx->load_verify_file(config->path_to_ca_cert, ec);
      99           0 :             if (ec.value() != 0) {
     100           0 :                 LOG(ERROR, "Error : " << ec.message()
     101             :                     << ", while using cacert file : "
     102             :                     << config->path_to_ca_cert);
     103           0 :                 exit(EINVAL);
     104             :             }
     105             :         }
     106             : 
     107             :         // server certificate
     108          44 :         ctx->use_certificate_file(config->path_to_server_cert,
     109             :                                   boost::asio::ssl::context::pem, ec);
     110          44 :         if (ec.value() != 0) {
     111           0 :             LOG(ERROR, "Error : " << ec.message()
     112             :                 << ", while using server cert file : "
     113             :                 << config->path_to_server_cert);
     114           0 :             exit(EINVAL);
     115             :         }
     116             : 
     117             :         // server private key
     118          44 :         ctx->use_private_key_file(config->path_to_server_priv_key,
     119             :                                   boost::asio::ssl::context::pem, ec);
     120          44 :         if (ec.value() != 0) {
     121           0 :             LOG(ERROR, "Error : " << ec.message()
     122             :                 << ", while using privkey file : "
     123             :                 << config->path_to_server_priv_key);
     124           0 :             exit(EINVAL);
     125             :         }
     126          44 :     }
     127          54 : }
     128             : 
     129             : class XmppConfigUpdater {
     130             : public:
     131          20 :     explicit XmppConfigUpdater(XmppServer *server,
     132          20 :                                BgpConfigManager *config_manager) :
     133          20 :             server_(server) {
     134          20 :         BgpConfigManager::Observers obs;
     135             :         obs.system= boost::bind(&XmppConfigUpdater::ProcessGlobalSystemConfig,
     136          20 :             this, _1, _2);
     137             :         obs.protocol = boost::bind(&XmppConfigUpdater::ProcessProtocolConfig,
     138          20 :             this, _1, _2);
     139          20 :         config_manager->RegisterObservers(obs);
     140          20 :     }
     141             : 
     142        1007 :     const BgpGlobalSystemConfig &config() const { return config_; }
     143             : 
     144          20 :     void ProcessProtocolConfig(const BgpProtocolConfig *protocol_config,
     145             :                                BgpConfigManager::EventType event) {
     146             : 
     147          20 :         if (server_->subcluster_name() != protocol_config->subcluster_name()) {
     148           0 :             server_->set_subcluster_name(protocol_config->subcluster_name());
     149           0 :             server_->ClearAllConnections();
     150             :         }
     151          20 :     }
     152             : 
     153          30 :     void ProcessGlobalSystemConfig(const BgpGlobalSystemConfig *system,
     154             :             BgpConfigManager::EventType event) {
     155             :         // Clear peers only if GR is or was enabled.
     156          30 :         bool clear_peers = config_.gr_enable() || system->gr_enable();
     157          30 :         bool update_peers = false;
     158          30 :         config_.set_gr_enable(system->gr_enable());
     159          30 :         config_.set_gr_time(system->gr_time());
     160          30 :         config_.set_llgr_time(system->llgr_time());
     161          30 :         config_.set_end_of_rib_timeout(system->end_of_rib_timeout());
     162          30 :         config_.set_gr_xmpp_helper(system->gr_xmpp_helper());
     163             : 
     164             :         // Process any change in xmpp-hold-time
     165          60 :         if (config_.fc_enabled() != system->fc_enabled() ||
     166          30 :             config_.xmpp_hold_time() != system->xmpp_hold_time()) {
     167           0 :             config_.set_xmpp_hold_time(system->xmpp_hold_time());
     168           0 :             config_.set_fc_enabled(system->fc_enabled());
     169             :             // if fc_enabled is not set, use default hold time
     170           0 :             if (!system->fc_enabled())
     171           0 :                 config_.set_xmpp_hold_time(DEFAULT_XMPP_HOLD_TIME);
     172           0 :             update_peers = true;
     173             :         }
     174             : 
     175             :         // Process any change in rd-cluster-seed knob
     176          30 :         if (config_.rd_cluster_seed() != system->rd_cluster_seed()) {
     177           0 :             config_.set_rd_cluster_seed(system->rd_cluster_seed());
     178           0 :             clear_peers = true;
     179             :         }
     180             : 
     181          30 :         if (clear_peers)
     182          30 :             server_->ClearAllConnections();
     183           0 :         else if (update_peers)
     184           0 :             server_->UpdateAllConnections(config_.xmpp_hold_time());
     185          30 :     }
     186             : 
     187             :     const string subcluster_name() const { return server_->subcluster_name(); }
     188             :     void set_subcluster_name(const string& name) {
     189             :         server_->set_subcluster_name(name);
     190             :     }
     191             : 
     192         136 :     uint8_t xmpp_hold_time() const { return config_.xmpp_hold_time(); }
     193             :     void set_xmpp_hold_time(int hold_time) {
     194             :         config_.set_xmpp_hold_time(hold_time);
     195             :     }
     196             : 
     197             : private:
     198             :     XmppServer *server_;
     199             :     BgpGlobalSystemConfig config_;
     200             : };
     201             : 
     202          39 : XmppServer::XmppServer(EventManager *evm, const string &server_addr)
     203             :     : XmppConnectionManager(evm, ssl::context::sslv23_server, false, false),
     204          39 :       max_connections_(0),
     205          39 :       lifetime_manager_(XmppStaticObjectFactory::Create<XmppLifetimeManager>(
     206             :           TaskScheduler::GetInstance()->GetTaskId("bgp::Config"))),
     207          39 :       deleter_(new DeleteActor(this)),
     208          39 :       server_addr_(server_addr),
     209          39 :       log_uve_(false),
     210          39 :       auth_enabled_(false),
     211          39 :       tcp_hold_time_(XmppChannelConfig::kTcpHoldTime),
     212          39 :       gr_helper_disable_(false),
     213          39 :       xmpp_config_updater_(NULL),
     214          39 :       dscp_value_(0),
     215          39 :       connection_queue_(TaskScheduler::GetInstance()->GetTaskId("bgp::Config"),
     216         117 :           0, boost::bind(&XmppServer::DequeueConnection, this, _1)) {
     217          39 : }
     218             : 
     219             : 
     220           7 : XmppServer::XmppServer(EventManager *evm)
     221             :     : XmppConnectionManager(evm, ssl::context::sslv23_server, false, false),
     222           7 :       max_connections_(0),
     223           7 :       lifetime_manager_(new LifetimeManager(
     224          14 :           TaskScheduler::GetInstance()->GetTaskId("bgp::Config"))),
     225           7 :       deleter_(new DeleteActor(this)),
     226           7 :       log_uve_(false),
     227           7 :       auth_enabled_(false),
     228           7 :       tcp_hold_time_(XmppChannelConfig::kTcpHoldTime),
     229           7 :       gr_helper_disable_(false),
     230           7 :       dscp_value_(0),
     231           7 :       connection_queue_(TaskScheduler::GetInstance()->GetTaskId("bgp::Config"),
     232          14 :           0, boost::bind(&XmppServer::DequeueConnection, this, _1)) {
     233           7 : }
     234             : 
     235          20 : void XmppServer::CreateConfigUpdater(BgpConfigManager *config_manager) {
     236          20 :     xmpp_config_updater_.reset(new XmppConfigUpdater(this, config_manager));
     237          20 : }
     238             : 
     239          16 : uint16_t XmppServer::GetGracefulRestartTime() const {
     240             :     // Check if GR is disabled..
     241          16 :     if (!xmpp_config_updater_ || !xmpp_config_updater_->config().gr_enable())
     242           0 :         return 0;
     243          16 :     return xmpp_config_updater_->config().gr_time();
     244             : }
     245             : 
     246           0 : uint32_t XmppServer::GetLongLivedGracefulRestartTime() const {
     247             :     // Check if GR is disabled..
     248           0 :     if (!xmpp_config_updater_ || !xmpp_config_updater_->config().gr_enable())
     249           0 :         return 0;
     250           0 :     return xmpp_config_updater_->config().llgr_time();
     251             : }
     252             : 
     253         136 : uint32_t XmppServer::GetEndOfRibReceiveTime() const {
     254         136 :     if (xmpp_config_updater_)
     255         136 :         return xmpp_config_updater_->config().end_of_rib_timeout();
     256           0 :     return BgpGlobalSystemConfig::kEndOfRibTime;
     257             : }
     258             : 
     259         527 : uint32_t XmppServer::GetEndOfRibSendTime() const {
     260         527 :     if (xmpp_config_updater_)
     261         527 :         xmpp_config_updater_->config().end_of_rib_timeout();
     262         527 :     return BgpGlobalSystemConfig::kEndOfRibTime;
     263             : }
     264             : 
     265         228 : bool XmppServer::IsGRHelperModeEnabled() const {
     266             :     // Check if disabled in .conf file.
     267         228 :     if (gr_helper_disable_)
     268          64 :         return false;
     269             : 
     270             :     // Check from configuration.
     271         164 :     if (!xmpp_config_updater_)
     272          44 :         return false;
     273             : 
     274             :     // Check if GR is disabled..
     275         120 :     if (!xmpp_config_updater_->config().gr_enable())
     276          16 :         return false;
     277             : 
     278         104 :     return xmpp_config_updater_->config().gr_xmpp_helper();
     279             : }
     280             : 
     281         275 : bool XmppServer::IsPeerCloseGraceful() const {
     282             : 
     283             :     // If the server is deleted, do not do graceful restart
     284         275 :     if (deleter()->IsDeleted())
     285          80 :         return false;
     286             : 
     287             :     // Check if GR helper mode is disabled.
     288         195 :     if (!IsGRHelperModeEnabled())
     289         107 :         return false;
     290             : 
     291             :     // Enable GR if either gr-time or llgr-time is configured.
     292          88 :     return (xmpp_config_updater_->config().gr_time() ||
     293          88 :             xmpp_config_updater_->config().llgr_time());
     294             : }
     295             : 
     296         169 : XmppServer::~XmppServer() {
     297         100 :     STLDeleteElements(&connection_endpoint_map_);
     298         100 :     TcpServer::ClearSessions();
     299         169 : }
     300             : 
     301           0 : bool XmppServer::Initialize(short port) {
     302           0 :     log_uve_ = false;
     303           0 :     return TcpServer::Initialize(port);
     304             : }
     305             : 
     306          98 : bool XmppServer::Initialize(short port, bool logUVE) {
     307          98 :     log_uve_ = logUVE;
     308          98 :     return TcpServer::Initialize(port);
     309             : }
     310             : 
     311           0 : bool XmppServer::Initialize(short port, bool logUVE, const IpAddress& ip) {
     312           0 :     log_uve_ = logUVE;
     313           0 :     return TcpServer::Initialize(port, ip);
     314             : }
     315             : 
     316             : //
     317             : // Can be removed after Shutdown is renamed to ManagedDelete.
     318             : //
     319          98 : void XmppServer::SessionShutdown() {
     320          98 :     XmppConnectionManager::Shutdown();
     321          98 : }
     322             : 
     323             : //
     324             : // Return true if it's possible to delete the XmppServer.
     325             : //
     326             : // No need to check the connection WorkQueue since XmppServerConnections on it
     327             : // are dependents of the XmppServer.
     328             : //
     329          98 : bool XmppServer::MayDelete() const {
     330          98 :     return (GetSessionQueueSize() == 0);
     331             : }
     332             : 
     333             : //
     334             : // Trigger deletion of the XmppServer.
     335             : //
     336             : // A mutex is used to ensure that we do not create new XmppServerConnections
     337             : // after this point.  Note that this routine and AcceptSession may be called
     338             : // concurrently from 2 different threads in tests.
     339             : //
     340          98 : void XmppServer::Shutdown() {
     341          98 :     std::scoped_lock lock(deletion_mutex_);
     342          98 :     deleter_->Delete();
     343          98 : }
     344             : 
     345             : //
     346             : // Called when the XmppServer delete actor is being destroyed.
     347             : //
     348          98 : void XmppServer::Terminate() {
     349          98 :     ClearSessions();
     350          98 :     connection_queue_.Shutdown();
     351          98 : }
     352             : 
     353         173 : LifetimeActor *XmppServer::deleter() {
     354         173 :     return deleter_.get();
     355             : }
     356             : 
     357         275 : LifetimeActor *XmppServer::deleter() const {
     358         275 :     return deleter_.get();
     359             : }
     360             : 
     361         273 : LifetimeManager *XmppServer::lifetime_manager() {
     362         273 :     return lifetime_manager_.get();
     363             : }
     364             : 
     365          22 : TcpSession *XmppServer::CreateSession() {
     366             :     typedef boost::asio::detail::socket_option::boolean<
     367             :         SOL_SOCKET, SO_REUSEADDR> reuse_addr_t;
     368          22 :     TcpSession *session = TcpServer::CreateSession();
     369          22 :     Socket *socket = session->socket();
     370             : 
     371          22 :     boost::system::error_code err;
     372          22 :     socket->open(ip::tcp::v4(), err);
     373          22 :     if (err) {
     374           0 :         XMPP_WARNING(ServerOpenFail, err.message());
     375             :     }
     376             : 
     377          22 :     socket->set_option(reuse_addr_t(true), err);
     378          22 :     if (err) {
     379           0 :         XMPP_WARNING(SetSockOptFail, "", XMPP_PEER_DIR_OUT, err.message());
     380             :     }
     381             : 
     382          22 :     socket->bind(LocalEndpoint(), err);
     383          22 :     if (err) {
     384          22 :         XMPP_WARNING(ServerBindFailure, err.message());
     385             :     }
     386             : 
     387          22 :     XmppSession *xmpps = static_cast<XmppSession *>(session);
     388          22 :     err = xmpps->EnableTcpKeepalive(tcp_hold_time_);
     389          22 :     if (err) {
     390           0 :         XMPP_WARNING(ServerKeepAliveFailure, session->ToUVEKey(),
     391             :                      XMPP_PEER_DIR_OUT, err.message());
     392             :     }
     393             : 
     394          22 :     return session;
     395             : }
     396             : 
     397           0 : size_t XmppServer::ConnectionEventCount() const {
     398           0 :     return connection_event_map_.size();
     399             : }
     400             : 
     401           0 : size_t XmppServer::ConnectionMapSize() const {
     402           0 :     ReadLock lock(connection_map_mutex_);
     403           0 :     return connection_map_.size();
     404           0 : }
     405             : 
     406           0 : size_t XmppServer::ConnectionCount() const {
     407           0 :     return ConnectionMapSize() + deleted_connection_set_.size();
     408             : }
     409             : 
     410         149 : XmppServerConnection *XmppServer::FindConnection(Endpoint remote_endpoint) {
     411         149 :     ReadLock lock(connection_map_mutex_);
     412         149 :     ConnectionMap::iterator loc = connection_map_.find(remote_endpoint);
     413         149 :     if (loc != connection_map_.end()) {
     414           0 :         return loc->second;
     415             :     }
     416         149 :     return NULL;
     417         149 : }
     418             : 
     419         488 : XmppServerConnection *XmppServer::FindConnection(const string &address) {
     420         488 :     ReadLock lock(connection_map_mutex_);
     421         502 :     for (auto& value : connection_map_) {
     422          31 :         if (value.second->ToString() == address)
     423          17 :             return value.second;
     424             :     }
     425         471 :     return NULL;
     426         488 : }
     427             : 
     428           0 : bool XmppServer::ClearConnection(const string &hostname) {
     429           0 :     ReadLock lock(connection_map_mutex_);
     430           0 :     for (auto& value : connection_map_) {
     431           0 :         if (value.second->GetComputeHostName() == hostname) {
     432           0 :             value.second->Clear();
     433           0 :             return true;
     434             :         }
     435             :     }
     436           0 :     return false;
     437           0 : }
     438             : 
     439           0 : void XmppServer::UpdateAllConnections(uint8_t time_out) {
     440           0 :     ReadLock lock(connection_map_mutex_);
     441           0 :     for (auto& value : connection_map_) {
     442           0 :         value.second->UpdateKeepAliveTimer(time_out);
     443             :     }
     444           0 : }
     445             : 
     446          70 : void XmppServer::ClearAllConnections() {
     447          70 :     ReadLock lock(connection_map_mutex_);
     448         110 :     for (auto& value : connection_map_) {
     449          40 :         value.second->Clear();
     450             :     }
     451          70 : }
     452             : 
     453          29 : void XmppServer::RegisterConnectionEvent(xmps::PeerId id,
     454             :                                          ConnectionEventCb cb) {
     455          29 :     connection_event_map_.insert(make_pair(id, cb));
     456          29 : }
     457             : 
     458          20 : void XmppServer::UnRegisterConnectionEvent(xmps::PeerId id) {
     459          20 :     ConnectionEventCbMap::iterator it =  connection_event_map_.find(id);
     460          20 :     if (it != connection_event_map_.end())
     461          20 :         connection_event_map_.erase(it);
     462          20 : }
     463             : 
     464         322 : void XmppServer::NotifyConnectionEvent(XmppChannelMux *mux,
     465             :                                        xmps::PeerState state) {
     466         322 :     ConnectionEventCbMap::iterator iter = connection_event_map_.begin();
     467         602 :     for (; iter != connection_event_map_.end(); ++iter) {
     468         280 :         ConnectionEventCb cb = iter->second;
     469         280 :         cb(mux, state);
     470         280 :     }
     471         322 : }
     472             : 
     473         171 : SslSession *XmppServer::AllocSession(SslSocket *socket) {
     474         171 :     SslSession *session = new XmppSession(this, socket);
     475         171 :     boost::system::error_code err;
     476         171 :     XmppSession *xmpp_session = static_cast<XmppSession *>(session);
     477         171 :     err = xmpp_session->EnableTcpKeepalive(tcp_hold_time_);
     478         171 :     if (err) {
     479          22 :         XMPP_WARNING(ServerKeepAliveFailure, xmpp_session->ToUVEKey(),
     480             :                      XMPP_PEER_DIR_OUT, err.message());
     481             :     }
     482         171 :     return session;
     483             : }
     484             : 
     485             : //
     486             : // Accept newly formed passive tcp session by creating necessary xmpp data
     487             : // structures. We do so to make sure that if there is any error reported
     488             : // over this tcp session, it can still be correctly handled, even though
     489             : // the allocated xmpp data structures are not fully processed yet.
     490             : //
     491         149 : bool XmppServer::AcceptSession(TcpSession *tcp_session) {
     492         149 :     std::scoped_lock lock(deletion_mutex_);
     493         149 :     if (deleter_->IsDeleted())
     494           0 :         return false;
     495             : 
     496         149 :     XmppSession *session = dynamic_cast<XmppSession *>(tcp_session);
     497         149 :     XmppServerConnection *connection = CreateConnection(session);
     498             : 
     499         149 :     if (xmpp_config_updater_) {
     500         272 :         connection->state_machine()->set_hold_time(
     501         136 :                 xmpp_config_updater_->xmpp_hold_time());
     502             :     }
     503             :     // Register event handler.
     504         149 :     tcp_session->set_observer(boost::bind(&XmppStateMachine::OnSessionEvent,
     505             :                                           connection->state_machine(), _1, _2));
     506             : 
     507             :     // set async_read_ready as false
     508         149 :     session->set_read_on_connect(false);
     509         149 :     connection->set_session(session);
     510         149 :     connection->state_machine()->set_session(session);
     511         149 :     connection->set_on_work_queue();
     512         149 :     connection_queue_.Enqueue(connection);
     513         149 :     return true;
     514         149 : }
     515             : 
     516             : //
     517             : // Remove the given XmppServerConnection from the ConnectionMap.
     518             : //
     519         173 : void XmppServer::RemoveConnection(XmppServerConnection *connection) {
     520         173 :     CHECK_CONCURRENCY("bgp::Config");
     521             : 
     522         173 :     assert(connection->IsDeleted());
     523         173 :     Endpoint endpoint = connection->endpoint();
     524         173 :     WriteLock lock(connection_map_mutex_);
     525         173 :     ConnectionMap::iterator loc = connection_map_.find(endpoint);
     526         173 :     assert(loc != connection_map_.end() && loc->second == connection);
     527         173 :     connection_map_.erase(loc);
     528         173 : }
     529             : 
     530          16 : void XmppServer::SwapXmppConnectionMapEntries(
     531             :         XmppConnection *connection1, XmppConnection *connection2) {
     532          16 :     WriteLock lock(connection_map_mutex_);
     533             :     ConnectionMap::iterator loc1 =
     534          16 :         connection_map_.find(connection1->endpoint());
     535          16 :     assert(loc1 != connection_map_.end());
     536             :     ConnectionMap::iterator loc2 =
     537          16 :         connection_map_.find(connection2->endpoint());
     538          16 :     assert(loc2 != connection_map_.end());
     539          16 :     swap(loc1->second, loc2->second);
     540          16 :     swap(loc1->second->endpoint(), loc2->second->endpoint());
     541          16 : }
     542             : 
     543             : //
     544             : // Insert the given XmppServerConnection into the ConnectionMap.
     545             : //
     546         173 : void XmppServer::InsertConnection(XmppServerConnection *connection) {
     547         173 :     CHECK_CONCURRENCY("bgp::Config");
     548             : 
     549         173 :     assert(!connection->IsDeleted());
     550         173 :     connection->Initialize();
     551         173 :     Endpoint endpoint = connection->endpoint();
     552         173 :     ConnectionMap::iterator loc;
     553             :     bool result;
     554         173 :     WriteLock lock(connection_map_mutex_);
     555         173 :     tie(loc, result) = connection_map_.insert(make_pair(endpoint, connection));
     556         173 :     assert(result);
     557         173 :     max_connections_ = max(max_connections_, connection_map_.size());
     558         173 : }
     559             : 
     560             : //
     561             : // Create XmppConnnection and its associated data structures. This API is
     562             : // only used to allocate data structures and initialize necessary fields.
     563             : // The data structures are not populated to any maps in the XmppServer at
     564             : // this point.  However, the newly created XmppServerConnection does add
     565             : // itself as a dependent of the XmppServer via LifetimeManager linkage.
     566             : //
     567         149 : XmppServerConnection *XmppServer::CreateConnection(XmppSession *session) {
     568             :     XmppServerConnection  *connection;
     569             : 
     570         149 :     XmppChannelConfig cfg(false);
     571         149 :     cfg.endpoint = session->remote_endpoint();
     572         149 :     cfg.local_endpoint = session->local_endpoint();
     573         149 :     cfg.FromAddr = server_addr_;
     574         149 :     cfg.logUVE = log_uve_;
     575         149 :     cfg.auth_enabled = auth_enabled_;
     576         149 :     cfg.dscp_value = dscp_value_;
     577             : 
     578         149 :     XMPP_DEBUG(XmppCreateConnection, session->ToUVEKey(), XMPP_PEER_DIR_OUT,
     579             :                session->ToString());
     580             :     connection = XmppStaticObjectFactory::Create<XmppServerConnection>
     581         149 :         (this, static_cast<const XmppChannelConfig*>(&cfg));
     582             : 
     583         149 :     return connection;
     584         149 : }
     585             : 
     586           0 : void XmppServer::SetDscpValue(uint8_t value) {
     587           0 :     ReadLock lock(connection_map_mutex_);
     588           0 :     dscp_value_ = value;
     589           0 :     for (auto& value : connection_map_) {
     590           0 :         XmppServerConnection *connection = value.second;
     591           0 :         connection->SetDscpValue(dscp_value_);
     592             :     }
     593           0 : }
     594             : //
     595             : // Handler for XmppServerConnections that are dequeued from the WorkQueue.
     596             : //
     597             : // Since the XmppServerConnections on the WorkQueue are dependents of the
     598             : // XmppServer, we are guaranteed that the XmppServer won't get destroyed
     599             : // before the connection WorkQueue is drained.
     600             : //
     601         149 : bool XmppServer::DequeueConnection(XmppServerConnection *connection) {
     602         149 :     CHECK_CONCURRENCY("bgp::Config");
     603         149 :     connection->clear_on_work_queue();
     604             : 
     605             :     // This happens if the XmppServer got deleted while the XmppConnnection
     606             :     // was on the WorkQueue.
     607         149 :     if (connection->IsDeleted()) {
     608           0 :         connection->RetryDelete();
     609           0 :         return true;
     610             :     }
     611             : 
     612         149 :     XmppSession *session = connection->session();
     613         149 :     connection->clear_session();
     614         149 :     Endpoint remote_endpoint = session->remote_endpoint();
     615         149 :     XmppServerConnection *old_connection = FindConnection(remote_endpoint);
     616             : 
     617             :     // Close as duplicate if we have a connection from the same Endpoint.
     618             :     // Otherwise go ahead and insert into the ConnectionMap. We may find
     619             :     // it has a conflicting Endpoint name and decide to terminate it when
     620             :     // we process the Open message.
     621         149 :     if (old_connection) {
     622           0 :         XMPP_DEBUG(XmppCreateConnection, session->ToUVEKey(), XMPP_PEER_DIR_IN,
     623             :                    "Close duplicate connection " + session->ToString());
     624             :         // Remove reference to the session from StateMachine directly. We don't
     625             :         // go through the entire normal cleanup pipeline for cleaning these
     626             :         // duplicate connections.
     627           0 :         assert(connection->state_machine()->session());
     628           0 :         assert(connection->state_machine()->session() == session);
     629           0 :         connection->state_machine()->RemoveSession();
     630           0 :         DeleteSession(session);
     631           0 :         connection->set_duplicate();
     632           0 :         connection->ManagedDelete();
     633           0 :         InsertDeletedConnection(connection);
     634             :     } else {
     635         149 :         InsertConnection(connection);
     636         149 :         connection->AcceptSession(session);
     637             :     }
     638             : 
     639         149 :     return true;
     640             : }
     641             : 
     642           0 : size_t XmppServer::GetConnectionQueueSize() const {
     643           0 :     return connection_queue_.Length();
     644             : }
     645             : 
     646           0 : void XmppServer::SetConnectionQueueDisable(bool disabled) {
     647           0 :     connection_queue_.set_disable(disabled);
     648           0 : }
     649             : 
     650             : //
     651             : // Connection is marked deleted, add it to the ConnectionSet.
     652             : //
     653         173 : void XmppServer::InsertDeletedConnection(XmppServerConnection *connection) {
     654         173 :     CHECK_CONCURRENCY("bgp::Config");
     655             : 
     656         173 :     assert(connection->IsDeleted());
     657         173 :     ConnectionSet::iterator it;
     658             :     bool result;
     659         173 :     tie(it, result) = deleted_connection_set_.insert(connection);
     660         173 :     assert(result);
     661         173 : }
     662             : 
     663             : //
     664             : // Connection is being destroyed, remove it from the ConnectionSet.
     665             : //
     666         173 : void XmppServer::RemoveDeletedConnection(XmppServerConnection *connection) {
     667         173 :     CHECK_CONCURRENCY("bgp::Config");
     668             : 
     669         173 :     assert(connection->IsDeleted());
     670         173 :     ConnectionSet::iterator it = deleted_connection_set_.find(connection);
     671         173 :     assert(it != deleted_connection_set_.end());
     672         173 :     deleted_connection_set_.erase(it);
     673         173 :     ReleaseConnectionEndpoint(connection);
     674         173 : }
     675             : 
     676         322 : XmppConnectionEndpoint *XmppServer::FindConnectionEndpoint(
     677             :     const string &endpoint_name) {
     678         322 :     std::scoped_lock lock(endpoint_map_mutex_);
     679             :     ConnectionEndpointMap::const_iterator loc =
     680         322 :         connection_endpoint_map_.find(endpoint_name);
     681         644 :     return (loc != connection_endpoint_map_.end() ? loc->second : NULL);
     682         322 : }
     683             : 
     684         159 : XmppConnectionEndpoint *XmppServer::LocateConnectionEndpoint(
     685             :         XmppServerConnection *connection, bool &created) {
     686         159 :     created = false;
     687         159 :     if (!connection)
     688           0 :         return NULL;
     689             : 
     690         159 :     std::scoped_lock lock(endpoint_map_mutex_);
     691             : 
     692             :     ConnectionEndpointMap::const_iterator loc =
     693         159 :         connection_endpoint_map_.find(connection->ToString());
     694             :     XmppConnectionEndpoint *conn_endpoint;
     695             : 
     696         159 :     if (loc != connection_endpoint_map_.end()) {
     697          56 :         conn_endpoint = loc->second;
     698          56 :         if (!conn_endpoint->connection()) {
     699          40 :             created = true;
     700          40 :             conn_endpoint->set_connection(connection);
     701          40 :             connection->set_conn_endpoint(conn_endpoint);
     702             :         }
     703          56 :         return conn_endpoint;
     704             :     }
     705             : 
     706         103 :     created = true;
     707         103 :     conn_endpoint = new XmppConnectionEndpoint(connection->ToString());
     708             :     bool result;
     709         103 :     tie(loc, result) = connection_endpoint_map_.insert(
     710         206 :             make_pair(connection->ToString(), conn_endpoint));
     711         103 :     assert(result);
     712         103 :     conn_endpoint->set_connection(connection);
     713         103 :     connection->set_conn_endpoint(conn_endpoint);
     714         103 :     return conn_endpoint;
     715         159 : }
     716             : 
     717             : //
     718             : // Remove association of the given XmppConnectionEndpoint with XmppConnection.
     719             : // This method is provided just to make things symmetrical - the caller could
     720             : // simply have called XmppConnectionEndpoint::reset_connection directly.
     721             : //
     722         346 : void XmppServer::ReleaseConnectionEndpoint(XmppServerConnection *connection) {
     723         346 :     std::scoped_lock lock(endpoint_map_mutex_);
     724             : 
     725         346 :     if (!connection->conn_endpoint())
     726         203 :         return;
     727         143 :     assert(connection->conn_endpoint()->connection() == connection);
     728         143 :     connection->conn_endpoint()->reset_connection();
     729         143 :     connection->set_conn_endpoint(NULL);
     730         346 : }
     731             : 
     732           0 : void XmppServer::FillShowConnections(
     733             :     vector<ShowXmppConnection> *show_connection_list) const {
     734           0 :     ReadLock lock(connection_map_mutex_);
     735           0 :     for (const auto& value : connection_map_) {
     736           0 :         const XmppServerConnection *connection = value.second;
     737           0 :         ShowXmppConnection show_connection;
     738           0 :         connection->FillShowInfo(&show_connection);
     739           0 :         show_connection_list->push_back(show_connection);
     740           0 :     }
     741           0 :     for (const auto& connection : deleted_connection_set_) {
     742           0 :         ShowXmppConnection show_connection;
     743           0 :         connection->FillShowInfo(&show_connection);
     744           0 :         show_connection_list->push_back(show_connection);
     745           0 :     }
     746           0 : }
     747             : 
     748           0 : void XmppServer::FillShowServer(ShowXmppServerResp *resp) const {
     749           0 :     SocketIOStats peer_socket_stats;
     750           0 :     GetRxSocketStats(&peer_socket_stats);
     751           0 :     resp->set_rx_socket_stats(peer_socket_stats);
     752           0 :     GetTxSocketStats(&peer_socket_stats);
     753           0 :     resp->set_tx_socket_stats(peer_socket_stats);
     754           0 :     resp->set_current_connections(ConnectionMapSize());
     755           0 :     resp->set_max_connections(max_connections_);
     756           0 : }
     757             : 
     758             : class ShowXmppConnectionHandler {
     759             : public:
     760           0 :     static bool CallbackS1(const Sandesh *sr,
     761             :             const RequestPipeline::PipeSpec ps, int stage, int instNum,
     762             :             RequestPipeline::InstData *data) {
     763             :         const ShowXmppConnectionReq *req =
     764           0 :             static_cast<const ShowXmppConnectionReq *>(ps.snhRequest_.get());
     765             :         XmppSandeshContext *xsc =
     766           0 :             dynamic_cast<XmppSandeshContext *>(req->module_context("XMPP"));
     767             : 
     768           0 :         ShowXmppConnectionResp *resp = new ShowXmppConnectionResp;
     769           0 :         vector<ShowXmppConnection> connections;
     770           0 :         if (xsc)
     771           0 :             xsc->xmpp_server->FillShowConnections(&connections);
     772           0 :         resp->set_connections(connections);
     773           0 :         resp->set_context(req->context());
     774           0 :         resp->Response();
     775           0 :         return true;
     776           0 :     }
     777             : };
     778             : 
     779           0 : void ShowXmppConnectionReq::HandleRequest() const {
     780           0 :     RequestPipeline::PipeSpec ps(this);
     781             : 
     782             :     // Request pipeline has single stage to collect connection info and
     783             :     // respond to the request.
     784           0 :     RequestPipeline::StageSpec s1;
     785           0 :     TaskScheduler *scheduler = TaskScheduler::GetInstance();
     786           0 :     s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand");
     787           0 :     s1.cbFn_ = ShowXmppConnectionHandler::CallbackS1;
     788           0 :     s1.instances_.push_back(0);
     789           0 :     ps.stages_.push_back(s1);
     790           0 :     RequestPipeline rp(ps);
     791           0 : }
     792             : 
     793             : class ClearXmppConnectionHandler {
     794             : public:
     795           0 :     static bool CallbackS1(const Sandesh *sr,
     796             :         const RequestPipeline::PipeSpec ps, int stage, int instNum,
     797             :         RequestPipeline::InstData *data) {
     798             : 
     799             :         const ClearXmppConnectionReq *req =
     800           0 :             static_cast<const ClearXmppConnectionReq *>(ps.snhRequest_.get());
     801             :         XmppSandeshContext *xsc =
     802           0 :             dynamic_cast<XmppSandeshContext *>(req->module_context("XMPP"));
     803             : 
     804           0 :         ClearXmppConnectionResp *resp = new ClearXmppConnectionResp;
     805           0 :         if (!xsc || !xsc->test_mode) {
     806           0 :             resp->set_success(false);
     807           0 :         } else if (req->get_hostname_or_all() != "all") {
     808           0 :             if (xsc->xmpp_server->ClearConnection(req->get_hostname_or_all())) {
     809           0 :                 resp->set_success(true);
     810             :             } else {
     811           0 :                 resp->set_success(false);
     812             :             }
     813             :         } else {
     814           0 :             if (xsc->xmpp_server->ConnectionCount()) {
     815           0 :                 xsc->xmpp_server->ClearAllConnections();
     816           0 :                 resp->set_success(true);
     817             :             } else {
     818           0 :                 resp->set_success(false);
     819             :             }
     820             :         }
     821             : 
     822           0 :         resp->set_context(req->context());
     823           0 :         resp->Response();
     824           0 :         return true;
     825             :     }
     826             : };
     827             : 
     828           0 : void ClearXmppConnectionReq::HandleRequest() const {
     829             : 
     830             :     // config task is used to create and delete connection objects.
     831             :     // hence use the same task to find the connection
     832           0 :     RequestPipeline::StageSpec s1;
     833           0 :     s1.taskId_ = TaskScheduler::GetInstance()->GetTaskId("bgp::Config");
     834           0 :     s1.instances_.push_back(0);
     835           0 :     s1.cbFn_ = ClearXmppConnectionHandler::CallbackS1;
     836             : 
     837           0 :     RequestPipeline::PipeSpec ps(this);
     838           0 :     ps.stages_.push_back(s1);
     839           0 :     RequestPipeline rp(ps);
     840           0 : }
     841             : 
     842             : class ShowXmppServerHandler {
     843             : public:
     844           0 :     static bool CallbackS1(const Sandesh *sr,
     845             :             const RequestPipeline::PipeSpec ps, int stage, int instNum,
     846             :             RequestPipeline::InstData *data) {
     847             :         const ShowXmppServerReq *req =
     848           0 :             static_cast<const ShowXmppServerReq *>(ps.snhRequest_.get());
     849             :         XmppSandeshContext *xsc =
     850           0 :             dynamic_cast<XmppSandeshContext *>(req->module_context("XMPP"));
     851             : 
     852           0 :         ShowXmppServerResp *resp = new ShowXmppServerResp;
     853           0 :         if (xsc)
     854           0 :             xsc->xmpp_server->FillShowServer(resp);
     855           0 :         resp->set_context(req->context());
     856           0 :         resp->Response();
     857           0 :         return true;
     858             :     }
     859             : };
     860             : 
     861           0 : void ShowXmppServerReq::HandleRequest() const {
     862           0 :     RequestPipeline::PipeSpec ps(this);
     863           0 :     RequestPipeline::StageSpec s1;
     864           0 :     TaskScheduler *scheduler = TaskScheduler::GetInstance();
     865           0 :     s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand");
     866           0 :     s1.cbFn_ = ShowXmppServerHandler::CallbackS1;
     867           0 :     s1.instances_.push_back(0);
     868           0 :     ps.stages_.push_back(s1);
     869           0 :     RequestPipeline rp(ps);
     870           0 : }

Generated by: LCOV version 1.14