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