LCOV - code coverage report
Current view: top level - xmpp - xmpp_connection.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 431 617 69.9 %
Date: 2026-11-16 02:06:09 Functions: 75 111 67.6 %
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_connection.h"
       7             : 
       8             : #include <boost/date_time/posix_time/posix_time.hpp>
       9             : #include <sstream>
      10             : 
      11             : #include "base/lifetime.h"
      12             : #include "base/task_annotations.h"
      13             : #include "io/event_manager.h"
      14             : #include "xml/xml_base.h"
      15             : #include "xmpp/xmpp_client.h"
      16             : #include "xmpp/xmpp_config.h"
      17             : #include "xmpp/xmpp_factory.h"
      18             : #include "xmpp/xmpp_log.h"
      19             : #include "xmpp/xmpp_server.h"
      20             : #include "xmpp/xmpp_session.h"
      21             : 
      22             : #include "sandesh/common/vns_types.h"
      23             : #include "sandesh/common/vns_constants.h"
      24             : #include "sandesh/xmpp_client_server_sandesh_types.h"
      25             : #include "sandesh/xmpp_message_sandesh_types.h"
      26             : #include "sandesh/xmpp_server_types.h"
      27             : #include "sandesh/xmpp_state_machine_sandesh_types.h"
      28             : #include "sandesh/xmpp_trace_sandesh_types.h"
      29             : #include "sandesh/xmpp_peer_info_types.h"
      30             : 
      31             : using namespace std;
      32             : using boost::system::error_code;
      33             : 
      34             : const char *XmppConnection::kAuthTypeNil = "NIL";
      35             : const char *XmppConnection::kAuthTypeTls = "TLS";
      36             : 
      37             : // Maximum XMPP control message size. Typically this is less then 256 bytes. But
      38             : // in scenarios where host names are quite long, we need a larger buffer size.
      39             : #define XMPP_CONTROL_MESSAGE_MAX_SIZE 1024
      40             : 
      41         311 : XmppConnection::XmppConnection(TcpServer *server,
      42         311 :                                const XmppChannelConfig *config)
      43         311 :     : server_(server),
      44         311 :       session_(NULL),
      45         311 :       endpoint_(config->endpoint),
      46         311 :       local_endpoint_(config->local_endpoint),
      47         311 :       config_(NULL),
      48         622 :       keepalive_timer_(TimerManager::CreateTimer(
      49         311 :                   *server->event_manager()->io_service(),
      50             :                   "Xmpp keepalive timer",
      51             :                   TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
      52         311 :                   GetTaskInstance(config->ClientOnly()))),
      53         311 :       is_client_(config->ClientOnly()),
      54         311 :       log_uve_(config->logUVE),
      55         311 :       admin_down_(false),
      56         311 :       disable_read_(false),
      57         311 :       from_(config->FromAddr),
      58         311 :       to_(config->ToAddr),
      59         311 :       auth_enabled_(config->auth_enabled),
      60         311 :       dscp_value_(config->dscp_value), xmlns_(config->xmlns),
      61         311 :       state_machine_(XmppStaticObjectFactory::Create<XmppStateMachine>(
      62         311 :           this, config->ClientOnly(), config->auth_enabled, config->xmpp_hold_time)),
      63        1866 :       mux_(XmppStaticObjectFactory::Create<XmppChannelMux>(this)) {
      64         311 :     ostringstream oss;
      65         311 :     oss << FromString() << ":" << endpoint().address().to_string();
      66         311 :     uve_key_str_ = oss.str();
      67         311 : }
      68             : 
      69         311 : XmppConnection::~XmppConnection() {
      70         311 :     StopKeepAliveTimer();
      71         311 :     TimerManager::DeleteTimer(keepalive_timer_);
      72         311 :     XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
      73             :                  "XmppConnection destructor", FromString(), ToString());
      74         311 : }
      75             : 
      76           0 : std::string XmppConnection::GetXmppAuthenticationType() const {
      77           0 :     if (auth_enabled_) {
      78           0 :         return (XmppConnection::kAuthTypeTls);
      79             :     } else {
      80           0 :         return (XmppConnection::kAuthTypeNil);
      81             :     }
      82             : }
      83             : 
      84           0 : void XmppConnection::SetConfig(const XmppChannelConfig *config) {
      85           0 :     config_ = config;
      86           0 : }
      87             : 
      88         511 : void XmppConnection::set_session(XmppSession *session) {
      89         511 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
      90         511 :     assert(session);
      91         511 :     session_ = session;
      92         511 :     if (session_ && dscp_value_) {
      93           0 :         session_->SetDscpSocketOption(dscp_value_);
      94             :     }
      95         511 : }
      96             : 
      97         590 : void XmppConnection::clear_session() {
      98         590 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
      99         590 :     if (!session_)
     100          95 :         return;
     101         495 :     session_->ClearConnection();
     102         495 :     session_ = NULL;
     103         590 : }
     104             : 
     105          25 : const XmppSession *XmppConnection::session() const {
     106          25 :     return session_;
     107             : }
     108             : 
     109         528 : XmppSession *XmppConnection::session() {
     110         528 :     return session_;
     111             : }
     112             : 
     113           0 : void XmppConnection::WriteReady() {
     114           0 :     boost::system::error_code ec;
     115           0 :     mux_->WriteReady(ec);
     116           0 : }
     117             : 
     118          40 : void XmppConnection::Shutdown() {
     119          40 :     ManagedDelete();
     120          40 : }
     121             : 
     122        2885 : bool XmppConnection::IsDeleted() const {
     123        2885 :     return deleter()->IsDeleted();
     124             : }
     125             : 
     126         431 : bool XmppConnection::MayDelete() const {
     127         431 :     return !mux_->ReceiverCount() && !mux_->RefererCount();
     128             : }
     129             : 
     130         270 : XmppSession *XmppConnection::CreateSession() {
     131         270 :     TcpSession *session = server_->CreateSession();
     132         270 :     XmppSession *xmpp_session = static_cast<XmppSession *>(session);
     133         270 :     xmpp_session->SetConnection(this);
     134         270 :     return xmpp_session;
     135             : }
     136             : 
     137             : //
     138             : // Return the task instance for this XmppConnection.
     139             : // Calculate from the remote IpAddress so that a restarting session uses the
     140             : // same value as before.
     141             : // Do not make this method virtual since it gets called from the constructor.
     142             : //
     143             : 
     144        2452 : int XmppConnection::GetTaskInstance(bool is_client) const {
     145        2452 :     if (is_client)
     146        1040 :         return 0;
     147        1412 :     IpAddress address = endpoint().address();
     148        1412 :     int thread_count = TaskScheduler::GetInstance()->HardwareThreadCount();
     149        1412 :     if (address.is_v4()) {
     150        1412 :         return address.to_v4().to_ulong() % thread_count;
     151             :     } else {
     152           0 :         return 0;
     153             :     }
     154             : }
     155             : 
     156      576095 : xmsm::XmState XmppConnection::GetStateMcState() const {
     157      576095 :     const XmppStateMachine *sm = state_machine();
     158      576055 :     assert(sm);
     159      576055 :     return sm->StateType();
     160             : }
     161             : 
     162      322276 : xmsm::XmOpenConfirmState XmppConnection::GetStateMcOpenConfirmState() const {
     163      322276 :     const XmppStateMachine *sm = state_machine();
     164      322276 :     assert(sm);
     165      322276 :     return sm->OpenConfirmStateType();
     166             : }
     167             : 
     168             : 
     169        1412 : boost::asio::ip::tcp::endpoint XmppConnection::endpoint() const {
     170        1412 :     return endpoint_;
     171             : }
     172             : 
     173         270 : boost::asio::ip::tcp::endpoint XmppConnection::local_endpoint() const {
     174         270 :     return local_endpoint_;
     175             : }
     176             : 
     177           0 : string XmppConnection::endpoint_string() const {
     178           0 :     ostringstream oss;
     179           0 :     oss << endpoint_;
     180           0 :     return oss.str();
     181           0 : }
     182             : 
     183           0 : string XmppConnection::local_endpoint_string() const {
     184           0 :     ostringstream oss;
     185           0 :     oss << local_endpoint_;
     186           0 :     return oss.str();
     187           0 : }
     188             : 
     189        2135 : const string &XmppConnection::FromString() const {
     190        2135 :     return from_;
     191             : }
     192             : 
     193      131255 : const string &XmppConnection::ToString() const {
     194      131255 :     return to_;
     195             : }
     196             : 
     197      476190 : const std::string &XmppConnection::ToUVEKey() const {
     198      476190 :     return uve_key_str_;
     199             : }
     200             : 
     201           0 : static void XMPPPeerInfoSend(XmppPeerInfoData &peer_info) {
     202           0 :     assert(!peer_info.get_name().empty());
     203           0 :     XMPPPeerInfo::Send(peer_info);
     204           0 : }
     205             : 
     206         494 : void XmppConnection::SetTo(const string &to) {
     207         494 :     if ((to_.size() == 0) && (to.size() != 0)) {
     208         191 :         to_ = to;
     209         191 :         if (!logUVE()) return;
     210           0 :         XmppPeerInfoData peer_info;
     211           0 :         peer_info.set_name(ToUVEKey());
     212           0 :         peer_info.set_identifier(to_);
     213           0 :         XMPPPeerInfoSend(peer_info);
     214           0 :     }
     215             : }
     216             : 
     217           0 : void XmppConnection::SetAdminDown(bool toggle) {
     218             :     // TODO: generate state machine event.
     219           0 :     admin_down_ = toggle;
     220           0 : }
     221             : 
     222         150 : bool XmppConnection::AcceptSession(XmppSession *session) {
     223         150 :     session->SetConnection(this);
     224         150 :     return state_machine_->PassiveOpen(session);
     225             : }
     226             : 
     227      121382 : bool XmppConnection::Send(const uint8_t *data, size_t size,
     228             :     const string *msg_str) {
     229      121382 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     230      121338 :     if (session_ == NULL) {
     231           0 :         return false;
     232             :     }
     233             : 
     234      121338 :     TcpSession::Endpoint endpoint = session_->remote_endpoint();
     235      121304 :     const string &endpoint_addr_str = session_->remote_addr_string();
     236      121297 :     string str;
     237      121297 :     if (!msg_str) {
     238        1326 :         str.append(reinterpret_cast<const char *>(data), size);
     239        1326 :         msg_str = &str;
     240             :     }
     241             : 
     242      121236 :     if (!(mux_ &&
     243      121281 :          (mux_->TxMessageTrace(endpoint_addr_str, endpoint.port(),
     244      121297 :                                size, *msg_str, NULL)))) {
     245      121237 :         XMPP_MESSAGE_TRACE(XmppTxStream,
     246             :                            endpoint_addr_str, endpoint.port(), size, *msg_str);
     247             :     }
     248             : 
     249      121405 :     stats_[1].update++;
     250             :     size_t sent;
     251      121405 :     return session_->Send(data, size, &sent);
     252      121377 : }
     253             : 
     254           0 : int XmppConnection::SetDscpValue(uint8_t value) {
     255           0 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     256           0 :     dscp_value_ = value;
     257           0 :     if (!session_) {
     258           0 :         return 0;
     259             :     }
     260           0 :     return session_->SetDscpSocketOption(value);
     261           0 : }
     262             : 
     263         264 : bool XmppConnection::SendOpen(XmppSession *session) {
     264         264 :     if (!session) return false;
     265         264 :     XmppProto::XmppStanza::XmppStreamMessage openstream;
     266         264 :     openstream.strmtype = XmppStanza::XmppStreamMessage::INIT_STREAM_HEADER;
     267             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     268         264 :     int len = XmppProto::EncodeStream(openstream, to_, from_, xmlns_, data,
     269             :                                       sizeof(data));
     270         264 :     if (len <= 0) {
     271           0 :         inc_open_fail();
     272           0 :         return false;
     273             :     } else {
     274         264 :         XMPP_UTDEBUG(XmppOpen, ToUVEKey(), XMPP_PEER_DIR_OUT, len, from_, to_,
     275             :                      xmlns_);
     276         264 :         session->Send(data, len, NULL);
     277         264 :         stats_[1].open++;
     278         264 :         return true;
     279             :     }
     280         264 : }
     281             : 
     282         241 : bool XmppConnection::SendOpenConfirm(XmppSession *session) {
     283         241 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     284         241 :     if (!session_) return false;
     285         241 :     XmppStanza::XmppStreamMessage openstream;
     286         241 :     openstream.strmtype = XmppStanza::XmppStreamMessage::INIT_STREAM_HEADER_RESP;
     287             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     288         241 :     int len = XmppProto::EncodeStream(openstream, to_, from_, xmlns_, data,
     289             :                                       sizeof(data));
     290         241 :     if (len <= 0) {
     291           0 :         inc_open_fail();
     292           0 :         return false;
     293             :     } else {
     294         241 :         XMPP_UTDEBUG(XmppOpenConfirm, ToUVEKey(), XMPP_PEER_DIR_OUT, len,
     295             :                      from_, to_);
     296         241 :         session_->Send(data, len, NULL);
     297         241 :         stats_[1].open++;
     298         241 :         return true;
     299             :     }
     300         241 : }
     301             : 
     302          82 : bool XmppConnection::SendStreamFeatureRequest(XmppSession *session) {
     303          82 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     304          82 :     if (!session_) return false;
     305          82 :     XmppStanza::XmppStreamMessage featurestream;
     306          82 :     featurestream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
     307          82 :     featurestream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_FEATURE_REQUEST;
     308             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     309          82 :     int len = XmppProto::EncodeStream(featurestream, to_, from_, xmlns_, data,
     310             :                                       sizeof(data));
     311          82 :     if (len <= 0) {
     312           0 :         inc_stream_feature_fail();
     313           0 :         return false;
     314             :     } else {
     315          82 :         XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
     316             :                      "Send Stream Feature Request", len, from_, to_);
     317          82 :         session_->Send(data, len, NULL);
     318             :         //stats_[1].open++;
     319          82 :         return true;
     320             :     }
     321          82 : }
     322             : 
     323          83 : bool XmppConnection::SendStartTls(XmppSession *session) {
     324          83 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     325          83 :     if (!session_) return false;
     326          83 :     XmppStanza::XmppStreamMessage stream;
     327          83 :     stream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
     328          83 :     stream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_START;
     329             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     330          83 :     int len = XmppProto::EncodeStream(stream, to_, from_, xmlns_, data,
     331             :                                       sizeof(data));
     332          83 :     if (len <= 0) {
     333           0 :         inc_stream_feature_fail();
     334           0 :         return false;
     335             :     } else {
     336          83 :         XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
     337             :                      "Send Start Tls", len, from_, to_);
     338          83 :         session_->Send(data, len, NULL);
     339             :         //stats_[1].open++;
     340          83 :         return true;
     341             :     }
     342          83 : }
     343             : 
     344          78 : bool XmppConnection::SendProceedTls(XmppSession *session) {
     345          78 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     346          78 :     if (!session_) return false;
     347          78 :     XmppStanza::XmppStreamMessage stream;
     348          78 :     stream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
     349          78 :     stream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_PROCEED;
     350             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     351          78 :     int len = XmppProto::EncodeStream(stream, to_, from_, xmlns_, data,
     352             :                                       sizeof(data));
     353          78 :     if (len <= 0) {
     354           0 :         inc_stream_feature_fail();
     355           0 :         return false;
     356             :     } else {
     357          78 :         XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
     358             :                      "Send Proceed Tls", len, from_, to_);
     359          78 :         session_->Send(data, len, NULL);
     360             :         //stats_[1].open++;
     361          78 :         return true;
     362             :     }
     363          78 : }
     364             : 
     365           2 : void XmppConnection::SendClose(XmppSession *session) {
     366           2 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     367           2 :     if (!session_) return;
     368           1 :     string str("</stream:stream>");
     369             :     uint8_t data[64];
     370           1 :     memcpy(data, str.data(), str.size());
     371           1 :     XMPP_UTDEBUG(XmppClose, ToUVEKey(), XMPP_PEER_DIR_OUT, str.size(), from_,
     372             :                  to_);
     373           1 :     session_->Send(data, str.size(), NULL);
     374           1 :     stats_[1].close++;
     375           2 : }
     376             : 
     377         138 : void XmppConnection::ProcessSslHandShakeResponse(SslSessionPtr session,
     378             :     const boost::system::error_code& error) {
     379         138 :     if (!state_machine())
     380           0 :         return;
     381             : 
     382         138 :     if (error) {
     383           0 :         inc_handshake_failure();
     384             : 
     385           0 :         if (error.category() == boost::asio::error::get_ssl_category()) {
     386           0 :             string err = error.message();
     387           0 :             err = string(" (")
     388           0 :                          +boost::lexical_cast<string>(ERR_GET_LIB(error.value()))+","
     389           0 :                          +boost::lexical_cast<string>(ERR_GET_REASON(error.value()))+") ";
     390             : 
     391             :              char buf[128];
     392           0 :              ::ERR_error_string_n(error.value(), buf, sizeof(buf));
     393           0 :              err += buf;
     394           0 :              XMPP_ALERT(XmppSslHandShakeFailure, ToUVEKey(), XMPP_PEER_DIR_IN,
     395             :                         "failure", err);
     396           0 :         }
     397             : 
     398           0 :         state_machine()->OnEvent(session.get(), xmsm::EvTLSHANDSHAKE_FAILURE);
     399             : 
     400             :     } else {
     401         138 :         XMPP_DEBUG(XmppSslHandShakeMessage, session->ToUVEKey(),
     402             :                    XMPP_PEER_DIR_IN, "success", "");
     403         138 :         state_machine()->OnEvent(session.get(), xmsm::EvTLSHANDSHAKE_SUCCESS);
     404             :     }
     405             : }
     406             : 
     407           0 : void XmppConnection::LogMsg(std::string msg) {
     408           0 :     log4cplus::Logger logger = log4cplus::Logger::getRoot();
     409           0 :     LOG4CPLUS_DEBUG(logger, msg << ToString() << " " <<
     410             :          local_endpoint_.address() << ":" << local_endpoint_.port() << "::" <<
     411             :          endpoint_.address() << ":" << endpoint_.port());
     412           0 : }
     413             : 
     414         166 : void XmppConnection::LogKeepAliveSend() {
     415             :     static bool init_ = false;
     416             :     static bool log_ = false;
     417             : 
     418         166 :     if (!init_) {
     419           6 :         char *str = getenv("XMPP_ASSERT_ON_HOLD_TIMEOUT");
     420           6 :         if (str && strtoul(str, NULL, 0) != 0) log_ = true;
     421           6 :         init_ = true;
     422             :     }
     423             : 
     424         166 :     if (log_) LogMsg("SEND KEEPALIVE: ");
     425         166 : }
     426             : 
     427         166 : void XmppConnection::SendKeepAlive() {
     428         166 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     429         166 :     if (!session_) return;
     430         166 :     XmppStanza::XmppMessage msg(XmppStanza::WHITESPACE_MESSAGE_STANZA);
     431             :     uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
     432         166 :     int len = XmppProto::EncodeStream(msg, data, sizeof(data));
     433         166 :     assert(len > 0);
     434         166 :     session_->Send(data, len, NULL);
     435         166 :     stats_[1].keepalive++;
     436         166 :     LogKeepAliveSend();
     437         166 : }
     438             : 
     439           0 : bool XmppConnection::KeepAliveTimerExpired() {
     440           0 :     if (state_machine_->get_state() != xmsm::ESTABLISHED)
     441           0 :         return false;
     442             : 
     443             :     // TODO: check timestamp of last received packet.
     444           0 :     SendKeepAlive();
     445             : 
     446             :     //
     447             :     // Start the timer again, by returning true
     448             :     //
     449           0 :     return true;
     450             : }
     451             : 
     452           0 : void XmppConnection::KeepaliveTimerErrorHanlder(string error_name,
     453             :                                                 string error_message) {
     454           0 :     XMPP_WARNING(XmppKeepaliveTimeError, ToUVEKey(), XMPP_PEER_DIR_NA,
     455             :                  error_name, error_message);
     456           0 : }
     457             : 
     458         325 : void XmppConnection::StartKeepAliveTimer() {
     459         325 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     460         325 :     if (!session_)
     461           0 :         return;
     462             : 
     463         325 :     int holdtime_msecs = state_machine_->hold_time_msecs();
     464         325 :     if (holdtime_msecs <= 0)
     465           0 :         return;
     466             : 
     467         325 :     keepalive_timer_->Start(holdtime_msecs / 3,
     468             :         boost::bind(&XmppConnection::KeepAliveTimerExpired, this),
     469             :         boost::bind(&XmppConnection::KeepaliveTimerErrorHanlder, this, _1, _2));
     470         325 : }
     471             : 
     472         631 : void XmppConnection::StopKeepAliveTimer() {
     473         631 :     tbb::spin_mutex::scoped_lock lock(spin_mutex_);
     474         631 :     keepalive_timer_->Cancel();
     475         631 : }
     476             : 
     477           0 : void XmppConnection::UpdateKeepAliveTimer(uint8_t time_out) {
     478           0 :     state_machine_->set_hold_time(time_out);
     479           0 :     StopKeepAliveTimer();
     480           0 :     StartKeepAliveTimer();
     481           0 : }
     482             : 
     483        2178 : XmppStateMachine *XmppConnection::state_machine() {
     484        2178 :     return state_machine_.get();
     485             : }
     486             : 
     487      898329 : const XmppStateMachine *XmppConnection::state_machine() const {
     488      898329 :     return state_machine_.get();
     489             : }
     490             : 
     491           0 : const XmppChannelMux *XmppConnection::channel_mux() const {
     492           0 :     return mux_.get();
     493             : }
     494             : 
     495      312819 : void XmppConnection::IncProtoStats(unsigned int type) {
     496      312819 :     switch (type) {
     497         643 :         case XmppStanza::STREAM_HEADER:
     498         643 :             stats_[0].open++;
     499         643 :             break;
     500      189866 :         case XmppStanza::WHITESPACE_MESSAGE_STANZA:
     501      189866 :             stats_[0].keepalive++;
     502      189866 :             break;
     503        2231 :         case XmppStanza::IQ_STANZA:
     504        2231 :             stats_[0].update++;
     505        2231 :             break;
     506      120080 :         case XmppStanza::MESSAGE_STANZA:
     507      120080 :             stats_[0].update++;
     508      120080 :             break;
     509             :     }
     510      312819 : }
     511             : 
     512          78 : void XmppConnection::inc_connect_error() {
     513          78 :     error_stats_.connect_error++;
     514          78 : }
     515             : 
     516         163 : void XmppConnection::inc_session_close() {
     517         163 :     error_stats_.session_close++;
     518         163 : }
     519             : 
     520           0 : void XmppConnection::inc_open_fail() {
     521           0 :     error_stats_.open_fail++;
     522           0 : }
     523             : 
     524           0 : void XmppConnection::inc_stream_feature_fail() {
     525           0 :     error_stats_.stream_feature_fail++;
     526           0 : }
     527             : 
     528           0 : void XmppConnection::inc_handshake_failure() {
     529           0 :     error_stats_.handshake_fail++;
     530           0 : }
     531             : 
     532           0 : size_t XmppConnection::get_connect_error() {
     533           0 :     return error_stats_.connect_error;
     534             : }
     535             : 
     536           0 : size_t XmppConnection::get_session_close() {
     537           0 :     return error_stats_.session_close;
     538             : }
     539             : 
     540           0 : size_t XmppConnection::get_open_fail() {
     541           0 :     return error_stats_.open_fail;
     542             : }
     543             : 
     544           0 : size_t XmppConnection::get_stream_feature_fail() {
     545           0 :     return error_stats_.stream_feature_fail;
     546             : }
     547             : 
     548           0 : size_t XmppConnection::get_handshake_failure() {
     549           0 :     return error_stats_.handshake_fail;
     550             : }
     551             : 
     552           0 : size_t XmppConnection::get_sm_connect_attempts() {
     553           0 :     return state_machine_->get_connect_attempts();
     554             : }
     555             : 
     556           0 : size_t XmppConnection::get_sm_keepalive_count() {
     557           0 :     return state_machine_->get_keepalive_count();
     558             : }
     559             : 
     560      312817 : void XmppConnection::ReceiveMsg(XmppSession *session, const string &msg) {
     561      312817 :     XmppStanza::XmppMessage *minfo = XmppDecode(msg);
     562             : 
     563      312818 :     if (minfo) {
     564      311913 :         session->IncStats((unsigned int)minfo->type, msg.size());
     565      311913 :         if (minfo->type != XmppStanza::WHITESPACE_MESSAGE_STANZA) {
     566      122048 :             if (!(mux_ &&
     567      244094 :                   (mux_->RxMessageTrace(session->
     568      244095 :                                         remote_endpoint().address().to_string(),
     569      244095 :                                         session->remote_endpoint().port(),
     570      244094 :                                         msg.size(), msg, minfo)))) {
     571      122048 :                 XMPP_MESSAGE_TRACE(XmppRxStream,
     572             :                                    session->
     573             :                                    remote_endpoint().address().to_string(),
     574             :                                    session->
     575             :                                    remote_endpoint().port(), msg.size(), msg);
     576             :             }
     577             :         }
     578      311914 :         IncProtoStats((unsigned int)minfo->type);
     579      311914 :         state_machine_->OnMessage(session, minfo);
     580         905 :     } else if ((minfo = last_msg_.get()) != NULL) {
     581         906 :         session->IncStats((unsigned int)minfo->type, msg.size());
     582         906 :         IncProtoStats((unsigned int)minfo->type);
     583             :     } else {
     584           0 :         session->IncStats(XmppStanza::INVALID, msg.size());
     585           0 :         XMPP_MESSAGE_TRACE(XmppRxStreamInvalid,
     586             :              session->remote_endpoint().address().to_string(),
     587             :              session->remote_endpoint().port(), msg.size(), msg);
     588             :     }
     589      312820 :     return;
     590             : }
     591             : 
     592      312817 : XmppStanza::XmppMessage *XmppConnection::XmppDecode(const string &msg) {
     593      312817 :     unique_ptr<XmppStanza::XmppMessage> minfo(XmppProto::Decode(this, msg));
     594      312820 :     if (minfo.get() == NULL) {
     595           0 :         XMPP_INFO(XmppSessionDelete, ToUVEKey(), XMPP_PEER_DIR_IN, "Server",
     596             :                   FromString(), ToString());
     597           0 :         Clear();
     598           0 :         return NULL;
     599             :     }
     600             : 
     601      312820 :     if (minfo->type == XmppStanza::IQ_STANZA) {
     602             :         const XmppStanza::XmppMessageIq *iq =
     603        2231 :             static_cast<const XmppStanza::XmppMessageIq *>(minfo.get());
     604             : 
     605             : 
     606        2231 :         if (iq->action.compare("publish") == 0) {
     607         906 :             last_msg_.reset(minfo.release());
     608         906 :             return NULL;
     609             :         }
     610             : 
     611        1325 :         if (iq->action.compare("collection") == 0) {
     612         906 :             if (last_msg_.get() != NULL) {
     613             :                 XmppStanza::XmppMessageIq *last_iq =
     614         906 :                     static_cast<XmppStanza::XmppMessageIq *>(last_msg_.get());
     615             : 
     616         906 :                 if (last_iq->node.compare(iq->as_node) == 0) {
     617         906 :                     XmlBase *impl = last_iq->dom.get();
     618         906 :                     impl->ReadNode("publish");
     619         906 :                     impl->ModifyAttribute("node", iq->node);
     620         906 :                     last_iq->node = impl->ReadAttrib("node");
     621         906 :                     last_iq->is_as_node = iq->is_as_node;
     622             :                     //Save the complete ass/dissociate node
     623         906 :                     last_iq->as_node = iq->as_node;
     624             :                 } else {
     625           0 :                     XMPP_WARNING(XmppIqMessageInvalid, ToUVEKey(),
     626             :                                  XMPP_PEER_DIR_IN);
     627           0 :                     goto error;
     628             :                 }
     629             :             } else {
     630           0 :                 XMPP_ERROR(XmppIqCollectionError, ToUVEKey(), XMPP_PEER_DIR_IN);
     631           0 :                 goto error;
     632             :             }
     633             :             // iq message merged with collection info
     634         906 :             return last_msg_.release();
     635             :         }
     636             :     }
     637      311008 :     return minfo.release();
     638             : 
     639           0 : error:
     640           0 :     last_msg_.reset();
     641           0 :     return NULL;
     642      312820 : }
     643             : 
     644      120084 : int XmppConnection::ProcessXmppChatMessage(
     645             :         const XmppStanza::XmppChatMessage *msg) {
     646      120084 :     mux_->ProcessXmppMessage(msg);
     647      120084 :     return 0;
     648             : }
     649             : 
     650        1325 : int XmppConnection::ProcessXmppIqMessage(const XmppStanza::XmppMessage *msg) {
     651        1325 :     mux_->ProcessXmppMessage(msg);
     652        1325 :     return 0;
     653             : }
     654             : 
     655             : class XmppServerConnection::DeleteActor : public LifetimeActor {
     656             : public:
     657         173 :     DeleteActor(XmppServer *server, XmppServerConnection *parent)
     658         173 :         : LifetimeActor(server->lifetime_manager()),
     659         173 :           server_(server), parent_(parent) {
     660         173 :     }
     661             : 
     662         293 :     virtual bool MayDelete() const {
     663         293 :         return (!parent_->on_work_queue() && parent_->MayDelete());
     664             :     }
     665             : 
     666         173 :     virtual void Shutdown() {
     667         173 :         CHECK_CONCURRENCY("bgp::Config");
     668             : 
     669             :         // If the connection is still on the WorkQueue, simply add it to the
     670             :         // ConnectionSet.  It won't be on the ConnectionMap.
     671         173 :         if (parent_->on_work_queue()) {
     672           0 :             server_->InsertDeletedConnection(parent_);
     673             :         }
     674             : 
     675             :         // If the connection was rejected as duplicate, it will already be in
     676             :         // the ConnectionSet. Non-duplicate connections need to be moved from
     677             :         // from the ConnectionMap into the ConnectionSet.  We add it to the
     678             :         // ConnectionSet and then remove it from ConnectionMap to ensure that
     679             :         // the XmppServer connection count doesn't temporarily become 0. This
     680             :         // is friendly to tests that wait for the XmppServer connection count
     681             :         // to become 0.
     682             :         //
     683             :         // Breaking association with the XmppConnectionEndpoint here allows
     684             :         // a new XmppServerConnection with the same Endpoint to come up. We
     685             :         // may end up leaking memory if current XmppServerConnection doesn't
     686             :         // get cleaned up completely, but we at least prevent the other end
     687             :         // from getting stuck forever.
     688         173 :         else if (!parent_->duplicate()) {
     689         173 :             server_->InsertDeletedConnection(parent_);
     690         173 :             server_->RemoveConnection(parent_);
     691         173 :             server_->ReleaseConnectionEndpoint(parent_);
     692             :         }
     693             : 
     694         173 :         if (parent_->state_machine()) {
     695         173 :             parent_->state_machine()->Clear();
     696             :         }
     697             : 
     698         173 :         XmppSession *session = NULL;
     699         173 :         if (parent_->state_machine()) {
     700         173 :             session = parent_->state_machine()->session();
     701         173 :             parent_->state_machine()->clear_session();
     702             :         }
     703         173 :         if (session) {
     704          90 :             server_->DeleteSession(session);
     705             :         }
     706         173 :     }
     707             : 
     708         173 :     virtual void Destroy() {
     709         173 :         delete parent_;
     710         173 :     }
     711             : 
     712             : private:
     713             :     XmppServer *server_;
     714             :     XmppServerConnection *parent_;
     715             : };
     716             : 
     717         173 : XmppServerConnection::XmppServerConnection(XmppServer *server,
     718         173 :     const XmppChannelConfig *config)
     719             :     : XmppConnection(server, config),
     720         173 :       duplicate_(false),
     721         173 :       on_work_queue_(false),
     722         173 :       conn_endpoint_(NULL),
     723         173 :       deleter_(new DeleteActor(server, this)),
     724         346 :       server_delete_ref_(this, server->deleter()) {
     725         173 :     assert(!config->ClientOnly());
     726         173 :     XMPP_INFO(XmppConnectionCreate, ToUVEKey(), XMPP_PEER_DIR_IN,
     727             :               "Server", FromString(), ToString());
     728         173 : }
     729             : 
     730         333 : XmppServerConnection::~XmppServerConnection() {
     731         173 :     CHECK_CONCURRENCY("bgp::Config");
     732             : 
     733         173 :     XMPP_INFO(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA, "Server",
     734             :               FromString(), ToString());
     735         173 :     server()->RemoveDeletedConnection(this);
     736         333 : }
     737             : 
     738         269 : void XmppServerConnection::ManagedDelete() {
     739         269 :     XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
     740             :                  "Managed server connection delete", FromString(), ToString());
     741         269 :     deleter_->Delete();
     742         269 : }
     743             : 
     744         137 : void XmppServerConnection::RetryDelete() {
     745         137 :     if (!deleter()->IsDeleted())
     746          17 :         return;
     747         120 :     deleter()->RetryDelete();
     748             : }
     749             : 
     750           0 : LifetimeManager *XmppServerConnection::lifetime_manager() {
     751           0 :     return server()->lifetime_manager();
     752             : }
     753             : 
     754         302 : XmppServer *XmppServerConnection::server() {
     755         302 :     return static_cast<XmppServer *>(server_);
     756             : }
     757             : 
     758         305 : LifetimeActor *XmppServerConnection::deleter() {
     759         305 :     return deleter_.get();
     760             : }
     761             : 
     762        2634 : const LifetimeActor *XmppServerConnection::deleter() const {
     763        2634 :     return deleter_.get();
     764             : }
     765             : 
     766           2 : void XmppServerConnection::set_close_reason(const string &close_reason) {
     767           2 :     if (conn_endpoint_)
     768           0 :         conn_endpoint_->set_close_reason(close_reason);
     769             : 
     770           2 :     if (!logUVE())
     771           2 :         return;
     772             : 
     773           0 :     XmppPeerInfoData peer_info;
     774           0 :     peer_info.set_name(ToUVEKey());
     775           0 :     peer_info.set_close_reason(close_reason);
     776           0 :     XMPPPeerInfoSend(peer_info);
     777           0 : }
     778             : 
     779           0 : uint32_t XmppServerConnection::flap_count() const {
     780           0 :     return conn_endpoint_ ? conn_endpoint_->flap_count() : 0;
     781             : }
     782             : 
     783         154 : void XmppServerConnection::increment_flap_count() {
     784         154 :     XmppConnectionEndpoint *conn_endpoint = conn_endpoint_;
     785         154 :     if (!conn_endpoint)
     786          80 :         conn_endpoint = server()->FindConnectionEndpoint(ToString());
     787         154 :     if (!conn_endpoint)
     788         154 :         return;
     789         154 :     conn_endpoint->increment_flap_count();
     790             : 
     791         154 :     if (!logUVE())
     792         154 :         return;
     793             : 
     794           0 :     XmppPeerInfoData peer_info;
     795           0 :     peer_info.set_name(ToUVEKey());
     796           0 :     PeerFlapInfo flap_info;
     797           0 :     flap_info.set_flap_count(conn_endpoint->flap_count());
     798           0 :     flap_info.set_flap_time(conn_endpoint->last_flap());
     799           0 :     peer_info.set_flap_info(flap_info);
     800           0 :     XMPPPeerInfoSend(peer_info);
     801           0 : }
     802             : 
     803           0 : const std::string XmppServerConnection::last_flap_at() const {
     804           0 :     return conn_endpoint_ ? conn_endpoint_->last_flap_at() : "";
     805             : }
     806             : 
     807           0 : void XmppServerConnection::FillShowInfo(
     808             :     ShowXmppConnection *show_connection) const {
     809           0 :     show_connection->set_name(ToString());
     810           0 :     show_connection->set_deleted(IsDeleted());
     811           0 :     show_connection->set_remote_endpoint(endpoint_string());
     812           0 :     show_connection->set_local_endpoint(local_endpoint_string());
     813           0 :     show_connection->set_state(StateName());
     814           0 :     show_connection->set_last_event(LastEvent());
     815           0 :     show_connection->set_last_state(LastStateName());
     816           0 :     show_connection->set_last_state_at(LastStateChangeAt());
     817           0 :     show_connection->set_receivers(channel_mux()->GetReceiverList());
     818           0 :     show_connection->set_server_auth_type(GetXmppAuthenticationType());
     819           0 :     show_connection->set_dscp_value(dscp_value());
     820           0 : }
     821             : 
     822             : class XmppClientConnection::DeleteActor : public LifetimeActor {
     823             : public:
     824         138 :     DeleteActor(XmppClient *client, XmppClientConnection *parent)
     825         138 :         : LifetimeActor(client->lifetime_manager()),
     826         138 :           client_(client), parent_(parent) {
     827         138 :     }
     828             : 
     829         138 :     virtual bool MayDelete() const {
     830         138 :         return parent_->MayDelete();
     831             :     }
     832             : 
     833         138 :     virtual void Shutdown() {
     834         138 :         if (parent_->session()) {
     835          25 :             client_->NotifyConnectionEvent(parent_->ChannelMux(),
     836             :                 xmps::NOT_READY);
     837             :         }
     838             : 
     839         138 :         XmppSession *session = NULL;
     840         138 :         if (parent_->state_machine()) {
     841         138 :             session = parent_->state_machine()->session();
     842         138 :             parent_->state_machine()->clear_session();
     843             :         }
     844         138 :         if (session) {
     845          30 :             client_->DeleteSession(session);
     846             :         }
     847         138 :     }
     848             : 
     849         138 :     virtual void Destroy() {
     850         138 :         delete parent_;
     851         138 :     }
     852             : 
     853             : private:
     854             :     XmppClient *client_;
     855             :     XmppClientConnection *parent_;
     856             : };
     857             : 
     858         138 : XmppClientConnection::XmppClientConnection(XmppClient *server,
     859         138 :     const XmppChannelConfig *config)
     860             :     : XmppConnection(server, config),
     861         138 :       flap_count_(0),
     862         138 :       deleter_(new DeleteActor(server, this)),
     863         276 :       server_delete_ref_(this, server->deleter()) {
     864         138 :     assert(config->ClientOnly());
     865         138 :     XMPP_UTDEBUG(XmppConnectionCreate, ToUVEKey(), XMPP_PEER_DIR_NA, "Client",
     866             :                  FromString(), ToString());
     867         138 : }
     868             : 
     869         249 : XmppClientConnection::~XmppClientConnection() {
     870         138 :     CHECK_CONCURRENCY("bgp::Config");
     871             : 
     872         138 :     XMPP_INFO(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
     873             :               "Client", FromString(), ToString());
     874         138 :     server()->RemoveConnection(this);
     875         249 : }
     876             : 
     877         138 : void XmppClientConnection::ManagedDelete() {
     878         138 :     XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
     879             :                  "Managed Client Delete", FromString(), ToString());
     880         138 :     deleter_->Delete();
     881         138 : }
     882             : 
     883          86 : void XmppClientConnection::RetryDelete() {
     884          86 :     if (!deleter()->IsDeleted())
     885          86 :         return;
     886           0 :     deleter()->RetryDelete();
     887             : }
     888             : 
     889           0 : LifetimeManager *XmppClientConnection::lifetime_manager() {
     890           0 :     return server()->lifetime_manager();
     891             : }
     892             : 
     893         138 : XmppClient *XmppClientConnection::server() {
     894         138 :     return static_cast<XmppClient *>(server_);
     895             : }
     896             : 
     897          86 : LifetimeActor *XmppClientConnection::deleter() {
     898          86 :     return deleter_.get();
     899             : }
     900             : 
     901         251 : const LifetimeActor *XmppClientConnection::deleter() const {
     902         251 :     return deleter_.get();
     903             : }
     904             : 
     905          42 : void XmppClientConnection::set_close_reason(const string &close_reason) {
     906          42 :     close_reason_ = close_reason;
     907          42 :     if (!logUVE())
     908          42 :         return;
     909             : 
     910           0 :     XmppPeerInfoData peer_info;
     911           0 :     peer_info.set_name(ToUVEKey());
     912           0 :     peer_info.set_close_reason(close_reason_);
     913           0 :     XMPPPeerInfoSend(peer_info);
     914           0 : }
     915             : 
     916           0 : uint32_t XmppClientConnection::flap_count() const {
     917           0 :     return flap_count_;
     918             : }
     919             : 
     920         146 : void XmppClientConnection::increment_flap_count() {
     921         146 :     flap_count_++;
     922         146 :     last_flap_ = UTCTimestampUsec();
     923             : 
     924         146 :     if (!logUVE())
     925         146 :         return;
     926             : 
     927           0 :     XmppPeerInfoData peer_info;
     928           0 :     peer_info.set_name(ToUVEKey());
     929           0 :     PeerFlapInfo flap_info;
     930           0 :     flap_info.set_flap_count(flap_count_);
     931           0 :     flap_info.set_flap_time(last_flap_);
     932           0 :     peer_info.set_flap_info(flap_info);
     933           0 :     XMPPPeerInfoSend(peer_info);
     934           0 : }
     935             : 
     936           0 : const std::string XmppClientConnection::last_flap_at() const {
     937           0 :     return last_flap_ ? integerToString(UTCUsecToPTime(last_flap_)) : "";
     938             : }
     939             : 
     940         103 : XmppConnectionEndpoint::XmppConnectionEndpoint(const string &client)
     941         103 :     : client_(client), flap_count_(0), last_flap_(0), connection_(NULL) {
     942         103 : }
     943             : 
     944           0 : void XmppConnectionEndpoint::set_close_reason(const string &close_reason) {
     945           0 :     close_reason_ = close_reason;
     946           0 : }
     947             : 
     948           0 : uint32_t XmppConnectionEndpoint::flap_count() const {
     949           0 :     return flap_count_;
     950             : }
     951             : 
     952         154 : void XmppConnectionEndpoint::increment_flap_count() {
     953         154 :     flap_count_++;
     954         154 :     last_flap_ = UTCTimestampUsec();
     955         154 : }
     956             : 
     957           0 : uint64_t XmppConnectionEndpoint::last_flap() const {
     958           0 :     return last_flap_;
     959             : }
     960             : 
     961           0 : const std::string XmppConnectionEndpoint::last_flap_at() const {
     962           0 :     return last_flap_ ? integerToString(UTCUsecToPTime(last_flap_)) : "";
     963             : }
     964             : 
     965         397 : XmppConnection *XmppConnectionEndpoint::connection() {
     966         397 :     return connection_;
     967             : }
     968             : 
     969           0 : const XmppConnection *XmppConnectionEndpoint::connection() const {
     970           0 :     return connection_;
     971             : }
     972             : 
     973         143 : void XmppConnectionEndpoint::set_connection(XmppConnection *connection) {
     974         143 :     assert(!connection_);
     975         143 :     connection_ = connection;
     976         143 : }
     977             : 
     978         143 : void XmppConnectionEndpoint::reset_connection() {
     979         143 :     assert(connection_);
     980         143 :     connection_ = NULL;
     981         143 : }
     982             : 
     983             : // Swap relavent contents between two XmppConnection objects.
     984          16 : void XmppConnection::SwapContents(XmppConnection *other) {
     985          16 :     assert(!IsClient());
     986          16 :     assert(!other->IsClient());
     987             :     // Update the ConnectionMap in the server as the endpoints are the keys.
     988          16 :     XmppServer *server = dynamic_cast<XmppServerConnection *>(this)->server();
     989          16 :     server->SwapXmppConnectionMapEntries(this, other);
     990             :     // Swap all other connection related information.
     991          16 :     swap(local_endpoint_, other->local_endpoint_);
     992          16 :     stats_[0].swap(other->stats_[0]);
     993          16 :     stats_[1].swap(other->stats_[1]);
     994          16 :     error_stats_.swap(other->error_stats_);
     995          16 :     swap(last_msg_, other->last_msg_);
     996          16 :     swap(to_, other->to_);
     997          16 :     swap(from_, other->from_);
     998          16 :     swap(xmlns_, other->xmlns_);
     999          16 :     swap(dscp_value_, other->dscp_value_);
    1000          16 :     swap(disable_read_, other->disable_read_);
    1001          16 : }

Generated by: LCOV version 1.14