Bring copyright headers into 2016
[quassel.git] / src / core / corenetwork.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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     // reset capability negotiation in case server changes during a reconnect
162     _capsQueued.clear();
163     _capsPending.clear();
164     _capsSupported.clear();
165
166     // use a random server?
167     if (useRandomServer()) {
168         _lastUsedServerIndex = qrand() % serverList().size();
169     }
170     else if (_previousConnectionAttemptFailed) {
171         // cycle to next server if previous connection attempt failed
172         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
173         if (++_lastUsedServerIndex >= serverList().size()) {
174             _lastUsedServerIndex = 0;
175         }
176     }
177     _previousConnectionAttemptFailed = false;
178
179     Server server = usedServer();
180     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
181     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
182
183     if (server.useProxy) {
184         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
185         socket.setProxy(proxy);
186     }
187     else {
188         socket.setProxy(QNetworkProxy::NoProxy);
189     }
190
191     enablePingTimeout();
192
193     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
194     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
195     QHostInfo::fromName(server.host);
196
197 #ifdef HAVE_SSL
198     if (server.useSsl) {
199         CoreIdentity *identity = identityPtr();
200         if (identity) {
201             socket.setLocalCertificate(identity->sslCert());
202             socket.setPrivateKey(identity->sslKey());
203         }
204         socket.connectToHostEncrypted(server.host, server.port);
205     }
206     else {
207         socket.connectToHost(server.host, server.port);
208     }
209 #else
210     socket.connectToHost(server.host, server.port);
211 #endif
212 }
213
214
215 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
216 {
217     _quitRequested = requested; // see socketDisconnected();
218     if (!withReconnect) {
219         _autoReconnectTimer.stop();
220         _autoReconnectCount = 0; // prohibiting auto reconnect
221     }
222     disablePingTimeout();
223     _msgQueue.clear();
224
225     IrcUser *me_ = me();
226     if (me_) {
227         QString awayMsg;
228         if (me_->isAway())
229             awayMsg = me_->awayMessage();
230         Core::setAwayMessage(userId(), networkId(), awayMsg);
231     }
232
233     if (reason.isEmpty() && identityPtr())
234         _quitReason = identityPtr()->quitReason();
235     else
236         _quitReason = reason;
237
238     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
239     if (socket.state() == QAbstractSocket::UnconnectedState) {
240         socketDisconnected();
241     } else {
242         if (socket.state() == QAbstractSocket::ConnectedState) {
243             userInputHandler()->issueQuit(_quitReason);
244         } else {
245             socket.close();
246         }
247         if (requested || withReconnect) {
248             // the irc server has 10 seconds to close the socket
249             _socketCloseTimer.start(10000);
250         }
251     }
252 }
253
254
255 void CoreNetwork::userInput(BufferInfo buf, QString msg)
256 {
257     userInputHandler()->handleUserInput(buf, msg);
258 }
259
260
261 void CoreNetwork::putRawLine(QByteArray s)
262 {
263     if (_tokenBucket > 0)
264         writeToSocket(s);
265     else
266         _msgQueue.append(s);
267 }
268
269
270 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix)
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);
288 }
289
290
291 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix)
292 {
293     QListIterator<QList<QByteArray>> i(params);
294     while (i.hasNext()) {
295         QList<QByteArray> msg = i.next();
296         putCmd(cmd, msg, prefix);
297     }
298 }
299
300
301 void CoreNetwork::setChannelJoined(const QString &channel)
302 {
303     queueAutoWhoOneshot(channel); // check this new channel first
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     // Request capabilities as per IRCv3.2 specifications
491     // Older servers should ignore this; newer servers won't downgrade to RFC1459
492     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
493     putRawLine(serverEncode(QString("CAP LS 302")));
494
495     if (!server.password.isEmpty()) {
496         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
497     }
498     QString nick;
499     if (identity->nicks().isEmpty()) {
500         nick = "quassel";
501         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
502     }
503     else {
504         nick = identity->nicks()[0];
505     }
506     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
507     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
508 }
509
510
511 void CoreNetwork::socketDisconnected()
512 {
513     disablePingTimeout();
514     _msgQueue.clear();
515
516     _autoWhoCycleTimer.stop();
517     _autoWhoTimer.stop();
518     _autoWhoQueue.clear();
519     _autoWhoPending.clear();
520
521     _socketCloseTimer.stop();
522
523     _tokenBucketTimer.stop();
524
525     IrcUser *me_ = me();
526     if (me_) {
527         foreach(QString channel, me_->channels())
528         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
529     }
530
531     setConnected(false);
532     emit disconnected(networkId());
533     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
534     if (_quitRequested) {
535         _quitRequested = false;
536         setConnectionState(Network::Disconnected);
537         Core::setNetworkConnected(userId(), networkId(), false);
538     }
539     else if (_autoReconnectCount != 0) {
540         setConnectionState(Network::Reconnecting);
541         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
542             doAutoReconnect();  // first try is immediate
543         else
544             _autoReconnectTimer.start();
545     }
546 }
547
548
549 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
550 {
551     Network::ConnectionState state;
552     switch (socketState) {
553     case QAbstractSocket::UnconnectedState:
554         state = Network::Disconnected;
555         socketDisconnected();
556         break;
557     case QAbstractSocket::HostLookupState:
558     case QAbstractSocket::ConnectingState:
559         state = Network::Connecting;
560         break;
561     case QAbstractSocket::ConnectedState:
562         state = Network::Initializing;
563         break;
564     case QAbstractSocket::ClosingState:
565         state = Network::Disconnecting;
566         break;
567     default:
568         state = Network::Disconnected;
569     }
570     setConnectionState(state);
571 }
572
573
574 void CoreNetwork::networkInitialized()
575 {
576     setConnectionState(Network::Initialized);
577     setConnected(true);
578     _quitRequested = false;
579
580     if (useAutoReconnect()) {
581         // reset counter
582         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
583     }
584
585     // restore away state
586     QString awayMsg = Core::awayMessage(userId(), networkId());
587     if (!awayMsg.isEmpty())
588         userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
589
590     sendPerform();
591
592     _sendPings = true;
593
594     if (networkConfig()->autoWhoEnabled()) {
595         _autoWhoCycleTimer.start();
596         _autoWhoTimer.start();
597         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
598     }
599
600     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
601     Core::setNetworkConnected(userId(), networkId(), true);
602 }
603
604
605 void CoreNetwork::sendPerform()
606 {
607     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
608
609     // do auto identify
610     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
611         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
612     }
613
614     // restore old user modes if server default mode is set.
615     IrcUser *me_ = me();
616     if (me_) {
617         if (!me_->userModes().isEmpty()) {
618             restoreUserModes();
619         }
620         else {
621             connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
622             connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
623         }
624     }
625
626     // send perform list
627     foreach(QString line, perform()) {
628         if (!line.isEmpty()) userInput(statusBuf, line);
629     }
630
631     // rejoin channels we've been in
632     if (rejoinChannels()) {
633         QStringList channels, keys;
634         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
635             QString key = channelKey(chan);
636             if (!key.isEmpty()) {
637                 channels.prepend(chan);
638                 keys.prepend(key);
639             }
640             else {
641                 channels.append(chan);
642             }
643         }
644         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
645         if (!joinString.isEmpty())
646             userInputHandler()->handleJoin(statusBuf, joinString);
647     }
648 }
649
650
651 void CoreNetwork::restoreUserModes()
652 {
653     IrcUser *me_ = me();
654     Q_ASSERT(me_);
655
656     disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
657     disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
658
659     QString modesDelta = Core::userModes(userId(), networkId());
660     QString currentModes = me_->userModes();
661
662     QString addModes, removeModes;
663     if (modesDelta.contains('-')) {
664         addModes = modesDelta.section('-', 0, 0);
665         removeModes = modesDelta.section('-', 1);
666     }
667     else {
668         addModes = modesDelta;
669     }
670
671     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
672     if (currentModes.isEmpty())
673         removeModes = QString();
674     else
675         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
676
677     if (addModes.isEmpty() && removeModes.isEmpty())
678         return;
679
680     if (!addModes.isEmpty())
681         addModes = '+' + addModes;
682     if (!removeModes.isEmpty())
683         removeModes = '-' + removeModes;
684
685     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
686     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
687 }
688
689
690 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
691 {
692     QString addModes;
693     QString removeModes;
694     bool addMode = true;
695
696     for (int i = 0; i < requestedModes.length(); i++) {
697         if (requestedModes[i] == '+') {
698             addMode = true;
699             continue;
700         }
701         if (requestedModes[i] == '-') {
702             addMode = false;
703             continue;
704         }
705         if (addMode) {
706             addModes += requestedModes[i];
707         }
708         else {
709             removeModes += requestedModes[i];
710         }
711     }
712
713     QString addModesOld = _requestedUserModes.section('-', 0, 0);
714     QString removeModesOld = _requestedUserModes.section('-', 1);
715
716     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
717     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
718     addModes += addModesOld;
719
720     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
721     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
722     removeModes += removeModesOld;
723
724     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
725 }
726
727
728 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
729 {
730     QString persistentUserModes = Core::userModes(userId(), networkId());
731
732     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
733     QString requestedRemove = _requestedUserModes.section('-', 1);
734
735     QString persistentAdd, persistentRemove;
736     if (persistentUserModes.contains('-')) {
737         persistentAdd = persistentUserModes.section('-', 0, 0);
738         persistentRemove = persistentUserModes.section('-', 1);
739     }
740     else {
741         persistentAdd = persistentUserModes;
742     }
743
744     // remove modes we didn't issue
745     if (requestedAdd.isEmpty())
746         addModes = QString();
747     else
748         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
749
750     if (requestedRemove.isEmpty())
751         removeModes = QString();
752     else
753         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
754
755     // deduplicate
756     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
757     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
758
759     // update
760     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
761     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
762
763     // update issued mode list
764     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
765     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
766     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
767
768     persistentAdd += addModes;
769     persistentRemove += removeModes;
770     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
771 }
772
773
774 void CoreNetwork::resetPersistentModes()
775 {
776     _requestedUserModes = QString('-');
777     Core::setUserModes(userId(), networkId(), QString());
778 }
779
780
781 void CoreNetwork::setUseAutoReconnect(bool use)
782 {
783     Network::setUseAutoReconnect(use);
784     if (!use)
785         _autoReconnectTimer.stop();
786 }
787
788
789 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
790 {
791     Network::setAutoReconnectInterval(interval);
792     _autoReconnectTimer.setInterval(interval * 1000);
793 }
794
795
796 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
797 {
798     Network::setAutoReconnectRetries(retries);
799     if (_autoReconnectCount != 0) {
800         if (unlimitedReconnectRetries())
801             _autoReconnectCount = -1;
802         else
803             _autoReconnectCount = autoReconnectRetries();
804     }
805 }
806
807
808 void CoreNetwork::doAutoReconnect()
809 {
810     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
811         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
812         return;
813     }
814     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
815         _autoReconnectCount--;  // -2 means we delay the next reconnect
816     connectToIrc(true);
817 }
818
819
820 void CoreNetwork::sendPing()
821 {
822     uint now = QDateTime::currentDateTime().toTime_t();
823     if (_pingCount != 0) {
824         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
825                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
826     }
827     if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
828         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
829         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
830         // and unable to even handle a ping answer. So we ignore those misses.
831         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
832     }
833     else {
834         _lastPingTime = now;
835         _pingCount++;
836         // Don't send pings until the network is initialized
837         if(_sendPings)
838             userInputHandler()->handlePing(BufferInfo(), QString());
839     }
840 }
841
842
843 void CoreNetwork::enablePingTimeout(bool enable)
844 {
845     if (!enable)
846         disablePingTimeout();
847     else {
848         resetPingTimeout();
849         if (networkConfig()->pingTimeoutEnabled())
850             _pingTimer.start();
851     }
852 }
853
854
855 void CoreNetwork::disablePingTimeout()
856 {
857     _pingTimer.stop();
858     _sendPings = false;
859     resetPingTimeout();
860 }
861
862
863 void CoreNetwork::setPingInterval(int interval)
864 {
865     _pingTimer.setInterval(interval * 1000);
866 }
867
868 /******** IRCv3 Capability Negotiation ********/
869
870 void CoreNetwork::addCap(const QString &capability, const QString &value)
871 {
872     // Clear from pending list, add to supported list
873     if (!_capsSupported.contains(capability)) {
874         if (value != "") {
875             // Value defined, just use it
876             _capsSupported[capability] = value;
877         } else if (_capsPending.contains(capability)) {
878             // Value not defined, but a pending capability had a value.
879             // E.g. CAP * LS :sasl=PLAIN multi-prefix
880             // Preserve the capability value for later use.
881             _capsSupported[capability] = _capsPending[capability];
882         } else {
883             // No value ever given, assign to blank
884             _capsSupported[capability] = QString();
885         }
886     }
887     if (_capsPending.contains(capability))
888         _capsPending.remove(capability);
889
890     // Handle special cases here
891     // TODO Use events if it makes sense
892     if (capability == "away-notify") {
893         // away-notify enabled, stop the automatic timers, handle manually
894         setAutoWhoEnabled(false);
895     }
896 }
897
898 void CoreNetwork::removeCap(const QString &capability)
899 {
900     // Clear from pending list, remove from supported list
901     if (_capsPending.contains(capability))
902         _capsPending.remove(capability);
903     if (_capsSupported.contains(capability))
904         _capsSupported.remove(capability);
905
906     // Handle special cases here
907     // TODO Use events if it makes sense
908     if (capability == "away-notify") {
909         // away-notify disabled, enable autowho according to configuration
910         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
911     }
912 }
913
914 QString CoreNetwork::capValue(const QString &capability) const
915 {
916     // If a supported capability exists, good; if not, return pending value.
917     // If capability isn't supported after all, the pending entry will be removed.
918     if (_capsSupported.contains(capability))
919         return _capsSupported[capability];
920     else if (_capsPending.contains(capability))
921         return _capsPending[capability];
922     else
923         return QString();
924 }
925
926 void CoreNetwork::queuePendingCap(const QString &capability, const QString &value)
927 {
928     if (!_capsQueued.contains(capability)) {
929         _capsQueued.append(capability);
930         // Some capabilities may have values attached, preserve them as pending
931         _capsPending[capability] = value;
932     }
933 }
934
935 QString CoreNetwork::takeQueuedCap()
936 {
937     if (!_capsQueued.empty()) {
938         return _capsQueued.takeFirst();
939     } else {
940         return QString();
941     }
942 }
943
944 /******** AutoWHO ********/
945
946 void CoreNetwork::startAutoWhoCycle()
947 {
948     if (!_autoWhoQueue.isEmpty()) {
949         _autoWhoCycleTimer.stop();
950         return;
951     }
952     _autoWhoQueue = channels();
953 }
954
955 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
956 {
957     // Prepend so these new channels/nicks are the first to be checked
958     // Don't allow duplicates
959     if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
960         _autoWhoQueue.prepend(channelOrNick.toLower());
961     }
962     if (useCapAwayNotify()) {
963         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
964         setAutoWhoEnabled(true);
965     }
966 }
967
968
969 void CoreNetwork::setAutoWhoDelay(int delay)
970 {
971     _autoWhoTimer.setInterval(delay * 1000);
972 }
973
974
975 void CoreNetwork::setAutoWhoInterval(int interval)
976 {
977     _autoWhoCycleTimer.setInterval(interval * 1000);
978 }
979
980
981 void CoreNetwork::setAutoWhoEnabled(bool enabled)
982 {
983     if (enabled && isConnected() && !_autoWhoTimer.isActive())
984         _autoWhoTimer.start();
985     else if (!enabled) {
986         _autoWhoTimer.stop();
987         _autoWhoCycleTimer.stop();
988     }
989 }
990
991
992 void CoreNetwork::sendAutoWho()
993 {
994     // Don't send autowho if there are still some pending
995     if (_autoWhoPending.count())
996         return;
997
998     while (!_autoWhoQueue.isEmpty()) {
999         QString chanOrNick = _autoWhoQueue.takeFirst();
1000         // Check if it's a known channel or nick
1001         IrcChannel *ircchan = ircChannel(chanOrNick);
1002         IrcUser *ircuser = ircUser(chanOrNick);
1003         if (ircchan) {
1004             // Apply channel limiting rules
1005             // If using away-notify, don't impose channel size limits in order to capture away
1006             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1007             if (networkConfig()->autoWhoNickLimit() > 0
1008                 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1009                 && !useCapAwayNotify())
1010                 continue;
1011             _autoWhoPending[chanOrNick.toLower()]++;
1012         } else if (ircuser) {
1013             // Checking a nick, add it to the pending list
1014             _autoWhoPending[ircuser->nick().toLower()]++;
1015         } else {
1016             // Not a channel or a nick, skip it
1017             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1018             continue;
1019         }
1020         // TODO Use WHO extended to poll away users and/or user accounts
1021         // If a server supports it, supports("WHOX") will be true
1022         // See: http://faerion.sourceforge.net/doc/irc/whox.var and HexChat
1023         putRawLine("WHO " + serverEncode(chanOrNick));
1024         break;
1025     }
1026
1027     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1028         && !useCapAwayNotify()) {
1029         // Timer was stopped, means a new cycle is due immediately
1030         // Don't run a new cycle if using away-notify; server will notify as appropriate
1031         _autoWhoCycleTimer.start();
1032         startAutoWhoCycle();
1033     } else if (useCapAwayNotify() && _autoWhoCycleTimer.isActive()) {
1034         // Don't run another who cycle if away-notify is enabled
1035         _autoWhoCycleTimer.stop();
1036     }
1037 }
1038
1039
1040 #ifdef HAVE_SSL
1041 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1042 {
1043     Q_UNUSED(sslErrors)
1044     socket.ignoreSslErrors();
1045     // TODO errorhandling
1046 }
1047
1048
1049 #endif  // HAVE_SSL
1050
1051 void CoreNetwork::fillBucketAndProcessQueue()
1052 {
1053     if (_tokenBucket < _burstSize) {
1054         _tokenBucket++;
1055     }
1056
1057     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1058         writeToSocket(_msgQueue.takeFirst());
1059     }
1060 }
1061
1062
1063 void CoreNetwork::writeToSocket(const QByteArray &data)
1064 {
1065     socket.write(data);
1066     socket.write("\r\n");
1067     _tokenBucket--;
1068 }
1069
1070
1071 Network::Server CoreNetwork::usedServer() const
1072 {
1073     if (_lastUsedServerIndex < serverList().count())
1074         return serverList()[_lastUsedServerIndex];
1075
1076     if (!serverList().isEmpty())
1077         return serverList()[0];
1078
1079     return Network::Server();
1080 }
1081
1082
1083 void CoreNetwork::requestConnect() const
1084 {
1085     if (connectionState() != Disconnected) {
1086         qWarning() << "Requesting connect while already being connected!";
1087         return;
1088     }
1089     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1090 }
1091
1092
1093 void CoreNetwork::requestDisconnect() const
1094 {
1095     if (connectionState() == Disconnected) {
1096         qWarning() << "Requesting disconnect while not being connected!";
1097         return;
1098     }
1099     userInputHandler()->handleQuit(BufferInfo(), QString());
1100 }
1101
1102
1103 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1104 {
1105     Network::Server currentServer = usedServer();
1106     setNetworkInfo(info);
1107     Core::updateNetwork(coreSession()->user(), info);
1108
1109     // the order of the servers might have changed,
1110     // so we try to find the previously used server
1111     _lastUsedServerIndex = 0;
1112     for (int i = 0; i < serverList().count(); i++) {
1113         Network::Server server = serverList()[i];
1114         if (server.host == currentServer.host && server.port == currentServer.port) {
1115             _lastUsedServerIndex = i;
1116             break;
1117         }
1118     }
1119 }
1120
1121
1122 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1123 {
1124     QString wrkMsg(message);
1125     QList<QList<QByteArray>> msgsToSend;
1126
1127     // do while (wrkMsg.size() > 0)
1128     do {
1129         // First, check to see if the whole message can be sent at once.  The
1130         // cmdGenerator function is passed in by the caller and is used to encode
1131         // and encrypt (if applicable) the message, since different callers might
1132         // want to use different encoding or encode different values.
1133         int splitPos = wrkMsg.size();
1134         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1135         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1136
1137         if (initialOverrun) {
1138             // If the message was too long to be sent, first try splitting it along
1139             // word boundaries with QTextBoundaryFinder.
1140             QString splitMsg(wrkMsg);
1141             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1142             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1143             QList<QByteArray> splitMsgEnc;
1144             int overrun = initialOverrun;
1145
1146             while (overrun) {
1147                 splitPos = qtbf.toPreviousBoundary();
1148
1149                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1150                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1151                 // the string.  Neither one of these works for us.
1152                 if (splitPos > 0) {
1153                     // If a split point could be found, split the message there, calculate the
1154                     // overrun, and continue with the loop.
1155                     splitMsg = splitMsg.left(splitPos);
1156                     splitMsgEnc = cmdGenerator(splitMsg);
1157                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1158                 }
1159                 else {
1160                     // If a split point could not be found (the beginning of the message
1161                     // is reached without finding a split point short enough to send) and we
1162                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1163                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1164                     // the previous attempt to find a split point.
1165                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1166                         splitMsg = wrkMsg;
1167                         splitPos = splitMsg.size();
1168                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1169                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1170                         qtbf = graphemeQtbf;
1171                     }
1172                     else {
1173                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1174                         // This should never happen, but it should be handled anyway.
1175                         qWarning() << "Unexpected failure to split message!";
1176                         return msgsToSend;
1177                     }
1178                 }
1179             }
1180
1181             // Once a message of sendable length has been found, remove it from the wrkMsg and
1182             // add it to the list of messages to be sent.
1183             wrkMsg.remove(0, splitPos);
1184             msgsToSend.append(splitMsgEnc);
1185         }
1186         else{
1187             // If the entire remaining message is short enough to be sent all at once, remove
1188             // it from the wrkMsg and add it to the list of messages to be sent.
1189             wrkMsg.remove(0, splitPos);
1190             msgsToSend.append(initialSplitMsgEnc);
1191         }
1192     } while (wrkMsg.size() > 0);
1193
1194     return msgsToSend;
1195 }