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