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