tackeling 30 sec ping timeout issues
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #include "corenetwork.h"
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "coreidentity.h"
26
27 #include "ircserverhandler.h"
28 #include "userinputhandler.h"
29 #include "ctcphandler.h"
30
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32   : Network(networkid, session),
33     _coreSession(session),
34     _ircServerHandler(new IrcServerHandler(this)),
35     _userInputHandler(new UserInputHandler(this)),
36     _ctcpHandler(new CtcpHandler(this)),
37     _autoReconnectCount(0),
38     _quitRequested(false),
39
40     _previousConnectionAttemptFailed(false),
41     _lastUsedServerIndex(0),
42
43     _lastPingTime(0),
44     _maxPingCount(3),
45     _pingCount(0),
46
47     // TODO make autowho configurable (possibly per-network)
48     _autoWhoEnabled(true),
49     _autoWhoInterval(90),
50     _autoWhoNickLimit(0), // unlimited
51     _autoWhoDelay(5)
52 {
53   _autoReconnectTimer.setSingleShot(true);
54   _socketCloseTimer.setSingleShot(true);
55   connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
56
57   _pingTimer.setInterval(30000);
58   connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
59
60   _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
61   _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
62
63   QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
64   foreach(QString chan, channels.keys()) {
65     _channelKeys[chan.toLower()] = channels[chan];
66   }
67
68   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
69   connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
70   connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
71   connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
72   connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
73
74
75   connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
76   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
77   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
78   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
79   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
80 #ifdef HAVE_SSL
81   connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
82   connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
83 #endif
84 }
85
86 CoreNetwork::~CoreNetwork() {
87   if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
88     disconnectFromIrc(false);      // clean up, but this does not count as requested disconnect!
89   disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
90   delete _ircServerHandler;
91   delete _userInputHandler;
92   delete _ctcpHandler;
93 }
94
95 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
96   if(!bufferName.isEmpty()) {
97     IrcChannel *channel = ircChannel(bufferName);
98     if(channel)
99       return channel->decodeString(string);
100   }
101   return decodeString(string);
102 }
103
104 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
105   IrcUser *user = ircUser(userNick);
106   if(user)
107     return user->decodeString(string);
108   return decodeString(string);
109 }
110
111 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
112   if(!bufferName.isEmpty()) {
113     IrcChannel *channel = ircChannel(bufferName);
114     if(channel)
115       return channel->encodeString(string);
116   }
117   return encodeString(string);
118 }
119
120 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
121   IrcUser *user = ircUser(userNick);
122   if(user)
123     return user->encodeString(string);
124   return encodeString(string);
125 }
126
127 void CoreNetwork::connectToIrc(bool reconnecting) {
128   if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
129     _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
130     if(unlimitedReconnectRetries())
131       _autoReconnectCount = -1;
132     else
133       _autoReconnectCount = autoReconnectRetries();
134   }
135   if(serverList().isEmpty()) {
136     qWarning() << "Server list empty, ignoring connect request!";
137     return;
138   }
139   CoreIdentity *identity = identityPtr();
140   if(!identity) {
141     qWarning() << "Invalid identity configures, ignoring connect request!";
142     return;
143   }
144
145   // cleaning up old quit reason
146   _quitReason.clear();
147
148   // use a random server?
149   if(useRandomServer()) {
150     _lastUsedServerIndex = qrand() % serverList().size();
151   } else if(_previousConnectionAttemptFailed) {
152     // cycle to next server if previous connection attempt failed
153     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
154     if(++_lastUsedServerIndex >= serverList().size()) {
155       _lastUsedServerIndex = 0;
156     }
157   }
158   _previousConnectionAttemptFailed = false;
159
160   Server server = usedServer();
161   displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
162   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
163
164   if(server.useProxy) {
165     QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
166     socket.setProxy(proxy);
167   } else {
168     socket.setProxy(QNetworkProxy::NoProxy);
169   }
170
171 #ifdef HAVE_SSL
172   socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
173   if(server.useSsl) {
174     CoreIdentity *identity = identityPtr();
175     if(identity) {
176       socket.setLocalCertificate(identity->sslCert());
177       socket.setPrivateKey(identity->sslKey());
178     }
179     socket.connectToHostEncrypted(server.host, server.port);
180   } else {
181     socket.connectToHost(server.host, server.port);
182   }
183 #else
184   socket.connectToHost(server.host, server.port);
185 #endif
186 }
187
188 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) {
189   _quitRequested = requested; // see socketDisconnected();
190   if(!withReconnect) {
191     _autoReconnectTimer.stop();
192     _autoReconnectCount = 0; // prohibiting auto reconnect
193   }
194   disablePingTimeout();
195
196   IrcUser *me_ = me();
197   if(me_) {
198     QString awayMsg;
199     if(me_->isAway())
200       awayMsg = me_->awayMessage();
201     Core::setAwayMessage(userId(), networkId(), awayMsg);
202     Core::setUserModes(userId(), networkId(), me_->userModes());
203   }
204
205   if(reason.isEmpty() && identityPtr())
206     _quitReason = identityPtr()->quitReason();
207   else
208     _quitReason = reason;
209
210   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
211   switch(socket.state()) {
212   case QAbstractSocket::ConnectedState:
213     userInputHandler()->issueQuit(_quitReason);
214     if(requested || withReconnect) {
215       // the irc server has 10 seconds to close the socket
216       _socketCloseTimer.start(10000);
217       break;
218     }
219   default:
220     socket.close();
221     socketDisconnected();
222   }
223 }
224
225 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
226   userInputHandler()->handleUserInput(buf, msg);
227 }
228
229 void CoreNetwork::putRawLine(QByteArray s) {
230   if(_tokenBucket > 0)
231     writeToSocket(s);
232   else
233     _msgQueue.append(s);
234 }
235
236 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) {
237   QByteArray msg;
238
239   if(!prefix.isEmpty())
240     msg += ":" + prefix + " ";
241   msg += cmd.toUpper().toAscii();
242
243   for(int i = 0; i < params.size() - 1; i++) {
244     msg += " " + params[i];
245   }
246   if(!params.isEmpty())
247     msg += " :" + params.last();
248
249   putRawLine(msg);
250 }
251
252 void CoreNetwork::setChannelJoined(const QString &channel) {
253   _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
254
255   Core::setChannelPersistent(userId(), networkId(), channel, true);
256   Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
257 }
258
259 void CoreNetwork::setChannelParted(const QString &channel) {
260   removeChannelKey(channel);
261   _autoWhoQueue.removeAll(channel.toLower());
262   _autoWhoPending.remove(channel.toLower());
263
264   Core::setChannelPersistent(userId(), networkId(), channel, false);
265 }
266
267 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
268   if(key.isEmpty()) {
269     removeChannelKey(channel);
270   } else {
271     _channelKeys[channel.toLower()] = key;
272   }
273 }
274
275 void CoreNetwork::removeChannelKey(const QString &channel) {
276   _channelKeys.remove(channel.toLower());
277 }
278
279 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
280   QString chan = channel.toLower();
281   if(_autoWhoPending.value(chan, 0) <= 0)
282     return false;
283   if(--_autoWhoPending[chan] <= 0)
284     _autoWhoPending.remove(chan);
285   return true;
286 }
287
288 void CoreNetwork::setMyNick(const QString &mynick) {
289   Network::setMyNick(mynick);
290   if(connectionState() == Network::Initializing)
291     networkInitialized();
292 }
293
294 void CoreNetwork::socketHasData() {
295   while(socket.canReadLine()) {
296     QByteArray s = socket.readLine().trimmed();
297     ircServerHandler()->handleServerMsg(s);
298   }
299 }
300
301 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
302   if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
303     return;
304
305   _previousConnectionAttemptFailed = true;
306   qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
307   emit connectionError(socket.errorString());
308   displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
309   emitConnectionError(socket.errorString());
310   if(socket.state() < QAbstractSocket::ConnectedState) {
311     socketDisconnected();
312   }
313 }
314
315 void CoreNetwork::socketInitialized() {
316   Server server = usedServer();
317 #ifdef HAVE_SSL
318   if(server.useSsl && !socket.isEncrypted())
319     return;
320 #endif
321
322   CoreIdentity *identity = identityPtr();
323   if(!identity) {
324     qCritical() << "Identity invalid!";
325     disconnectFromIrc();
326     return;
327   }
328
329   // TokenBucket to avoid sending too much at once
330   _messagesPerSecond = 1;
331   _burstSize = 5;
332   _tokenBucket = 5; // init with a full bucket
333   _tokenBucketTimer.start(_messagesPerSecond * 1000);
334
335   if(!server.password.isEmpty()) {
336     putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
337   }
338   QString nick;
339   if(identity->nicks().isEmpty()) {
340     nick = "quassel";
341     qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
342   } else {
343     nick = identity->nicks()[0];
344   }
345   putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
346   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
347 }
348
349 void CoreNetwork::socketDisconnected() {
350   disablePingTimeout();
351
352   _autoWhoCycleTimer.stop();
353   _autoWhoTimer.stop();
354   _autoWhoQueue.clear();
355   _autoWhoPending.clear();
356
357   _socketCloseTimer.stop();
358
359   _tokenBucketTimer.stop();
360
361   IrcUser *me_ = me();
362   if(me_) {
363     foreach(QString channel, me_->channels())
364       displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
365   }
366
367   setConnected(false);
368   emit disconnected(networkId());
369   if(_quitRequested) {
370     setConnectionState(Network::Disconnected);
371     Core::setNetworkConnected(userId(), networkId(), false);
372   } else if(_autoReconnectCount != 0) {
373     setConnectionState(Network::Reconnecting);
374     if(_autoReconnectCount == autoReconnectRetries())
375       doAutoReconnect(); // first try is immediate
376     else
377       _autoReconnectTimer.start();
378   }
379 }
380
381 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
382   Network::ConnectionState state;
383   switch(socketState) {
384     case QAbstractSocket::UnconnectedState:
385       state = Network::Disconnected;
386       break;
387     case QAbstractSocket::HostLookupState:
388     case QAbstractSocket::ConnectingState:
389       state = Network::Connecting;
390       break;
391     case QAbstractSocket::ConnectedState:
392       state = Network::Initializing;
393       break;
394     case QAbstractSocket::ClosingState:
395       state = Network::Disconnecting;
396       break;
397     default:
398       state = Network::Disconnected;
399   }
400   setConnectionState(state);
401 }
402
403 void CoreNetwork::networkInitialized() {
404   setConnectionState(Network::Initialized);
405   setConnected(true);
406   _quitRequested = false;
407
408   if(useAutoReconnect()) {
409     // reset counter
410     _autoReconnectCount = autoReconnectRetries();
411   }
412
413   // restore away state
414   QString awayMsg = Core::awayMessage(userId(), networkId());
415   if(!awayMsg.isEmpty())
416     userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
417
418   // restore old user modes if server default mode is set.
419   IrcUser *me_ = me();
420   if(me_) {
421     if(!me_->userModes().isEmpty()) {
422       restoreUserModes();
423     } else {
424       connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
425       connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
426     }
427   }
428
429   sendPerform();
430
431   enablePingTimeout();
432
433   if(_autoWhoEnabled) {
434     _autoWhoCycleTimer.start();
435     _autoWhoTimer.start();
436     startAutoWhoCycle();  // FIXME wait for autojoin to be completed
437   }
438
439   Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
440   Core::setNetworkConnected(userId(), networkId(), true);
441 }
442
443 void CoreNetwork::sendPerform() {
444   BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
445
446   // do auto identify
447   if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
448     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
449   }
450
451   // send perform list
452   foreach(QString line, perform()) {
453     if(!line.isEmpty()) userInput(statusBuf, line);
454   }
455
456   // rejoin channels we've been in
457   if(rejoinChannels()) {
458     QStringList channels, keys;
459     foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
460       QString key = channelKey(chan);
461       if(!key.isEmpty()) {
462         channels.prepend(chan);
463         keys.prepend(key);
464       } else {
465         channels.append(chan);
466       }
467     }
468     QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
469     if(!joinString.isEmpty())
470       userInputHandler()->handleJoin(statusBuf, joinString);
471   }
472 }
473
474 void CoreNetwork::restoreUserModes() {
475   IrcUser *me_ = me();
476   Q_ASSERT(me_);
477
478   disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
479   disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
480
481   QString removeModes;
482   QString addModes = Core::userModes(userId(), networkId());
483   QString currentModes = me_->userModes();
484
485   removeModes = currentModes;
486   removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
487   addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
488
489   removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
490   addModes = QString("%1 +%2").arg(me_->nick(), addModes);
491   userInputHandler()->handleMode(BufferInfo(), removeModes);
492   userInputHandler()->handleMode(BufferInfo(), addModes);
493 }
494
495 void CoreNetwork::setUseAutoReconnect(bool use) {
496   Network::setUseAutoReconnect(use);
497   if(!use)
498     _autoReconnectTimer.stop();
499 }
500
501 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
502   Network::setAutoReconnectInterval(interval);
503   _autoReconnectTimer.setInterval(interval * 1000);
504 }
505
506 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
507   Network::setAutoReconnectRetries(retries);
508   if(_autoReconnectCount != 0) {
509     if(unlimitedReconnectRetries())
510       _autoReconnectCount = -1;
511     else
512       _autoReconnectCount = autoReconnectRetries();
513   }
514 }
515
516 void CoreNetwork::doAutoReconnect() {
517   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
518     qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
519     return;
520   }
521   if(_autoReconnectCount > 0)
522     _autoReconnectCount--;
523   connectToIrc(true);
524 }
525
526 void CoreNetwork::sendPing() {
527   uint now = QDateTime::currentDateTime().toTime_t();
528   if(_pingCount >= _maxPingCount && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
529     // the second check compares the actual elapsed time since the last ping and the pingTimer interval
530     // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
531     // and unable to even handle a ping answer. So we ignore those misses.
532     disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_maxPingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
533   } else {
534     _lastPingTime = now;
535     _pingCount++;
536     userInputHandler()->handlePing(BufferInfo(), QString());
537   }
538 }
539
540 void CoreNetwork::enablePingTimeout() {
541   resetPingTimeout();
542   _pingTimer.start();
543 }
544
545 void CoreNetwork::disablePingTimeout() {
546   _pingTimer.stop();
547   resetPingTimeout();
548 }
549
550 void CoreNetwork::sendAutoWho() {
551   // Don't send autowho if there are still some pending
552   if(_autoWhoPending.count())
553     return;
554
555   while(!_autoWhoQueue.isEmpty()) {
556     QString chan = _autoWhoQueue.takeFirst();
557     IrcChannel *ircchan = ircChannel(chan);
558     if(!ircchan) continue;
559     if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
560     _autoWhoPending[chan]++;
561     putRawLine("WHO " + serverEncode(chan));
562     if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
563       // Timer was stopped, means a new cycle is due immediately
564       _autoWhoCycleTimer.start();
565       startAutoWhoCycle();
566     }
567     break;
568   }
569 }
570
571 void CoreNetwork::startAutoWhoCycle() {
572   if(!_autoWhoQueue.isEmpty()) {
573     _autoWhoCycleTimer.stop();
574     return;
575   }
576   _autoWhoQueue = channels();
577 }
578
579 #ifdef HAVE_SSL
580 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
581   Q_UNUSED(sslErrors)
582   socket.ignoreSslErrors();
583   // TODO errorhandling
584 }
585 #endif  // HAVE_SSL
586
587 void CoreNetwork::fillBucketAndProcessQueue() {
588   if(_tokenBucket < _burstSize) {
589     _tokenBucket++;
590   }
591
592   while(_msgQueue.size() > 0 && _tokenBucket > 0) {
593     writeToSocket(_msgQueue.takeFirst());
594   }
595 }
596
597 void CoreNetwork::writeToSocket(const QByteArray &data) {
598   socket.write(data);
599   socket.write("\r\n");
600   _tokenBucket--;
601 }
602
603 Network::Server CoreNetwork::usedServer() const {
604   if(_lastUsedServerIndex < serverList().count())
605     return serverList()[_lastUsedServerIndex];
606
607   if(!serverList().isEmpty())
608     return serverList()[0];
609
610   return Network::Server();
611 }
612
613 void CoreNetwork::requestConnect() const {
614   if(connectionState() != Disconnected) {
615     qWarning() << "Requesting connect while already being connected!";
616     return;
617   }
618   Network::requestConnect();
619 }
620
621 void CoreNetwork::requestDisconnect() const {
622   if(connectionState() == Disconnected) {
623     qWarning() << "Requesting disconnect while not being connected!";
624     return;
625   }
626   userInputHandler()->handleQuit(BufferInfo(), QString());
627 }
628
629 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
630   Network::Server currentServer = usedServer();
631   setNetworkInfo(info);
632   Core::updateNetwork(coreSession()->user(), info);
633
634   // the order of the servers might have changed,
635   // so we try to find the previously used server
636   _lastUsedServerIndex = 0;
637   for(int i = 0; i < serverList().count(); i++) {
638     Network::Server server = serverList()[i];
639     if(server.host == currentServer.host && server.port == currentServer.port) {
640       _lastUsedServerIndex = i;
641       break;
642     }
643   }
644 }