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