Merge pull request #198 - IRCv3 improvements
[quassel.git] / src / common / network.h
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 #ifndef NETWORK_H
22 #define NETWORK_H
23
24 #include <QString>
25 #include <QStringList>
26 #include <QList>
27 #include <QNetworkProxy>
28 #include <QHash>
29 #include <QVariantMap>
30 #include <QPointer>
31 #include <QMutex>
32 #include <QByteArray>
33
34 #include "types.h"
35 #include "util.h"
36 #include "syncableobject.h"
37
38 #include "signalproxy.h"
39 #include "ircuser.h"
40 #include "ircchannel.h"
41
42 // defined below!
43 struct NetworkInfo;
44
45 // TODO: ConnectionInfo to propagate and sync the current state of NetworkConnection, encodings etcpp
46
47 class Network : public SyncableObject
48 {
49     SYNCABLE_OBJECT
50     Q_OBJECT
51     Q_ENUMS(ConnectionState)
52
53     Q_PROPERTY(QString networkName READ networkName WRITE setNetworkName)
54     Q_PROPERTY(QString currentServer READ currentServer WRITE setCurrentServer)
55     Q_PROPERTY(QString myNick READ myNick WRITE setMyNick)
56     Q_PROPERTY(int latency READ latency WRITE setLatency)
57     Q_PROPERTY(QByteArray codecForServer READ codecForServer WRITE setCodecForServer)
58     Q_PROPERTY(QByteArray codecForEncoding READ codecForEncoding WRITE setCodecForEncoding)
59     Q_PROPERTY(QByteArray codecForDecoding READ codecForDecoding WRITE setCodecForDecoding)
60     Q_PROPERTY(IdentityId identityId READ identity WRITE setIdentity)
61     Q_PROPERTY(bool isConnected READ isConnected WRITE setConnected)
62     //Q_PROPERTY(Network::ConnectionState connectionState READ connectionState WRITE setConnectionState)
63     Q_PROPERTY(int connectionState READ connectionState WRITE setConnectionState)
64     Q_PROPERTY(bool useRandomServer READ useRandomServer WRITE setUseRandomServer)
65     Q_PROPERTY(QStringList perform READ perform WRITE setPerform)
66     Q_PROPERTY(bool useAutoIdentify READ useAutoIdentify WRITE setUseAutoIdentify)
67     Q_PROPERTY(QString autoIdentifyService READ autoIdentifyService WRITE setAutoIdentifyService)
68     Q_PROPERTY(QString autoIdentifyPassword READ autoIdentifyPassword WRITE setAutoIdentifyPassword)
69     Q_PROPERTY(bool useSasl READ useSasl WRITE setUseSasl)
70     Q_PROPERTY(QString saslAccount READ saslAccount WRITE setSaslAccount)
71     Q_PROPERTY(QString saslPassword READ saslPassword WRITE setSaslPassword)
72     Q_PROPERTY(bool useAutoReconnect READ useAutoReconnect WRITE setUseAutoReconnect)
73     Q_PROPERTY(quint32 autoReconnectInterval READ autoReconnectInterval WRITE setAutoReconnectInterval)
74     Q_PROPERTY(quint16 autoReconnectRetries READ autoReconnectRetries WRITE setAutoReconnectRetries)
75     Q_PROPERTY(bool unlimitedReconnectRetries READ unlimitedReconnectRetries WRITE setUnlimitedReconnectRetries)
76     Q_PROPERTY(bool rejoinChannels READ rejoinChannels WRITE setRejoinChannels)
77
78 public :
79         enum ConnectionState {
80         Disconnected,
81         Connecting,
82         Initializing,
83         Initialized,
84         Reconnecting,
85         Disconnecting
86     };
87
88     // see:
89     //  http://www.irc.org/tech_docs/005.html
90     //  http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt
91     enum ChannelModeType {
92         NOT_A_CHANMODE = 0x00,
93         A_CHANMODE = 0x01,
94         B_CHANMODE = 0x02,
95         C_CHANMODE = 0x04,
96         D_CHANMODE = 0x08
97     };
98
99     struct Server {
100         QString host;
101         uint port;
102         QString password;
103         bool useSsl;
104         int sslVersion;
105
106         bool useProxy;
107         int proxyType;
108         QString proxyHost;
109         uint proxyPort;
110         QString proxyUser;
111         QString proxyPass;
112
113         Server() : port(6667), useSsl(false), sslVersion(0), useProxy(false), proxyType(QNetworkProxy::Socks5Proxy), proxyHost("localhost"), proxyPort(8080) {}
114         Server(const QString &host, uint port, const QString &password, bool useSsl)
115             : host(host), port(port), password(password), useSsl(useSsl), sslVersion(0),
116             useProxy(false), proxyType(QNetworkProxy::Socks5Proxy), proxyHost("localhost"), proxyPort(8080) {}
117         bool operator==(const Server &other) const;
118         bool operator!=(const Server &other) const;
119     };
120     typedef QList<Server> ServerList;
121
122     Network(const NetworkId &networkid, QObject *parent = 0);
123     ~Network();
124
125     inline NetworkId networkId() const { return _networkId; }
126
127     inline SignalProxy *proxy() const { return _proxy; }
128     inline void setProxy(SignalProxy *proxy) { _proxy = proxy; }
129
130     inline bool isMyNick(const QString &nick) const { return (myNick().toLower() == nick.toLower()); }
131     inline bool isMe(IrcUser *ircuser) const { return (ircuser->nick().toLower() == myNick().toLower()); }
132
133     bool isChannelName(const QString &channelname) const;
134
135     /**
136      * Checks if the target counts as a STATUSMSG
137      *
138      * Status messages are prefixed with one or more characters from the server-provided STATUSMSG
139      * if available, otherwise "@" and "+" are assumed.  Generally, status messages sent to a
140      * channel are only visible to those with the same or higher permissions, e.g. voiced.
141      *
142      * @param[in] target Name of destination, e.g. a channel or query
143      * @returns True if a STATUSMSG, otherwise false
144      */
145     bool isStatusMsg(const QString &target) const;
146
147     inline bool isConnected() const { return _connected; }
148     //Network::ConnectionState connectionState() const;
149     inline int connectionState() const { return _connectionState; }
150
151     QString prefixToMode(const QString &prefix) const;
152     inline QString prefixToMode(const QCharRef &prefix) const { return prefixToMode(QString(prefix)); }
153     QString modeToPrefix(const QString &mode) const;
154     inline QString modeToPrefix(const QCharRef &mode) const { return modeToPrefix(QString(mode)); }
155
156     ChannelModeType channelModeType(const QString &mode);
157     inline ChannelModeType channelModeType(const QCharRef &mode) { return channelModeType(QString(mode)); }
158
159     inline const QString &networkName() const { return _networkName; }
160     inline const QString &currentServer() const { return _currentServer; }
161     inline const QString &myNick() const { return _myNick; }
162     inline int latency() const { return _latency; }
163     inline IrcUser *me() const { return ircUser(myNick()); }
164     inline IdentityId identity() const { return _identity; }
165     QStringList nicks() const;
166     inline QStringList channels() const { return _ircChannels.keys(); }
167     /**
168      * Gets the list of available capabilities.
169      *
170      * @returns QStringList of available capabilities
171      */
172     inline const QStringList caps() const { return QStringList(_caps.keys()); }
173     /**
174      * Gets the list of enabled (acknowledged) capabilities.
175      *
176      * @returns QStringList of enabled (acknowledged) capabilities
177      */
178     inline const QStringList capsEnabled() const { return _capsEnabled; }
179     inline const ServerList &serverList() const { return _serverList; }
180     inline bool useRandomServer() const { return _useRandomServer; }
181     inline const QStringList &perform() const { return _perform; }
182     inline bool useAutoIdentify() const { return _useAutoIdentify; }
183     inline const QString &autoIdentifyService() const { return _autoIdentifyService; }
184     inline const QString &autoIdentifyPassword() const { return _autoIdentifyPassword; }
185     inline bool useSasl() const { return _useSasl; }
186     inline const QString &saslAccount() const { return _saslAccount; }
187     inline const QString &saslPassword() const { return _saslPassword; }
188     inline bool useAutoReconnect() const { return _useAutoReconnect; }
189     inline quint32 autoReconnectInterval() const { return _autoReconnectInterval; }
190     inline quint16 autoReconnectRetries() const { return _autoReconnectRetries; }
191     inline bool unlimitedReconnectRetries() const { return _unlimitedReconnectRetries; }
192     inline bool rejoinChannels() const { return _rejoinChannels; }
193
194     NetworkInfo networkInfo() const;
195     void setNetworkInfo(const NetworkInfo &);
196
197     QString prefixes() const;
198     QString prefixModes() const;
199     void determinePrefixes() const;
200
201     bool supports(const QString &param) const { return _supports.contains(param); }
202     QString support(const QString &param) const;
203
204     /**
205      * Checks if a given capability is acknowledged and active.
206      *
207      * @param[in] capability Name of capability
208      * @returns True if acknowledged (active), otherwise false
209      */
210     inline bool capEnabled(const QString &capability) const { return _capsEnabled.contains(capability.toLower()); }
211     // IRCv3 specs all use lowercase capability names
212
213     /**
214      * Gets the value of an available capability, e.g. for SASL, "EXTERNAL,PLAIN".
215      *
216      * @param[in] capability Name of capability
217      * @returns Value of capability if one was specified, otherwise empty string
218      */
219     QString capValue(const QString &capability) const { return _caps.value(capability.toLower()); }
220     // IRCv3 specs all use lowercase capability names
221     // QHash returns the default constructed value if not found, in this case, empty string
222     // See:  https://doc.qt.io/qt-4.8/qhash.html#value
223
224     IrcUser *newIrcUser(const QString &hostmask, const QVariantMap &initData = QVariantMap());
225     inline IrcUser *newIrcUser(const QByteArray &hostmask) { return newIrcUser(decodeServerString(hostmask)); }
226     IrcUser *ircUser(QString nickname) const;
227     inline IrcUser *ircUser(const QByteArray &nickname) const { return ircUser(decodeServerString(nickname)); }
228     inline QList<IrcUser *> ircUsers() const { return _ircUsers.values(); }
229     inline quint32 ircUserCount() const { return _ircUsers.count(); }
230
231     IrcChannel *newIrcChannel(const QString &channelname, const QVariantMap &initData = QVariantMap());
232     inline IrcChannel *newIrcChannel(const QByteArray &channelname) { return newIrcChannel(decodeServerString(channelname)); }
233     IrcChannel *ircChannel(QString channelname) const;
234     inline IrcChannel *ircChannel(const QByteArray &channelname) const { return ircChannel(decodeServerString(channelname)); }
235     inline QList<IrcChannel *> ircChannels() const { return _ircChannels.values(); }
236     inline quint32 ircChannelCount() const { return _ircChannels.count(); }
237
238     QByteArray codecForServer() const;
239     QByteArray codecForEncoding() const;
240     QByteArray codecForDecoding() const;
241     void setCodecForServer(QTextCodec *codec);
242     void setCodecForEncoding(QTextCodec *codec);
243     void setCodecForDecoding(QTextCodec *codec);
244
245     QString decodeString(const QByteArray &text) const;
246     QByteArray encodeString(const QString &string) const;
247     QString decodeServerString(const QByteArray &text) const;
248     QByteArray encodeServerString(const QString &string) const;
249
250     static QByteArray defaultCodecForServer();
251     static QByteArray defaultCodecForEncoding();
252     static QByteArray defaultCodecForDecoding();
253     static void setDefaultCodecForServer(const QByteArray &name);
254     static void setDefaultCodecForEncoding(const QByteArray &name);
255     static void setDefaultCodecForDecoding(const QByteArray &name);
256
257     inline bool autoAwayActive() const { return _autoAwayActive; }
258     inline void setAutoAwayActive(bool active) { _autoAwayActive = active; }
259
260 public slots:
261     void setNetworkName(const QString &networkName);
262     void setCurrentServer(const QString &currentServer);
263     void setConnected(bool isConnected);
264     void setConnectionState(int state);
265     virtual void setMyNick(const QString &mynick);
266     void setLatency(int latency);
267     void setIdentity(IdentityId);
268
269     void setServerList(const QVariantList &serverList);
270     void setUseRandomServer(bool);
271     void setPerform(const QStringList &);
272     void setUseAutoIdentify(bool);
273     void setAutoIdentifyService(const QString &);
274     void setAutoIdentifyPassword(const QString &);
275     void setUseSasl(bool);
276     void setSaslAccount(const QString &);
277     void setSaslPassword(const QString &);
278     virtual void setUseAutoReconnect(bool);
279     virtual void setAutoReconnectInterval(quint32);
280     virtual void setAutoReconnectRetries(quint16);
281     void setUnlimitedReconnectRetries(bool);
282     void setRejoinChannels(bool);
283
284     void setCodecForServer(const QByteArray &codecName);
285     void setCodecForEncoding(const QByteArray &codecName);
286     void setCodecForDecoding(const QByteArray &codecName);
287
288     void addSupport(const QString &param, const QString &value = QString());
289     void removeSupport(const QString &param);
290
291     // IRCv3 capability negotiation (can be connected to signals)
292
293     /**
294      * Add an available capability, optionally providing a value.
295      *
296      * This may happen during first connect, or at any time later if a new capability becomes
297      * available (e.g. SASL service starting).
298      *
299      * @param[in] capability Name of the capability
300      * @param[in] value
301      * @parblock
302      * Optional value of the capability, e.g. sasl=plain.
303      * @endparblock
304      */
305     void addCap(const QString &capability, const QString &value = QString());
306
307     /**
308      * Marks a capability as acknowledged (enabled by the IRC server).
309      *
310      * @param[in] capability Name of the capability
311      */
312     void acknowledgeCap(const QString &capability);
313
314     /**
315      * Removes a capability from the list of available capabilities.
316      *
317      * This may happen during first connect, or at any time later if an existing capability becomes
318      * unavailable (e.g. SASL service stopping).  This also removes the capability from the list
319      * of acknowledged capabilities.
320      *
321      * @param[in] capability Name of the capability
322      */
323     void removeCap(const QString &capability);
324
325     /**
326      * Clears all capabilities from the list of available capabilities.
327      *
328      * This also removes the capability from the list of acknowledged capabilities.
329      */
330     void clearCaps();
331
332     inline void addIrcUser(const QString &hostmask) { newIrcUser(hostmask); }
333     inline void addIrcChannel(const QString &channel) { newIrcChannel(channel); }
334
335     //init geters
336     QVariantMap initSupports() const;
337     /**
338      * Get the initial list of available capabilities.
339      *
340      * @return QVariantMap of <QString, QString> indicating available capabilities and values
341      */
342     QVariantMap initCaps() const;
343     /**
344      * Get the initial list of enabled (acknowledged) capabilities.
345      *
346      * @return QVariantList of QString indicating enabled (acknowledged) capabilities and values
347      */
348     QVariantList initCapsEnabled() const { return toVariantList(capsEnabled()); }
349     inline QVariantList initServerList() const { return toVariantList(serverList()); }
350     virtual QVariantMap initIrcUsersAndChannels() const;
351
352     //init seters
353     void initSetSupports(const QVariantMap &supports);
354     /**
355      * Initialize the list of available capabilities.
356      *
357      * @param[in] caps QVariantMap of <QString, QString> indicating available capabilities and values
358      */
359     void initSetCaps(const QVariantMap &caps);
360     /**
361      * Initialize the list of enabled (acknowledged) capabilities.
362      *
363      * @param[in] caps QVariantList of QString indicating enabled (acknowledged) capabilities and values
364      */
365     inline void initSetCapsEnabled(const QVariantList &capsEnabled) { _capsEnabled = fromVariantList<QString>(capsEnabled); }
366     inline void initSetServerList(const QVariantList &serverList) { _serverList = fromVariantList<Server>(serverList); }
367     virtual void initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels);
368
369     /**
370      * Update IrcUser hostmask and username from mask, creating an IrcUser if one does not exist.
371      *
372      * @param[in] mask   Full nick!user@hostmask string
373      * @return IrcUser of the matching nick if exists, otherwise a new IrcUser
374      */
375     IrcUser *updateNickFromMask(const QString &mask);
376
377     // these slots are to keep the hashlists of all users and the
378     // channel lists up to date
379     void ircUserNickChanged(QString newnick);
380
381     virtual inline void requestConnect() const { REQUEST(NO_ARG) }
382     virtual inline void requestDisconnect() const { REQUEST(NO_ARG) }
383     virtual inline void requestSetNetworkInfo(const NetworkInfo &info) { REQUEST(ARG(info)) }
384
385     void emitConnectionError(const QString &);
386
387 protected slots:
388     virtual void removeIrcUser(IrcUser *ircuser);
389     virtual void removeIrcChannel(IrcChannel *ircChannel);
390     virtual void removeChansAndUsers();
391
392 signals:
393     void aboutToBeDestroyed();
394     void networkNameSet(const QString &networkName);
395     void currentServerSet(const QString &currentServer);
396     void connectedSet(bool isConnected);
397     void connectionStateSet(Network::ConnectionState);
398 //   void connectionStateSet(int);
399     void connectionError(const QString &errorMsg);
400     void myNickSet(const QString &mynick);
401 //   void latencySet(int latency);
402     void identitySet(IdentityId);
403
404     void configChanged();
405
406     //   void serverListSet(QVariantList serverList);
407 //   void useRandomServerSet(bool);
408 //   void performSet(const QStringList &);
409 //   void useAutoIdentifySet(bool);
410 //   void autoIdentifyServiceSet(const QString &);
411 //   void autoIdentifyPasswordSet(const QString &);
412 //   void useAutoReconnectSet(bool);
413 //   void autoReconnectIntervalSet(quint32);
414 //   void autoReconnectRetriesSet(quint16);
415 //   void unlimitedReconnectRetriesSet(bool);
416 //   void rejoinChannelsSet(bool);
417
418 //   void codecForServerSet(const QByteArray &codecName);
419 //   void codecForEncodingSet(const QByteArray &codecName);
420 //   void codecForDecodingSet(const QByteArray &codecName);
421
422 //   void supportAdded(const QString &param, const QString &value);
423 //   void supportRemoved(const QString &param);
424
425     // IRCv3 capability negotiation (can drive other slots)
426     /**
427      * Indicates a capability is now available, with optional value in Network::capValue().
428      *
429      * @see Network::addCap()
430      *
431      * @param[in] capability Name of the capability
432      */
433     void capAdded (const QString &capability);
434
435     /**
436      * Indicates a capability was acknowledged (enabled by the IRC server).
437      *
438      * @see Network::acknowledgeCap()
439      *
440      * @param[in] capability Name of the capability
441      */
442     void capAcknowledged(const QString &capability);
443
444     /**
445      * Indicates a capability was removed from the list of available capabilities.
446      *
447      * @see Network::removeCap()
448      *
449      * @param[in] capability Name of the capability
450      */
451     void capRemoved(const QString &capability);
452
453 //   void ircUserAdded(const QString &hostmask);
454     void ircUserAdded(IrcUser *);
455 //   void ircChannelAdded(const QString &channelname);
456     void ircChannelAdded(IrcChannel *);
457
458 //   void connectRequested() const;
459 //   void disconnectRequested() const;
460 //   void setNetworkInfoRequested(const NetworkInfo &) const;
461
462 protected:
463     inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new IrcChannel(channelname, this); }
464     inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new IrcUser(hostmask, this); }
465
466 private:
467     QPointer<SignalProxy> _proxy;
468
469     NetworkId _networkId;
470     IdentityId _identity;
471
472     QString _myNick;
473     int _latency;
474     QString _networkName;
475     QString _currentServer;
476     bool _connected;
477     ConnectionState _connectionState;
478
479     mutable QString _prefixes;
480     mutable QString _prefixModes;
481
482     QHash<QString, IrcUser *> _ircUsers; // stores all known nicks for the server
483     QHash<QString, IrcChannel *> _ircChannels; // stores all known channels
484     QHash<QString, QString> _supports; // stores results from RPL_ISUPPORT
485
486     QHash<QString, QString> _caps;  /// Capabilities supported by the IRC server
487     // By synchronizing the supported capabilities, the client could suggest certain behaviors, e.g.
488     // in the Network settings dialog, recommending SASL instead of using NickServ, or warning if
489     // SASL EXTERNAL isn't available.
490     QStringList _capsEnabled;       /// Enabled capabilities that received 'CAP ACK'
491     // _capsEnabled uses the same values from the <name>=<value> pairs stored in _caps
492
493     ServerList _serverList;
494     bool _useRandomServer;
495     QStringList _perform;
496
497     bool _useAutoIdentify;
498     QString _autoIdentifyService;
499     QString _autoIdentifyPassword;
500
501     bool _useSasl;
502     QString _saslAccount;
503     QString _saslPassword;
504
505     bool _useAutoReconnect;
506     quint32 _autoReconnectInterval;
507     quint16 _autoReconnectRetries;
508     bool _unlimitedReconnectRetries;
509     bool _rejoinChannels;
510
511     QTextCodec *_codecForServer;
512     QTextCodec *_codecForEncoding;
513     QTextCodec *_codecForDecoding;
514
515     static QTextCodec *_defaultCodecForServer;
516     static QTextCodec *_defaultCodecForEncoding;
517     static QTextCodec *_defaultCodecForDecoding;
518
519     bool _autoAwayActive; // when this is active handle305 and handle306 don't trigger any output
520
521     friend class IrcUser;
522     friend class IrcChannel;
523 };
524
525
526 //! Stores all editable information about a network (as opposed to runtime state).
527 struct NetworkInfo {
528     // set some default values, note that this does not initialize e.g. name and id
529     NetworkInfo();
530
531     NetworkId networkId;
532     QString networkName;
533     IdentityId identity;
534
535     bool useCustomEncodings; // not used!
536     QByteArray codecForServer;
537     QByteArray codecForEncoding;
538     QByteArray codecForDecoding;
539
540     Network::ServerList serverList;
541     bool useRandomServer;
542
543     QStringList perform;
544
545     bool useAutoIdentify;
546     QString autoIdentifyService;
547     QString autoIdentifyPassword;
548
549     bool useSasl;
550     QString saslAccount;
551     QString saslPassword;
552
553     bool useAutoReconnect;
554     quint32 autoReconnectInterval;
555     quint16 autoReconnectRetries;
556     bool unlimitedReconnectRetries;
557     bool rejoinChannels;
558
559     bool operator==(const NetworkInfo &other) const;
560     bool operator!=(const NetworkInfo &other) const;
561 };
562
563 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info);
564 QDataStream &operator>>(QDataStream &in, NetworkInfo &info);
565 QDebug operator<<(QDebug dbg, const NetworkInfo &i);
566 Q_DECLARE_METATYPE(NetworkInfo)
567
568 QDataStream &operator<<(QDataStream &out, const Network::Server &server);
569 QDataStream &operator>>(QDataStream &in, Network::Server &server);
570 QDebug operator<<(QDebug dbg, const Network::Server &server);
571 Q_DECLARE_METATYPE(Network::Server)
572
573 #endif