LCOV - code coverage report
Current view: top level - xmpp - xmpp_session.cc (source / functions) Hit Total Coverage
Test: OpenSDN C/C++ coverage (all TARGET_SET jobs) Lines: 151 171 88.3 %
Date: 2026-11-23 02:04:52 Functions: 15 17 88.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 "base/regex.h"
       7             : #include "xmpp/xmpp_session.h"
       8             : 
       9             : #include "xmpp/xmpp_connection.h"
      10             : #include "xmpp/xmpp_log.h"
      11             : #include "xmpp/xmpp_proto.h"
      12             : #include "xmpp/xmpp_server.h"
      13             : #include "xmpp/xmpp_state_machine.h"
      14             : 
      15             : #include "sandesh/sandesh_trace.h"
      16             : #include "sandesh/xmpp_trace_sandesh_types.h"
      17             : 
      18             : using namespace std;
      19             : using contrail::regex;
      20             : using contrail::regex_match;
      21             : using contrail::regex_search;
      22             : 
      23             : using boost::asio::mutable_buffer;
      24             : 
      25             : const regex XmppSession::patt_(rXMPP_MESSAGE);
      26             : const regex XmppSession::stream_patt_(rXMPP_STREAM_START);
      27             : const regex XmppSession::stream_res_end_(rXMPP_STREAM_END);
      28             : const regex XmppSession::whitespace_(sXMPP_WHITESPACE);
      29             : const regex XmppSession::stream_features_patt_(rXMPP_STREAM_FEATURES);
      30             : const regex XmppSession::starttls_patt_(rXMPP_STREAM_STARTTLS);
      31             : const regex XmppSession::proceed_patt_(rXMPP_STREAM_PROCEED);
      32             : const regex XmppSession::end_patt_(rXMPP_STREAM_STANZA_END);
      33             : 
      34         130 : XmppSession::XmppSession(XmppConnectionManager *manager, SslSocket *socket,
      35         130 :     bool async_ready)
      36             :     : SslSession(manager, socket, async_ready),
      37         130 :       manager_(manager),
      38         130 :       connection_(NULL),
      39         130 :       tag_known_(0),
      40         130 :       task_instance_(-1),
      41         130 :       stats_(XmppStanza::RESERVED_STANZA, XmppSession::StatsPair(0, 0)),
      42         130 :       keepalive_probes_(kSessionKeepaliveProbes) {
      43         130 :     buf_.reserve(kMaxMessageSize);
      44         130 :     offset_ = buf_.begin();
      45         130 :     stream_open_matched_ = false;
      46         130 : }
      47             : 
      48         259 : XmppSession::~XmppSession() {
      49         130 :     set_observer(NULL);
      50         130 :     connection_ = NULL;
      51         259 : }
      52             : 
      53         129 : void XmppSession::SetConnection(XmppConnection *connection) {
      54         129 :     assert(connection);
      55         129 :     connection_ = connection;
      56         129 :     task_instance_ = connection_->GetTaskInstance();
      57         129 : }
      58             : 
      59             : //
      60             : // Dissociate the connection from the this XmppSession.
      61             : // Do not invalidate the task_instance since it can be used to spawn an
      62             : // io::ReaderTask while this method is being executed.
      63             : //
      64         267 : void XmppSession::ClearConnection() {
      65         267 :     connection_ = NULL;
      66         267 : }
      67             : 
      68             : //
      69             : // Concurrency: called in the context of bgp::Config task.
      70             : //
      71             : // Process write ready callback.
      72             : //
      73           0 : void XmppSession::ProcessWriteReady() {
      74           0 :     if (!connection_)
      75           0 :         return;
      76           0 :     connection_->WriteReady();
      77             : }
      78             : 
      79             : //
      80             : // Concurrency: called in the context of io thread.
      81             : //
      82             : // Handle write ready callback.
      83             : //
      84             : // Enqueue session to the XmppConnectionManager. The session is added to a
      85             : // WorkQueue gets processed in the context of bgp::Config task. Doing this
      86             : // ensures that we don't access the XmppConnection while the XmppConnection
      87             : // is trying to clear our back pointer to it.
      88             : //
      89             : // We can ignore any errors since the StateMachine will get informed of the
      90             : // TcpSession close independently and react to it.
      91             : //
      92           0 : void XmppSession::WriteReady(const boost::system::error_code &error) {
      93           0 :     if (error)
      94           0 :         return;
      95           0 :     manager_->EnqueueSession(this);
      96             : }
      97             : 
      98          30 : XmppSession::StatsPair XmppSession::Stats(unsigned int type) const {
      99          30 :     assert (type < (unsigned int)XmppStanza::RESERVED_STANZA);
     100          30 :     return stats_[type];
     101             : }
     102             : 
     103        9551 : void XmppSession::IncStats(unsigned int type, uint64_t bytes) {
     104        9551 :     assert (type < (unsigned int)XmppStanza::RESERVED_STANZA);
     105        9551 :     stats_[type].first++;
     106        9551 :     stats_[type].second += bytes;
     107        9551 : }
     108             : 
     109          74 : boost::system::error_code XmppSession::EnableTcpKeepalive(int hold_time) {
     110          74 :     char *keepalive_time_str = getenv("TCP_KEEPALIVE_SECONDS");
     111          74 :     if (keepalive_time_str) {
     112           0 :         hold_time = strtoul(keepalive_time_str, NULL, 0) * 3;
     113           0 :         if (!hold_time)
     114           0 :             return boost::system::error_code();
     115             :     }
     116             : 
     117          74 :     if (hold_time <= 9) {
     118           0 :         hold_time = 9; // min hold-time in secs.
     119             :     }
     120          74 :     hold_time = ((hold_time > 18)? hold_time/2 : hold_time);
     121          74 :     keepalive_idle_time_ = hold_time/3;
     122          74 :     keepalive_interval_ =
     123          74 :         ((hold_time - keepalive_idle_time_)/keepalive_probes_);
     124          74 :     tcp_user_timeout_ = (hold_time * 1000); // msec
     125             : 
     126          74 :     return (SetSocketKeepaliveOptions(keepalive_idle_time_,
     127             :                                       keepalive_interval_,
     128             :                                       keepalive_probes_,
     129          74 :                                       tcp_user_timeout_));
     130             : }
     131             : 
     132        4459 : regex XmppSession::tag_to_pattern(const char *tag) {
     133        4459 :     std::string token("</");
     134        4459 :     token += ++tag;
     135        4459 :     token += "[\\s\\t\\r\\n]*>";
     136             : 
     137        8918 :     regex exp(token.c_str());
     138        8918 :     return exp;
     139        4459 : }
     140             : 
     141        4449 : void XmppSession::SetBuf(const std::string &str) {
     142        4449 :     if (buf_.empty()) {
     143        4411 :         ReplaceBuf(str);
     144             :     } else {
     145          38 :         int pos = offset_ - buf_.begin();
     146          38 :         buf_ += str;
     147          38 :         offset_ = buf_.begin() + pos;
     148             :     }
     149        4448 : }
     150             : 
     151       11518 : void XmppSession::ReplaceBuf(const std::string &str) {
     152       11518 :     buf_ = str;
     153       11517 :     buf_.reserve(kMaxMessageSize+8);
     154       11517 :     offset_ = buf_.begin();
     155       11518 : }
     156             : 
     157        9552 : bool XmppSession::LeftOver() const {
     158        9552 :     if (buf_.empty())
     159           0 :         return false;
     160        9552 :     return (buf_.end() != offset_);
     161             : }
     162             : 
     163             : // Match a pattern in the buffer. Partially matched string is
     164             : // kept in buf_ for use in conjucntion with next buffer read.
     165        9043 : int XmppSession::MatchRegex(const regex &patt) {
     166             : 
     167        9043 :     std::string::const_iterator end = buf_.end();
     168             : 
     169        9043 :     if (regex_search(offset_, end, res_, patt,
     170        9041 :                      boost::match_default | boost::match_partial) == 0) {
     171          27 :         return -1;
     172             :     }
     173        9014 :     if(res_[0].matched == false) {
     174             :         // partial match
     175          12 :         offset_ = res_[0].first;
     176          12 :         return 1;
     177             :     } else {
     178        9002 :         begin_tag_ = string(res_[0].first, res_[0].second);
     179        9002 :         offset_ = res_[0].second;
     180        9001 :         return 0;
     181             :     }
     182             : }
     183             : 
     184       11544 : bool XmppSession::Match(Buffer buffer, int *result, bool NewBuf) {
     185       11544 :     const XmppConnection *connection = this->Connection();
     186             : 
     187       11544 :     if (connection == NULL) {
     188           0 :         return true;
     189             :     }
     190             : 
     191       11544 :     xmsm::XmState state = connection->GetStateMcState();
     192             :     xmsm::XmOpenConfirmState oc_state =
     193       11543 :         connection->GetStateMcOpenConfirmState();
     194             : 
     195       11544 :     if (NewBuf) {
     196        4446 :         const uint8_t *cp = BufferData(buffer);
     197             :         // TODO Avoid this copy
     198        4446 :         std::string str(cp, cp + BufferSize(buffer));
     199        4446 :         XmppSession::SetBuf(str);
     200        4446 :     }
     201             : 
     202       11544 :     int m = -1;
     203       11544 :     *result = 0;
     204             :     do {
     205       16041 :         if (!tag_known_) {
     206             :             // check for whitespaces
     207       11519 :             size_t pos = buf_.find_first_not_of(sXMPP_VALIDWS);
     208       11518 :             if (pos != 0) {
     209        7009 :                 if (pos == string::npos) pos = buf_.size();
     210        7009 :                 offset_ = buf_.begin() + pos;
     211        7011 :                 return false;
     212             :             }
     213             :         }
     214             : 
     215        9031 :         if (state == xmsm::ACTIVE || state == xmsm::IDLE) {
     216          60 :             m = MatchRegex(tag_known_ ? stream_res_end_:stream_patt_);
     217        8971 :         } else if (state == xmsm::CONNECT || state == xmsm::OPENSENT) {
     218             :             // Note, these are client only states
     219          62 :             if (!stream_open_matched_) {
     220          60 :                 m = MatchRegex(tag_known_ ? stream_res_end_:stream_patt_);
     221          60 :                 if ((m == 0) && (tag_known_)) {
     222          30 :                     stream_open_matched_ = true;
     223             :                 }
     224             :             } else {
     225           2 :                 m = MatchRegex(tag_known_ ? tag_to_pattern(begin_tag_.c_str()):
     226             :                                             stream_features_patt_);
     227             :             }
     228        8909 :         } else if ((state == xmsm::OPENCONFIRM) && !(IsSslDisabled())) {
     229           8 :             if (connection->IsClient()) {
     230           4 :                 if (oc_state == xmsm::OPENCONFIRM_FEATURE_NEGOTIATION) {
     231           2 :                     m = MatchRegex(tag_known_ ? end_patt_: proceed_patt_);
     232           2 :                     if ((m == 0) && (tag_known_)) {
     233             :                         // set the flag, as we do not want OnRead function to
     234             :                         // read any more data from basic socket.
     235           1 :                         SetSslHandShakeInProgress(true);
     236             :                     }
     237           2 :                 } else if (oc_state == xmsm::OPENCONFIRM_FEATURE_SUCCESS) {
     238           2 :                     m = MatchRegex(tag_known_ ? stream_res_end_:stream_patt_);
     239             :                 } else {
     240           0 :                     m = MatchRegex(tag_known_ ? tag_to_pattern(begin_tag_.c_str()):
     241             :                                                 stream_features_patt_);
     242             :                 }
     243             :             } else {
     244           4 :                 if (oc_state == xmsm::OPENCONFIRM_FEATURE_SUCCESS) {
     245           2 :                     m = MatchRegex(tag_known_ ? stream_res_end_:stream_patt_);
     246             :                 } else {
     247           2 :                     m = MatchRegex(tag_known_ ? end_patt_:starttls_patt_);
     248           2 :                     if ((m == 0) && (tag_known_)) {
     249           1 :                         SetSslHandShakeInProgress(true);
     250             :                     }
     251             :                 }
     252             :             }
     253        8901 :         } else if (state == xmsm::OPENCONFIRM || state == xmsm::ESTABLISHED) {
     254        8901 :             m = MatchRegex(tag_known_ ? tag_to_pattern(begin_tag_.c_str()):patt_);
     255             :         }
     256             : 
     257        9030 :         if (m == 0) { // full match
     258        8995 :             *result = 0;
     259        8995 :             tag_known_ ^= 1;
     260        8995 :             if (!tag_known_) {
     261             :                 // Found well formed xml
     262        4498 :                 return false;
     263             :             }
     264          35 :         } else if (m == -1) { // no match
     265          25 :             return true;
     266             :         } else {
     267          10 :             return true; // partial. read more
     268             :         }
     269        4497 :     } while (true);
     270             : 
     271             :     return true;
     272             : }
     273             : 
     274             : // Read the socket stream and send messages to the connection object.
     275             : // The buffer is copied to local string for regex match.
     276             : // TODO Code need to change st Match() is done on buffer itself.
     277        4446 : void XmppSession::OnRead(Buffer buffer) {
     278        4446 :     if (this->Connection() == NULL || !connection_) {
     279             :         // Connection is deleted. Session is being deleted as well
     280             :         // Drop the packet.
     281           0 :         ReleaseBuffer(buffer);
     282           0 :         return;
     283             :     }
     284             : 
     285        4446 :     if (connection_->disable_read()) {
     286           0 :         ReleaseBuffer(buffer);
     287             : 
     288             :         // Reset the hold timer as we did receive some thing from the peer
     289           0 :         connection_->state_machine()->StartHoldTimer();
     290           0 :         return;
     291             :     }
     292             : 
     293        4446 :     int result = 0;
     294        4446 :     bool more = Match(buffer, &result, true);
     295             :     do {
     296       11544 :         if (more == false) {
     297       11509 :             if (result < 0) {
     298             :                 // TODO generate error, close connection.
     299        1957 :                 break;
     300             :             }
     301             : 
     302             :             // We got good match. Process the message
     303       11509 :             std::string::const_iterator st = buf_.begin();
     304       11509 :             std::string xml = string(st, offset_);
     305             :             // Ensure we have not reached the end
     306       11508 :             if (buf_.begin() == offset_) { // xml.size() == 0
     307        1957 :                 buf_.clear();
     308        1957 :                 break;
     309             :             }
     310             : 
     311        9552 :             connection_->ReceiveMsg(this, xml);
     312             : 
     313       11508 :         } else {
     314             :             // Read more data. Either we have partial match
     315             :             // or no match but in this state we need to keep
     316             :             // reading data.
     317          35 :             break;
     318             :         }
     319             : 
     320        9552 :         if (LeftOver()) {
     321        7098 :             std::string::const_iterator st = buf_.end();
     322        7098 :             ReplaceBuf(string(offset_, st));
     323        7098 :             more = Match(buffer, &result, false);
     324             :         } else {
     325             :             // No more data in the Buffer
     326        2454 :             buf_.clear();
     327        2454 :             break;
     328             :         }
     329        7098 :     } while (true);
     330             : 
     331        4446 :     ReleaseBuffer(buffer);
     332        4446 :     return;
     333             : }

Generated by: LCOV version 1.14