OpenSDN source code
xmpp_session.cc
Go to the documentation of this file.
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"
14 
15 #include "sandesh/sandesh_trace.h"
16 #include "sandesh/xmpp_trace_sandesh_types.h"
17 
18 using namespace std;
19 using contrail::regex;
22 
23 using boost::asio::mutable_buffer;
24 
33 
35  bool async_ready)
36  : SslSession(manager, socket, async_ready),
37  manager_(manager),
38  connection_(NULL),
39  tag_known_(0),
40  task_instance_(-1),
41  stats_(XmppStanza::RESERVED_STANZA, XmppSession::StatsPair(0, 0)),
42  keepalive_probes_(kSessionKeepaliveProbes) {
43  buf_.reserve(kMaxMessageSize);
44  offset_ = buf_.begin();
45  stream_open_matched_ = false;
46 }
47 
49  set_observer(NULL);
50  connection_ = NULL;
51 }
52 
54  assert(connection);
55  connection_ = connection;
57 }
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 //
65  connection_ = NULL;
66 }
67 
68 //
69 // Concurrency: called in the context of bgp::Config task.
70 //
71 // Process write ready callback.
72 //
74  if (!connection_)
75  return;
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 void XmppSession::WriteReady(const boost::system::error_code &error) {
93  if (error)
94  return;
95  manager_->EnqueueSession(this);
96 }
97 
99  assert (type < (unsigned int)XmppStanza::RESERVED_STANZA);
100  return stats_[type];
101 }
102 
103 void XmppSession::IncStats(unsigned int type, uint64_t bytes) {
104  assert (type < (unsigned int)XmppStanza::RESERVED_STANZA);
105  stats_[type].first++;
106  stats_[type].second += bytes;
107 }
108 
109 boost::system::error_code XmppSession::EnableTcpKeepalive(int hold_time) {
110  char *keepalive_time_str = getenv("TCP_KEEPALIVE_SECONDS");
111  if (keepalive_time_str) {
112  hold_time = strtoul(keepalive_time_str, NULL, 0) * 3;
113  if (!hold_time)
114  return boost::system::error_code();
115  }
116 
117  if (hold_time <= 9) {
118  hold_time = 9; // min hold-time in secs.
119  }
120  hold_time = ((hold_time > 18)? hold_time/2 : hold_time);
121  keepalive_idle_time_ = hold_time/3;
123  ((hold_time - keepalive_idle_time_)/keepalive_probes_);
124  tcp_user_timeout_ = (hold_time * 1000); // msec
125 
130 }
131 
133  std::string token("</");
134  token += ++tag;
135  token += "[\\s\\t\\r\\n]*>";
136 
137  regex exp(token.c_str());
138  return exp;
139 }
140 
141 void XmppSession::SetBuf(const std::string &str) {
142  if (buf_.empty()) {
143  ReplaceBuf(str);
144  } else {
145  int pos = offset_ - buf_.begin();
146  buf_ += str;
147  offset_ = buf_.begin() + pos;
148  }
149 }
150 
151 void XmppSession::ReplaceBuf(const std::string &str) {
152  buf_ = str;
153  buf_.reserve(kMaxMessageSize+8);
154  offset_ = buf_.begin();
155 }
156 
157 bool XmppSession::LeftOver() const {
158  if (buf_.empty())
159  return false;
160  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 int XmppSession::MatchRegex(const regex &patt) {
166 
167  std::string::const_iterator end = buf_.end();
168 
169  if (regex_search(offset_, end, res_, patt,
170  boost::match_default | boost::match_partial) == 0) {
171  return -1;
172  }
173  if(res_[0].matched == false) {
174  // partial match
175  offset_ = res_[0].first;
176  return 1;
177  } else {
178  begin_tag_ = string(res_[0].first, res_[0].second);
179  offset_ = res_[0].second;
180  return 0;
181  }
182 }
183 
184 bool XmppSession::Match(Buffer buffer, int *result, bool NewBuf) {
185  const XmppConnection *connection = this->Connection();
186 
187  if (connection == NULL) {
188  return true;
189  }
190 
191  xmsm::XmState state = connection->GetStateMcState();
192  xmsm::XmOpenConfirmState oc_state =
193  connection->GetStateMcOpenConfirmState();
194 
195  if (NewBuf) {
196  const uint8_t *cp = BufferData(buffer);
197  // TODO Avoid this copy
198  std::string str(cp, cp + BufferSize(buffer));
199  XmppSession::SetBuf(str);
200  }
201 
202  int m = -1;
203  *result = 0;
204  do {
205  if (!tag_known_) {
206  // check for whitespaces
207  size_t pos = buf_.find_first_not_of(sXMPP_VALIDWS);
208  if (pos != 0) {
209  if (pos == string::npos) pos = buf_.size();
210  offset_ = buf_.begin() + pos;
211  return false;
212  }
213  }
214 
215  if (state == xmsm::ACTIVE || state == xmsm::IDLE) {
217  } else if (state == xmsm::CONNECT || state == xmsm::OPENSENT) {
218  // Note, these are client only states
219  if (!stream_open_matched_) {
221  if ((m == 0) && (tag_known_)) {
222  stream_open_matched_ = true;
223  }
224  } else {
227  }
228  } else if ((state == xmsm::OPENCONFIRM) && !(IsSslDisabled())) {
229  if (connection->IsClient()) {
230  if (oc_state == xmsm::OPENCONFIRM_FEATURE_NEGOTIATION) {
232  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.
236  }
237  } else if (oc_state == xmsm::OPENCONFIRM_FEATURE_SUCCESS) {
239  } else {
242  }
243  } else {
244  if (oc_state == xmsm::OPENCONFIRM_FEATURE_SUCCESS) {
246  } else {
248  if ((m == 0) && (tag_known_)) {
250  }
251  }
252  }
253  } else if (state == xmsm::OPENCONFIRM || state == xmsm::ESTABLISHED) {
255  }
256 
257  if (m == 0) { // full match
258  *result = 0;
259  tag_known_ ^= 1;
260  if (!tag_known_) {
261  // Found well formed xml
262  return false;
263  }
264  } else if (m == -1) { // no match
265  return true;
266  } else {
267  return true; // partial. read more
268  }
269  } 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.
278  if (this->Connection() == NULL || !connection_) {
279  // Connection is deleted. Session is being deleted as well
280  // Drop the packet.
281  ReleaseBuffer(buffer);
282  return;
283  }
284 
285  if (connection_->disable_read()) {
286  ReleaseBuffer(buffer);
287 
288  // Reset the hold timer as we did receive some thing from the peer
290  return;
291  }
292 
293  int result = 0;
294  bool more = Match(buffer, &result, true);
295  do {
296  if (more == false) {
297  if (result < 0) {
298  // TODO generate error, close connection.
299  break;
300  }
301 
302  // We got good match. Process the message
303  std::string::const_iterator st = buf_.begin();
304  std::string xml = string(st, offset_);
305  // Ensure we have not reached the end
306  if (buf_.begin() == offset_) { // xml.size() == 0
307  buf_.clear();
308  break;
309  }
310 
311  connection_->ReceiveMsg(this, xml);
312 
313  } 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  break;
318  }
319 
320  if (LeftOver()) {
321  std::string::const_iterator st = buf_.end();
322  ReplaceBuf(string(offset_, st));
323  more = Match(buffer, &result, false);
324  } else {
325  // No more data in the Buffer
326  buf_.clear();
327  break;
328  }
329  } while (true);
330 
331  ReleaseBuffer(buffer);
332  return;
333 }
bool IsSslDisabled()
Definition: ssl_session.h:33
boost::asio::ssl::stream< boost::asio::ip::tcp::socket > SslSocket
Definition: ssl_session.h:21
void SetSslHandShakeInProgress(bool state)
Definition: ssl_session.h:55
static const uint8_t * BufferData(const Buffer &buffer)
Definition: tcp_session.h:110
static size_t BufferSize(const Buffer &buffer)
Definition: tcp_session.h:113
virtual void ReleaseBuffer(Buffer buffer)
Definition: tcp_session.cc:145
void set_observer(EventObserver observer)
Definition: tcp_session.cc:220
boost::asio::const_buffer Buffer
Definition: tcp_session.h:61
boost::system::error_code SetSocketKeepaliveOptions(int keepalive_time, int keepalive_intvl, int keepalive_probes, int tcp_user_timeout_val=0)
Definition: tcp_session.cc:804
void EnqueueSession(XmppSession *session)
int GetTaskInstance() const
bool disable_read() const
virtual void ReceiveMsg(XmppSession *session, const std::string &)
xmsm::XmOpenConfirmState GetStateMcOpenConfirmState() const
virtual void WriteReady()
XmppStateMachine * state_machine()
bool IsClient() const
xmsm::XmState GetStateMcState() const
std::vector< StatsPair > stats_
Definition: xmpp_session.h:72
static const contrail::regex whitespace_
Definition: xmpp_session.h:82
std::string begin_tag_
Definition: xmpp_session.h:66
int tcp_user_timeout_
Definition: xmpp_session.h:76
static const contrail::regex proceed_patt_
Definition: xmpp_session.h:85
XmppConnection * Connection()
Definition: xmpp_session.h:27
int keepalive_idle_time_
Definition: xmpp_session.h:73
boost::match_results< std::string::const_iterator > res_
Definition: xmpp_session.h:71
bool LeftOver() const
int MatchRegex(const contrail::regex &patt)
void IncStats(unsigned int message_type, uint64_t bytes)
static const int kMaxMessageSize
Definition: xmpp_session.h:36
virtual void OnRead(Buffer buffer)
boost::system::error_code EnableTcpKeepalive(int tcp_hold_time)
XmppSession(XmppConnectionManager *manager, SslSocket *sock, bool async_ready=true)
Definition: xmpp_session.cc:34
XmppConnectionManager * manager_
Definition: xmpp_session.h:63
void ProcessWriteReady()
Definition: xmpp_session.cc:73
virtual ~XmppSession()
Definition: xmpp_session.cc:48
std::string buf_
Definition: xmpp_session.h:67
std::pair< uint64_t, uint64_t > StatsPair
Definition: xmpp_session.h:32
void SetConnection(XmppConnection *connection)
Definition: xmpp_session.cc:53
static const contrail::regex end_patt_
Definition: xmpp_session.h:86
void SetBuf(const std::string &)
void ClearConnection()
Definition: xmpp_session.cc:64
std::string::const_iterator offset_
Definition: xmpp_session.h:68
int keepalive_interval_
Definition: xmpp_session.h:74
static const contrail::regex patt_
Definition: xmpp_session.h:79
int task_instance_
Definition: xmpp_session.h:70
XmppConnection * connection_
Definition: xmpp_session.h:64
contrail::regex tag_to_pattern(const char *)
virtual void WriteReady(const boost::system::error_code &error)
Definition: xmpp_session.cc:92
static const contrail::regex stream_patt_
Definition: xmpp_session.h:80
StatsPair Stats(unsigned int message_type) const
Definition: xmpp_session.cc:98
int keepalive_probes_
Definition: xmpp_session.h:75
static const contrail::regex stream_res_end_
Definition: xmpp_session.h:81
static const contrail::regex starttls_patt_
Definition: xmpp_session.h:84
static const contrail::regex stream_features_patt_
Definition: xmpp_session.h:83
void ReplaceBuf(const std::string &)
bool Match(Buffer buffer, int *result, bool NewBuf)
bool stream_open_matched_
Definition: xmpp_session.h:77
@ RESERVED_STANZA
Definition: xmpp_proto.h:22
virtual void StartHoldTimer()
uint8_t type
Definition: load_balance.h:2
static bool regex_search(const std::string &input, const regex &regex)
Definition: regex.h:26
static bool regex_match(const std::string &input, const regex &regex)
Definition: regex.h:35
@ OPENCONFIRM_FEATURE_NEGOTIATION
@ OPENCONFIRM_FEATURE_SUCCESS
#define sXMPP_VALIDWS
Definition: xmpp_str.h:49
#define rXMPP_STREAM_END
Definition: xmpp_str.h:60
#define rXMPP_MESSAGE
Definition: xmpp_str.h:58
#define rXMPP_STREAM_PROCEED
Definition: xmpp_str.h:63
#define rXMPP_STREAM_STANZA_END
Definition: xmpp_str.h:64
#define rXMPP_STREAM_STARTTLS
Definition: xmpp_str.h:62
#define rXMPP_STREAM_START
Definition: xmpp_str.h:59
#define rXMPP_STREAM_FEATURES
Definition: xmpp_str.h:61
#define sXMPP_WHITESPACE
Definition: xmpp_str.h:47