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