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