core: connectToIrc: Pick first IRC server specified when not failed
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <QHostInfo>
22
23 #include "corenetwork.h"
24
25 #include "core.h"
26 #include "coreidentity.h"
27 #include "corenetworkconfig.h"
28 #include "coresession.h"
29 #include "coreuserinputhandler.h"
30 #include "networkevent.h"
31
32 INIT_SYNCABLE_OBJECT(CoreNetwork)
33 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
34     : Network(networkid, session),
35     _coreSession(session),
36     _userInputHandler(new CoreUserInputHandler(this)),
37     _autoReconnectCount(0),
38     _quitRequested(false),
39     _disconnectExpected(false),
40
41     _previousConnectionAttemptFailed(false),
42     _lastUsedServerIndex(0),
43
44     _lastPingTime(0),
45     _pingCount(0),
46     _sendPings(false),
47     _requestedUserModes('-')
48 {
49     _autoReconnectTimer.setSingleShot(true);
50     connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
51
52     setPingInterval(networkConfig()->pingInterval());
53     connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
54
55     setAutoWhoDelay(networkConfig()->autoWhoDelay());
56     setAutoWhoInterval(networkConfig()->autoWhoInterval());
57
58     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
59     foreach(QString chan, channels.keys()) {
60         _channelKeys[chan.toLower()] = channels[chan];
61     }
62
63     connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
64     connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
65     connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
66     connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
67     connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
68
69     connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
70     connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
71     connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
72     connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
73
74     connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
75     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
76     connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
77     connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
78 #ifdef HAVE_SSL
79     connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
80     connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
81 #endif
82     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
83
84     if (Quassel::isOptionSet("oidentd")) {
85         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
86         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
87     }
88 }
89
90
91 CoreNetwork::~CoreNetwork()
92 {
93     // Request a proper disconnect, but don't count as user-requested disconnect
94     if (socketConnected()) {
95         // Only try if the socket's fully connected (not initializing or disconnecting).
96         // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
97         // shown even if other messages are queued.
98         disconnectFromIrc(false, QString(), false, true);
99         // Process the putCmd events that trigger the quit.  Without this, shutting down the core
100         // results in abrubtly closing the socket rather than sending the QUIT as expected.
101         QCoreApplication::processEvents();
102         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
103         if (!forceDisconnect()) {
104             qWarning() << "Timed out quitting network" << networkName() <<
105                           "(user ID " << userId() << ")";
106         }
107     }
108     disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
109     delete _userInputHandler;
110 }
111
112
113 bool CoreNetwork::forceDisconnect(int msecs)
114 {
115     if (socket.state() == QAbstractSocket::UnconnectedState) {
116         // Socket already disconnected.
117         return true;
118     }
119     // Request a socket-level disconnect if not already happened
120     socket.disconnectFromHost();
121     // Return the result of waiting for disconnect; true if successful, otherwise false
122     return socket.waitForDisconnected(msecs);
123 }
124
125
126 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
127 {
128     if (!bufferName.isEmpty()) {
129         IrcChannel *channel = ircChannel(bufferName);
130         if (channel)
131             return channel->decodeString(string);
132     }
133     return decodeString(string);
134 }
135
136
137 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
138 {
139     IrcUser *user = ircUser(userNick);
140     if (user)
141         return user->decodeString(string);
142     return decodeString(string);
143 }
144
145
146 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
147 {
148     if (!bufferName.isEmpty()) {
149         IrcChannel *channel = ircChannel(bufferName);
150         if (channel)
151             return channel->encodeString(string);
152     }
153     return encodeString(string);
154 }
155
156
157 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
158 {
159     IrcUser *user = ircUser(userNick);
160     if (user)
161         return user->encodeString(string);
162     return encodeString(string);
163 }
164
165
166 void CoreNetwork::connectToIrc(bool reconnecting)
167 {
168     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
169         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
170         if (unlimitedReconnectRetries())
171             _autoReconnectCount = -1;
172         else
173             _autoReconnectCount = autoReconnectRetries();
174     }
175     if (serverList().isEmpty()) {
176         qWarning() << "Server list empty, ignoring connect request!";
177         return;
178     }
179     CoreIdentity *identity = identityPtr();
180     if (!identity) {
181         qWarning() << "Invalid identity configures, ignoring connect request!";
182         return;
183     }
184
185     // cleaning up old quit reason
186     _quitReason.clear();
187
188     // use a random server?
189     if (useRandomServer()) {
190         _lastUsedServerIndex = qrand() % serverList().size();
191     }
192     else if (_previousConnectionAttemptFailed) {
193         // cycle to next server if previous connection attempt failed
194         _previousConnectionAttemptFailed = false;
195         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
196         if (++_lastUsedServerIndex >= serverList().size()) {
197             _lastUsedServerIndex = 0;
198         }
199     }
200     else {
201         // Start out with the top server in the list
202         _lastUsedServerIndex = 0;
203     }
204
205     Server server = usedServer();
206     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
207     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
208
209     if (server.useProxy) {
210         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
211         socket.setProxy(proxy);
212     }
213     else {
214         socket.setProxy(QNetworkProxy::NoProxy);
215     }
216
217     enablePingTimeout();
218
219     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
220     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
221     QHostInfo::fromName(server.host);
222
223 #ifdef HAVE_SSL
224     if (server.useSsl) {
225         CoreIdentity *identity = identityPtr();
226         if (identity) {
227             socket.setLocalCertificate(identity->sslCert());
228             socket.setPrivateKey(identity->sslKey());
229         }
230         socket.connectToHostEncrypted(server.host, server.port);
231     }
232     else {
233         socket.connectToHost(server.host, server.port);
234     }
235 #else
236     socket.connectToHost(server.host, server.port);
237 #endif
238 }
239
240
241 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
242                                     bool forceImmediate)
243 {
244     // Disconnecting from the network, should expect a socket close or error
245     _disconnectExpected = true;
246     _quitRequested = requested; // see socketDisconnected();
247     if (!withReconnect) {
248         _autoReconnectTimer.stop();
249         _autoReconnectCount = 0; // prohibiting auto reconnect
250     }
251     disablePingTimeout();
252     _msgQueue.clear();
253
254     IrcUser *me_ = me();
255     if (me_) {
256         QString awayMsg;
257         if (me_->isAway())
258             awayMsg = me_->awayMessage();
259         Core::setAwayMessage(userId(), networkId(), awayMsg);
260     }
261
262     if (reason.isEmpty() && identityPtr())
263         _quitReason = identityPtr()->quitReason();
264     else
265         _quitReason = reason;
266
267     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
268     if (socket.state() == QAbstractSocket::UnconnectedState) {
269         socketDisconnected();
270     } else {
271         if (socket.state() == QAbstractSocket::ConnectedState) {
272             userInputHandler()->issueQuit(_quitReason, forceImmediate);
273         } else {
274             socket.close();
275         }
276         if (requested || withReconnect) {
277             // the irc server has 10 seconds to close the socket
278             _socketCloseTimer.start(10000);
279         }
280     }
281 }
282
283
284 void CoreNetwork::userInput(BufferInfo buf, QString msg)
285 {
286     userInputHandler()->handleUserInput(buf, msg);
287 }
288
289
290 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
291 {
292     if (_tokenBucket > 0) {
293         writeToSocket(s);
294     } else {
295         if (prepend) {
296             _msgQueue.prepend(s);
297         } else {
298             _msgQueue.append(s);
299         }
300     }
301 }
302
303
304 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix, const bool prepend)
305 {
306     QByteArray msg;
307
308     if (!prefix.isEmpty())
309         msg += ":" + prefix + " ";
310     msg += cmd.toUpper().toLatin1();
311
312     for (int i = 0; i < params.size(); i++) {
313         msg += " ";
314
315         if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
316             msg += ":";
317
318         msg += params[i];
319     }
320
321     putRawLine(msg, prepend);
322 }
323
324
325 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix, const bool prependAll)
326 {
327     QListIterator<QList<QByteArray>> i(params);
328     while (i.hasNext()) {
329         QList<QByteArray> msg = i.next();
330         putCmd(cmd, msg, prefix, prependAll);
331     }
332 }
333
334
335 void CoreNetwork::setChannelJoined(const QString &channel)
336 {
337     _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
338
339     Core::setChannelPersistent(userId(), networkId(), channel, true);
340     Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
341 }
342
343
344 void CoreNetwork::setChannelParted(const QString &channel)
345 {
346     removeChannelKey(channel);
347     _autoWhoQueue.removeAll(channel.toLower());
348     _autoWhoPending.remove(channel.toLower());
349
350     Core::setChannelPersistent(userId(), networkId(), channel, false);
351 }
352
353
354 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
355 {
356     if (key.isEmpty()) {
357         removeChannelKey(channel);
358     }
359     else {
360         _channelKeys[channel.toLower()] = key;
361     }
362 }
363
364
365 void CoreNetwork::removeChannelKey(const QString &channel)
366 {
367     _channelKeys.remove(channel.toLower());
368 }
369
370
371 #ifdef HAVE_QCA2
372 Cipher *CoreNetwork::cipher(const QString &target)
373 {
374     if (target.isEmpty())
375         return 0;
376
377     if (!Cipher::neededFeaturesAvailable())
378         return 0;
379
380     CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
381     if (channel) {
382         return channel->cipher();
383     }
384     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
385     if (user) {
386         return user->cipher();
387     } else if (!isChannelName(target)) {
388         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
389     }
390     return 0;
391 }
392
393
394 QByteArray CoreNetwork::cipherKey(const QString &target) const
395 {
396     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
397     if (c)
398         return c->cipher()->key();
399
400     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
401     if (u)
402         return u->cipher()->key();
403
404     return QByteArray();
405 }
406
407
408 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
409 {
410     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
411     if (c) {
412         c->setEncrypted(c->cipher()->setKey(key));
413         return;
414     }
415
416     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
417     if (!u && !isChannelName(target))
418         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
419
420     if (u) {
421         u->setEncrypted(u->cipher()->setKey(key));
422         return;
423     }
424 }
425
426
427 bool CoreNetwork::cipherUsesCBC(const QString &target)
428 {
429     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
430     if (c)
431         return c->cipher()->usesCBC();
432     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
433     if (u)
434         return u->cipher()->usesCBC();
435
436     return false;
437 }
438 #endif /* HAVE_QCA2 */
439
440 bool CoreNetwork::setAutoWhoDone(const QString &channel)
441 {
442     QString chan = channel.toLower();
443     if (_autoWhoPending.value(chan, 0) <= 0)
444         return false;
445     if (--_autoWhoPending[chan] <= 0)
446         _autoWhoPending.remove(chan);
447     return true;
448 }
449
450
451 void CoreNetwork::setMyNick(const QString &mynick)
452 {
453     Network::setMyNick(mynick);
454     if (connectionState() == Network::Initializing)
455         networkInitialized();
456 }
457
458
459 void CoreNetwork::socketHasData()
460 {
461     while (socket.canReadLine()) {
462         QByteArray s = socket.readLine();
463         if (s.endsWith("\r\n"))
464             s.chop(2);
465         else if (s.endsWith("\n"))
466             s.chop(1);
467         NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
468         event->setTimestamp(QDateTime::currentDateTimeUtc());
469         emit newEvent(event);
470     }
471 }
472
473
474 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
475 {
476     // Ignore socket closed errors if expected
477     if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
478         return;
479     }
480
481     _previousConnectionAttemptFailed = true;
482     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
483     emit connectionError(socket.errorString());
484     displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
485     emitConnectionError(socket.errorString());
486     if (socket.state() < QAbstractSocket::ConnectedState) {
487         socketDisconnected();
488     }
489 }
490
491
492 void CoreNetwork::socketInitialized()
493 {
494     CoreIdentity *identity = identityPtr();
495     if (!identity) {
496         qCritical() << "Identity invalid!";
497         disconnectFromIrc();
498         return;
499     }
500
501     Server server = usedServer();
502
503 #ifdef HAVE_SSL
504     // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
505     // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
506     if (!server.useSsl || !socket.isEncrypted()) {
507         emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
508     }
509
510     if (server.useSsl && !socket.isEncrypted()) {
511         // We'll finish setup once we're encrypted, and called again
512         return;
513     }
514 #else
515     emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
516 #endif
517
518     socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
519
520     // TokenBucket to avoid sending too much at once
521     _messageDelay = 2200;  // this seems to be a safe value (2.2 seconds delay)
522     _burstSize = 5;
523     _tokenBucket = _burstSize; // init with a full bucket
524     _tokenBucketTimer.start(_messageDelay);
525
526     if (networkInfo().useSasl) {
527         putRawLine(serverEncode(QString("CAP REQ :sasl")));
528     }
529     if (!server.password.isEmpty()) {
530         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
531     }
532     QString nick;
533     if (identity->nicks().isEmpty()) {
534         nick = "quassel";
535         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
536     }
537     else {
538         nick = identity->nicks()[0];
539     }
540     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
541     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
542 }
543
544
545 void CoreNetwork::socketDisconnected()
546 {
547     disablePingTimeout();
548     _msgQueue.clear();
549
550     _autoWhoCycleTimer.stop();
551     _autoWhoTimer.stop();
552     _autoWhoQueue.clear();
553     _autoWhoPending.clear();
554
555     _socketCloseTimer.stop();
556
557     _tokenBucketTimer.stop();
558
559     IrcUser *me_ = me();
560     if (me_) {
561         foreach(QString channel, me_->channels())
562         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
563     }
564
565     setConnected(false);
566     emit disconnected(networkId());
567     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
568     // Reset disconnect expectations
569     _disconnectExpected = false;
570     if (_quitRequested) {
571         _quitRequested = false;
572         setConnectionState(Network::Disconnected);
573         Core::setNetworkConnected(userId(), networkId(), false);
574     }
575     else if (_autoReconnectCount != 0) {
576         setConnectionState(Network::Reconnecting);
577         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
578             doAutoReconnect();  // first try is immediate
579         else
580             _autoReconnectTimer.start();
581     }
582 }
583
584
585 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
586 {
587     Network::ConnectionState state;
588     switch (socketState) {
589     case QAbstractSocket::UnconnectedState:
590         state = Network::Disconnected;
591         socketDisconnected();
592         break;
593     case QAbstractSocket::HostLookupState:
594     case QAbstractSocket::ConnectingState:
595         state = Network::Connecting;
596         break;
597     case QAbstractSocket::ConnectedState:
598         state = Network::Initializing;
599         break;
600     case QAbstractSocket::ClosingState:
601         state = Network::Disconnecting;
602         break;
603     default:
604         state = Network::Disconnected;
605     }
606     setConnectionState(state);
607 }
608
609
610 void CoreNetwork::networkInitialized()
611 {
612     setConnectionState(Network::Initialized);
613     setConnected(true);
614     _disconnectExpected = false;
615     _quitRequested = false;
616
617     if (useAutoReconnect()) {
618         // reset counter
619         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
620     }
621
622     // restore away state
623     QString awayMsg = Core::awayMessage(userId(), networkId());
624     if (!awayMsg.isEmpty())
625         userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
626
627     sendPerform();
628
629     _sendPings = true;
630
631     if (networkConfig()->autoWhoEnabled()) {
632         _autoWhoCycleTimer.start();
633         _autoWhoTimer.start();
634         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
635     }
636
637     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
638     Core::setNetworkConnected(userId(), networkId(), true);
639 }
640
641
642 void CoreNetwork::sendPerform()
643 {
644     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
645
646     // do auto identify
647     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
648         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
649     }
650
651     // restore old user modes if server default mode is set.
652     IrcUser *me_ = me();
653     if (me_) {
654         if (!me_->userModes().isEmpty()) {
655             restoreUserModes();
656         }
657         else {
658             connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
659             connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
660         }
661     }
662
663     // send perform list
664     foreach(QString line, perform()) {
665         if (!line.isEmpty()) userInput(statusBuf, line);
666     }
667
668     // rejoin channels we've been in
669     if (rejoinChannels()) {
670         QStringList channels, keys;
671         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
672             QString key = channelKey(chan);
673             if (!key.isEmpty()) {
674                 channels.prepend(chan);
675                 keys.prepend(key);
676             }
677             else {
678                 channels.append(chan);
679             }
680         }
681         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
682         if (!joinString.isEmpty())
683             userInputHandler()->handleJoin(statusBuf, joinString);
684     }
685 }
686
687
688 void CoreNetwork::restoreUserModes()
689 {
690     IrcUser *me_ = me();
691     Q_ASSERT(me_);
692
693     disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
694     disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
695
696     QString modesDelta = Core::userModes(userId(), networkId());
697     QString currentModes = me_->userModes();
698
699     QString addModes, removeModes;
700     if (modesDelta.contains('-')) {
701         addModes = modesDelta.section('-', 0, 0);
702         removeModes = modesDelta.section('-', 1);
703     }
704     else {
705         addModes = modesDelta;
706     }
707
708     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
709     if (currentModes.isEmpty())
710         removeModes = QString();
711     else
712         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
713
714     if (addModes.isEmpty() && removeModes.isEmpty())
715         return;
716
717     if (!addModes.isEmpty())
718         addModes = '+' + addModes;
719     if (!removeModes.isEmpty())
720         removeModes = '-' + removeModes;
721
722     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
723     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
724 }
725
726
727 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
728 {
729     QString addModes;
730     QString removeModes;
731     bool addMode = true;
732
733     for (int i = 0; i < requestedModes.length(); i++) {
734         if (requestedModes[i] == '+') {
735             addMode = true;
736             continue;
737         }
738         if (requestedModes[i] == '-') {
739             addMode = false;
740             continue;
741         }
742         if (addMode) {
743             addModes += requestedModes[i];
744         }
745         else {
746             removeModes += requestedModes[i];
747         }
748     }
749
750     QString addModesOld = _requestedUserModes.section('-', 0, 0);
751     QString removeModesOld = _requestedUserModes.section('-', 1);
752
753     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
754     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
755     addModes += addModesOld;
756
757     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
758     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
759     removeModes += removeModesOld;
760
761     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
762 }
763
764
765 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
766 {
767     QString persistentUserModes = Core::userModes(userId(), networkId());
768
769     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
770     QString requestedRemove = _requestedUserModes.section('-', 1);
771
772     QString persistentAdd, persistentRemove;
773     if (persistentUserModes.contains('-')) {
774         persistentAdd = persistentUserModes.section('-', 0, 0);
775         persistentRemove = persistentUserModes.section('-', 1);
776     }
777     else {
778         persistentAdd = persistentUserModes;
779     }
780
781     // remove modes we didn't issue
782     if (requestedAdd.isEmpty())
783         addModes = QString();
784     else
785         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
786
787     if (requestedRemove.isEmpty())
788         removeModes = QString();
789     else
790         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
791
792     // deduplicate
793     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
794     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
795
796     // update
797     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
798     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
799
800     // update issued mode list
801     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
802     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
803     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
804
805     persistentAdd += addModes;
806     persistentRemove += removeModes;
807     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
808 }
809
810
811 void CoreNetwork::resetPersistentModes()
812 {
813     _requestedUserModes = QString('-');
814     Core::setUserModes(userId(), networkId(), QString());
815 }
816
817
818 void CoreNetwork::setUseAutoReconnect(bool use)
819 {
820     Network::setUseAutoReconnect(use);
821     if (!use)
822         _autoReconnectTimer.stop();
823 }
824
825
826 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
827 {
828     Network::setAutoReconnectInterval(interval);
829     _autoReconnectTimer.setInterval(interval * 1000);
830 }
831
832
833 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
834 {
835     Network::setAutoReconnectRetries(retries);
836     if (_autoReconnectCount != 0) {
837         if (unlimitedReconnectRetries())
838             _autoReconnectCount = -1;
839         else
840             _autoReconnectCount = autoReconnectRetries();
841     }
842 }
843
844
845 void CoreNetwork::doAutoReconnect()
846 {
847     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
848         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
849         return;
850     }
851     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
852         _autoReconnectCount--;  // -2 means we delay the next reconnect
853     connectToIrc(true);
854 }
855
856
857 void CoreNetwork::sendPing()
858 {
859     uint now = QDateTime::currentDateTime().toTime_t();
860     if (_pingCount != 0) {
861         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
862                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
863     }
864     if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
865         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
866         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
867         // and unable to even handle a ping answer. So we ignore those misses.
868         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
869     }
870     else {
871         _lastPingTime = now;
872         _pingCount++;
873         // Don't send pings until the network is initialized
874         if(_sendPings)
875             userInputHandler()->handlePing(BufferInfo(), QString());
876     }
877 }
878
879
880 void CoreNetwork::enablePingTimeout(bool enable)
881 {
882     if (!enable)
883         disablePingTimeout();
884     else {
885         resetPingTimeout();
886         if (networkConfig()->pingTimeoutEnabled())
887             _pingTimer.start();
888     }
889 }
890
891
892 void CoreNetwork::disablePingTimeout()
893 {
894     _pingTimer.stop();
895     _sendPings = false;
896     resetPingTimeout();
897 }
898
899
900 void CoreNetwork::setPingInterval(int interval)
901 {
902     _pingTimer.setInterval(interval * 1000);
903 }
904
905
906 /******** AutoWHO ********/
907
908 void CoreNetwork::startAutoWhoCycle()
909 {
910     if (!_autoWhoQueue.isEmpty()) {
911         _autoWhoCycleTimer.stop();
912         return;
913     }
914     _autoWhoQueue = channels();
915 }
916
917
918 void CoreNetwork::setAutoWhoDelay(int delay)
919 {
920     _autoWhoTimer.setInterval(delay * 1000);
921 }
922
923
924 void CoreNetwork::setAutoWhoInterval(int interval)
925 {
926     _autoWhoCycleTimer.setInterval(interval * 1000);
927 }
928
929
930 void CoreNetwork::setAutoWhoEnabled(bool enabled)
931 {
932     if (enabled && isConnected() && !_autoWhoTimer.isActive())
933         _autoWhoTimer.start();
934     else if (!enabled) {
935         _autoWhoTimer.stop();
936         _autoWhoCycleTimer.stop();
937     }
938 }
939
940
941 void CoreNetwork::sendAutoWho()
942 {
943     // Don't send autowho if there are still some pending
944     if (_autoWhoPending.count())
945         return;
946
947     while (!_autoWhoQueue.isEmpty()) {
948         QString chan = _autoWhoQueue.takeFirst();
949         IrcChannel *ircchan = ircChannel(chan);
950         if (!ircchan) continue;
951         if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit())
952             continue;
953         _autoWhoPending[chan]++;
954         putRawLine("WHO " + serverEncode(chan));
955         break;
956     }
957     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) {
958         // Timer was stopped, means a new cycle is due immediately
959         _autoWhoCycleTimer.start();
960         startAutoWhoCycle();
961     }
962 }
963
964
965 #ifdef HAVE_SSL
966 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
967 {
968     Q_UNUSED(sslErrors)
969     socket.ignoreSslErrors();
970     // TODO errorhandling
971 }
972
973
974 #endif  // HAVE_SSL
975
976 void CoreNetwork::fillBucketAndProcessQueue()
977 {
978     if (_tokenBucket < _burstSize) {
979         _tokenBucket++;
980     }
981
982     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
983         writeToSocket(_msgQueue.takeFirst());
984     }
985 }
986
987
988 void CoreNetwork::writeToSocket(const QByteArray &data)
989 {
990     socket.write(data);
991     socket.write("\r\n");
992     _tokenBucket--;
993 }
994
995
996 Network::Server CoreNetwork::usedServer() const
997 {
998     if (_lastUsedServerIndex < serverList().count())
999         return serverList()[_lastUsedServerIndex];
1000
1001     if (!serverList().isEmpty())
1002         return serverList()[0];
1003
1004     return Network::Server();
1005 }
1006
1007
1008 void CoreNetwork::requestConnect() const
1009 {
1010     if (connectionState() != Disconnected) {
1011         qWarning() << "Requesting connect while already being connected!";
1012         return;
1013     }
1014     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1015 }
1016
1017
1018 void CoreNetwork::requestDisconnect() const
1019 {
1020     if (connectionState() == Disconnected) {
1021         qWarning() << "Requesting disconnect while not being connected!";
1022         return;
1023     }
1024     userInputHandler()->handleQuit(BufferInfo(), QString());
1025 }
1026
1027
1028 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1029 {
1030     Network::Server currentServer = usedServer();
1031     setNetworkInfo(info);
1032     Core::updateNetwork(coreSession()->user(), info);
1033
1034     // the order of the servers might have changed,
1035     // so we try to find the previously used server
1036     _lastUsedServerIndex = 0;
1037     for (int i = 0; i < serverList().count(); i++) {
1038         Network::Server server = serverList()[i];
1039         if (server.host == currentServer.host && server.port == currentServer.port) {
1040             _lastUsedServerIndex = i;
1041             break;
1042         }
1043     }
1044 }
1045
1046
1047 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1048 {
1049     QString wrkMsg(message);
1050     QList<QList<QByteArray>> msgsToSend;
1051
1052     // do while (wrkMsg.size() > 0)
1053     do {
1054         // First, check to see if the whole message can be sent at once.  The
1055         // cmdGenerator function is passed in by the caller and is used to encode
1056         // and encrypt (if applicable) the message, since different callers might
1057         // want to use different encoding or encode different values.
1058         int splitPos = wrkMsg.size();
1059         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1060         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1061
1062         if (initialOverrun) {
1063             // If the message was too long to be sent, first try splitting it along
1064             // word boundaries with QTextBoundaryFinder.
1065             QString splitMsg(wrkMsg);
1066             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1067             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1068             QList<QByteArray> splitMsgEnc;
1069             int overrun = initialOverrun;
1070
1071             while (overrun) {
1072                 splitPos = qtbf.toPreviousBoundary();
1073
1074                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1075                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1076                 // the string.  Neither one of these works for us.
1077                 if (splitPos > 0) {
1078                     // If a split point could be found, split the message there, calculate the
1079                     // overrun, and continue with the loop.
1080                     splitMsg = splitMsg.left(splitPos);
1081                     splitMsgEnc = cmdGenerator(splitMsg);
1082                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1083                 }
1084                 else {
1085                     // If a split point could not be found (the beginning of the message
1086                     // is reached without finding a split point short enough to send) and we
1087                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1088                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1089                     // the previous attempt to find a split point.
1090                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1091                         splitMsg = wrkMsg;
1092                         splitPos = splitMsg.size();
1093                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1094                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1095                         qtbf = graphemeQtbf;
1096                     }
1097                     else {
1098                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1099                         // This should never happen, but it should be handled anyway.
1100                         qWarning() << "Unexpected failure to split message!";
1101                         return msgsToSend;
1102                     }
1103                 }
1104             }
1105
1106             // Once a message of sendable length has been found, remove it from the wrkMsg and
1107             // add it to the list of messages to be sent.
1108             wrkMsg.remove(0, splitPos);
1109             msgsToSend.append(splitMsgEnc);
1110         }
1111         else{
1112             // If the entire remaining message is short enough to be sent all at once, remove
1113             // it from the wrkMsg and add it to the list of messages to be sent.
1114             wrkMsg.remove(0, splitPos);
1115             msgsToSend.append(initialSplitMsgEnc);
1116         }
1117     } while (wrkMsg.size() > 0);
1118
1119     return msgsToSend;
1120 }