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 125 : XmppConnection::XmppConnection(TcpServer *server,
42 125 : const XmppChannelConfig *config)
43 125 : : server_(server),
44 125 : session_(NULL),
45 125 : endpoint_(config->endpoint),
46 125 : local_endpoint_(config->local_endpoint),
47 125 : config_(NULL),
48 250 : keepalive_timer_(TimerManager::CreateTimer(
49 125 : *server->event_manager()->io_service(),
50 : "Xmpp keepalive timer",
51 : TaskScheduler::GetInstance()->GetTaskId("xmpp::StateMachine"),
52 125 : GetTaskInstance(config->ClientOnly()))),
53 125 : is_client_(config->ClientOnly()),
54 125 : log_uve_(config->logUVE),
55 125 : admin_down_(false),
56 125 : disable_read_(false),
57 125 : from_(config->FromAddr),
58 125 : to_(config->ToAddr),
59 125 : auth_enabled_(config->auth_enabled),
60 125 : dscp_value_(config->dscp_value), xmlns_(config->xmlns),
61 125 : state_machine_(XmppStaticObjectFactory::Create<XmppStateMachine>(
62 125 : this, config->ClientOnly(), config->auth_enabled, config->xmpp_hold_time)),
63 750 : mux_(XmppStaticObjectFactory::Create<XmppChannelMux>(this)) {
64 125 : ostringstream oss;
65 125 : oss << FromString() << ":" << endpoint().address().to_string();
66 125 : uve_key_str_ = oss.str();
67 125 : }
68 :
69 125 : XmppConnection::~XmppConnection() {
70 125 : StopKeepAliveTimer();
71 125 : TimerManager::DeleteTimer(keepalive_timer_);
72 125 : XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
73 : "XmppConnection destructor", FromString(), ToString());
74 125 : }
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 138 : void XmppConnection::set_session(XmppSession *session) {
89 138 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
90 138 : assert(session);
91 138 : session_ = session;
92 138 : if (session_ && dscp_value_) {
93 0 : session_->SetDscpSocketOption(dscp_value_);
94 : }
95 138 : }
96 :
97 159 : void XmppConnection::clear_session() {
98 159 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
99 159 : if (!session_)
100 21 : return;
101 138 : session_->ClearConnection();
102 138 : session_ = NULL;
103 159 : }
104 :
105 25 : const XmppSession *XmppConnection::session() const {
106 25 : return session_;
107 : }
108 :
109 342 : XmppSession *XmppConnection::session() {
110 342 : 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 24 : void XmppConnection::Shutdown() {
119 24 : ManagedDelete();
120 24 : }
121 :
122 1205 : bool XmppConnection::IsDeleted() const {
123 1205 : return deleter()->IsDeleted();
124 : }
125 :
126 142 : bool XmppConnection::MayDelete() const {
127 142 : return !mux_->ReceiverCount() && !mux_->RefererCount();
128 : }
129 :
130 77 : XmppSession *XmppConnection::CreateSession() {
131 77 : TcpSession *session = server_->CreateSession();
132 77 : XmppSession *xmpp_session = static_cast<XmppSession *>(session);
133 77 : xmpp_session->SetConnection(this);
134 77 : 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 822 : int XmppConnection::GetTaskInstance(bool is_client) const {
145 822 : if (is_client)
146 449 : return 0;
147 373 : IpAddress address = endpoint().address();
148 373 : int thread_count = TaskScheduler::GetInstance()->HardwareThreadCount();
149 373 : if (address.is_v4()) {
150 373 : return address.to_v4().to_ulong() % thread_count;
151 : } else {
152 0 : return 0;
153 : }
154 : }
155 :
156 21311 : xmsm::XmState XmppConnection::GetStateMcState() const {
157 21311 : const XmppStateMachine *sm = state_machine();
158 21310 : assert(sm);
159 21310 : return sm->StateType();
160 : }
161 :
162 11543 : xmsm::XmOpenConfirmState XmppConnection::GetStateMcOpenConfirmState() const {
163 11543 : const XmppStateMachine *sm = state_machine();
164 11543 : assert(sm);
165 11543 : return sm->OpenConfirmStateType();
166 : }
167 :
168 :
169 373 : boost::asio::ip::tcp::endpoint XmppConnection::endpoint() const {
170 373 : return endpoint_;
171 : }
172 :
173 77 : boost::asio::ip::tcp::endpoint XmppConnection::local_endpoint() const {
174 77 : 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 837 : const string &XmppConnection::FromString() const {
190 837 : return from_;
191 : }
192 :
193 5757 : const string &XmppConnection::ToString() const {
194 5757 : return to_;
195 : }
196 :
197 22575 : const std::string &XmppConnection::ToUVEKey() const {
198 22575 : 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 120 : void XmppConnection::SetTo(const string &to) {
207 120 : if ((to_.size() == 0) && (to.size() != 0)) {
208 72 : to_ = to;
209 72 : 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 31 : bool XmppConnection::AcceptSession(XmppSession *session) {
223 31 : session->SetConnection(this);
224 31 : return state_machine_->PassiveOpen(session);
225 : }
226 :
227 3792 : bool XmppConnection::Send(const uint8_t *data, size_t size,
228 : const string *msg_str) {
229 3792 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
230 3792 : if (session_ == NULL) {
231 0 : return false;
232 : }
233 :
234 3792 : TcpSession::Endpoint endpoint = session_->remote_endpoint();
235 3792 : const string &endpoint_addr_str = session_->remote_addr_string();
236 3792 : string str;
237 3792 : if (!msg_str) {
238 696 : str.append(reinterpret_cast<const char *>(data), size);
239 696 : msg_str = &str;
240 : }
241 :
242 3792 : if (!(mux_ &&
243 3792 : (mux_->TxMessageTrace(endpoint_addr_str, endpoint.port(),
244 3792 : size, *msg_str, NULL)))) {
245 3792 : XMPP_MESSAGE_TRACE(XmppTxStream,
246 : endpoint_addr_str, endpoint.port(), size, *msg_str);
247 : }
248 :
249 3792 : stats_[1].update++;
250 : size_t sent;
251 3792 : return session_->Send(data, size, &sent);
252 3792 : }
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 77 : bool XmppConnection::SendOpen(XmppSession *session) {
264 77 : if (!session) return false;
265 77 : XmppProto::XmppStanza::XmppStreamMessage openstream;
266 77 : openstream.strmtype = XmppStanza::XmppStreamMessage::INIT_STREAM_HEADER;
267 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
268 77 : int len = XmppProto::EncodeStream(openstream, to_, from_, xmlns_, data,
269 : sizeof(data));
270 77 : if (len <= 0) {
271 0 : inc_open_fail();
272 0 : return false;
273 : } else {
274 77 : XMPP_UTDEBUG(XmppOpen, ToUVEKey(), XMPP_PEER_DIR_OUT, len, from_, to_,
275 : xmlns_);
276 77 : session->Send(data, len, NULL);
277 77 : stats_[1].open++;
278 77 : return true;
279 : }
280 77 : }
281 :
282 54 : bool XmppConnection::SendOpenConfirm(XmppSession *session) {
283 54 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
284 54 : if (!session_) return false;
285 54 : XmppStanza::XmppStreamMessage openstream;
286 54 : openstream.strmtype = XmppStanza::XmppStreamMessage::INIT_STREAM_HEADER_RESP;
287 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
288 54 : int len = XmppProto::EncodeStream(openstream, to_, from_, xmlns_, data,
289 : sizeof(data));
290 54 : if (len <= 0) {
291 0 : inc_open_fail();
292 0 : return false;
293 : } else {
294 54 : XMPP_UTDEBUG(XmppOpenConfirm, ToUVEKey(), XMPP_PEER_DIR_OUT, len,
295 : from_, to_);
296 54 : session_->Send(data, len, NULL);
297 54 : stats_[1].open++;
298 54 : return true;
299 : }
300 54 : }
301 :
302 14 : bool XmppConnection::SendStreamFeatureRequest(XmppSession *session) {
303 14 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
304 14 : if (!session_) return false;
305 14 : XmppStanza::XmppStreamMessage featurestream;
306 14 : featurestream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
307 14 : featurestream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_FEATURE_REQUEST;
308 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
309 14 : int len = XmppProto::EncodeStream(featurestream, to_, from_, xmlns_, data,
310 : sizeof(data));
311 14 : if (len <= 0) {
312 0 : inc_stream_feature_fail();
313 0 : return false;
314 : } else {
315 14 : XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
316 : "Send Stream Feature Request", len, from_, to_);
317 14 : session_->Send(data, len, NULL);
318 : //stats_[1].open++;
319 14 : return true;
320 : }
321 14 : }
322 :
323 15 : bool XmppConnection::SendStartTls(XmppSession *session) {
324 15 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
325 15 : if (!session_) return false;
326 15 : XmppStanza::XmppStreamMessage stream;
327 15 : stream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
328 15 : stream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_START;
329 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
330 15 : int len = XmppProto::EncodeStream(stream, to_, from_, xmlns_, data,
331 : sizeof(data));
332 15 : if (len <= 0) {
333 0 : inc_stream_feature_fail();
334 0 : return false;
335 : } else {
336 15 : XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
337 : "Send Start Tls", len, from_, to_);
338 15 : session_->Send(data, len, NULL);
339 : //stats_[1].open++;
340 15 : return true;
341 : }
342 15 : }
343 :
344 10 : bool XmppConnection::SendProceedTls(XmppSession *session) {
345 10 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
346 10 : if (!session_) return false;
347 10 : XmppStanza::XmppStreamMessage stream;
348 10 : stream.strmtype = XmppStanza::XmppStreamMessage::FEATURE_TLS;
349 10 : stream.strmtlstype = XmppStanza::XmppStreamMessage::TLS_PROCEED;
350 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
351 10 : int len = XmppProto::EncodeStream(stream, to_, from_, xmlns_, data,
352 : sizeof(data));
353 10 : if (len <= 0) {
354 0 : inc_stream_feature_fail();
355 0 : return false;
356 : } else {
357 10 : XMPP_UTDEBUG(XmppControlMessage, ToUVEKey(), XMPP_PEER_DIR_OUT,
358 : "Send Proceed Tls", len, from_, to_);
359 10 : session_->Send(data, len, NULL);
360 : //stats_[1].open++;
361 10 : return true;
362 : }
363 10 : }
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 2 : void XmppConnection::ProcessSslHandShakeResponse(SslSessionPtr session,
378 : const boost::system::error_code& error) {
379 2 : if (!state_machine())
380 0 : return;
381 :
382 2 : 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 2 : XMPP_DEBUG(XmppSslHandShakeMessage, session->ToUVEKey(),
402 : XMPP_PEER_DIR_IN, "success", "");
403 2 : 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 47 : void XmppConnection::LogKeepAliveSend() {
415 : static bool init_ = false;
416 : static bool log_ = false;
417 :
418 47 : 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 47 : if (log_) LogMsg("SEND KEEPALIVE: ");
425 47 : }
426 :
427 47 : void XmppConnection::SendKeepAlive() {
428 47 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
429 47 : if (!session_) return;
430 47 : XmppStanza::XmppMessage msg(XmppStanza::WHITESPACE_MESSAGE_STANZA);
431 : uint8_t data[XMPP_CONTROL_MESSAGE_MAX_SIZE];
432 47 : int len = XmppProto::EncodeStream(msg, data, sizeof(data));
433 47 : assert(len > 0);
434 47 : session_->Send(data, len, NULL);
435 47 : stats_[1].keepalive++;
436 47 : LogKeepAliveSend();
437 47 : }
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 87 : void XmppConnection::StartKeepAliveTimer() {
459 87 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
460 87 : if (!session_)
461 0 : return;
462 :
463 87 : int holdtime_msecs = state_machine_->hold_time_msecs();
464 87 : if (holdtime_msecs <= 0)
465 0 : return;
466 :
467 87 : keepalive_timer_->Start(holdtime_msecs / 3,
468 : boost::bind(&XmppConnection::KeepAliveTimerExpired, this),
469 : boost::bind(&XmppConnection::KeepaliveTimerErrorHanlder, this, _1, _2));
470 87 : }
471 :
472 240 : void XmppConnection::StopKeepAliveTimer() {
473 240 : tbb::spin_mutex::scoped_lock lock(spin_mutex_);
474 240 : keepalive_timer_->Cancel();
475 240 : }
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 582 : XmppStateMachine *XmppConnection::state_machine() {
484 582 : return state_machine_.get();
485 : }
486 :
487 32853 : const XmppStateMachine *XmppConnection::state_machine() const {
488 32853 : return state_machine_.get();
489 : }
490 :
491 0 : const XmppChannelMux *XmppConnection::channel_mux() const {
492 0 : return mux_.get();
493 : }
494 :
495 9552 : void XmppConnection::IncProtoStats(unsigned int type) {
496 9552 : switch (type) {
497 65 : case XmppStanza::STREAM_HEADER:
498 65 : stats_[0].open++;
499 65 : break;
500 5054 : case XmppStanza::WHITESPACE_MESSAGE_STANZA:
501 5054 : stats_[0].keepalive++;
502 5054 : break;
503 1337 : case XmppStanza::IQ_STANZA:
504 1337 : stats_[0].update++;
505 1337 : break;
506 3096 : case XmppStanza::MESSAGE_STANZA:
507 3096 : stats_[0].update++;
508 3096 : break;
509 : }
510 9552 : }
511 :
512 4 : void XmppConnection::inc_connect_error() {
513 4 : error_stats_.connect_error++;
514 4 : }
515 :
516 44 : void XmppConnection::inc_session_close() {
517 44 : error_stats_.session_close++;
518 44 : }
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 9552 : void XmppConnection::ReceiveMsg(XmppSession *session, const string &msg) {
561 9552 : XmppStanza::XmppMessage *minfo = XmppDecode(msg);
562 :
563 9551 : if (minfo) {
564 8909 : session->IncStats((unsigned int)minfo->type, msg.size());
565 8909 : if (minfo->type != XmppStanza::WHITESPACE_MESSAGE_STANZA) {
566 3856 : if (!(mux_ &&
567 7712 : (mux_->RxMessageTrace(session->
568 7712 : remote_endpoint().address().to_string(),
569 7712 : session->remote_endpoint().port(),
570 7712 : msg.size(), msg, minfo)))) {
571 3856 : XMPP_MESSAGE_TRACE(XmppRxStream,
572 : session->
573 : remote_endpoint().address().to_string(),
574 : session->
575 : remote_endpoint().port(), msg.size(), msg);
576 : }
577 : }
578 8909 : IncProtoStats((unsigned int)minfo->type);
579 8910 : state_machine_->OnMessage(session, minfo);
580 642 : } else if ((minfo = last_msg_.get()) != NULL) {
581 642 : session->IncStats((unsigned int)minfo->type, msg.size());
582 642 : 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 9552 : return;
590 : }
591 :
592 9552 : XmppStanza::XmppMessage *XmppConnection::XmppDecode(const string &msg) {
593 9552 : unique_ptr<XmppStanza::XmppMessage> minfo(XmppProto::Decode(this, msg));
594 9552 : 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 9552 : if (minfo->type == XmppStanza::IQ_STANZA) {
602 : const XmppStanza::XmppMessageIq *iq =
603 1337 : static_cast<const XmppStanza::XmppMessageIq *>(minfo.get());
604 :
605 :
606 1337 : if (iq->action.compare("publish") == 0) {
607 642 : last_msg_.reset(minfo.release());
608 642 : return NULL;
609 : }
610 :
611 695 : if (iq->action.compare("collection") == 0) {
612 642 : if (last_msg_.get() != NULL) {
613 : XmppStanza::XmppMessageIq *last_iq =
614 642 : static_cast<XmppStanza::XmppMessageIq *>(last_msg_.get());
615 :
616 642 : if (last_iq->node.compare(iq->as_node) == 0) {
617 642 : XmlBase *impl = last_iq->dom.get();
618 642 : impl->ReadNode("publish");
619 642 : impl->ModifyAttribute("node", iq->node);
620 642 : last_iq->node = impl->ReadAttrib("node");
621 642 : last_iq->is_as_node = iq->is_as_node;
622 : //Save the complete ass/dissociate node
623 642 : 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 642 : return last_msg_.release();
635 : }
636 : }
637 8268 : return minfo.release();
638 :
639 0 : error:
640 0 : last_msg_.reset();
641 0 : return NULL;
642 9552 : }
643 :
644 3100 : int XmppConnection::ProcessXmppChatMessage(
645 : const XmppStanza::XmppChatMessage *msg) {
646 3100 : mux_->ProcessXmppMessage(msg);
647 3100 : return 0;
648 : }
649 :
650 695 : int XmppConnection::ProcessXmppIqMessage(const XmppStanza::XmppMessage *msg) {
651 695 : mux_->ProcessXmppMessage(msg);
652 695 : return 0;
653 : }
654 :
655 : class XmppServerConnection::DeleteActor : public LifetimeActor {
656 : public:
657 54 : DeleteActor(XmppServer *server, XmppServerConnection *parent)
658 54 : : LifetimeActor(server->lifetime_manager()),
659 54 : server_(server), parent_(parent) {
660 54 : }
661 :
662 71 : virtual bool MayDelete() const {
663 71 : return (!parent_->on_work_queue() && parent_->MayDelete());
664 : }
665 :
666 54 : virtual void Shutdown() {
667 54 : 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 54 : 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 54 : else if (!parent_->duplicate()) {
689 54 : server_->InsertDeletedConnection(parent_);
690 54 : server_->RemoveConnection(parent_);
691 54 : server_->ReleaseConnectionEndpoint(parent_);
692 : }
693 :
694 54 : if (parent_->state_machine()) {
695 54 : parent_->state_machine()->Clear();
696 : }
697 :
698 54 : XmppSession *session = NULL;
699 54 : if (parent_->state_machine()) {
700 54 : session = parent_->state_machine()->session();
701 54 : parent_->state_machine()->clear_session();
702 : }
703 54 : if (session) {
704 11 : server_->DeleteSession(session);
705 : }
706 54 : }
707 :
708 54 : virtual void Destroy() {
709 54 : delete parent_;
710 54 : }
711 :
712 : private:
713 : XmppServer *server_;
714 : XmppServerConnection *parent_;
715 : };
716 :
717 54 : XmppServerConnection::XmppServerConnection(XmppServer *server,
718 54 : const XmppChannelConfig *config)
719 : : XmppConnection(server, config),
720 54 : duplicate_(false),
721 54 : on_work_queue_(false),
722 54 : conn_endpoint_(NULL),
723 54 : deleter_(new DeleteActor(server, this)),
724 108 : server_delete_ref_(this, server->deleter()) {
725 54 : assert(!config->ClientOnly());
726 54 : XMPP_INFO(XmppConnectionCreate, ToUVEKey(), XMPP_PEER_DIR_IN,
727 : "Server", FromString(), ToString());
728 54 : }
729 :
730 95 : XmppServerConnection::~XmppServerConnection() {
731 54 : CHECK_CONCURRENCY("bgp::Config");
732 :
733 54 : XMPP_INFO(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA, "Server",
734 : FromString(), ToString());
735 54 : server()->RemoveDeletedConnection(this);
736 95 : }
737 :
738 87 : void XmppServerConnection::ManagedDelete() {
739 87 : XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
740 : "Managed server connection delete", FromString(), ToString());
741 87 : deleter_->Delete();
742 87 : }
743 :
744 34 : void XmppServerConnection::RetryDelete() {
745 34 : if (!deleter()->IsDeleted())
746 17 : return;
747 17 : deleter()->RetryDelete();
748 : }
749 :
750 0 : LifetimeManager *XmppServerConnection::lifetime_manager() {
751 0 : return server()->lifetime_manager();
752 : }
753 :
754 88 : XmppServer *XmppServerConnection::server() {
755 88 : return static_cast<XmppServer *>(server_);
756 : }
757 :
758 99 : LifetimeActor *XmppServerConnection::deleter() {
759 99 : return deleter_.get();
760 : }
761 :
762 1088 : const LifetimeActor *XmppServerConnection::deleter() const {
763 1088 : 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 34 : void XmppServerConnection::increment_flap_count() {
784 34 : XmppConnectionEndpoint *conn_endpoint = conn_endpoint_;
785 34 : if (!conn_endpoint)
786 0 : conn_endpoint = server()->FindConnectionEndpoint(ToString());
787 34 : if (!conn_endpoint)
788 34 : return;
789 34 : conn_endpoint->increment_flap_count();
790 :
791 34 : if (!logUVE())
792 34 : 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 71 : DeleteActor(XmppClient *client, XmppClientConnection *parent)
825 71 : : LifetimeActor(client->lifetime_manager()),
826 71 : client_(client), parent_(parent) {
827 71 : }
828 :
829 71 : virtual bool MayDelete() const {
830 71 : return parent_->MayDelete();
831 : }
832 :
833 71 : virtual void Shutdown() {
834 71 : if (parent_->session()) {
835 25 : client_->NotifyConnectionEvent(parent_->ChannelMux(),
836 : xmps::NOT_READY);
837 : }
838 :
839 71 : XmppSession *session = NULL;
840 71 : if (parent_->state_machine()) {
841 71 : session = parent_->state_machine()->session();
842 71 : parent_->state_machine()->clear_session();
843 : }
844 71 : if (session) {
845 30 : client_->DeleteSession(session);
846 : }
847 71 : }
848 :
849 71 : virtual void Destroy() {
850 71 : delete parent_;
851 71 : }
852 :
853 : private:
854 : XmppClient *client_;
855 : XmppClientConnection *parent_;
856 : };
857 :
858 71 : XmppClientConnection::XmppClientConnection(XmppClient *server,
859 71 : const XmppChannelConfig *config)
860 : : XmppConnection(server, config),
861 71 : flap_count_(0),
862 71 : deleter_(new DeleteActor(server, this)),
863 142 : server_delete_ref_(this, server->deleter()) {
864 71 : assert(config->ClientOnly());
865 71 : XMPP_UTDEBUG(XmppConnectionCreate, ToUVEKey(), XMPP_PEER_DIR_NA, "Client",
866 : FromString(), ToString());
867 71 : }
868 :
869 115 : XmppClientConnection::~XmppClientConnection() {
870 71 : CHECK_CONCURRENCY("bgp::Config");
871 :
872 71 : XMPP_INFO(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
873 : "Client", FromString(), ToString());
874 71 : server()->RemoveConnection(this);
875 115 : }
876 :
877 71 : void XmppClientConnection::ManagedDelete() {
878 71 : XMPP_UTDEBUG(XmppConnectionDelete, ToUVEKey(), XMPP_PEER_DIR_NA,
879 : "Managed Client Delete", FromString(), ToString());
880 71 : deleter_->Delete();
881 71 : }
882 :
883 19 : void XmppClientConnection::RetryDelete() {
884 19 : if (!deleter()->IsDeleted())
885 19 : return;
886 0 : deleter()->RetryDelete();
887 : }
888 :
889 0 : LifetimeManager *XmppClientConnection::lifetime_manager() {
890 0 : return server()->lifetime_manager();
891 : }
892 :
893 71 : XmppClient *XmppClientConnection::server() {
894 71 : return static_cast<XmppClient *>(server_);
895 : }
896 :
897 19 : LifetimeActor *XmppClientConnection::deleter() {
898 19 : return deleter_.get();
899 : }
900 :
901 117 : const LifetimeActor *XmppClientConnection::deleter() const {
902 117 : return deleter_.get();
903 : }
904 :
905 27 : void XmppClientConnection::set_close_reason(const string &close_reason) {
906 27 : close_reason_ = close_reason;
907 27 : if (!logUVE())
908 27 : 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 27 : void XmppClientConnection::increment_flap_count() {
921 27 : flap_count_++;
922 27 : last_flap_ = UTCTimestampUsec();
923 :
924 27 : if (!logUVE())
925 27 : 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 40 : XmppConnectionEndpoint::XmppConnectionEndpoint(const string &client)
941 40 : : client_(client), flap_count_(0), last_flap_(0), connection_(NULL) {
942 40 : }
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 34 : void XmppConnectionEndpoint::increment_flap_count() {
953 34 : flap_count_++;
954 34 : last_flap_ = UTCTimestampUsec();
955 34 : }
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 42 : XmppConnection *XmppConnectionEndpoint::connection() {
966 42 : return connection_;
967 : }
968 :
969 0 : const XmppConnection *XmppConnectionEndpoint::connection() const {
970 0 : return connection_;
971 : }
972 :
973 40 : void XmppConnectionEndpoint::set_connection(XmppConnection *connection) {
974 40 : assert(!connection_);
975 40 : connection_ = connection;
976 40 : }
977 :
978 40 : void XmppConnectionEndpoint::reset_connection() {
979 40 : assert(connection_);
980 40 : connection_ = NULL;
981 40 : }
982 :
983 : // Swap relavent contents between two XmppConnection objects.
984 0 : void XmppConnection::SwapContents(XmppConnection *other) {
985 0 : assert(!IsClient());
986 0 : assert(!other->IsClient());
987 : // Update the ConnectionMap in the server as the endpoints are the keys.
988 0 : XmppServer *server = dynamic_cast<XmppServerConnection *>(this)->server();
989 0 : server->SwapXmppConnectionMapEntries(this, other);
990 : // Swap all other connection related information.
991 0 : swap(local_endpoint_, other->local_endpoint_);
992 0 : stats_[0].swap(other->stats_[0]);
993 0 : stats_[1].swap(other->stats_[1]);
994 0 : error_stats_.swap(other->error_stats_);
995 0 : swap(last_msg_, other->last_msg_);
996 0 : swap(to_, other->to_);
997 0 : swap(from_, other->from_);
998 0 : swap(xmlns_, other->xmlns_);
999 0 : swap(dscp_value_, other->dscp_value_);
1000 0 : swap(disable_read_, other->disable_read_);
1001 0 : }
|