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