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