c4019cc83e66feeb16e5cf854f1b8dfafc7f83f1
[quassel.git] / src / common / network.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 <QTextCodec>
22
23 #include "network.h"
24 #include "peer.h"
25
26 QTextCodec *Network::_defaultCodecForServer = 0;
27 QTextCodec *Network::_defaultCodecForEncoding = 0;
28 QTextCodec *Network::_defaultCodecForDecoding = 0;
29
30 // ====================
31 //  Public:
32 // ====================
33 INIT_SYNCABLE_OBJECT(Network)
34 Network::Network(const NetworkId &networkid, QObject *parent)
35     : SyncableObject(parent),
36     _proxy(0),
37     _networkId(networkid),
38     _identity(0),
39     _myNick(QString()),
40     _latency(0),
41     _networkName(QString("<not initialized>")),
42     _currentServer(QString()),
43     _connected(false),
44     _connectionState(Disconnected),
45     _prefixes(QString()),
46     _prefixModes(QString()),
47     _useRandomServer(false),
48     _useAutoIdentify(false),
49     _useSasl(false),
50     _useAutoReconnect(false),
51     _autoReconnectInterval(60),
52     _autoReconnectRetries(10),
53     _unlimitedReconnectRetries(false),
54     _useCustomMessageRate(false),
55     _messageRateBurstSize(5),
56     _messageRateDelay(2200),
57     _unlimitedMessageRate(false),
58     _codecForServer(0),
59     _codecForEncoding(0),
60     _codecForDecoding(0),
61     _autoAwayActive(false)
62 {
63     setObjectName(QString::number(networkid.toInt()));
64 }
65
66
67 Network::~Network()
68 {
69     emit aboutToBeDestroyed();
70 }
71
72
73 bool Network::isChannelName(const QString &channelname) const
74 {
75     if (channelname.isEmpty())
76         return false;
77
78     if (supports("CHANTYPES"))
79         return support("CHANTYPES").contains(channelname[0]);
80     else
81         return QString("#&!+").contains(channelname[0]);
82 }
83
84
85 bool Network::isStatusMsg(const QString &target) const
86 {
87     if (target.isEmpty())
88         return false;
89
90     if (supports("STATUSMSG"))
91         return support("STATUSMSG").contains(target[0]);
92     else
93         return QString("@+").contains(target[0]);
94 }
95
96
97 NetworkInfo Network::networkInfo() const
98 {
99     NetworkInfo info;
100     info.networkName = networkName();
101     info.networkId = networkId();
102     info.identity = identity();
103     info.codecForServer = codecForServer();
104     info.codecForEncoding = codecForEncoding();
105     info.codecForDecoding = codecForDecoding();
106     info.serverList = serverList();
107     info.useRandomServer = useRandomServer();
108     info.perform = perform();
109     info.useAutoIdentify = useAutoIdentify();
110     info.autoIdentifyService = autoIdentifyService();
111     info.autoIdentifyPassword = autoIdentifyPassword();
112     info.useSasl = useSasl();
113     info.saslAccount = saslAccount();
114     info.saslPassword = saslPassword();
115     info.useAutoReconnect = useAutoReconnect();
116     info.autoReconnectInterval = autoReconnectInterval();
117     info.autoReconnectRetries = autoReconnectRetries();
118     info.unlimitedReconnectRetries = unlimitedReconnectRetries();
119     info.rejoinChannels = rejoinChannels();
120     info.useCustomMessageRate = useCustomMessageRate();
121     info.messageRateBurstSize = messageRateBurstSize();
122     info.messageRateDelay = messageRateDelay();
123     info.unlimitedMessageRate = unlimitedMessageRate();
124     return info;
125 }
126
127
128 void Network::setNetworkInfo(const NetworkInfo &info)
129 {
130     // we don't set our ID!
131     if (!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
132     if (info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
133     if (info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer));
134     if (info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
135     if (info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
136     if (info.serverList.count()) setServerList(toVariantList(info.serverList));  // FIXME compare components
137     if (info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer);
138     if (info.perform != perform()) setPerform(info.perform);
139     if (info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify);
140     if (info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService);
141     if (info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword);
142     if (info.useSasl != useSasl()) setUseSasl(info.useSasl);
143     if (info.saslAccount != saslAccount()) setSaslAccount(info.saslAccount);
144     if (info.saslPassword != saslPassword()) setSaslPassword(info.saslPassword);
145     if (info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect);
146     if (info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval);
147     if (info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries);
148     if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
149     if (info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels);
150     // Custom rate limiting
151     if (info.useCustomMessageRate != useCustomMessageRate())
152         setUseCustomMessageRate(info.useCustomMessageRate);
153     if (info.messageRateBurstSize != messageRateBurstSize())
154         setMessageRateBurstSize(info.messageRateBurstSize);
155     if (info.messageRateDelay != messageRateDelay())
156         setMessageRateDelay(info.messageRateDelay);
157     if (info.unlimitedMessageRate != unlimitedMessageRate())
158         setUnlimitedMessageRate(info.unlimitedMessageRate);
159 }
160
161
162 QString Network::prefixToMode(const QString &prefix) const
163 {
164     if (prefixes().contains(prefix))
165         return QString(prefixModes()[prefixes().indexOf(prefix)]);
166     else
167         return QString();
168 }
169
170
171 QString Network::modeToPrefix(const QString &mode) const
172 {
173     if (prefixModes().contains(mode))
174         return QString(prefixes()[prefixModes().indexOf(mode)]);
175     else
176         return QString();
177 }
178
179
180 QStringList Network::nicks() const
181 {
182     // we don't use _ircUsers.keys() since the keys may be
183     // not up to date after a nick change
184     QStringList nicks;
185     foreach(IrcUser *ircuser, _ircUsers.values()) {
186         nicks << ircuser->nick();
187     }
188     return nicks;
189 }
190
191
192 QString Network::prefixes() const
193 {
194     if (_prefixes.isNull())
195         determinePrefixes();
196
197     return _prefixes;
198 }
199
200
201 QString Network::prefixModes() const
202 {
203     if (_prefixModes.isNull())
204         determinePrefixes();
205
206     return _prefixModes;
207 }
208
209
210 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
211 Network::ChannelModeType Network::channelModeType(const QString &mode)
212 {
213     if (mode.isEmpty())
214         return NOT_A_CHANMODE;
215
216     QString chanmodes = support("CHANMODES");
217     if (chanmodes.isEmpty())
218         return NOT_A_CHANMODE;
219
220     ChannelModeType modeType = A_CHANMODE;
221     for (int i = 0; i < chanmodes.count(); i++) {
222         if (chanmodes[i] == mode[0])
223             break;
224         else if (chanmodes[i] == ',')
225             modeType = (ChannelModeType)(modeType << 1);
226     }
227     if (modeType > D_CHANMODE) {
228         qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
229         modeType = NOT_A_CHANMODE;
230     }
231     return modeType;
232 }
233
234
235 QString Network::support(const QString &param) const
236 {
237     QString support_ = param.toUpper();
238     if (_supports.contains(support_))
239         return _supports[support_];
240     else
241         return QString();
242 }
243
244
245 bool Network::saslMaybeSupports(const QString &saslMechanism) const
246 {
247     if (!capAvailable(IrcCap::SASL)) {
248         // If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs.
249         // Unfortunately, we don't know for sure, but Quassel won't request SASL without it being
250         // advertised, anyways.
251         // This may also occur if the network's disconnected or negotiation hasn't yet happened.
252         return false;
253     }
254
255     // Get the SASL capability value
256     QString saslCapValue = capValue(IrcCap::SASL);
257     // SASL mechanisms are only specified in capability values as part of SASL 3.2.  In SASL 3.1,
258     // it's handled differently.  If we don't know via capability value, assume it's supported to
259     // reduce the risk of breaking existing setups.
260     // See: http://ircv3.net/specs/extensions/sasl-3.1.html
261     // And: http://ircv3.net/specs/extensions/sasl-3.2.html
262     return (saslCapValue.length() == 0)
263             || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
264 }
265
266
267 IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData)
268 {
269     QString nick(nickFromMask(hostmask).toLower());
270     if (!_ircUsers.contains(nick)) {
271         IrcUser *ircuser = ircUserFactory(hostmask);
272         if (!initData.isEmpty()) {
273             ircuser->fromVariantMap(initData);
274             ircuser->setInitialized();
275         }
276
277         if (proxy())
278             proxy()->synchronize(ircuser);
279         else
280             qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
281
282         connect(ircuser, SIGNAL(nickSet(QString)), this, SLOT(ircUserNickChanged(QString)));
283
284         _ircUsers[nick] = ircuser;
285
286         // This method will be called with a nick instead of hostmask by setInitIrcUsersAndChannels().
287         // Not a problem because initData contains all we need; however, making sure here to get the real
288         // hostmask out of the IrcUser afterwards.
289         QString mask = ircuser->hostmask();
290         SYNC_OTHER(addIrcUser, ARG(mask));
291         // emit ircUserAdded(mask);
292         emit ircUserAdded(ircuser);
293     }
294
295     return _ircUsers[nick];
296 }
297
298
299 IrcUser *Network::ircUser(QString nickname) const
300 {
301     nickname = nickname.toLower();
302     if (_ircUsers.contains(nickname))
303         return _ircUsers[nickname];
304     else
305         return 0;
306 }
307
308
309 void Network::removeIrcUser(IrcUser *ircuser)
310 {
311     QString nick = _ircUsers.key(ircuser);
312     if (nick.isNull())
313         return;
314
315     _ircUsers.remove(nick);
316     disconnect(ircuser, 0, this, 0);
317     ircuser->deleteLater();
318 }
319
320
321 void Network::removeIrcChannel(IrcChannel *channel)
322 {
323     QString chanName = _ircChannels.key(channel);
324     if (chanName.isNull())
325         return;
326
327     _ircChannels.remove(chanName);
328     disconnect(channel, 0, this, 0);
329     channel->deleteLater();
330 }
331
332
333 void Network::removeChansAndUsers()
334 {
335     QList<IrcUser *> users = ircUsers();
336     _ircUsers.clear();
337     QList<IrcChannel *> channels = ircChannels();
338     _ircChannels.clear();
339
340     qDeleteAll(users);
341     qDeleteAll(channels);
342 }
343
344
345 IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData)
346 {
347     if (!_ircChannels.contains(channelname.toLower())) {
348         IrcChannel *channel = ircChannelFactory(channelname);
349         if (!initData.isEmpty()) {
350             channel->fromVariantMap(initData);
351             channel->setInitialized();
352         }
353
354         if (proxy())
355             proxy()->synchronize(channel);
356         else
357             qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
358
359         _ircChannels[channelname.toLower()] = channel;
360
361         SYNC_OTHER(addIrcChannel, ARG(channelname))
362         // emit ircChannelAdded(channelname);
363         emit ircChannelAdded(channel);
364     }
365     return _ircChannels[channelname.toLower()];
366 }
367
368
369 IrcChannel *Network::ircChannel(QString channelname) const
370 {
371     channelname = channelname.toLower();
372     if (_ircChannels.contains(channelname))
373         return _ircChannels[channelname];
374     else
375         return 0;
376 }
377
378
379 QByteArray Network::defaultCodecForServer()
380 {
381     if (_defaultCodecForServer)
382         return _defaultCodecForServer->name();
383     return QByteArray();
384 }
385
386
387 void Network::setDefaultCodecForServer(const QByteArray &name)
388 {
389     _defaultCodecForServer = QTextCodec::codecForName(name);
390 }
391
392
393 QByteArray Network::defaultCodecForEncoding()
394 {
395     if (_defaultCodecForEncoding)
396         return _defaultCodecForEncoding->name();
397     return QByteArray();
398 }
399
400
401 void Network::setDefaultCodecForEncoding(const QByteArray &name)
402 {
403     _defaultCodecForEncoding = QTextCodec::codecForName(name);
404 }
405
406
407 QByteArray Network::defaultCodecForDecoding()
408 {
409     if (_defaultCodecForDecoding)
410         return _defaultCodecForDecoding->name();
411     return QByteArray();
412 }
413
414
415 void Network::setDefaultCodecForDecoding(const QByteArray &name)
416 {
417     _defaultCodecForDecoding = QTextCodec::codecForName(name);
418 }
419
420
421 QByteArray Network::codecForServer() const
422 {
423     if (_codecForServer)
424         return _codecForServer->name();
425     return QByteArray();
426 }
427
428
429 void Network::setCodecForServer(const QByteArray &name)
430 {
431     setCodecForServer(QTextCodec::codecForName(name));
432 }
433
434
435 void Network::setCodecForServer(QTextCodec *codec)
436 {
437     _codecForServer = codec;
438     QByteArray codecName = codecForServer();
439     SYNC_OTHER(setCodecForServer, ARG(codecName))
440     emit configChanged();
441 }
442
443
444 QByteArray Network::codecForEncoding() const
445 {
446     if (_codecForEncoding)
447         return _codecForEncoding->name();
448     return QByteArray();
449 }
450
451
452 void Network::setCodecForEncoding(const QByteArray &name)
453 {
454     setCodecForEncoding(QTextCodec::codecForName(name));
455 }
456
457
458 void Network::setCodecForEncoding(QTextCodec *codec)
459 {
460     _codecForEncoding = codec;
461     QByteArray codecName = codecForEncoding();
462     SYNC_OTHER(setCodecForEncoding, ARG(codecName))
463     emit configChanged();
464 }
465
466
467 QByteArray Network::codecForDecoding() const
468 {
469     if (_codecForDecoding)
470         return _codecForDecoding->name();
471     else return QByteArray();
472 }
473
474
475 void Network::setCodecForDecoding(const QByteArray &name)
476 {
477     setCodecForDecoding(QTextCodec::codecForName(name));
478 }
479
480
481 void Network::setCodecForDecoding(QTextCodec *codec)
482 {
483     _codecForDecoding = codec;
484     QByteArray codecName = codecForDecoding();
485     SYNC_OTHER(setCodecForDecoding, ARG(codecName))
486     emit configChanged();
487 }
488
489
490 // FIXME use server encoding if appropriate
491 QString Network::decodeString(const QByteArray &text) const
492 {
493     if (_codecForDecoding)
494         return ::decodeString(text, _codecForDecoding);
495     else return ::decodeString(text, _defaultCodecForDecoding);
496 }
497
498
499 QByteArray Network::encodeString(const QString &string) const
500 {
501     if (_codecForEncoding) {
502         return _codecForEncoding->fromUnicode(string);
503     }
504     if (_defaultCodecForEncoding) {
505         return _defaultCodecForEncoding->fromUnicode(string);
506     }
507     return string.toLatin1();
508 }
509
510
511 QString Network::decodeServerString(const QByteArray &text) const
512 {
513     if (_codecForServer)
514         return ::decodeString(text, _codecForServer);
515     else
516         return ::decodeString(text, _defaultCodecForServer);
517 }
518
519
520 QByteArray Network::encodeServerString(const QString &string) const
521 {
522     if (_codecForServer) {
523         return _codecForServer->fromUnicode(string);
524     }
525     if (_defaultCodecForServer) {
526         return _defaultCodecForServer->fromUnicode(string);
527     }
528     return string.toLatin1();
529 }
530
531
532 // ====================
533 //  Public Slots:
534 // ====================
535 void Network::setNetworkName(const QString &networkName)
536 {
537     _networkName = networkName;
538     SYNC(ARG(networkName))
539     emit networkNameSet(networkName);
540     emit configChanged();
541 }
542
543
544 void Network::setCurrentServer(const QString &currentServer)
545 {
546     _currentServer = currentServer;
547     SYNC(ARG(currentServer))
548     emit currentServerSet(currentServer);
549 }
550
551
552 void Network::setConnected(bool connected)
553 {
554     if (_connected == connected)
555         return;
556
557     _connected = connected;
558     if (!connected) {
559         setMyNick(QString());
560         setCurrentServer(QString());
561         removeChansAndUsers();
562     }
563     SYNC(ARG(connected))
564     emit connectedSet(connected);
565 }
566
567
568 //void Network::setConnectionState(ConnectionState state) {
569 void Network::setConnectionState(int state)
570 {
571     _connectionState = (ConnectionState)state;
572     //qDebug() << "netstate" << networkId() << networkName() << state;
573     SYNC(ARG(state))
574     emit connectionStateSet(_connectionState);
575 }
576
577
578 void Network::setMyNick(const QString &nickname)
579 {
580     _myNick = nickname;
581     if (!_myNick.isEmpty() && !ircUser(myNick())) {
582         newIrcUser(myNick());
583     }
584     SYNC(ARG(nickname))
585     emit myNickSet(nickname);
586 }
587
588
589 void Network::setLatency(int latency)
590 {
591     if (_latency == latency)
592         return;
593     _latency = latency;
594     SYNC(ARG(latency))
595 }
596
597
598 void Network::setIdentity(IdentityId id)
599 {
600     _identity = id;
601     SYNC(ARG(id))
602     emit identitySet(id);
603     emit configChanged();
604 }
605
606
607 void Network::setServerList(const QVariantList &serverList)
608 {
609     _serverList = fromVariantList<Server>(serverList);
610     SYNC(ARG(serverList))
611     emit configChanged();
612 }
613
614
615 void Network::setUseRandomServer(bool use)
616 {
617     _useRandomServer = use;
618     SYNC(ARG(use))
619     emit configChanged();
620 }
621
622
623 void Network::setPerform(const QStringList &perform)
624 {
625     _perform = perform;
626     SYNC(ARG(perform))
627     emit configChanged();
628 }
629
630
631 void Network::setUseAutoIdentify(bool use)
632 {
633     _useAutoIdentify = use;
634     SYNC(ARG(use))
635     emit configChanged();
636 }
637
638
639 void Network::setAutoIdentifyService(const QString &service)
640 {
641     _autoIdentifyService = service;
642     SYNC(ARG(service))
643     emit configChanged();
644 }
645
646
647 void Network::setAutoIdentifyPassword(const QString &password)
648 {
649     _autoIdentifyPassword = password;
650     SYNC(ARG(password))
651     emit configChanged();
652 }
653
654
655 void Network::setUseSasl(bool use)
656 {
657     _useSasl = use;
658     SYNC(ARG(use))
659     emit configChanged();
660 }
661
662
663 void Network::setSaslAccount(const QString &account)
664 {
665     _saslAccount = account;
666     SYNC(ARG(account))
667     emit configChanged();
668 }
669
670
671 void Network::setSaslPassword(const QString &password)
672 {
673     _saslPassword = password;
674     SYNC(ARG(password))
675     emit configChanged();
676 }
677
678
679 void Network::setUseAutoReconnect(bool use)
680 {
681     _useAutoReconnect = use;
682     SYNC(ARG(use))
683     emit configChanged();
684 }
685
686
687 void Network::setAutoReconnectInterval(quint32 interval)
688 {
689     _autoReconnectInterval = interval;
690     SYNC(ARG(interval))
691     emit configChanged();
692 }
693
694
695 void Network::setAutoReconnectRetries(quint16 retries)
696 {
697     _autoReconnectRetries = retries;
698     SYNC(ARG(retries))
699     emit configChanged();
700 }
701
702
703 void Network::setUnlimitedReconnectRetries(bool unlimited)
704 {
705     _unlimitedReconnectRetries = unlimited;
706     SYNC(ARG(unlimited))
707     emit configChanged();
708 }
709
710
711 void Network::setRejoinChannels(bool rejoin)
712 {
713     _rejoinChannels = rejoin;
714     SYNC(ARG(rejoin))
715     emit configChanged();
716 }
717
718
719 void Network::setUseCustomMessageRate(bool useCustomRate)
720 {
721     if (_useCustomMessageRate != useCustomRate) {
722         _useCustomMessageRate = useCustomRate;
723         SYNC(ARG(useCustomRate))
724         emit configChanged();
725         emit useCustomMessageRateSet(_useCustomMessageRate);
726     }
727 }
728
729
730 void Network::setMessageRateBurstSize(quint32 burstSize)
731 {
732     if (burstSize < 1) {
733         // Can't go slower than one message at a time.  Also blocks old clients from trying to set
734         // this to 0.
735         qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be "
736                     "non-zero positive, given" << burstSize;
737         return;
738     }
739     if (_messageRateBurstSize != burstSize) {
740         _messageRateBurstSize = burstSize;
741         SYNC(ARG(burstSize))
742         emit configChanged();
743         emit messageRateBurstSizeSet(_messageRateBurstSize);
744     }
745 }
746
747
748 void Network::setMessageRateDelay(quint32 messageDelay)
749 {
750     if (messageDelay == 0) {
751         // Nonsensical to have no delay - just check the Unlimited box instead.  Also blocks old
752         // clients from trying to set this to 0.
753         qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
754                     "positive, given" << messageDelay;
755         return;
756     }
757     if (_messageRateDelay != messageDelay) {
758         _messageRateDelay = messageDelay;
759         SYNC(ARG(messageDelay))
760         emit configChanged();
761         emit messageRateDelaySet(_messageRateDelay);
762     }
763 }
764
765
766 void Network::setUnlimitedMessageRate(bool unlimitedRate)
767 {
768     if (_unlimitedMessageRate != unlimitedRate) {
769         _unlimitedMessageRate = unlimitedRate;
770         SYNC(ARG(unlimitedRate))
771         emit configChanged();
772         emit unlimitedMessageRateSet(_unlimitedMessageRate);
773     }
774 }
775
776
777 void Network::addSupport(const QString &param, const QString &value)
778 {
779     if (!_supports.contains(param)) {
780         _supports[param] = value;
781         SYNC(ARG(param), ARG(value))
782     }
783 }
784
785
786 void Network::removeSupport(const QString &param)
787 {
788     if (_supports.contains(param)) {
789         _supports.remove(param);
790         SYNC(ARG(param))
791     }
792 }
793
794
795 QVariantMap Network::initSupports() const
796 {
797     QVariantMap supports;
798     QHashIterator<QString, QString> iter(_supports);
799     while (iter.hasNext()) {
800         iter.next();
801         supports[iter.key()] = iter.value();
802     }
803     return supports;
804 }
805
806 void Network::addCap(const QString &capability, const QString &value)
807 {
808     // IRCv3 specs all use lowercase capability names
809     QString _capLowercase = capability.toLower();
810     if (!_caps.contains(_capLowercase)) {
811         _caps[_capLowercase] = value;
812         SYNC(ARG(capability), ARG(value))
813         emit capAdded(_capLowercase);
814     }
815 }
816
817 void Network::acknowledgeCap(const QString &capability)
818 {
819     // IRCv3 specs all use lowercase capability names
820     QString _capLowercase = capability.toLower();
821     if (!_capsEnabled.contains(_capLowercase)) {
822         _capsEnabled.append(_capLowercase);
823         SYNC(ARG(capability))
824         emit capAcknowledged(_capLowercase);
825     }
826 }
827
828 void Network::removeCap(const QString &capability)
829 {
830     // IRCv3 specs all use lowercase capability names
831     QString _capLowercase = capability.toLower();
832     if (_caps.contains(_capLowercase)) {
833         // Remove from the list of available capabilities.
834         _caps.remove(_capLowercase);
835         // Remove it from the acknowledged list if it was previously acknowledged.  The SYNC call
836         // ensures this propogates to the other side.
837         // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
838         _capsEnabled.removeOne(_capLowercase);
839         SYNC(ARG(capability))
840         emit capRemoved(_capLowercase);
841     }
842 }
843
844 void Network::clearCaps()
845 {
846     // IRCv3 specs all use lowercase capability names
847     if (_caps.empty() && _capsEnabled.empty()) {
848         // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
849         return;
850     }
851     // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
852     // If performance issues arise, this can be converted to a more-efficient setup without breaking
853     // protocol (in theory).
854     QString _capLowercase;
855     foreach (const QString &capability, _caps) {
856         _capLowercase = capability.toLower();
857         emit capRemoved(_capLowercase);
858     }
859     // Clear capabilities from the stored list
860     _caps.clear();
861     _capsEnabled.clear();
862
863     SYNC(NO_ARG)
864 }
865
866 QVariantMap Network::initCaps() const
867 {
868     QVariantMap caps;
869     QHashIterator<QString, QString> iter(_caps);
870     while (iter.hasNext()) {
871         iter.next();
872         caps[iter.key()] = iter.value();
873     }
874     return caps;
875 }
876
877
878 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
879 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
880 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
881 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
882 // (without compression) with a decent amount of IrcUsers.
883 QVariantMap Network::initIrcUsersAndChannels() const
884 {
885     Q_ASSERT(proxy());
886     Q_ASSERT(proxy()->targetPeer());
887     QVariantMap usersAndChannels;
888
889     if (_ircUsers.count()) {
890         QHash<QString, QVariantList> users;
891         QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
892         QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
893         while (it != end) {
894             QVariantMap map = it.value()->toVariantMap();
895             // If the peer doesn't support LongTime, replace the lastAwayMessage field
896             // with the 32-bit numerical seconds value used in older versions
897             if (!proxy()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
898 #if QT_VERSION >= 0x050800
899                 int lastAwayMessage = it.value()->lastAwayMessage().toSecsSinceEpoch();
900 #else
901                 // toSecsSinceEpoch() was added in Qt 5.8.  Manually downconvert to seconds for now.
902                 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
903                 int lastAwayMessage = it.value()->lastAwayMessage().toMSecsSinceEpoch() / 1000;
904 #endif
905                 map["lastAwayMessage"] = lastAwayMessage;
906             }
907
908             QVariantMap::const_iterator mapiter = map.begin();
909             while (mapiter != map.end()) {
910                 users[mapiter.key()] << mapiter.value();
911                 ++mapiter;
912             }
913             ++it;
914         }
915         // Can't have a container with a value type != QVariant in a QVariant :(
916         // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
917         QVariantMap userMap;
918         foreach(const QString &key, users.keys())
919             userMap[key] = users[key];
920         usersAndChannels["Users"] = userMap;
921     }
922
923     if (_ircChannels.count()) {
924         QHash<QString, QVariantList> channels;
925         QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
926         QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
927         while (it != end) {
928             const QVariantMap &map = it.value()->toVariantMap();
929             QVariantMap::const_iterator mapiter = map.begin();
930             while (mapiter != map.end()) {
931                 channels[mapiter.key()] << mapiter.value();
932                 ++mapiter;
933             }
934             ++it;
935         }
936         QVariantMap channelMap;
937         foreach(const QString &key, channels.keys())
938             channelMap[key] = channels[key];
939         usersAndChannels["Channels"] = channelMap;
940     }
941
942     return usersAndChannels;
943 }
944
945
946 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
947 {
948     Q_ASSERT(proxy());
949     Q_ASSERT(proxy()->sourcePeer());
950     if (isInitialized()) {
951         qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
952         return;
953     }
954
955     // toMap() and toList() are cheap, so we can avoid copying to lists...
956     // However, we really have to make sure to never accidentally detach from the shared data!
957
958     const QVariantMap &users = usersAndChannels["Users"].toMap();
959
960     // sanity check
961     int count = users["nick"].toList().count();
962     foreach(const QString &key, users.keys()) {
963         if (users[key].toList().count() != count) {
964             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
965             return;
966         }
967     }
968
969     // now create the individual IrcUsers
970     for(int i = 0; i < count; i++) {
971         QVariantMap map;
972         foreach(const QString &key, users.keys())
973             map[key] = users[key].toList().at(i);
974
975         // If the peer doesn't support LongTime, upconvert the lastAwayMessage field
976         // from the 32-bit numerical seconds value used in older versions to QDateTime
977         if (!proxy()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) {
978             QDateTime lastAwayMessage = QDateTime();
979             lastAwayMessage.setTimeSpec(Qt::UTC);
980 #if QT_VERSION >= 0x050800
981             lastAwayMessage.fromSecsSinceEpoch(map["lastAwayMessage"].toInt());
982 #else
983             // toSecsSinceEpoch() was added in Qt 5.8.  Manually downconvert to seconds for now.
984             // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
985             lastAwayMessage.fromMSecsSinceEpoch(map["lastAwayMessage"].toInt() * 1000);
986 #endif
987             map["lastAwayMessage"] = lastAwayMessage;
988         }
989
990         newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
991     }
992
993     // same thing for IrcChannels
994     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
995
996     // sanity check
997     count = channels["name"].toList().count();
998     foreach(const QString &key, channels.keys()) {
999         if (channels[key].toList().count() != count) {
1000             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
1001             return;
1002         }
1003     }
1004     // now create the individual IrcChannels
1005     for(int i = 0; i < count; i++) {
1006         QVariantMap map;
1007         foreach(const QString &key, channels.keys())
1008             map[key] = channels[key].toList().at(i);
1009         newIrcChannel(map["name"].toString(), map);
1010     }
1011 }
1012
1013
1014 void Network::initSetSupports(const QVariantMap &supports)
1015 {
1016     QMapIterator<QString, QVariant> iter(supports);
1017     while (iter.hasNext()) {
1018         iter.next();
1019         addSupport(iter.key(), iter.value().toString());
1020     }
1021 }
1022
1023
1024 void Network::initSetCaps(const QVariantMap &caps)
1025 {
1026     QMapIterator<QString, QVariant> iter(caps);
1027     while (iter.hasNext()) {
1028         iter.next();
1029         addCap(iter.key(), iter.value().toString());
1030     }
1031 }
1032
1033
1034 IrcUser *Network::updateNickFromMask(const QString &mask)
1035 {
1036     QString nick(nickFromMask(mask).toLower());
1037     IrcUser *ircuser;
1038
1039     if (_ircUsers.contains(nick)) {
1040         ircuser = _ircUsers[nick];
1041         ircuser->updateHostmask(mask);
1042     }
1043     else {
1044         ircuser = newIrcUser(mask);
1045     }
1046     return ircuser;
1047 }
1048
1049
1050 void Network::ircUserNickChanged(QString newnick)
1051 {
1052     QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
1053
1054     if (oldnick.isNull())
1055         return;
1056
1057     if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
1058
1059     if (myNick().toLower() == oldnick)
1060         setMyNick(newnick);
1061 }
1062
1063
1064 void Network::emitConnectionError(const QString &errorMsg)
1065 {
1066     emit connectionError(errorMsg);
1067 }
1068
1069
1070 // ====================
1071 //  Private:
1072 // ====================
1073 void Network::determinePrefixes() const
1074 {
1075     // seems like we have to construct them first
1076     QString prefix = support("PREFIX");
1077
1078     if (prefix.startsWith("(") && prefix.contains(")")) {
1079         _prefixes = prefix.section(")", 1);
1080         _prefixModes = prefix.mid(1).section(")", 0, 0);
1081     }
1082     else {
1083         QString defaultPrefixes("~&@%+");
1084         QString defaultPrefixModes("qaohv");
1085
1086         if (prefix.isEmpty()) {
1087             _prefixes = defaultPrefixes;
1088             _prefixModes = defaultPrefixModes;
1089             return;
1090         }
1091         // clear the existing modes, just in case we're run multiple times
1092         _prefixes = QString();
1093         _prefixModes = QString();
1094
1095         // we just assume that in PREFIX are only prefix chars stored
1096         for (int i = 0; i < defaultPrefixes.size(); i++) {
1097             if (prefix.contains(defaultPrefixes[i])) {
1098                 _prefixes += defaultPrefixes[i];
1099                 _prefixModes += defaultPrefixModes[i];
1100             }
1101         }
1102         // check for success
1103         if (!_prefixes.isNull())
1104             return;
1105
1106         // well... our assumption was obviously wrong...
1107         // check if it's only prefix modes
1108         for (int i = 0; i < defaultPrefixes.size(); i++) {
1109             if (prefix.contains(defaultPrefixModes[i])) {
1110                 _prefixes += defaultPrefixes[i];
1111                 _prefixModes += defaultPrefixModes[i];
1112             }
1113         }
1114         // now we've done all we've could...
1115     }
1116 }
1117
1118
1119 /************************************************************************
1120  * NetworkInfo
1121  ************************************************************************/
1122
1123 NetworkInfo::NetworkInfo()
1124     : networkId(0),
1125     identity(1),
1126     useRandomServer(false),
1127     useAutoIdentify(false),
1128     autoIdentifyService("NickServ"),
1129     useSasl(false),
1130     useAutoReconnect(true),
1131     autoReconnectInterval(60),
1132     autoReconnectRetries(20),
1133     unlimitedReconnectRetries(false),
1134     rejoinChannels(true),
1135     useCustomMessageRate(false),
1136     messageRateBurstSize(5),
1137     messageRateDelay(2200),
1138     unlimitedMessageRate(false)
1139 {
1140 }
1141
1142
1143 bool NetworkInfo::operator==(const NetworkInfo &other) const
1144 {
1145     if (networkId != other.networkId) return false;
1146     if (networkName != other.networkName) return false;
1147     if (identity != other.identity) return false;
1148     if (codecForServer != other.codecForServer) return false;
1149     if (codecForEncoding != other.codecForEncoding) return false;
1150     if (codecForDecoding != other.codecForDecoding) return false;
1151     if (serverList != other.serverList) return false;
1152     if (useRandomServer != other.useRandomServer) return false;
1153     if (perform != other.perform) return false;
1154     if (useAutoIdentify != other.useAutoIdentify) return false;
1155     if (autoIdentifyService != other.autoIdentifyService) return false;
1156     if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
1157     if (useSasl != other.useSasl) return false;
1158     if (saslAccount != other.saslAccount) return false;
1159     if (saslPassword != other.saslPassword) return false;
1160     if (useAutoReconnect != other.useAutoReconnect) return false;
1161     if (autoReconnectInterval != other.autoReconnectInterval) return false;
1162     if (autoReconnectRetries != other.autoReconnectRetries) return false;
1163     if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
1164     if (rejoinChannels != other.rejoinChannels) return false;
1165     // Custom rate limiting
1166     if (useCustomMessageRate != other.useCustomMessageRate) return false;
1167     if (messageRateBurstSize != other.messageRateBurstSize) return false;
1168     if (messageRateDelay != other.messageRateDelay) return false;
1169     if (unlimitedMessageRate != other.unlimitedMessageRate) return false;
1170     return true;
1171 }
1172
1173
1174 bool NetworkInfo::operator!=(const NetworkInfo &other) const
1175 {
1176     return !(*this == other);
1177 }
1178
1179
1180 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
1181 {
1182     QVariantMap i;
1183     i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
1184     i["NetworkName"] = info.networkName;
1185     i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
1186     i["CodecForServer"] = info.codecForServer;
1187     i["CodecForEncoding"] = info.codecForEncoding;
1188     i["CodecForDecoding"] = info.codecForDecoding;
1189     i["ServerList"] = toVariantList(info.serverList);
1190     i["UseRandomServer"] = info.useRandomServer;
1191     i["Perform"] = info.perform;
1192     i["UseAutoIdentify"] = info.useAutoIdentify;
1193     i["AutoIdentifyService"] = info.autoIdentifyService;
1194     i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1195     i["UseSasl"] = info.useSasl;
1196     i["SaslAccount"] = info.saslAccount;
1197     i["SaslPassword"] = info.saslPassword;
1198     i["UseAutoReconnect"] = info.useAutoReconnect;
1199     i["AutoReconnectInterval"] = info.autoReconnectInterval;
1200     i["AutoReconnectRetries"] = info.autoReconnectRetries;
1201     i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1202     i["RejoinChannels"] = info.rejoinChannels;
1203     // Custom rate limiting
1204     i["UseCustomMessageRate"] = info.useCustomMessageRate;
1205     i["MessageRateBurstSize"] = info.messageRateBurstSize;
1206     i["MessageRateDelay"] = info.messageRateDelay;
1207     i["UnlimitedMessageRate"] = info.unlimitedMessageRate;
1208     out << i;
1209     return out;
1210 }
1211
1212
1213 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
1214 {
1215     QVariantMap i;
1216     in >> i;
1217     info.networkId = i["NetworkId"].value<NetworkId>();
1218     info.networkName = i["NetworkName"].toString();
1219     info.identity = i["Identity"].value<IdentityId>();
1220     info.codecForServer = i["CodecForServer"].toByteArray();
1221     info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1222     info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1223     info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1224     info.useRandomServer = i["UseRandomServer"].toBool();
1225     info.perform = i["Perform"].toStringList();
1226     info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1227     info.autoIdentifyService = i["AutoIdentifyService"].toString();
1228     info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1229     info.useSasl = i["UseSasl"].toBool();
1230     info.saslAccount = i["SaslAccount"].toString();
1231     info.saslPassword = i["SaslPassword"].toString();
1232     info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1233     info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1234     info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1235     info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1236     info.rejoinChannels = i["RejoinChannels"].toBool();
1237     // Custom rate limiting
1238     info.useCustomMessageRate = i["UseCustomMessageRate"].toBool();
1239     info.messageRateBurstSize = i["MessageRateBurstSize"].toUInt();
1240     info.messageRateDelay = i["MessageRateDelay"].toUInt();
1241     info.unlimitedMessageRate = i["UnlimitedMessageRate"].toBool();
1242     return in;
1243 }
1244
1245
1246 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1247 {
1248     dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1249     << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1250     << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1251     << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1252     << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1253     << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1254     << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1255     << " rejoinChannels = " << i.rejoinChannels
1256     << " useCustomMessageRate = " << i.useCustomMessageRate
1257     << " messageRateBurstSize = " << i.messageRateBurstSize
1258     << " messageRateDelay = " << i.messageRateDelay
1259     << " unlimitedMessageRate = " << i.unlimitedMessageRate
1260     << ")";
1261     return dbg.space();
1262 }
1263
1264
1265 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1266 {
1267     QVariantMap serverMap;
1268     serverMap["Host"] = server.host;
1269     serverMap["Port"] = server.port;
1270     serverMap["Password"] = server.password;
1271     serverMap["UseSSL"] = server.useSsl;
1272     serverMap["sslVerify"] = server.sslVerify;
1273     serverMap["sslVersion"] = server.sslVersion;
1274     serverMap["UseProxy"] = server.useProxy;
1275     serverMap["ProxyType"] = server.proxyType;
1276     serverMap["ProxyHost"] = server.proxyHost;
1277     serverMap["ProxyPort"] = server.proxyPort;
1278     serverMap["ProxyUser"] = server.proxyUser;
1279     serverMap["ProxyPass"] = server.proxyPass;
1280     out << serverMap;
1281     return out;
1282 }
1283
1284
1285 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1286 {
1287     QVariantMap serverMap;
1288     in >> serverMap;
1289     server.host = serverMap["Host"].toString();
1290     server.port = serverMap["Port"].toUInt();
1291     server.password = serverMap["Password"].toString();
1292     server.useSsl = serverMap["UseSSL"].toBool();
1293     server.sslVerify = serverMap["sslVerify"].toBool();
1294     server.sslVersion = serverMap["sslVersion"].toInt();
1295     server.useProxy = serverMap["UseProxy"].toBool();
1296     server.proxyType = serverMap["ProxyType"].toInt();
1297     server.proxyHost = serverMap["ProxyHost"].toString();
1298     server.proxyPort = serverMap["ProxyPort"].toUInt();
1299     server.proxyUser = serverMap["ProxyUser"].toString();
1300     server.proxyPass = serverMap["ProxyPass"].toString();
1301     return in;
1302 }
1303
1304
1305 bool Network::Server::operator==(const Server &other) const
1306 {
1307     if (host != other.host) return false;
1308     if (port != other.port) return false;
1309     if (password != other.password) return false;
1310     if (useSsl != other.useSsl) return false;
1311     if (sslVerify != other.sslVerify) return false;
1312     if (sslVersion != other.sslVersion) return false;
1313     if (useProxy != other.useProxy) return false;
1314     if (proxyType != other.proxyType) return false;
1315     if (proxyHost != other.proxyHost) return false;
1316     if (proxyPort != other.proxyPort) return false;
1317     if (proxyUser != other.proxyUser) return false;
1318     if (proxyPass != other.proxyPass) return false;
1319     return true;
1320 }
1321
1322
1323 bool Network::Server::operator!=(const Server &other) const
1324 {
1325     return !(*this == other);
1326 }
1327
1328
1329 QDebug operator<<(QDebug dbg, const Network::Server &server)
1330 {
1331     dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " <<
1332                      server.useSsl << ", sslVerify = " << server.sslVerify << ")";
1333     return dbg.space();
1334 }