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