1 /***************************************************************************
2 * Copyright (C) 2005-2020 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
29 QTextCodec* Network::_defaultCodecForServer = nullptr;
30 QTextCodec* Network::_defaultCodecForEncoding = nullptr;
31 QTextCodec* Network::_defaultCodecForDecoding = nullptr;
33 // ====================
35 // ====================
37 Network::Network(const NetworkId& networkid, QObject* parent)
38 : SyncableObject(parent)
40 , _networkId(networkid)
44 , _networkName(QString("<not initialized>"))
45 , _currentServer(QString())
47 , _connectionState(Disconnected)
48 , _prefixes(QString())
49 , _prefixModes(QString())
50 , _useRandomServer(false)
51 , _useAutoIdentify(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)
66 setObjectName(QString::number(networkid.toInt()));
71 emit aboutToBeDestroyed();
74 bool Network::isChannelName(const QString& channelname) const
76 if (channelname.isEmpty())
79 if (supports("CHANTYPES"))
80 return support("CHANTYPES").contains(channelname[0]);
82 return QString("#&!+").contains(channelname[0]);
85 bool Network::isStatusMsg(const QString& target) const
90 if (supports("STATUSMSG"))
91 return support("STATUSMSG").contains(target[0]);
93 return QString("@+").contains(target[0]);
96 NetworkInfo Network::networkInfo() const
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.skipCaps = skipCaps();
109 info.useAutoIdentify = useAutoIdentify();
110 info.autoIdentifyService = autoIdentifyService();
111 info.autoIdentifyPassword = autoIdentifyPassword();
112 info.useSasl = useSasl();
113 info.saslAccount = saslAccount();
114 info.saslPassword = saslPassword();
115 info.useAutoReconnect = useAutoReconnect();
116 info.autoReconnectInterval = autoReconnectInterval();
117 info.autoReconnectRetries = autoReconnectRetries();
118 info.unlimitedReconnectRetries = unlimitedReconnectRetries();
119 info.rejoinChannels = rejoinChannels();
120 info.useCustomMessageRate = useCustomMessageRate();
121 info.messageRateBurstSize = messageRateBurstSize();
122 info.messageRateDelay = messageRateDelay();
123 info.unlimitedMessageRate = unlimitedMessageRate();
127 void Network::setNetworkInfo(const NetworkInfo& info)
129 // we don't set our ID!
130 if (!info.networkName.isEmpty() && info.networkName != networkName())
131 setNetworkName(info.networkName);
132 if (info.identity > 0 && info.identity != identity())
133 setIdentity(info.identity);
134 if (info.codecForServer != codecForServer())
135 setCodecForServer(QTextCodec::codecForName(info.codecForServer));
136 if (info.codecForEncoding != codecForEncoding())
137 setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
138 if (info.codecForDecoding != codecForDecoding())
139 setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
140 if (info.serverList.count())
141 setServerList(toVariantList(info.serverList)); // FIXME compare components
142 if (info.useRandomServer != useRandomServer())
143 setUseRandomServer(info.useRandomServer);
144 if (info.perform != perform())
145 setPerform(info.perform);
146 if (info.skipCaps != skipCaps())
147 setSkipCaps(info.skipCaps);
148 if (info.useAutoIdentify != useAutoIdentify())
149 setUseAutoIdentify(info.useAutoIdentify);
150 if (info.autoIdentifyService != autoIdentifyService())
151 setAutoIdentifyService(info.autoIdentifyService);
152 if (info.autoIdentifyPassword != autoIdentifyPassword())
153 setAutoIdentifyPassword(info.autoIdentifyPassword);
154 if (info.useSasl != useSasl())
155 setUseSasl(info.useSasl);
156 if (info.saslAccount != saslAccount())
157 setSaslAccount(info.saslAccount);
158 if (info.saslPassword != saslPassword())
159 setSaslPassword(info.saslPassword);
160 if (info.useAutoReconnect != useAutoReconnect())
161 setUseAutoReconnect(info.useAutoReconnect);
162 if (info.autoReconnectInterval != autoReconnectInterval())
163 setAutoReconnectInterval(info.autoReconnectInterval);
164 if (info.autoReconnectRetries != autoReconnectRetries())
165 setAutoReconnectRetries(info.autoReconnectRetries);
166 if (info.unlimitedReconnectRetries != unlimitedReconnectRetries())
167 setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
168 if (info.rejoinChannels != rejoinChannels())
169 setRejoinChannels(info.rejoinChannels);
170 // Custom rate limiting
171 if (info.useCustomMessageRate != useCustomMessageRate())
172 setUseCustomMessageRate(info.useCustomMessageRate);
173 if (info.messageRateBurstSize != messageRateBurstSize())
174 setMessageRateBurstSize(info.messageRateBurstSize);
175 if (info.messageRateDelay != messageRateDelay())
176 setMessageRateDelay(info.messageRateDelay);
177 if (info.unlimitedMessageRate != unlimitedMessageRate())
178 setUnlimitedMessageRate(info.unlimitedMessageRate);
181 QString Network::prefixToMode(const QString& prefix) const
183 if (prefixes().contains(prefix))
184 return QString(prefixModes()[prefixes().indexOf(prefix)]);
189 QString Network::modeToPrefix(const QString& mode) const
191 if (prefixModes().contains(mode))
192 return QString(prefixes()[prefixModes().indexOf(mode)]);
197 QString Network::sortPrefixModes(const QString& modes) const
199 // If modes is empty or we don't have any modes, nothing can be sorted, bail out early
200 if (modes.isEmpty() || prefixModes().isEmpty()) {
204 // Store a copy of the modes for modification
205 // QString should be efficient and not copy memory if nothing changes, but if mistaken,
206 // std::is_sorted could be called first.
207 QString sortedModes = QString(modes);
209 // Sort modes as if a QChar array
210 // See https://en.cppreference.com/w/cpp/algorithm/sort
211 // Defining lambda with [&] implicitly captures variables by reference
212 std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar& lmode, const QChar& rmode) {
213 // Compare characters according to prefix modes
214 // Return true if lmode comes before rmode (is "less than")
216 // Check for unknown modes...
217 if (!prefixModes().contains(lmode)) {
218 // Left mode not in prefix list, send to end
221 else if (!prefixModes().contains(rmode)) {
222 // Right mode not in prefix list, send to end
226 // Both characters known, sort according to index in prefixModes()
227 return (prefixModes().indexOf(lmode) < prefixModes().indexOf(rmode));
234 QStringList Network::nicks() const
236 // we don't use _ircUsers.keys() since the keys may be
237 // not up to date after a nick change
239 foreach (IrcUser* ircuser, _ircUsers.values()) {
240 nicks << ircuser->nick();
245 QString Network::prefixes() const
247 if (_prefixes.isNull())
253 QString Network::prefixModes() const
255 if (_prefixModes.isNull())
261 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
262 Network::ChannelModeType Network::channelModeType(const QString& mode)
265 return NOT_A_CHANMODE;
267 QString chanmodes = support("CHANMODES");
268 if (chanmodes.isEmpty())
269 return NOT_A_CHANMODE;
271 ChannelModeType modeType = A_CHANMODE;
272 for (int i = 0; i < chanmodes.count(); i++) {
273 if (chanmodes[i] == mode[0])
275 else if (chanmodes[i] == ',')
276 modeType = (ChannelModeType)(modeType << 1);
278 if (modeType > D_CHANMODE) {
279 qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
280 modeType = NOT_A_CHANMODE;
285 QString Network::support(const QString& param) const
287 QString support_ = param.toUpper();
288 if (_supports.contains(support_))
289 return _supports[support_];
294 bool Network::saslMaybeSupports(const QString& saslMechanism) const
296 if (!capAvailable(IrcCap::SASL)) {
297 // If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs.
298 // Unfortunately, we don't know for sure, but Quassel won't request SASL without it being
299 // advertised, anyways.
300 // This may also occur if the network's disconnected or negotiation hasn't yet happened.
304 // Get the SASL capability value
305 QString saslCapValue = capValue(IrcCap::SASL);
306 // SASL mechanisms are only specified in capability values as part of SASL 3.2. In SASL 3.1,
307 // it's handled differently. If we don't know via capability value, assume it's supported to
308 // reduce the risk of breaking existing setups.
309 // See: http://ircv3.net/specs/extensions/sasl-3.1.html
310 // And: http://ircv3.net/specs/extensions/sasl-3.2.html
311 return (saslCapValue.length() == 0) || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
314 IrcUser* Network::newIrcUser(const QString& hostmask, const QVariantMap& initData)
316 QString nick(nickFromMask(hostmask).toLower());
317 if (!_ircUsers.contains(nick)) {
318 IrcUser* ircuser = ircUserFactory(hostmask);
319 if (!initData.isEmpty()) {
320 ircuser->fromVariantMap(initData);
321 ircuser->setInitialized();
325 proxy()->synchronize(ircuser);
327 qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
329 connect(ircuser, &IrcUser::nickSet, this, &Network::ircUserNickChanged);
331 _ircUsers[nick] = ircuser;
333 // This method will be called with a nick instead of hostmask by setInitIrcUsersAndChannels().
334 // Not a problem because initData contains all we need; however, making sure here to get the real
335 // hostmask out of the IrcUser afterwards.
336 QString mask = ircuser->hostmask();
337 SYNC_OTHER(addIrcUser, ARG(mask));
338 // emit ircUserAdded(mask);
339 emit ircUserAdded(ircuser);
342 return _ircUsers[nick];
345 IrcUser* Network::ircUser(QString nickname) const
347 nickname = nickname.toLower();
348 if (_ircUsers.contains(nickname))
349 return _ircUsers[nickname];
354 void Network::removeIrcUser(IrcUser* ircuser)
356 QString nick = _ircUsers.key(ircuser);
360 _ircUsers.remove(nick);
361 disconnect(ircuser, nullptr, this, nullptr);
362 ircuser->deleteLater();
365 void Network::removeIrcChannel(IrcChannel* channel)
367 QString chanName = _ircChannels.key(channel);
368 if (chanName.isNull())
371 _ircChannels.remove(chanName);
372 disconnect(channel, nullptr, this, nullptr);
373 channel->deleteLater();
376 void Network::removeChansAndUsers()
378 QList<IrcUser*> users = ircUsers();
380 QList<IrcChannel*> channels = ircChannels();
381 _ircChannels.clear();
384 qDeleteAll(channels);
387 IrcChannel* Network::newIrcChannel(const QString& channelname, const QVariantMap& initData)
389 if (!_ircChannels.contains(channelname.toLower())) {
390 IrcChannel* channel = ircChannelFactory(channelname);
391 if (!initData.isEmpty()) {
392 channel->fromVariantMap(initData);
393 channel->setInitialized();
397 proxy()->synchronize(channel);
399 qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
401 _ircChannels[channelname.toLower()] = channel;
403 SYNC_OTHER(addIrcChannel, ARG(channelname))
404 // emit ircChannelAdded(channelname);
405 emit ircChannelAdded(channel);
407 return _ircChannels[channelname.toLower()];
410 IrcChannel* Network::ircChannel(QString channelname) const
412 channelname = channelname.toLower();
413 if (_ircChannels.contains(channelname))
414 return _ircChannels[channelname];
419 QByteArray Network::defaultCodecForServer()
421 if (_defaultCodecForServer)
422 return _defaultCodecForServer->name();
426 void Network::setDefaultCodecForServer(const QByteArray& name)
428 _defaultCodecForServer = QTextCodec::codecForName(name);
431 QByteArray Network::defaultCodecForEncoding()
433 if (_defaultCodecForEncoding)
434 return _defaultCodecForEncoding->name();
438 void Network::setDefaultCodecForEncoding(const QByteArray& name)
440 _defaultCodecForEncoding = QTextCodec::codecForName(name);
443 QByteArray Network::defaultCodecForDecoding()
445 if (_defaultCodecForDecoding)
446 return _defaultCodecForDecoding->name();
450 void Network::setDefaultCodecForDecoding(const QByteArray& name)
452 _defaultCodecForDecoding = QTextCodec::codecForName(name);
455 QByteArray Network::codecForServer() const
458 return _codecForServer->name();
462 void Network::setCodecForServer(const QByteArray& name)
464 setCodecForServer(QTextCodec::codecForName(name));
467 void Network::setCodecForServer(QTextCodec* codec)
469 _codecForServer = codec;
470 QByteArray codecName = codecForServer();
471 SYNC_OTHER(setCodecForServer, ARG(codecName))
472 emit configChanged();
475 QByteArray Network::codecForEncoding() const
477 if (_codecForEncoding)
478 return _codecForEncoding->name();
482 void Network::setCodecForEncoding(const QByteArray& name)
484 setCodecForEncoding(QTextCodec::codecForName(name));
487 void Network::setCodecForEncoding(QTextCodec* codec)
489 _codecForEncoding = codec;
490 QByteArray codecName = codecForEncoding();
491 SYNC_OTHER(setCodecForEncoding, ARG(codecName))
492 emit configChanged();
495 QByteArray Network::codecForDecoding() const
497 if (_codecForDecoding)
498 return _codecForDecoding->name();
503 void Network::setCodecForDecoding(const QByteArray& name)
505 setCodecForDecoding(QTextCodec::codecForName(name));
508 void Network::setCodecForDecoding(QTextCodec* codec)
510 _codecForDecoding = codec;
511 QByteArray codecName = codecForDecoding();
512 SYNC_OTHER(setCodecForDecoding, ARG(codecName))
513 emit configChanged();
516 // FIXME use server encoding if appropriate
517 QString Network::decodeString(const QByteArray& text) const
519 if (_codecForDecoding)
520 return ::decodeString(text, _codecForDecoding);
522 return ::decodeString(text, _defaultCodecForDecoding);
525 QByteArray Network::encodeString(const QString& string) const
527 if (_codecForEncoding) {
528 return _codecForEncoding->fromUnicode(string);
530 if (_defaultCodecForEncoding) {
531 return _defaultCodecForEncoding->fromUnicode(string);
533 return string.toLatin1();
536 QString Network::decodeServerString(const QByteArray& text) const
539 return ::decodeString(text, _codecForServer);
541 return ::decodeString(text, _defaultCodecForServer);
544 QByteArray Network::encodeServerString(const QString& string) const
546 if (_codecForServer) {
547 return _codecForServer->fromUnicode(string);
549 if (_defaultCodecForServer) {
550 return _defaultCodecForServer->fromUnicode(string);
552 return string.toLatin1();
555 // ====================
557 // ====================
558 void Network::setNetworkName(const QString& networkName)
560 _networkName = networkName;
561 SYNC(ARG(networkName))
562 emit networkNameSet(networkName);
563 emit configChanged();
566 void Network::setCurrentServer(const QString& currentServer)
568 _currentServer = currentServer;
569 SYNC(ARG(currentServer))
570 emit currentServerSet(currentServer);
573 void Network::setConnected(bool connected)
575 if (_connected == connected)
578 _connected = connected;
580 setMyNick(QString());
581 setCurrentServer(QString());
582 removeChansAndUsers();
585 emit connectedSet(connected);
588 // void Network::setConnectionState(ConnectionState state) {
589 void Network::setConnectionState(int state)
591 _connectionState = (ConnectionState)state;
592 // qDebug() << "netstate" << networkId() << networkName() << state;
594 emit connectionStateSet(_connectionState);
597 void Network::setMyNick(const QString& nickname)
600 if (!_myNick.isEmpty() && !ircUser(myNick())) {
601 newIrcUser(myNick());
604 emit myNickSet(nickname);
607 void Network::setLatency(int latency)
609 if (_latency == latency)
615 void Network::setIdentity(IdentityId id)
619 emit identitySet(id);
620 emit configChanged();
623 void Network::setServerList(const QVariantList& serverList)
625 _serverList = fromVariantList<Server>(serverList);
626 SYNC(ARG(serverList))
627 emit configChanged();
630 void Network::setUseRandomServer(bool use)
632 _useRandomServer = use;
634 emit configChanged();
637 void Network::setPerform(const QStringList& perform)
641 emit configChanged();
644 void Network::setSkipCaps(const QStringList& skipCaps)
646 _skipCaps = skipCaps;
647 // Ensure the list of skipped capabilities remains sorted
649 // This becomes important in CoreNetwork::beginCapNegotiation() when finding the intersection of
650 // available capabilities and skipped capabilities. It's a bit more efficient to sort on first
651 // initialization and changes afterwards instead of on every (re)connection to the IRC network.
654 emit configChanged();
657 void Network::setUseAutoIdentify(bool use)
659 _useAutoIdentify = use;
661 emit configChanged();
664 void Network::setAutoIdentifyService(const QString& service)
666 _autoIdentifyService = service;
668 emit configChanged();
671 void Network::setAutoIdentifyPassword(const QString& password)
673 _autoIdentifyPassword = password;
675 emit configChanged();
678 void Network::setUseSasl(bool use)
682 emit configChanged();
685 void Network::setSaslAccount(const QString& account)
687 _saslAccount = account;
689 emit configChanged();
692 void Network::setSaslPassword(const QString& password)
694 _saslPassword = password;
696 emit configChanged();
699 void Network::setUseAutoReconnect(bool use)
701 _useAutoReconnect = use;
703 emit configChanged();
706 void Network::setAutoReconnectInterval(quint32 interval)
708 _autoReconnectInterval = interval;
710 emit configChanged();
713 void Network::setAutoReconnectRetries(quint16 retries)
715 _autoReconnectRetries = retries;
717 emit configChanged();
720 void Network::setUnlimitedReconnectRetries(bool unlimited)
722 _unlimitedReconnectRetries = unlimited;
724 emit configChanged();
727 void Network::setRejoinChannels(bool rejoin)
729 _rejoinChannels = rejoin;
731 emit configChanged();
734 void Network::setUseCustomMessageRate(bool useCustomRate)
736 if (_useCustomMessageRate != useCustomRate) {
737 _useCustomMessageRate = useCustomRate;
738 SYNC(ARG(useCustomRate))
739 emit configChanged();
740 emit useCustomMessageRateSet(_useCustomMessageRate);
744 void Network::setMessageRateBurstSize(quint32 burstSize)
747 // Can't go slower than one message at a time. Also blocks old clients from trying to set
749 qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be "
750 "non-zero positive, given"
754 if (_messageRateBurstSize != burstSize) {
755 _messageRateBurstSize = burstSize;
757 emit configChanged();
758 emit messageRateBurstSizeSet(_messageRateBurstSize);
762 void Network::setMessageRateDelay(quint32 messageDelay)
764 if (messageDelay == 0) {
765 // Nonsensical to have no delay - just check the Unlimited box instead. Also blocks old
766 // clients from trying to set this to 0.
767 qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
772 if (_messageRateDelay != messageDelay) {
773 _messageRateDelay = messageDelay;
774 SYNC(ARG(messageDelay))
775 emit configChanged();
776 emit messageRateDelaySet(_messageRateDelay);
780 void Network::setUnlimitedMessageRate(bool unlimitedRate)
782 if (_unlimitedMessageRate != unlimitedRate) {
783 _unlimitedMessageRate = unlimitedRate;
784 SYNC(ARG(unlimitedRate))
785 emit configChanged();
786 emit unlimitedMessageRateSet(_unlimitedMessageRate);
790 void Network::addSupport(const QString& param, const QString& value)
792 if (!_supports.contains(param)) {
793 _supports[param] = value;
794 SYNC(ARG(param), ARG(value))
798 void Network::removeSupport(const QString& param)
800 if (_supports.contains(param)) {
801 _supports.remove(param);
806 QVariantMap Network::initSupports() const
808 QVariantMap supports;
809 QHashIterator<QString, QString> iter(_supports);
810 while (iter.hasNext()) {
812 supports[iter.key()] = iter.value();
817 void Network::addCap(const QString& capability, const QString& value)
819 // IRCv3 specs all use lowercase capability names
820 QString _capLowercase = capability.toLower();
821 if (!_caps.contains(_capLowercase)) {
822 _caps[_capLowercase] = value;
823 SYNC(ARG(capability), ARG(value))
824 emit capAdded(_capLowercase);
828 void Network::acknowledgeCap(const QString& capability)
830 // IRCv3 specs all use lowercase capability names
831 QString _capLowercase = capability.toLower();
832 if (!_capsEnabled.contains(_capLowercase)) {
833 _capsEnabled.append(_capLowercase);
834 SYNC(ARG(capability))
835 emit capAcknowledged(_capLowercase);
839 void Network::removeCap(const QString& capability)
841 // IRCv3 specs all use lowercase capability names
842 QString _capLowercase = capability.toLower();
843 if (_caps.contains(_capLowercase)) {
844 // Remove from the list of available capabilities.
845 _caps.remove(_capLowercase);
846 // Remove it from the acknowledged list if it was previously acknowledged. The SYNC call
847 // ensures this propogates to the other side.
848 // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
849 _capsEnabled.removeOne(_capLowercase);
850 SYNC(ARG(capability))
851 emit capRemoved(_capLowercase);
855 void Network::clearCaps()
857 // IRCv3 specs all use lowercase capability names
858 if (_caps.empty() && _capsEnabled.empty()) {
859 // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
862 // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
863 // If performance issues arise, this can be converted to a more-efficient setup without breaking
864 // protocol (in theory).
865 QString _capLowercase;
866 foreach (const QString& capability, _caps) {
867 _capLowercase = capability.toLower();
868 emit capRemoved(_capLowercase);
870 // Clear capabilities from the stored list
872 _capsEnabled.clear();
877 QVariantMap Network::initCaps() const
880 QHashIterator<QString, QString> iter(_caps);
881 while (iter.hasNext()) {
883 caps[iter.key()] = iter.value();
888 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
889 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
890 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
891 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
892 // (without compression) with a decent amount of IrcUsers.
893 QVariantMap Network::initIrcUsersAndChannels() const
896 Q_ASSERT(proxy()->targetPeer());
897 QVariantMap usersAndChannels;
899 if (_ircUsers.count()) {
900 QHash<QString, QVariantList> users;
901 QHash<QString, IrcUser*>::const_iterator it = _ircUsers.begin();
902 QHash<QString, IrcUser*>::const_iterator end = _ircUsers.end();
904 QVariantMap map = it.value()->toVariantMap();
905 // If the peer doesn't support LongTime, replace the lastAwayMessageTime field
906 // with the 32-bit numerical seconds value (lastAwayMessage) used in older versions
907 if (!proxy()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
908 #if QT_VERSION >= 0x050800
909 int lastAwayMessage = it.value()->lastAwayMessageTime().toSecsSinceEpoch();
911 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
912 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
913 int lastAwayMessage = it.value()->lastAwayMessageTime().toMSecsSinceEpoch() / 1000;
915 map.remove("lastAwayMessageTime");
916 map["lastAwayMessage"] = lastAwayMessage;
919 QVariantMap::const_iterator mapiter = map.begin();
920 while (mapiter != map.end()) {
921 users[mapiter.key()] << mapiter.value();
926 // Can't have a container with a value type != QVariant in a QVariant :(
927 // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
929 foreach (const QString& key, users.keys())
930 userMap[key] = users[key];
931 usersAndChannels["Users"] = userMap;
934 if (_ircChannels.count()) {
935 QHash<QString, QVariantList> channels;
936 QHash<QString, IrcChannel*>::const_iterator it = _ircChannels.begin();
937 QHash<QString, IrcChannel*>::const_iterator end = _ircChannels.end();
939 const QVariantMap& map = it.value()->toVariantMap();
940 QVariantMap::const_iterator mapiter = map.begin();
941 while (mapiter != map.end()) {
942 channels[mapiter.key()] << mapiter.value();
947 QVariantMap channelMap;
948 foreach (const QString& key, channels.keys())
949 channelMap[key] = channels[key];
950 usersAndChannels["Channels"] = channelMap;
953 return usersAndChannels;
956 void Network::initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels)
959 Q_ASSERT(proxy()->sourcePeer());
960 if (isInitialized()) {
961 qWarning() << "Network" << networkId()
962 << "received init data for users and channels although there already are known users or channels!";
966 // toMap() and toList() are cheap, so we can avoid copying to lists...
967 // However, we really have to make sure to never accidentally detach from the shared data!
969 const QVariantMap& users = usersAndChannels["Users"].toMap();
972 int count = users["nick"].toList().count();
973 foreach (const QString& key, users.keys()) {
974 if (users[key].toList().count() != count) {
975 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
980 // now create the individual IrcUsers
981 for (int i = 0; i < count; i++) {
983 foreach (const QString& key, users.keys())
984 map[key] = users[key].toList().at(i);
986 // If the peer doesn't support LongTime, upconvert the lastAwayMessageTime field
987 // from the 32-bit numerical seconds value used in older versions to QDateTime
988 if (!proxy()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) {
989 QDateTime lastAwayMessageTime = QDateTime();
990 lastAwayMessageTime.setTimeSpec(Qt::UTC);
991 #if QT_VERSION >= 0x050800
992 lastAwayMessageTime.fromSecsSinceEpoch(map.take("lastAwayMessage").toInt());
994 // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
995 // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
996 lastAwayMessageTime.fromMSecsSinceEpoch(map.take("lastAwayMessage").toInt() * 1000);
998 map["lastAwayMessageTime"] = lastAwayMessageTime;
1001 newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
1004 // same thing for IrcChannels
1005 const QVariantMap& channels = usersAndChannels["Channels"].toMap();
1008 count = channels["name"].toList().count();
1009 foreach (const QString& key, channels.keys()) {
1010 if (channels[key].toList().count() != count) {
1011 qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
1015 // now create the individual IrcChannels
1016 for (int i = 0; i < count; i++) {
1018 foreach (const QString& key, channels.keys())
1019 map[key] = channels[key].toList().at(i);
1020 newIrcChannel(map["name"].toString(), map);
1024 void Network::initSetSupports(const QVariantMap& supports)
1026 QMapIterator<QString, QVariant> iter(supports);
1027 while (iter.hasNext()) {
1029 addSupport(iter.key(), iter.value().toString());
1033 void Network::initSetCaps(const QVariantMap& caps)
1035 QMapIterator<QString, QVariant> iter(caps);
1036 while (iter.hasNext()) {
1038 addCap(iter.key(), iter.value().toString());
1042 IrcUser* Network::updateNickFromMask(const QString& mask)
1044 QString nick(nickFromMask(mask).toLower());
1047 if (_ircUsers.contains(nick)) {
1048 ircuser = _ircUsers[nick];
1049 ircuser->updateHostmask(mask);
1052 ircuser = newIrcUser(mask);
1057 void Network::ircUserNickChanged(QString newnick)
1059 QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
1061 if (oldnick.isNull())
1064 if (newnick.toLower() != oldnick)
1065 _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
1067 if (myNick().toLower() == oldnick)
1071 void Network::emitConnectionError(const QString& errorMsg)
1073 emit connectionError(errorMsg);
1076 // ====================
1078 // ====================
1079 void Network::determinePrefixes() const
1081 // seems like we have to construct them first
1082 QString prefix = support("PREFIX");
1084 if (prefix.startsWith("(") && prefix.contains(")")) {
1085 _prefixes = prefix.section(")", 1);
1086 _prefixModes = prefix.mid(1).section(")", 0, 0);
1089 QString defaultPrefixes("~&@%+");
1090 QString defaultPrefixModes("qaohv");
1092 if (prefix.isEmpty()) {
1093 _prefixes = defaultPrefixes;
1094 _prefixModes = defaultPrefixModes;
1097 // clear the existing modes, just in case we're run multiple times
1098 _prefixes = QString();
1099 _prefixModes = QString();
1101 // we just assume that in PREFIX are only prefix chars stored
1102 for (int i = 0; i < defaultPrefixes.size(); i++) {
1103 if (prefix.contains(defaultPrefixes[i])) {
1104 _prefixes += defaultPrefixes[i];
1105 _prefixModes += defaultPrefixModes[i];
1108 // check for success
1109 if (!_prefixes.isNull())
1112 // well... our assumption was obviously wrong...
1113 // check if it's only prefix modes
1114 for (int i = 0; i < defaultPrefixes.size(); i++) {
1115 if (prefix.contains(defaultPrefixModes[i])) {
1116 _prefixes += defaultPrefixes[i];
1117 _prefixModes += defaultPrefixModes[i];
1120 // now we've done all we've could...
1124 /************************************************************************
1126 ************************************************************************/
1128 QString NetworkInfo::skipCapsToString() const {
1129 // Sort the list of capabilities when rendering to a string. This isn't required as
1130 // Network::setSkipCaps() will sort as well, but this looks nicer when displayed to the user.
1131 // This also results in the list being sorted before storing in the database, too.
1132 auto sortedSkipCaps = skipCaps;
1133 sortedSkipCaps.sort();
1135 // IRCv3 capabilities are transmitted space-separated, so it should be safe to assume spaces
1136 // won't ever be inside them
1138 // See https://ircv3.net/specs/core/capability-negotiation
1139 return sortedSkipCaps.join(" ");
1142 void NetworkInfo::skipCapsFromString(const QString& flattenedSkipCaps) {
1143 // IRCv3 capabilities should all use lowercase capability names, though it's not strictly
1144 // required by the specification. Quassel currently converts all caps to lowercase before doing
1147 // This would only become an issue if two capabilities have the same name and only differ by
1148 // case, or if an IRC server transmits an uppercase capability and compares case-sensitively.
1150 // (QString::toLower() is always done in the C locale, so locale-dependent case-sensitivity
1151 // won't ever be an issue, thankfully.)
1153 // See Network::addCap(), Network::acknowledgeCap(), and friends
1154 // And https://ircv3.net/specs/core/capability-negotiation
1155 skipCaps = flattenedSkipCaps.toLower().split(" ", QString::SplitBehavior::SkipEmptyParts);
1158 bool NetworkInfo::operator==(const NetworkInfo& other) const
1160 return networkName == other.networkName
1161 && serverList == other.serverList
1162 && perform == other.perform
1163 && skipCaps == other.skipCaps
1164 && autoIdentifyService == other.autoIdentifyService
1165 && autoIdentifyPassword == other.autoIdentifyPassword
1166 && saslAccount == other.saslAccount
1167 && saslPassword == other.saslPassword
1168 && codecForServer == other.codecForServer
1169 && codecForEncoding == other.codecForEncoding
1170 && codecForDecoding == other.codecForDecoding
1171 && networkId == other.networkId
1172 && identity == other.identity
1173 && messageRateBurstSize == other.messageRateBurstSize
1174 && messageRateDelay == other.messageRateDelay
1175 && autoReconnectInterval == other.autoReconnectInterval
1176 && autoReconnectRetries == other.autoReconnectRetries
1177 && rejoinChannels == other.rejoinChannels
1178 && useRandomServer == other.useRandomServer
1179 && useAutoIdentify == other.useAutoIdentify
1180 && useSasl == other.useSasl
1181 && useAutoReconnect == other.useAutoReconnect
1182 && unlimitedReconnectRetries == other.unlimitedReconnectRetries
1183 && useCustomMessageRate == other.useCustomMessageRate
1184 && unlimitedMessageRate == other.unlimitedMessageRate
1188 bool NetworkInfo::operator!=(const NetworkInfo& other) const
1190 return !(*this == other);
1193 QDataStream& operator<<(QDataStream& out, const NetworkInfo& info)
1196 i["NetworkName"] = info.networkName;
1197 i["ServerList"] = toVariantList(info.serverList);
1198 i["Perform"] = info.perform;
1199 i["SkipCaps"] = info.skipCaps;
1200 i["AutoIdentifyService"] = info.autoIdentifyService;
1201 i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1202 i["SaslAccount"] = info.saslAccount;
1203 i["SaslPassword"] = info.saslPassword;
1204 i["CodecForServer"] = info.codecForServer;
1205 i["CodecForEncoding"] = info.codecForEncoding;
1206 i["CodecForDecoding"] = info.codecForDecoding;
1207 i["NetworkId"] = QVariant::fromValue(info.networkId);
1208 i["Identity"] = QVariant::fromValue(info.identity);
1209 i["MessageRateBurstSize"] = info.messageRateBurstSize;
1210 i["MessageRateDelay"] = info.messageRateDelay;
1211 i["AutoReconnectInterval"] = info.autoReconnectInterval;
1212 i["AutoReconnectRetries"] = info.autoReconnectRetries;
1213 i["RejoinChannels"] = info.rejoinChannels;
1214 i["UseRandomServer"] = info.useRandomServer;
1215 i["UseAutoIdentify"] = info.useAutoIdentify;
1216 i["UseSasl"] = info.useSasl;
1217 i["UseAutoReconnect"] = info.useAutoReconnect;
1218 i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1219 i["UseCustomMessageRate"] = info.useCustomMessageRate;
1220 i["UnlimitedMessageRate"] = info.unlimitedMessageRate;
1225 QDataStream& operator>>(QDataStream& in, NetworkInfo& info)
1229 info.networkName = i["NetworkName"].toString();
1230 info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1231 info.perform = i["Perform"].toStringList();
1232 info.skipCaps = i["SkipCaps"].toStringList();
1233 info.autoIdentifyService = i["AutoIdentifyService"].toString();
1234 info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1235 info.saslAccount = i["SaslAccount"].toString();
1236 info.saslPassword = i["SaslPassword"].toString();
1237 info.codecForServer = i["CodecForServer"].toByteArray();
1238 info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1239 info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1240 info.networkId = i["NetworkId"].value<NetworkId>();
1241 info.identity = i["Identity"].value<IdentityId>();
1242 info.messageRateBurstSize = i["MessageRateBurstSize"].toUInt();
1243 info.messageRateDelay = i["MessageRateDelay"].toUInt();
1244 info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1245 info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1246 info.rejoinChannels = i["RejoinChannels"].toBool();
1247 info.useRandomServer = i["UseRandomServer"].toBool();
1248 info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1249 info.useSasl = i["UseSasl"].toBool();
1250 info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1251 info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1252 info.useCustomMessageRate = i["UseCustomMessageRate"].toBool();
1253 info.unlimitedMessageRate = i["UnlimitedMessageRate"].toBool();
1257 QDebug operator<<(QDebug dbg, const NetworkInfo& i)
1259 dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1260 << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding
1261 << " codecForDecoding = " << i.codecForDecoding << " serverList = " << i.serverList
1262 << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1263 << " skipCaps = " << i.skipCaps << " useAutoIdentify = " << i.useAutoIdentify
1264 << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1265 << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1266 << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1267 << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1268 << " rejoinChannels = " << i.rejoinChannels << " useCustomMessageRate = " << i.useCustomMessageRate
1269 << " messageRateBurstSize = " << i.messageRateBurstSize << " messageRateDelay = " << i.messageRateDelay
1270 << " unlimitedMessageRate = " << i.unlimitedMessageRate << ")";
1274 QDataStream& operator<<(QDataStream& out, const Network::Server& server)
1276 QVariantMap serverMap;
1277 serverMap["Host"] = server.host;
1278 serverMap["Port"] = server.port;
1279 serverMap["Password"] = server.password;
1280 serverMap["UseSSL"] = server.useSsl;
1281 serverMap["sslVerify"] = server.sslVerify;
1282 serverMap["sslVersion"] = server.sslVersion;
1283 serverMap["UseProxy"] = server.useProxy;
1284 serverMap["ProxyType"] = server.proxyType;
1285 serverMap["ProxyHost"] = server.proxyHost;
1286 serverMap["ProxyPort"] = server.proxyPort;
1287 serverMap["ProxyUser"] = server.proxyUser;
1288 serverMap["ProxyPass"] = server.proxyPass;
1293 QDataStream& operator>>(QDataStream& in, Network::Server& server)
1295 QVariantMap serverMap;
1297 server.host = serverMap["Host"].toString();
1298 server.port = serverMap["Port"].toUInt();
1299 server.password = serverMap["Password"].toString();
1300 server.useSsl = serverMap["UseSSL"].toBool();
1301 server.sslVerify = serverMap["sslVerify"].toBool();
1302 server.sslVersion = serverMap["sslVersion"].toInt();
1303 server.useProxy = serverMap["UseProxy"].toBool();
1304 server.proxyType = serverMap["ProxyType"].toInt();
1305 server.proxyHost = serverMap["ProxyHost"].toString();
1306 server.proxyPort = serverMap["ProxyPort"].toUInt();
1307 server.proxyUser = serverMap["ProxyUser"].toString();
1308 server.proxyPass = serverMap["ProxyPass"].toString();
1312 bool Network::Server::operator==(const Server& other) const
1314 if (host != other.host)
1316 if (port != other.port)
1318 if (password != other.password)
1320 if (useSsl != other.useSsl)
1322 if (sslVerify != other.sslVerify)
1324 if (sslVersion != other.sslVersion)
1326 if (useProxy != other.useProxy)
1328 if (proxyType != other.proxyType)
1330 if (proxyHost != other.proxyHost)
1332 if (proxyPort != other.proxyPort)
1334 if (proxyUser != other.proxyUser)
1336 if (proxyPass != other.proxyPass)
1341 bool Network::Server::operator!=(const Server& other) const
1343 return !(*this == other);
1346 QDebug operator<<(QDebug dbg, const Network::Server& server)
1348 dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl
1349 << ", sslVerify = " << server.sslVerify << ")";