d768837f5408449a3a1697cd0b800a82ed925e89
[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.  Also blocks old clients from trying to set
711         // this to 0.
712         qWarning() << "Received invalid setMessageRateBurstSize data - message burst size must be "
713                       "non-zero positive, given" << burstSize;
714         return;
715     }
716     if (_messageRateBurstSize != burstSize) {
717         _messageRateBurstSize = burstSize;
718         SYNC(ARG(burstSize))
719         emit configChanged();
720         emit messageRateBurstSizeSet(_messageRateBurstSize);
721     }
722 }
723
724
725 void Network::setMessageRateDelay(quint32 messageDelay)
726 {
727     if (messageDelay == 0) {
728         // Nonsensical to have no delay - just check the Unlimited box instead.  Also blocks old
729         // clients from trying to set this to 0.
730         qWarning() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
731                       "positive, given" << messageDelay;
732         return;
733     }
734     if (_messageRateDelay != messageDelay) {
735         _messageRateDelay = messageDelay;
736         SYNC(ARG(messageDelay))
737         emit configChanged();
738         emit messageRateDelaySet(_messageRateDelay);
739     }
740 }
741
742
743 void Network::setUnlimitedMessageRate(bool unlimitedRate)
744 {
745     if (_unlimitedMessageRate != unlimitedRate) {
746         _unlimitedMessageRate = unlimitedRate;
747         SYNC(ARG(unlimitedRate))
748         emit configChanged();
749         emit unlimitedMessageRateSet(_unlimitedMessageRate);
750     }
751 }
752
753
754 void Network::addSupport(const QString &param, const QString &value)
755 {
756     if (!_supports.contains(param)) {
757         _supports[param] = value;
758         SYNC(ARG(param), ARG(value))
759     }
760 }
761
762
763 void Network::removeSupport(const QString &param)
764 {
765     if (_supports.contains(param)) {
766         _supports.remove(param);
767         SYNC(ARG(param))
768     }
769 }
770
771
772 QVariantMap Network::initSupports() const
773 {
774     QVariantMap supports;
775     QHashIterator<QString, QString> iter(_supports);
776     while (iter.hasNext()) {
777         iter.next();
778         supports[iter.key()] = iter.value();
779     }
780     return supports;
781 }
782
783 void Network::addCap(const QString &capability, const QString &value)
784 {
785     // IRCv3 specs all use lowercase capability names
786     QString _capLowercase = capability.toLower();
787     if (!_caps.contains(_capLowercase)) {
788         _caps[_capLowercase] = value;
789         SYNC(ARG(capability), ARG(value))
790         emit capAdded(_capLowercase);
791     }
792 }
793
794 void Network::acknowledgeCap(const QString &capability)
795 {
796     // IRCv3 specs all use lowercase capability names
797     QString _capLowercase = capability.toLower();
798     if (!_capsEnabled.contains(_capLowercase)) {
799         _capsEnabled.append(_capLowercase);
800         SYNC(ARG(capability))
801         emit capAcknowledged(_capLowercase);
802     }
803 }
804
805 void Network::removeCap(const QString &capability)
806 {
807     // IRCv3 specs all use lowercase capability names
808     QString _capLowercase = capability.toLower();
809     if (_caps.contains(_capLowercase)) {
810         // Remove from the list of available capabilities.
811         _caps.remove(_capLowercase);
812         // Remove it from the acknowledged list if it was previously acknowledged.  The SYNC call
813         // ensures this propogates to the other side.
814         // Use removeOne() for speed; no more than one due to contains() check in acknowledgeCap().
815         _capsEnabled.removeOne(_capLowercase);
816         SYNC(ARG(capability))
817         emit capRemoved(_capLowercase);
818     }
819 }
820
821 void Network::clearCaps()
822 {
823     // IRCv3 specs all use lowercase capability names
824     if (_caps.empty() && _capsEnabled.empty()) {
825         // Avoid the sync call if there's nothing to clear (e.g. failed reconnects)
826         return;
827     }
828     // To ease core-side configuration, loop through the list and emit capRemoved for each entry.
829     // If performance issues arise, this can be converted to a more-efficient setup without breaking
830     // protocol (in theory).
831     QString _capLowercase;
832     foreach (const QString &capability, _caps) {
833         _capLowercase = capability.toLower();
834         emit capRemoved(_capLowercase);
835     }
836     // Clear capabilities from the stored list
837     _caps.clear();
838     _capsEnabled.clear();
839
840     SYNC(NO_ARG)
841 }
842
843 QVariantMap Network::initCaps() const
844 {
845     QVariantMap caps;
846     QHashIterator<QString, QString> iter(_caps);
847     while (iter.hasNext()) {
848         iter.next();
849         caps[iter.key()] = iter.value();
850     }
851     return caps;
852 }
853
854
855 // There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
856 // Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
857 // where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
858 // Benchmarks have shown space savings of around 56%, resulting in saving several MBs worth of data on sync
859 // (without compression) with a decent amount of IrcUsers.
860 QVariantMap Network::initIrcUsersAndChannels() const
861 {
862     QVariantMap usersAndChannels;
863
864     if (_ircUsers.count()) {
865         QHash<QString, QVariantList> users;
866         QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
867         QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
868         while (it != end) {
869             const QVariantMap &map = it.value()->toVariantMap();
870             QVariantMap::const_iterator mapiter = map.begin();
871             while (mapiter != map.end()) {
872                 users[mapiter.key()] << mapiter.value();
873                 ++mapiter;
874             }
875             ++it;
876         }
877         // Can't have a container with a value type != QVariant in a QVariant :(
878         // However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
879         QVariantMap userMap;
880         foreach(const QString &key, users.keys())
881             userMap[key] = users[key];
882         usersAndChannels["Users"] = userMap;
883     }
884
885     if (_ircChannels.count()) {
886         QHash<QString, QVariantList> channels;
887         QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
888         QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
889         while (it != end) {
890             const QVariantMap &map = it.value()->toVariantMap();
891             QVariantMap::const_iterator mapiter = map.begin();
892             while (mapiter != map.end()) {
893                 channels[mapiter.key()] << mapiter.value();
894                 ++mapiter;
895             }
896             ++it;
897         }
898         QVariantMap channelMap;
899         foreach(const QString &key, channels.keys())
900             channelMap[key] = channels[key];
901         usersAndChannels["Channels"] = channelMap;
902     }
903
904     return usersAndChannels;
905 }
906
907
908 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
909 {
910     Q_ASSERT(proxy());
911     if (isInitialized()) {
912         qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
913         return;
914     }
915
916     // toMap() and toList() are cheap, so we can avoid copying to lists...
917     // However, we really have to make sure to never accidentally detach from the shared data!
918
919     const QVariantMap &users = usersAndChannels["Users"].toMap();
920
921     // sanity check
922     int count = users["nick"].toList().count();
923     foreach(const QString &key, users.keys()) {
924         if (users[key].toList().count() != count) {
925             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
926             return;
927         }
928     }
929
930     // now create the individual IrcUsers
931     for(int i = 0; i < count; i++) {
932         QVariantMap map;
933         foreach(const QString &key, users.keys())
934             map[key] = users[key].toList().at(i);
935         newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
936     }
937
938     // same thing for IrcChannels
939     const QVariantMap &channels = usersAndChannels["Channels"].toMap();
940
941     // sanity check
942     count = channels["name"].toList().count();
943     foreach(const QString &key, channels.keys()) {
944         if (channels[key].toList().count() != count) {
945             qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
946             return;
947         }
948     }
949     // now create the individual IrcChannels
950     for(int i = 0; i < count; i++) {
951         QVariantMap map;
952         foreach(const QString &key, channels.keys())
953             map[key] = channels[key].toList().at(i);
954         newIrcChannel(map["name"].toString(), map);
955     }
956 }
957
958
959 void Network::initSetSupports(const QVariantMap &supports)
960 {
961     QMapIterator<QString, QVariant> iter(supports);
962     while (iter.hasNext()) {
963         iter.next();
964         addSupport(iter.key(), iter.value().toString());
965     }
966 }
967
968
969 void Network::initSetCaps(const QVariantMap &caps)
970 {
971     QMapIterator<QString, QVariant> iter(caps);
972     while (iter.hasNext()) {
973         iter.next();
974         addCap(iter.key(), iter.value().toString());
975     }
976 }
977
978
979 IrcUser *Network::updateNickFromMask(const QString &mask)
980 {
981     QString nick(nickFromMask(mask).toLower());
982     IrcUser *ircuser;
983
984     if (_ircUsers.contains(nick)) {
985         ircuser = _ircUsers[nick];
986         ircuser->updateHostmask(mask);
987     }
988     else {
989         ircuser = newIrcUser(mask);
990     }
991     return ircuser;
992 }
993
994
995 void Network::ircUserNickChanged(QString newnick)
996 {
997     QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
998
999     if (oldnick.isNull())
1000         return;
1001
1002     if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
1003
1004     if (myNick().toLower() == oldnick)
1005         setMyNick(newnick);
1006 }
1007
1008
1009 void Network::emitConnectionError(const QString &errorMsg)
1010 {
1011     emit connectionError(errorMsg);
1012 }
1013
1014
1015 // ====================
1016 //  Private:
1017 // ====================
1018 void Network::determinePrefixes() const
1019 {
1020     // seems like we have to construct them first
1021     QString prefix = support("PREFIX");
1022
1023     if (prefix.startsWith("(") && prefix.contains(")")) {
1024         _prefixes = prefix.section(")", 1);
1025         _prefixModes = prefix.mid(1).section(")", 0, 0);
1026     }
1027     else {
1028         QString defaultPrefixes("~&@%+");
1029         QString defaultPrefixModes("qaohv");
1030
1031         if (prefix.isEmpty()) {
1032             _prefixes = defaultPrefixes;
1033             _prefixModes = defaultPrefixModes;
1034             return;
1035         }
1036         // clear the existing modes, just in case we're run multiple times
1037         _prefixes = QString();
1038         _prefixModes = QString();
1039
1040         // we just assume that in PREFIX are only prefix chars stored
1041         for (int i = 0; i < defaultPrefixes.size(); i++) {
1042             if (prefix.contains(defaultPrefixes[i])) {
1043                 _prefixes += defaultPrefixes[i];
1044                 _prefixModes += defaultPrefixModes[i];
1045             }
1046         }
1047         // check for success
1048         if (!_prefixes.isNull())
1049             return;
1050
1051         // well... our assumption was obviously wrong...
1052         // check if it's only prefix modes
1053         for (int i = 0; i < defaultPrefixes.size(); i++) {
1054             if (prefix.contains(defaultPrefixModes[i])) {
1055                 _prefixes += defaultPrefixes[i];
1056                 _prefixModes += defaultPrefixModes[i];
1057             }
1058         }
1059         // now we've done all we've could...
1060     }
1061 }
1062
1063
1064 /************************************************************************
1065  * NetworkInfo
1066  ************************************************************************/
1067
1068 NetworkInfo::NetworkInfo()
1069     : networkId(0),
1070     identity(1),
1071     useRandomServer(false),
1072     useAutoIdentify(false),
1073     autoIdentifyService("NickServ"),
1074     useSasl(false),
1075     useAutoReconnect(true),
1076     autoReconnectInterval(60),
1077     autoReconnectRetries(20),
1078     unlimitedReconnectRetries(false),
1079     rejoinChannels(true),
1080     useCustomMessageRate(false),
1081     messageRateBurstSize(5),
1082     messageRateDelay(2200),
1083     unlimitedMessageRate(false)
1084 {
1085 }
1086
1087
1088 bool NetworkInfo::operator==(const NetworkInfo &other) const
1089 {
1090     if (networkId != other.networkId) return false;
1091     if (networkName != other.networkName) return false;
1092     if (identity != other.identity) return false;
1093     if (codecForServer != other.codecForServer) return false;
1094     if (codecForEncoding != other.codecForEncoding) return false;
1095     if (codecForDecoding != other.codecForDecoding) return false;
1096     if (serverList != other.serverList) return false;
1097     if (useRandomServer != other.useRandomServer) return false;
1098     if (perform != other.perform) return false;
1099     if (useAutoIdentify != other.useAutoIdentify) return false;
1100     if (autoIdentifyService != other.autoIdentifyService) return false;
1101     if (autoIdentifyPassword != other.autoIdentifyPassword) return false;
1102     if (useSasl != other.useSasl) return false;
1103     if (saslAccount != other.saslAccount) return false;
1104     if (saslPassword != other.saslPassword) return false;
1105     if (useAutoReconnect != other.useAutoReconnect) return false;
1106     if (autoReconnectInterval != other.autoReconnectInterval) return false;
1107     if (autoReconnectRetries != other.autoReconnectRetries) return false;
1108     if (unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
1109     if (rejoinChannels != other.rejoinChannels) return false;
1110     // Custom rate limiting
1111     if (useCustomMessageRate != other.useCustomMessageRate) return false;
1112     if (messageRateBurstSize != other.messageRateBurstSize) return false;
1113     if (messageRateDelay != other.messageRateDelay) return false;
1114     if (unlimitedMessageRate != other.unlimitedMessageRate) return false;
1115     return true;
1116 }
1117
1118
1119 bool NetworkInfo::operator!=(const NetworkInfo &other) const
1120 {
1121     return !(*this == other);
1122 }
1123
1124
1125 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
1126 {
1127     QVariantMap i;
1128     i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
1129     i["NetworkName"] = info.networkName;
1130     i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
1131     i["CodecForServer"] = info.codecForServer;
1132     i["CodecForEncoding"] = info.codecForEncoding;
1133     i["CodecForDecoding"] = info.codecForDecoding;
1134     i["ServerList"] = toVariantList(info.serverList);
1135     i["UseRandomServer"] = info.useRandomServer;
1136     i["Perform"] = info.perform;
1137     i["UseAutoIdentify"] = info.useAutoIdentify;
1138     i["AutoIdentifyService"] = info.autoIdentifyService;
1139     i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
1140     i["UseSasl"] = info.useSasl;
1141     i["SaslAccount"] = info.saslAccount;
1142     i["SaslPassword"] = info.saslPassword;
1143     i["UseAutoReconnect"] = info.useAutoReconnect;
1144     i["AutoReconnectInterval"] = info.autoReconnectInterval;
1145     i["AutoReconnectRetries"] = info.autoReconnectRetries;
1146     i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
1147     i["RejoinChannels"] = info.rejoinChannels;
1148     // Custom rate limiting
1149     i["UseCustomMessageRate"] = info.useCustomMessageRate;
1150     i["MessageRateBurstSize"] = info.messageRateBurstSize;
1151     i["MessageRateDelay"] = info.messageRateDelay;
1152     i["UnlimitedMessageRate"] = info.unlimitedMessageRate;
1153     out << i;
1154     return out;
1155 }
1156
1157
1158 QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
1159 {
1160     QVariantMap i;
1161     in >> i;
1162     info.networkId = i["NetworkId"].value<NetworkId>();
1163     info.networkName = i["NetworkName"].toString();
1164     info.identity = i["Identity"].value<IdentityId>();
1165     info.codecForServer = i["CodecForServer"].toByteArray();
1166     info.codecForEncoding = i["CodecForEncoding"].toByteArray();
1167     info.codecForDecoding = i["CodecForDecoding"].toByteArray();
1168     info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
1169     info.useRandomServer = i["UseRandomServer"].toBool();
1170     info.perform = i["Perform"].toStringList();
1171     info.useAutoIdentify = i["UseAutoIdentify"].toBool();
1172     info.autoIdentifyService = i["AutoIdentifyService"].toString();
1173     info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
1174     info.useSasl = i["UseSasl"].toBool();
1175     info.saslAccount = i["SaslAccount"].toString();
1176     info.saslPassword = i["SaslPassword"].toString();
1177     info.useAutoReconnect = i["UseAutoReconnect"].toBool();
1178     info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
1179     info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
1180     info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
1181     info.rejoinChannels = i["RejoinChannels"].toBool();
1182     // Custom rate limiting
1183     info.useCustomMessageRate = i["UseCustomMessageRate"].toBool();
1184     info.messageRateBurstSize = i["MessageRateBurstSize"].toUInt();
1185     info.messageRateDelay = i["MessageRateDelay"].toUInt();
1186     info.unlimitedMessageRate = i["UnlimitedMessageRate"].toBool();
1187     return in;
1188 }
1189
1190
1191 QDebug operator<<(QDebug dbg, const NetworkInfo &i)
1192 {
1193     dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
1194     << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
1195     << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
1196     << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
1197     << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
1198     << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
1199     << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
1200     << " rejoinChannels = " << i.rejoinChannels
1201     << " useCustomMessageRate = " << i.useCustomMessageRate
1202     << " messageRateBurstSize = " << i.messageRateBurstSize
1203     << " messageRateDelay = " << i.messageRateDelay
1204     << " unlimitedMessageRate = " << i.unlimitedMessageRate
1205     << ")";
1206     return dbg.space();
1207 }
1208
1209
1210 QDataStream &operator<<(QDataStream &out, const Network::Server &server)
1211 {
1212     QVariantMap serverMap;
1213     serverMap["Host"] = server.host;
1214     serverMap["Port"] = server.port;
1215     serverMap["Password"] = server.password;
1216     serverMap["UseSSL"] = server.useSsl;
1217     serverMap["sslVerify"] = server.sslVerify;
1218     serverMap["sslVersion"] = server.sslVersion;
1219     serverMap["UseProxy"] = server.useProxy;
1220     serverMap["ProxyType"] = server.proxyType;
1221     serverMap["ProxyHost"] = server.proxyHost;
1222     serverMap["ProxyPort"] = server.proxyPort;
1223     serverMap["ProxyUser"] = server.proxyUser;
1224     serverMap["ProxyPass"] = server.proxyPass;
1225     out << serverMap;
1226     return out;
1227 }
1228
1229
1230 QDataStream &operator>>(QDataStream &in, Network::Server &server)
1231 {
1232     QVariantMap serverMap;
1233     in >> serverMap;
1234     server.host = serverMap["Host"].toString();
1235     server.port = serverMap["Port"].toUInt();
1236     server.password = serverMap["Password"].toString();
1237     server.useSsl = serverMap["UseSSL"].toBool();
1238     server.sslVerify = serverMap["sslVerify"].toBool();
1239     server.sslVersion = serverMap["sslVersion"].toInt();
1240     server.useProxy = serverMap["UseProxy"].toBool();
1241     server.proxyType = serverMap["ProxyType"].toInt();
1242     server.proxyHost = serverMap["ProxyHost"].toString();
1243     server.proxyPort = serverMap["ProxyPort"].toUInt();
1244     server.proxyUser = serverMap["ProxyUser"].toString();
1245     server.proxyPass = serverMap["ProxyPass"].toString();
1246     return in;
1247 }
1248
1249
1250 bool Network::Server::operator==(const Server &other) const
1251 {
1252     if (host != other.host) return false;
1253     if (port != other.port) return false;
1254     if (password != other.password) return false;
1255     if (useSsl != other.useSsl) return false;
1256     if (sslVerify != other.sslVerify) return false;
1257     if (sslVersion != other.sslVersion) return false;
1258     if (useProxy != other.useProxy) return false;
1259     if (proxyType != other.proxyType) return false;
1260     if (proxyHost != other.proxyHost) return false;
1261     if (proxyPort != other.proxyPort) return false;
1262     if (proxyUser != other.proxyUser) return false;
1263     if (proxyPass != other.proxyPass) return false;
1264     return true;
1265 }
1266
1267
1268 bool Network::Server::operator!=(const Server &other) const
1269 {
1270     return !(*this == other);
1271 }
1272
1273
1274 QDebug operator<<(QDebug dbg, const Network::Server &server)
1275 {
1276     dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " <<
1277                      server.useSsl << ", sslVerify = " << server.sslVerify << ")";
1278     return dbg.space();
1279 }