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