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