Batch request capabilities during negotiation
[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 // IRCv3 capabilities
33 #include "irccap.h"
34
35 INIT_SYNCABLE_OBJECT(CoreNetwork)
36 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
37     : Network(networkid, session),
38     _coreSession(session),
39     _userInputHandler(new CoreUserInputHandler(this)),
40     _autoReconnectCount(0),
41     _quitRequested(false),
42     _disconnectExpected(false),
43
44     _previousConnectionAttemptFailed(false),
45     _lastUsedServerIndex(0),
46
47     _lastPingTime(0),
48     _pingCount(0),
49     _sendPings(false),
50     _requestedUserModes('-')
51 {
52     _autoReconnectTimer.setSingleShot(true);
53     connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
54
55     setPingInterval(networkConfig()->pingInterval());
56     connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
57
58     setAutoWhoDelay(networkConfig()->autoWhoDelay());
59     setAutoWhoInterval(networkConfig()->autoWhoInterval());
60
61     QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
62     foreach(QString chan, channels.keys()) {
63         _channelKeys[chan.toLower()] = channels[chan];
64     }
65
66     connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
67     connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
68     connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
69     connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
70     connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
71
72     connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
73     connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
74     connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
75     connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
76
77     connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
78     connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
79     connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
80     connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
81 #ifdef HAVE_SSL
82     connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
83     connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
84 #endif
85     connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
86
87     // IRCv3 capability handling
88     // These react to CAP messages from the server
89     connect(this, SIGNAL(capAdded(QString)), this, SLOT(serverCapAdded(QString)));
90     connect(this, SIGNAL(capAcknowledged(QString)), this, SLOT(serverCapAcknowledged(QString)));
91     connect(this, SIGNAL(capRemoved(QString)), this, SLOT(serverCapRemoved(QString)));
92
93     if (Quassel::isOptionSet("oidentd")) {
94         connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
95         connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
96     }
97 }
98
99
100 CoreNetwork::~CoreNetwork()
101 {
102     // Request a proper disconnect, but don't count as user-requested disconnect
103     if (socketConnected()) {
104         // Only try if the socket's fully connected (not initializing or disconnecting).
105         // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
106         // shown even if other messages are queued.
107         disconnectFromIrc(false, QString(), false, true);
108         // Process the putCmd events that trigger the quit.  Without this, shutting down the core
109         // results in abrubtly closing the socket rather than sending the QUIT as expected.
110         QCoreApplication::processEvents();
111         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
112         if (!forceDisconnect()) {
113             qWarning() << "Timed out quitting network" << networkName() <<
114                           "(user ID " << userId() << ")";
115         }
116     }
117     disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
118     delete _userInputHandler;
119 }
120
121
122 bool CoreNetwork::forceDisconnect(int msecs)
123 {
124     if (socket.state() == QAbstractSocket::UnconnectedState) {
125         // Socket already disconnected.
126         return true;
127     }
128     // Request a socket-level disconnect if not already happened
129     socket.disconnectFromHost();
130     // Return the result of waiting for disconnect; true if successful, otherwise false
131     return socket.waitForDisconnected(msecs);
132 }
133
134
135 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
136 {
137     if (!bufferName.isEmpty()) {
138         IrcChannel *channel = ircChannel(bufferName);
139         if (channel)
140             return channel->decodeString(string);
141     }
142     return decodeString(string);
143 }
144
145
146 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
147 {
148     IrcUser *user = ircUser(userNick);
149     if (user)
150         return user->decodeString(string);
151     return decodeString(string);
152 }
153
154
155 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
156 {
157     if (!bufferName.isEmpty()) {
158         IrcChannel *channel = ircChannel(bufferName);
159         if (channel)
160             return channel->encodeString(string);
161     }
162     return encodeString(string);
163 }
164
165
166 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
167 {
168     IrcUser *user = ircUser(userNick);
169     if (user)
170         return user->encodeString(string);
171     return encodeString(string);
172 }
173
174
175 void CoreNetwork::connectToIrc(bool reconnecting)
176 {
177     if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
178         _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
179         if (unlimitedReconnectRetries())
180             _autoReconnectCount = -1;
181         else
182             _autoReconnectCount = autoReconnectRetries();
183     }
184     if (serverList().isEmpty()) {
185         qWarning() << "Server list empty, ignoring connect request!";
186         return;
187     }
188     CoreIdentity *identity = identityPtr();
189     if (!identity) {
190         qWarning() << "Invalid identity configures, ignoring connect request!";
191         return;
192     }
193
194     // cleaning up old quit reason
195     _quitReason.clear();
196
197     // Reset capability negotiation tracking, also handling server changes during reconnect
198     _capsQueuedIndividual.clear();
199     _capsQueuedBundled.clear();
200     clearCaps();
201     _capNegotiationActive = false;
202     _capInitialNegotiationEnded = false;
203
204     // use a random server?
205     if (useRandomServer()) {
206         _lastUsedServerIndex = qrand() % serverList().size();
207     }
208     else if (_previousConnectionAttemptFailed) {
209         // cycle to next server if previous connection attempt failed
210         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
211         if (++_lastUsedServerIndex >= serverList().size()) {
212             _lastUsedServerIndex = 0;
213         }
214     }
215     _previousConnectionAttemptFailed = false;
216
217     Server server = usedServer();
218     displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
219     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
220
221     if (server.useProxy) {
222         QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
223         socket.setProxy(proxy);
224     }
225     else {
226         socket.setProxy(QNetworkProxy::NoProxy);
227     }
228
229     enablePingTimeout();
230
231     // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
232     // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
233     QHostInfo::fromName(server.host);
234
235 #ifdef HAVE_SSL
236     if (server.useSsl) {
237         CoreIdentity *identity = identityPtr();
238         if (identity) {
239             socket.setLocalCertificate(identity->sslCert());
240             socket.setPrivateKey(identity->sslKey());
241         }
242         socket.connectToHostEncrypted(server.host, server.port);
243     }
244     else {
245         socket.connectToHost(server.host, server.port);
246     }
247 #else
248     socket.connectToHost(server.host, server.port);
249 #endif
250 }
251
252
253 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect,
254                                     bool forceImmediate)
255 {
256     // Disconnecting from the network, should expect a socket close or error
257     _disconnectExpected = true;
258     _quitRequested = requested; // see socketDisconnected();
259     if (!withReconnect) {
260         _autoReconnectTimer.stop();
261         _autoReconnectCount = 0; // prohibiting auto reconnect
262     }
263     disablePingTimeout();
264     _msgQueue.clear();
265
266     IrcUser *me_ = me();
267     if (me_) {
268         QString awayMsg;
269         if (me_->isAway())
270             awayMsg = me_->awayMessage();
271         Core::setAwayMessage(userId(), networkId(), awayMsg);
272     }
273
274     if (reason.isEmpty() && identityPtr())
275         _quitReason = identityPtr()->quitReason();
276     else
277         _quitReason = reason;
278
279     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
280     if (socket.state() == QAbstractSocket::UnconnectedState) {
281         socketDisconnected();
282     } else {
283         if (socket.state() == QAbstractSocket::ConnectedState) {
284             userInputHandler()->issueQuit(_quitReason, forceImmediate);
285         } else {
286             socket.close();
287         }
288         if (requested || withReconnect) {
289             // the irc server has 10 seconds to close the socket
290             _socketCloseTimer.start(10000);
291         }
292     }
293 }
294
295
296 void CoreNetwork::userInput(BufferInfo buf, QString msg)
297 {
298     userInputHandler()->handleUserInput(buf, msg);
299 }
300
301
302 void CoreNetwork::putRawLine(const QByteArray s, const bool prepend)
303 {
304     if (_tokenBucket > 0) {
305         writeToSocket(s);
306     } else {
307         if (prepend) {
308             _msgQueue.prepend(s);
309         } else {
310             _msgQueue.append(s);
311         }
312     }
313 }
314
315
316 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix, const bool prepend)
317 {
318     QByteArray msg;
319
320     if (!prefix.isEmpty())
321         msg += ":" + prefix + " ";
322     msg += cmd.toUpper().toLatin1();
323
324     for (int i = 0; i < params.size(); i++) {
325         msg += " ";
326
327         if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':')))
328             msg += ":";
329
330         msg += params[i];
331     }
332
333     putRawLine(msg, prepend);
334 }
335
336
337 void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix, const bool prependAll)
338 {
339     QListIterator<QList<QByteArray>> i(params);
340     while (i.hasNext()) {
341         QList<QByteArray> msg = i.next();
342         putCmd(cmd, msg, prefix, prependAll);
343     }
344 }
345
346
347 void CoreNetwork::setChannelJoined(const QString &channel)
348 {
349     queueAutoWhoOneshot(channel); // check this new channel first
350
351     Core::setChannelPersistent(userId(), networkId(), channel, true);
352     Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
353 }
354
355
356 void CoreNetwork::setChannelParted(const QString &channel)
357 {
358     removeChannelKey(channel);
359     _autoWhoQueue.removeAll(channel.toLower());
360     _autoWhoPending.remove(channel.toLower());
361
362     Core::setChannelPersistent(userId(), networkId(), channel, false);
363 }
364
365
366 void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
367 {
368     if (key.isEmpty()) {
369         removeChannelKey(channel);
370     }
371     else {
372         _channelKeys[channel.toLower()] = key;
373     }
374 }
375
376
377 void CoreNetwork::removeChannelKey(const QString &channel)
378 {
379     _channelKeys.remove(channel.toLower());
380 }
381
382
383 #ifdef HAVE_QCA2
384 Cipher *CoreNetwork::cipher(const QString &target)
385 {
386     if (target.isEmpty())
387         return 0;
388
389     if (!Cipher::neededFeaturesAvailable())
390         return 0;
391
392     CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
393     if (channel) {
394         return channel->cipher();
395     }
396     CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
397     if (user) {
398         return user->cipher();
399     } else if (!isChannelName(target)) {
400         return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
401     }
402     return 0;
403 }
404
405
406 QByteArray CoreNetwork::cipherKey(const QString &target) const
407 {
408     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
409     if (c)
410         return c->cipher()->key();
411
412     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
413     if (u)
414         return u->cipher()->key();
415
416     return QByteArray();
417 }
418
419
420 void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
421 {
422     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
423     if (c) {
424         c->setEncrypted(c->cipher()->setKey(key));
425         return;
426     }
427
428     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
429     if (!u && !isChannelName(target))
430         u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
431
432     if (u) {
433         u->setEncrypted(u->cipher()->setKey(key));
434         return;
435     }
436 }
437
438
439 bool CoreNetwork::cipherUsesCBC(const QString &target)
440 {
441     CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
442     if (c)
443         return c->cipher()->usesCBC();
444     CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target));
445     if (u)
446         return u->cipher()->usesCBC();
447
448     return false;
449 }
450 #endif /* HAVE_QCA2 */
451
452 bool CoreNetwork::setAutoWhoDone(const QString &channel)
453 {
454     QString chan = channel.toLower();
455     if (_autoWhoPending.value(chan, 0) <= 0)
456         return false;
457     if (--_autoWhoPending[chan] <= 0)
458         _autoWhoPending.remove(chan);
459     return true;
460 }
461
462
463 void CoreNetwork::setMyNick(const QString &mynick)
464 {
465     Network::setMyNick(mynick);
466     if (connectionState() == Network::Initializing)
467         networkInitialized();
468 }
469
470
471 void CoreNetwork::socketHasData()
472 {
473     while (socket.canReadLine()) {
474         QByteArray s = socket.readLine();
475         if (s.endsWith("\r\n"))
476             s.chop(2);
477         else if (s.endsWith("\n"))
478             s.chop(1);
479         NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
480         event->setTimestamp(QDateTime::currentDateTimeUtc());
481         emit newEvent(event);
482     }
483 }
484
485
486 void CoreNetwork::socketError(QAbstractSocket::SocketError error)
487 {
488     // Ignore socket closed errors if expected
489     if (_disconnectExpected && error == QAbstractSocket::RemoteHostClosedError) {
490         return;
491     }
492
493     _previousConnectionAttemptFailed = true;
494     qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
495     emit connectionError(socket.errorString());
496     displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
497     emitConnectionError(socket.errorString());
498     if (socket.state() < QAbstractSocket::ConnectedState) {
499         socketDisconnected();
500     }
501 }
502
503
504 void CoreNetwork::socketInitialized()
505 {
506     CoreIdentity *identity = identityPtr();
507     if (!identity) {
508         qCritical() << "Identity invalid!";
509         disconnectFromIrc();
510         return;
511     }
512
513     Server server = usedServer();
514
515 #ifdef HAVE_SSL
516     // Non-SSL connections enter here only once, always emit socketInitialized(...) in these cases
517     // SSL connections call socketInitialized() twice, only emit socketInitialized(...) on the first (not yet encrypted) run
518     if (!server.useSsl || !socket.isEncrypted()) {
519         emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
520     }
521
522     if (server.useSsl && !socket.isEncrypted()) {
523         // We'll finish setup once we're encrypted, and called again
524         return;
525     }
526 #else
527     emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
528 #endif
529
530     socket.setSocketOption(QAbstractSocket::KeepAliveOption, true);
531
532     // TokenBucket to avoid sending too much at once
533     _messageDelay = 2200;  // this seems to be a safe value (2.2 seconds delay)
534     _burstSize = 5;
535     _tokenBucket = _burstSize; // init with a full bucket
536     _tokenBucketTimer.start(_messageDelay);
537
538     // Request capabilities as per IRCv3.2 specifications
539     // Older servers should ignore this; newer servers won't downgrade to RFC1459
540     displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Requesting capability list..."));
541     putRawLine(serverEncode(QString("CAP LS 302")));
542
543     if (!server.password.isEmpty()) {
544         putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
545     }
546     QString nick;
547     if (identity->nicks().isEmpty()) {
548         nick = "quassel";
549         qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
550     }
551     else {
552         nick = identity->nicks()[0];
553     }
554     putRawLine(serverEncode(QString("NICK %1").arg(nick)));
555     putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
556 }
557
558
559 void CoreNetwork::socketDisconnected()
560 {
561     disablePingTimeout();
562     _msgQueue.clear();
563
564     _autoWhoCycleTimer.stop();
565     _autoWhoTimer.stop();
566     _autoWhoQueue.clear();
567     _autoWhoPending.clear();
568
569     _socketCloseTimer.stop();
570
571     _tokenBucketTimer.stop();
572
573     IrcUser *me_ = me();
574     if (me_) {
575         foreach(QString channel, me_->channels())
576         displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
577     }
578
579     setConnected(false);
580     emit disconnected(networkId());
581     emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort());
582     // Reset disconnect expectations
583     _disconnectExpected = false;
584     if (_quitRequested) {
585         _quitRequested = false;
586         setConnectionState(Network::Disconnected);
587         Core::setNetworkConnected(userId(), networkId(), false);
588     }
589     else if (_autoReconnectCount != 0) {
590         setConnectionState(Network::Reconnecting);
591         if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries())
592             doAutoReconnect();  // first try is immediate
593         else
594             _autoReconnectTimer.start();
595     }
596 }
597
598
599 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
600 {
601     Network::ConnectionState state;
602     switch (socketState) {
603     case QAbstractSocket::UnconnectedState:
604         state = Network::Disconnected;
605         socketDisconnected();
606         break;
607     case QAbstractSocket::HostLookupState:
608     case QAbstractSocket::ConnectingState:
609         state = Network::Connecting;
610         break;
611     case QAbstractSocket::ConnectedState:
612         state = Network::Initializing;
613         break;
614     case QAbstractSocket::ClosingState:
615         state = Network::Disconnecting;
616         break;
617     default:
618         state = Network::Disconnected;
619     }
620     setConnectionState(state);
621 }
622
623
624 void CoreNetwork::networkInitialized()
625 {
626     setConnectionState(Network::Initialized);
627     setConnected(true);
628     _disconnectExpected = false;
629     _quitRequested = false;
630
631     if (useAutoReconnect()) {
632         // reset counter
633         _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries();
634     }
635
636     // restore away state
637     QString awayMsg = Core::awayMessage(userId(), networkId());
638     if (!awayMsg.isEmpty())
639         userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
640
641     sendPerform();
642
643     _sendPings = true;
644
645     if (networkConfig()->autoWhoEnabled()) {
646         _autoWhoCycleTimer.start();
647         _autoWhoTimer.start();
648         startAutoWhoCycle(); // FIXME wait for autojoin to be completed
649     }
650
651     Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
652     Core::setNetworkConnected(userId(), networkId(), true);
653 }
654
655
656 void CoreNetwork::sendPerform()
657 {
658     BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
659
660     // do auto identify
661     if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
662         userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
663     }
664
665     // restore old user modes if server default mode is set.
666     IrcUser *me_ = me();
667     if (me_) {
668         if (!me_->userModes().isEmpty()) {
669             restoreUserModes();
670         }
671         else {
672             connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
673             connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
674         }
675     }
676
677     // send perform list
678     foreach(QString line, perform()) {
679         if (!line.isEmpty()) userInput(statusBuf, line);
680     }
681
682     // rejoin channels we've been in
683     if (rejoinChannels()) {
684         QStringList channels, keys;
685         foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
686             QString key = channelKey(chan);
687             if (!key.isEmpty()) {
688                 channels.prepend(chan);
689                 keys.prepend(key);
690             }
691             else {
692                 channels.append(chan);
693             }
694         }
695         QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
696         if (!joinString.isEmpty())
697             userInputHandler()->handleJoin(statusBuf, joinString);
698     }
699 }
700
701
702 void CoreNetwork::restoreUserModes()
703 {
704     IrcUser *me_ = me();
705     Q_ASSERT(me_);
706
707     disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
708     disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
709
710     QString modesDelta = Core::userModes(userId(), networkId());
711     QString currentModes = me_->userModes();
712
713     QString addModes, removeModes;
714     if (modesDelta.contains('-')) {
715         addModes = modesDelta.section('-', 0, 0);
716         removeModes = modesDelta.section('-', 1);
717     }
718     else {
719         addModes = modesDelta;
720     }
721
722     addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
723     if (currentModes.isEmpty())
724         removeModes = QString();
725     else
726         removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes)));
727
728     if (addModes.isEmpty() && removeModes.isEmpty())
729         return;
730
731     if (!addModes.isEmpty())
732         addModes = '+' + addModes;
733     if (!removeModes.isEmpty())
734         removeModes = '-' + removeModes;
735
736     // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes
737     putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
738 }
739
740
741 void CoreNetwork::updateIssuedModes(const QString &requestedModes)
742 {
743     QString addModes;
744     QString removeModes;
745     bool addMode = true;
746
747     for (int i = 0; i < requestedModes.length(); i++) {
748         if (requestedModes[i] == '+') {
749             addMode = true;
750             continue;
751         }
752         if (requestedModes[i] == '-') {
753             addMode = false;
754             continue;
755         }
756         if (addMode) {
757             addModes += requestedModes[i];
758         }
759         else {
760             removeModes += requestedModes[i];
761         }
762     }
763
764     QString addModesOld = _requestedUserModes.section('-', 0, 0);
765     QString removeModesOld = _requestedUserModes.section('-', 1);
766
767     addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
768     addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
769     addModes += addModesOld;
770
771     removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
772     removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
773     removeModes += removeModesOld;
774
775     _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
776 }
777
778
779 void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
780 {
781     QString persistentUserModes = Core::userModes(userId(), networkId());
782
783     QString requestedAdd = _requestedUserModes.section('-', 0, 0);
784     QString requestedRemove = _requestedUserModes.section('-', 1);
785
786     QString persistentAdd, persistentRemove;
787     if (persistentUserModes.contains('-')) {
788         persistentAdd = persistentUserModes.section('-', 0, 0);
789         persistentRemove = persistentUserModes.section('-', 1);
790     }
791     else {
792         persistentAdd = persistentUserModes;
793     }
794
795     // remove modes we didn't issue
796     if (requestedAdd.isEmpty())
797         addModes = QString();
798     else
799         addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd)));
800
801     if (requestedRemove.isEmpty())
802         removeModes = QString();
803     else
804         removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove)));
805
806     // deduplicate
807     persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
808     persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
809
810     // update
811     persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes)));
812     persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes)));
813
814     // update issued mode list
815     requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes)));
816     requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes)));
817     _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove);
818
819     persistentAdd += addModes;
820     persistentRemove += removeModes;
821     Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
822 }
823
824
825 void CoreNetwork::resetPersistentModes()
826 {
827     _requestedUserModes = QString('-');
828     Core::setUserModes(userId(), networkId(), QString());
829 }
830
831
832 void CoreNetwork::setUseAutoReconnect(bool use)
833 {
834     Network::setUseAutoReconnect(use);
835     if (!use)
836         _autoReconnectTimer.stop();
837 }
838
839
840 void CoreNetwork::setAutoReconnectInterval(quint32 interval)
841 {
842     Network::setAutoReconnectInterval(interval);
843     _autoReconnectTimer.setInterval(interval * 1000);
844 }
845
846
847 void CoreNetwork::setAutoReconnectRetries(quint16 retries)
848 {
849     Network::setAutoReconnectRetries(retries);
850     if (_autoReconnectCount != 0) {
851         if (unlimitedReconnectRetries())
852             _autoReconnectCount = -1;
853         else
854             _autoReconnectCount = autoReconnectRetries();
855     }
856 }
857
858
859 void CoreNetwork::doAutoReconnect()
860 {
861     if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
862         qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
863         return;
864     }
865     if (_autoReconnectCount > 0 || _autoReconnectCount == -1)
866         _autoReconnectCount--;  // -2 means we delay the next reconnect
867     connectToIrc(true);
868 }
869
870
871 void CoreNetwork::sendPing()
872 {
873     uint now = QDateTime::currentDateTime().toTime_t();
874     if (_pingCount != 0) {
875         qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
876                  << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
877     }
878     if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) {
879         // the second check compares the actual elapsed time since the last ping and the pingTimer interval
880         // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
881         // and unable to even handle a ping answer. So we ignore those misses.
882         disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
883     }
884     else {
885         _lastPingTime = now;
886         _pingCount++;
887         // Don't send pings until the network is initialized
888         if(_sendPings)
889             userInputHandler()->handlePing(BufferInfo(), QString());
890     }
891 }
892
893
894 void CoreNetwork::enablePingTimeout(bool enable)
895 {
896     if (!enable)
897         disablePingTimeout();
898     else {
899         resetPingTimeout();
900         if (networkConfig()->pingTimeoutEnabled())
901             _pingTimer.start();
902     }
903 }
904
905
906 void CoreNetwork::disablePingTimeout()
907 {
908     _pingTimer.stop();
909     _sendPings = false;
910     resetPingTimeout();
911 }
912
913
914 void CoreNetwork::setPingInterval(int interval)
915 {
916     _pingTimer.setInterval(interval * 1000);
917 }
918
919 /******** IRCv3 Capability Negotiation ********/
920
921 void CoreNetwork::serverCapAdded(const QString &capability)
922 {
923     // Check if it's a known capability; if so, add it to the list
924     // Handle special cases first
925     if (capability == IrcCap::SASL) {
926         // Only request SASL if it's enabled
927         if (networkInfo().useSasl)
928             queueCap(capability);
929     } else if (IrcCap::knownCaps.contains(capability)) {
930         // Handling for general known capabilities
931         queueCap(capability);
932     }
933 }
934
935 void CoreNetwork::serverCapAcknowledged(const QString &capability)
936 {
937     // This may be called multiple times in certain situations.
938
939     // Handle core-side configuration
940     if (capability == IrcCap::AWAY_NOTIFY) {
941         // away-notify enabled, stop the autoWho timers, handle manually
942         setAutoWhoEnabled(false);
943     }
944
945     // Handle capabilities that require further messages sent to the IRC server
946     // If you change this list, ALSO change the list in CoreNetwork::capsRequiringServerMessages
947     if (capability == IrcCap::SASL) {
948         // If SASL mechanisms specified, limit to what's accepted for authentication
949         // if the current identity has a cert set, use SASL EXTERNAL
950         // FIXME use event
951 #ifdef HAVE_SSL
952         if (!identityPtr()->sslCert().isNull()) {
953             if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::EXTERNAL)) {
954                 // EXTERNAL authentication supported, send request
955                 putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
956             } else {
957                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
958                            tr("SASL EXTERNAL authentication not supported"));
959                 sendNextCap();
960             }
961         } else {
962 #endif
963             if (IrcCap::SaslMech::maybeSupported(capValue(IrcCap::SASL), IrcCap::SaslMech::PLAIN)) {
964                 // PLAIN authentication supported, send request
965                 // Only working with PLAIN atm, blowfish later
966                 putRawLine(serverEncode("AUTHENTICATE PLAIN"));
967             } else {
968                 displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
969                            tr("SASL PLAIN authentication not supported"));
970                 sendNextCap();
971             }
972 #ifdef HAVE_SSL
973         }
974 #endif
975     }
976 }
977
978 void CoreNetwork::serverCapRemoved(const QString &capability)
979 {
980     // This may be called multiple times in certain situations.
981
982     // Handle special cases here
983     if (capability == IrcCap::AWAY_NOTIFY) {
984         // away-notify disabled, enable autoWho according to configuration
985         setAutoWhoEnabled(networkConfig()->autoWhoEnabled());
986     }
987 }
988
989 void CoreNetwork::queueCap(const QString &capability)
990 {
991     // IRCv3 specs all use lowercase capability names
992     QString _capLowercase = capability.toLower();
993
994     if(capsRequiringConfiguration.contains(_capLowercase)) {
995         // The capability requires additional configuration before being acknowledged (e.g. SASL),
996         // so we should negotiate it separately from all other capabilities.  Otherwise new
997         // capabilities will be requested while still configuring the previous one.
998         if (!_capsQueuedIndividual.contains(_capLowercase)) {
999             _capsQueuedIndividual.append(_capLowercase);
1000         }
1001     } else {
1002         // The capability doesn't need any special configuration, so it should be safe to try
1003         // bundling together with others.  "Should" being the imperative word, as IRC servers can do
1004         // anything.
1005         if (!_capsQueuedBundled.contains(_capLowercase)) {
1006             _capsQueuedBundled.append(_capLowercase);
1007         }
1008     }
1009 }
1010
1011 QString CoreNetwork::takeQueuedCaps()
1012 {
1013     // Clear the record of the most recently negotiated capability bundle.  Does nothing if the list
1014     // is empty.
1015     _capsQueuedLastBundle.clear();
1016
1017     // First, negotiate all the standalone capabilities that require additional configuration.
1018     if (!_capsQueuedIndividual.empty()) {
1019         // We have an individual capability available.  Take the first and pass it back.
1020         return _capsQueuedIndividual.takeFirst();
1021     } else if (!_capsQueuedBundled.empty()) {
1022         // We have capabilities available that can be grouped.  Try to fit in as many as within the
1023         // maximum length.
1024         // See CoreNetwork::maxCapRequestLength
1025
1026         // Response must have at least one capability regardless of max length for anything to
1027         // happen.
1028         QString capBundle = _capsQueuedBundled.takeFirst();
1029         QString nextCap("");
1030         while (!_capsQueuedBundled.empty()) {
1031             // As long as capabilities remain, get the next...
1032             nextCap = _capsQueuedBundled.first();
1033             if ((capBundle.length() + 1 + nextCap.length()) <= maxCapRequestLength) {
1034                 // [capability + 1 for a space + this new capability] fit within length limits
1035                 // Add it to formatted list
1036                 capBundle.append(" " + nextCap);
1037                 // Add it to most recent bundle of requested capabilities (simplifies retry logic)
1038                 _capsQueuedLastBundle.append(nextCap);
1039                 // Then remove it from the queue
1040                 _capsQueuedBundled.removeFirst();
1041             } else {
1042                 // We've reached the length limit for a single capability request, stop adding more
1043                 break;
1044             }
1045         }
1046         // Return this space-separated set of capabilities, removing any extra spaces
1047         return capBundle.trimmed();
1048     } else {
1049         // No capabilities left to negotiate, return an empty string.
1050         return QString();
1051     }
1052 }
1053
1054 void CoreNetwork::retryCapsIndividually()
1055 {
1056     // The most recent set of capabilities got denied by the IRC server.  As we don't know what got
1057     // denied, try each capability individually.
1058     if (_capsQueuedLastBundle.empty()) {
1059         // No most recently tried capability set, just return.
1060         return;
1061         // Note: there's little point in retrying individually requested caps during negotiation.
1062         // We know the individual capability was the one that failed, and it's not likely it'll
1063         // suddenly start working within a few seconds.  'cap-notify' provides a better system for
1064         // handling capability removal and addition.
1065     }
1066
1067     // This should be fairly rare, e.g. services restarting during negotiation, so simplicity wins
1068     // over efficiency.  If this becomes an issue, implement a binary splicing system instead,
1069     // keeping track of which halves of the group fail, dividing the set each time.
1070
1071     // Add most recently tried capability set to individual list, re-requesting them one at a time
1072     _capsQueuedIndividual.append(_capsQueuedLastBundle);
1073     // Warn of this issue to explain the slower login.  Servers usually shouldn't trigger this.
1074     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1075                tr("Could not negotiate some capabilities, retrying individually (%1)...")
1076                .arg(_capsQueuedLastBundle.join(", ")));
1077     // Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
1078     // need to remove them here.
1079     // Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
1080     // indefinitely.
1081     _capsQueuedLastBundle.clear();
1082 }
1083
1084 void CoreNetwork::beginCapNegotiation()
1085 {
1086     // Don't begin negotiation if no capabilities are queued to request
1087     if (!capNegotiationInProgress()) {
1088         // If the server doesn't have any capabilities, but supports CAP LS, continue on with the
1089         // normal connection.
1090         displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("No capabilities available"));
1091         endCapNegotiation();
1092         return;
1093     }
1094
1095     _capNegotiationActive = true;
1096     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1097                tr("Ready to negotiate (found: %1)").arg(caps().join(", ")));
1098
1099     // Build a list of queued capabilities, starting with individual, then bundled, only adding the
1100     // comma separator between the two if needed.
1101     QString queuedCapsDisplay =
1102             (!_capsQueuedIndividual.empty() ? _capsQueuedIndividual.join(", ") + ", " : "")
1103             + _capsQueuedBundled.join(", ");
1104     displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1105                tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
1106
1107     sendNextCap();
1108 }
1109
1110 void CoreNetwork::sendNextCap()
1111 {
1112     if (capNegotiationInProgress()) {
1113         // Request the next set of capabilities and remove them from the list
1114         putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
1115     } else {
1116         // No pending desired capabilities, capability negotiation finished
1117         // If SASL requested but not available, print a warning
1118         if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
1119             displayMsg(Message::Error, BufferInfo::StatusBuffer, "",
1120                        tr("SASL authentication currently not supported by server"));
1121
1122         if (_capNegotiationActive) {
1123             displayMsg(Message::Server, BufferInfo::StatusBuffer, "",
1124                    tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
1125             _capNegotiationActive = false;
1126         }
1127
1128         endCapNegotiation();
1129     }
1130 }
1131
1132 void CoreNetwork::endCapNegotiation()
1133 {
1134     // If nick registration is already complete, CAP END is not required
1135     if (!_capInitialNegotiationEnded) {
1136         putRawLine(serverEncode(QString("CAP END")));
1137         _capInitialNegotiationEnded = true;
1138     }
1139 }
1140
1141 /******** AutoWHO ********/
1142
1143 void CoreNetwork::startAutoWhoCycle()
1144 {
1145     if (!_autoWhoQueue.isEmpty()) {
1146         _autoWhoCycleTimer.stop();
1147         return;
1148     }
1149     _autoWhoQueue = channels();
1150 }
1151
1152 void CoreNetwork::queueAutoWhoOneshot(const QString &channelOrNick)
1153 {
1154     // Prepend so these new channels/nicks are the first to be checked
1155     // Don't allow duplicates
1156     if (!_autoWhoQueue.contains(channelOrNick.toLower())) {
1157         _autoWhoQueue.prepend(channelOrNick.toLower());
1158     }
1159     if (capEnabled(IrcCap::AWAY_NOTIFY)) {
1160         // When away-notify is active, the timer's stopped.  Start a new cycle to who this channel.
1161         setAutoWhoEnabled(true);
1162     }
1163 }
1164
1165
1166 void CoreNetwork::setAutoWhoDelay(int delay)
1167 {
1168     _autoWhoTimer.setInterval(delay * 1000);
1169 }
1170
1171
1172 void CoreNetwork::setAutoWhoInterval(int interval)
1173 {
1174     _autoWhoCycleTimer.setInterval(interval * 1000);
1175 }
1176
1177
1178 void CoreNetwork::setAutoWhoEnabled(bool enabled)
1179 {
1180     if (enabled && isConnected() && !_autoWhoTimer.isActive())
1181         _autoWhoTimer.start();
1182     else if (!enabled) {
1183         _autoWhoTimer.stop();
1184         _autoWhoCycleTimer.stop();
1185     }
1186 }
1187
1188
1189 void CoreNetwork::sendAutoWho()
1190 {
1191     // Don't send autowho if there are still some pending
1192     if (_autoWhoPending.count())
1193         return;
1194
1195     while (!_autoWhoQueue.isEmpty()) {
1196         QString chanOrNick = _autoWhoQueue.takeFirst();
1197         // Check if it's a known channel or nick
1198         IrcChannel *ircchan = ircChannel(chanOrNick);
1199         IrcUser *ircuser = ircUser(chanOrNick);
1200         if (ircchan) {
1201             // Apply channel limiting rules
1202             // If using away-notify, don't impose channel size limits in order to capture away
1203             // state of everyone.  Auto-who won't run on a timer so network impact is minimal.
1204             if (networkConfig()->autoWhoNickLimit() > 0
1205                 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
1206                 && !capEnabled(IrcCap::AWAY_NOTIFY))
1207                 continue;
1208             _autoWhoPending[chanOrNick.toLower()]++;
1209         } else if (ircuser) {
1210             // Checking a nick, add it to the pending list
1211             _autoWhoPending[ircuser->nick().toLower()]++;
1212         } else {
1213             // Not a channel or a nick, skip it
1214             qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
1215             continue;
1216         }
1217         if (supports("WHOX")) {
1218             // Use WHO extended to poll away users and/or user accounts
1219             // See http://faerion.sourceforge.net/doc/irc/whox.var
1220             // And https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
1221             putRawLine(serverEncode(QString("WHO %1 %%chtsunfra,%2")
1222                                     .arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
1223         } else {
1224             putRawLine(serverEncode(QString("WHO %1").arg(chanOrNick)));
1225         }
1226         break;
1227     }
1228
1229     if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
1230         && !capEnabled(IrcCap::AWAY_NOTIFY)) {
1231         // Timer was stopped, means a new cycle is due immediately
1232         // Don't run a new cycle if using away-notify; server will notify as appropriate
1233         _autoWhoCycleTimer.start();
1234         startAutoWhoCycle();
1235     } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
1236         // Don't run another who cycle if away-notify is enabled
1237         _autoWhoCycleTimer.stop();
1238     }
1239 }
1240
1241
1242 #ifdef HAVE_SSL
1243 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors)
1244 {
1245     Server server = usedServer();
1246     if (server.sslVerify) {
1247         // Treat the SSL error as a hard error
1248         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, disconnecting "
1249                                      "since verification is required");
1250         if (!sslErrors.empty()) {
1251             // Add the error reason if known
1252             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1253         }
1254         displayMsg(Message::Error, BufferInfo::StatusBuffer, "", sslErrorMessage);
1255
1256         // Disconnect, triggering a reconnect in case it's a temporary issue with certificate
1257         // validity, network trouble, etc.
1258         disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
1259     } else {
1260         // Treat the SSL error as a warning, continue to connect anyways
1261         QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
1262                                      "since verification is not required");
1263         if (!sslErrors.empty()) {
1264             // Add the error reason if known
1265             sslErrorMessage.append(tr(" (Reason: %1)").arg(sslErrors.first().errorString()));
1266         }
1267         displayMsg(Message::Info, BufferInfo::StatusBuffer, "", sslErrorMessage);
1268
1269         // Proceed with the connection
1270         socket.ignoreSslErrors();
1271     }
1272 }
1273
1274
1275 #endif  // HAVE_SSL
1276
1277 void CoreNetwork::fillBucketAndProcessQueue()
1278 {
1279     if (_tokenBucket < _burstSize) {
1280         _tokenBucket++;
1281     }
1282
1283     while (_msgQueue.size() > 0 && _tokenBucket > 0) {
1284         writeToSocket(_msgQueue.takeFirst());
1285     }
1286 }
1287
1288
1289 void CoreNetwork::writeToSocket(const QByteArray &data)
1290 {
1291     socket.write(data);
1292     socket.write("\r\n");
1293     _tokenBucket--;
1294 }
1295
1296
1297 Network::Server CoreNetwork::usedServer() const
1298 {
1299     if (_lastUsedServerIndex < serverList().count())
1300         return serverList()[_lastUsedServerIndex];
1301
1302     if (!serverList().isEmpty())
1303         return serverList()[0];
1304
1305     return Network::Server();
1306 }
1307
1308
1309 void CoreNetwork::requestConnect() const
1310 {
1311     if (connectionState() != Disconnected) {
1312         qWarning() << "Requesting connect while already being connected!";
1313         return;
1314     }
1315     QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
1316 }
1317
1318
1319 void CoreNetwork::requestDisconnect() const
1320 {
1321     if (connectionState() == Disconnected) {
1322         qWarning() << "Requesting disconnect while not being connected!";
1323         return;
1324     }
1325     userInputHandler()->handleQuit(BufferInfo(), QString());
1326 }
1327
1328
1329 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
1330 {
1331     Network::Server currentServer = usedServer();
1332     setNetworkInfo(info);
1333     Core::updateNetwork(coreSession()->user(), info);
1334
1335     // the order of the servers might have changed,
1336     // so we try to find the previously used server
1337     _lastUsedServerIndex = 0;
1338     for (int i = 0; i < serverList().count(); i++) {
1339         Network::Server server = serverList()[i];
1340         if (server.host == currentServer.host && server.port == currentServer.port) {
1341             _lastUsedServerIndex = i;
1342             break;
1343         }
1344     }
1345 }
1346
1347
1348 QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator)
1349 {
1350     QString wrkMsg(message);
1351     QList<QList<QByteArray>> msgsToSend;
1352
1353     // do while (wrkMsg.size() > 0)
1354     do {
1355         // First, check to see if the whole message can be sent at once.  The
1356         // cmdGenerator function is passed in by the caller and is used to encode
1357         // and encrypt (if applicable) the message, since different callers might
1358         // want to use different encoding or encode different values.
1359         int splitPos = wrkMsg.size();
1360         QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg);
1361         int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc);
1362
1363         if (initialOverrun) {
1364             // If the message was too long to be sent, first try splitting it along
1365             // word boundaries with QTextBoundaryFinder.
1366             QString splitMsg(wrkMsg);
1367             QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg);
1368             qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1369             QList<QByteArray> splitMsgEnc;
1370             int overrun = initialOverrun;
1371
1372             while (overrun) {
1373                 splitPos = qtbf.toPreviousBoundary();
1374
1375                 // splitPos==-1 means the QTBF couldn't find a split point at all and
1376                 // splitPos==0 means the QTBF could only find a boundary at the beginning of
1377                 // the string.  Neither one of these works for us.
1378                 if (splitPos > 0) {
1379                     // If a split point could be found, split the message there, calculate the
1380                     // overrun, and continue with the loop.
1381                     splitMsg = splitMsg.left(splitPos);
1382                     splitMsgEnc = cmdGenerator(splitMsg);
1383                     overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc);
1384                 }
1385                 else {
1386                     // If a split point could not be found (the beginning of the message
1387                     // is reached without finding a split point short enough to send) and we
1388                     // are still in Word mode, switch to Grapheme mode.  We also need to restore
1389                     // the full wrkMsg to splitMsg, since splitMsg may have been cut down during
1390                     // the previous attempt to find a split point.
1391                     if (qtbf.type() == QTextBoundaryFinder::Word) {
1392                         splitMsg = wrkMsg;
1393                         splitPos = splitMsg.size();
1394                         QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg);
1395                         graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun);
1396                         qtbf = graphemeQtbf;
1397                     }
1398                     else {
1399                         // If the QTBF fails to find a split point in Grapheme mode, we give up.
1400                         // This should never happen, but it should be handled anyway.
1401                         qWarning() << "Unexpected failure to split message!";
1402                         return msgsToSend;
1403                     }
1404                 }
1405             }
1406
1407             // Once a message of sendable length has been found, remove it from the wrkMsg and
1408             // add it to the list of messages to be sent.
1409             wrkMsg.remove(0, splitPos);
1410             msgsToSend.append(splitMsgEnc);
1411         }
1412         else{
1413             // If the entire remaining message is short enough to be sent all at once, remove
1414             // it from the wrkMsg and add it to the list of messages to be sent.
1415             wrkMsg.remove(0, splitPos);
1416             msgsToSend.append(initialSplitMsgEnc);
1417         }
1418     } while (wrkMsg.size() > 0);
1419
1420     return msgsToSend;
1421 }