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