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