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