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