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