cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / core / corenetwork.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 #pragma once
22
23 #include <functional>
24
25 #include <QSslError>
26 #include <QSslSocket>
27 #include <QTimer>
28
29 #ifdef HAVE_QCA2
30 #    include "cipher.h"
31 #endif
32
33 #include "coreircchannel.h"
34 #include "coreircuser.h"
35 #include "coresession.h"
36 #include "irccap.h"
37 #include "irctag.h"
38 #include "network.h"
39
40 class CoreIdentity;
41 class CoreUserInputHandler;
42 class CoreIgnoreListManager;
43 class Event;
44
45 class CoreNetwork : public Network
46 {
47     Q_OBJECT
48
49 public:
50     CoreNetwork(const NetworkId& networkid, CoreSession* session);
51     ~CoreNetwork() override;
52
53     inline CoreIdentity* identityPtr() const { return coreSession()->identity(identity()); }
54     inline CoreSession* coreSession() const { return _coreSession; }
55     inline CoreNetworkConfig* networkConfig() const { return coreSession()->networkConfig(); }
56
57     inline CoreUserInputHandler* userInputHandler() const { return _userInputHandler; }
58     inline CoreIgnoreListManager* ignoreListManager() { return coreSession()->ignoreListManager(); }
59
60     //! Decode a string using the server (network) decoding.
61     inline QString serverDecode(const QByteArray& string) const { return decodeServerString(string); }
62
63     //! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
64     QString channelDecode(const QString& channelName, const QByteArray& string) const;
65
66     //! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
67     QString userDecode(const QString& userNick, const QByteArray& string) const;
68
69     //! Encode a string using the server (network) encoding.
70     inline QByteArray serverEncode(const QString& string) const { return encodeServerString(string); }
71
72     //! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
73     QByteArray channelEncode(const QString& channelName, const QString& string) const;
74
75     //! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
76     QByteArray userEncode(const QString& userNick, const QString& string) const;
77
78     inline QString channelKey(const QString& channel) const { return _channelKeys.value(channel.toLower(), QString()); }
79
80     inline QByteArray readChannelCipherKey(const QString& channel) const { return _cipherKeys.value(channel.toLower()); }
81     inline void storeChannelCipherKey(const QString& channel, const QByteArray& key) { _cipherKeys[channel.toLower()] = key; }
82
83     /**
84      * Checks if the given target has an automatic WHO in progress
85      *
86      * @param name Channel or nickname
87      * @return True if an automatic WHO is in progress, otherwise false
88      */
89     inline bool isAutoWhoInProgress(const QString& name) const { return _autoWhoPending.value(name.toLower(), 0); }
90
91     inline UserId userId() const { return _coreSession->user(); }
92
93     inline QAbstractSocket::SocketState socketState() const { return socket.state(); }
94     inline bool socketConnected() const { return socket.state() == QAbstractSocket::ConnectedState; }
95     inline QHostAddress localAddress() const { return socket.localAddress(); }
96     inline QHostAddress peerAddress() const { return socket.peerAddress(); }
97     inline quint16 localPort() const { return socket.localPort(); }
98     inline quint16 peerPort() const { return socket.peerPort(); }
99
100     /**
101      * Gets whether or not a disconnect was expected.
102      *
103      * Distinguishes desired quits from unexpected disconnections such as socket errors or timeouts.
104      *
105      * @return True if disconnect was requested, otherwise false.
106      */
107     inline bool disconnectExpected() const { return _disconnectExpected; }
108
109     /**
110      * Gets whether or not the server replies to automated PINGs with a valid timestamp
111      *
112      * Distinguishes between servers that reply by quoting the text sent, and those that respond
113      * with whatever they want.
114      *
115      * @return True if a valid timestamp has been received as a PONG, otherwise false.
116      */
117     inline bool isPongTimestampValid() const { return _pongTimestampValid; }
118
119     /**
120      * Gets whether or not an automated PING has been sent without any PONG received
121      *
122      * Reset whenever any PONG is received, not just the automated one sent.
123      *
124      * @return True if a PING has been sent without a PONG received, otherwise false.
125      */
126     inline bool isPongReplyPending() const { return _pongReplyPending; }
127
128     QList<QList<QByteArray>> splitMessage(const QString& cmd,
129                                           const QString& message,
130                                           const std::function<QList<QByteArray>(QString&)>& cmdGenerator);
131
132     // IRCv3 capability negotiation
133
134     /**
135      * Checks if capability negotiation is currently ongoing.
136      *
137      * @returns True if in progress, otherwise false
138      */
139     inline bool capsPendingNegotiation() const { return (!_capsQueuedIndividual.empty() || !_capsQueuedBundled.empty()); }
140
141     /**
142      * Queues a capability to be requested.
143      *
144      * Adds to the list of capabilities being requested.  If non-empty, CAP REQ messages are sent
145      * to the IRC server.  This may happen at login or if capabilities are announced via CAP NEW.
146      *
147      * @param[in] capability Name of the capability
148      */
149     void queueCap(const QString& capability);
150
151     /**
152      * Begins capability negotiation if capabilities are queued, otherwise returns.
153      *
154      * If any capabilities are queued, this will begin the cycle of taking each capability and
155      * requesting it.  When no capabilities remain, capability negotiation is suitably ended.
156      */
157     void beginCapNegotiation();
158
159     /**
160      * Ends capability negotiation.
161      *
162      * This won't have effect if other CAP commands are in the command queue before calling this
163      * command.  It should only be called when capability negotiation is complete.
164      */
165     void endCapNegotiation();
166
167     /**
168      * Queues the most recent capability set for retrying individually.
169      *
170      * Retries the most recent bundle of capabilities one at a time instead of as a group, working
171      * around the issue that IRC servers can deny a group of requested capabilities without
172      * indicating which capabilities failed.
173      *
174      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
175      *
176      * This does NOT call CoreNetwork::sendNextCap().  Call that when ready afterwards.  Does
177      * nothing if the last capability tried was individual instead of a set.
178      */
179     void retryCapsIndividually();
180
181     /**
182      * List of capabilities requiring further core<->server messages to configure.
183      *
184      * For example, SASL requires the back-and-forth of AUTHENTICATE, so the next capability cannot
185      * be immediately sent.
186      *
187      * Any capabilities in this list must call CoreNetwork::sendNextCap() on their own and they will
188      * not be batched together with other capabilities.
189      *
190      * See: http://ircv3.net/specs/extensions/sasl-3.2.html
191      */
192     const QStringList capsRequiringConfiguration = QStringList{IrcCap::SASL};
193
194 public slots:
195     void setMyNick(const QString& mynick) override;
196
197     void requestConnect() const override;
198     void requestDisconnect() const override;
199     void requestSetNetworkInfo(const NetworkInfo& info) override;
200
201     void setUseAutoReconnect(bool) override;
202     void setAutoReconnectInterval(quint32) override;
203     void setAutoReconnectRetries(quint16) override;
204
205     void setPingInterval(int interval);
206
207     /**
208      * Sets whether or not the IRC server has replied to PING with a valid timestamp
209      *
210      * This allows determining whether or not an IRC server responds to PING with a PONG that quotes
211      * what was sent, or if it does something else (and therefore PONGs should be more aggressively
212      * hidden).
213      *
214      * @param timestampValid If true, a valid timestamp has been received via PONG reply
215      */
216     void setPongTimestampValid(bool validTimestamp);
217
218     /**
219      * Indicates that the CoreSession is shutting down.
220      *
221      * Disconnects the network if connected, and sets a flag that prevents reconnections.
222      */
223     void shutdown();
224
225     void connectToIrc(bool reconnecting = false);
226     /**
227      * Disconnect from the IRC server.
228      *
229      * Begin disconnecting from the IRC server, including optionally reconnecting.
230      *
231      * @param requested       If true, user requested this disconnect; don't try to reconnect
232      * @param reason          Reason for quitting, defaulting to the user-configured quit reason
233      * @param withReconnect   Reconnect to the network after disconnecting (e.g. ping timeout)
234      */
235     void disconnectFromIrc(bool requested = true, const QString& reason = QString(), bool withReconnect = false);
236
237     /**
238      * Forcibly close the IRC server socket, waiting for it to close.
239      *
240      * Call CoreNetwork::disconnectFromIrc() first, allow the event loop to run, then if you need to
241      * be sure the network's disconnected (e.g. clean-up), call this.
242      *
243      * @param msecs  Maximum time to wait for socket to close, in milliseconds.
244      * @return True if socket closes successfully; false if error occurs or timeout reached
245      */
246     bool forceDisconnect(int msecs = 1000);
247
248     void userInput(const BufferInfo& bufferInfo, QString msg);
249
250     /**
251      * Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
252      *
253      * @param[in] input   QByteArray of encoded characters
254      * @param[in] prepend
255      * @parmblock
256      * If true, the line is prepended into the start of the queue, otherwise, it's appended to the
257      * end.  This should be used sparingly, for if either the core or the IRC server cannot maintain
258      * PING/PONG replies, the other side will close the connection.
259      * @endparmblock
260      */
261     void putRawLine(const QByteArray& input, bool prepend = false);
262
263     /**
264      * Sends the command with encoded parameters, with optional prefix or high priority.
265      *
266      * @param[in] cmd      Command to send, ignoring capitalization
267      * @param[in] params   Parameters for the command, encoded within a QByteArray
268      * @param[in] prefix   Optional command prefix
269      * @param[in] prepend
270      * @parmblock
271      * If true, the command is prepended into the start of the queue, otherwise, it's appended to
272      * the end.  This should be used sparingly, for if either the core or the IRC server cannot
273      * maintain PING/PONG replies, the other side will close the connection.
274      * @endparmblock
275      */
276     void putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix = {}, const QHash<IrcTagKey, QString> &tags = {}, bool prepend = false);
277
278     /**
279      * Sends the command for each set of encoded parameters, with optional prefix or high priority.
280      *
281      * @param[in] cmd         Command to send, ignoring capitalization
282      * @param[in] params
283      * @parmblock
284      * List of parameter lists for the command, encoded within a QByteArray.  The command will be
285      * sent multiple times, once for each set of params stored within the outer list.
286      * @endparmblock
287      * @param[in] prefix      Optional command prefix
288      * @param[in] prependAll
289      * @parmblock
290      * If true, ALL of the commands are prepended into the start of the queue, otherwise, they're
291      * appended to the end.  This should be used sparingly, for if either the core or the IRC server
292      * cannot maintain PING/PONG replies, the other side will close the connection.
293      * @endparmblock
294      */
295     void putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix = {}, const QHash<IrcTagKey, QString> &tags = {}, bool prependAll = false);
296
297     void setChannelJoined(const QString& channel);
298     void setChannelParted(const QString& channel);
299     void addChannelKey(const QString& channel, const QString& key);
300     void removeChannelKey(const QString& channel);
301
302     // Blowfish stuff
303 #ifdef HAVE_QCA2
304     Cipher* cipher(const QString& recipient);
305     QByteArray cipherKey(const QString& recipient) const;
306     void setCipherKey(const QString& recipient, const QByteArray& key);
307     bool cipherUsesCBC(const QString& target);
308 #endif
309
310     // Custom rate limiting (can be connected to signals)
311
312     /**
313      * Update rate limiting according to Network configuration
314      *
315      * Updates the token bucket and message queue timer according to the network configuration, such
316      * as on first load, or after changing settings.
317      *
318      * Calling this will reset any ongoing queue delays.  If messages exist in the queue when rate
319      * limiting is disabled, messages will be quickly sent (100 ms) with new messages queued to send
320      * until the queue is cleared.
321      *
322      * @see Network::useCustomMessageRate()
323      * @see Network::messageRateBurstSize()
324      * @see Network::messageRateDelay()
325      * @see Network::unlimitedMessageRate()
326      *
327      * @param[in] forceUnlimited
328      * @parmblock
329      * If true, override user settings to disable message rate limiting, otherwise apply rate limits
330      * set by the user.  Use with caution and remember to re-enable configured limits when done.
331      * @endparmblock
332      */
333     void updateRateLimiting(bool forceUnlimited = false);
334
335     /**
336      * Resets the token bucket up to the maximum
337      *
338      * Call this if the connection's been reset after calling updateRateLimiting() if needed.
339      *
340      * @see CoreNetwork::updateRateLimiting()
341      */
342     void resetTokenBucket();
343
344     // IRCv3 capability negotiation (can be connected to signals)
345
346     /**
347      * Indicates a capability is now available, with optional value in Network::capValue().
348      *
349      * @see Network::addCap()
350      *
351      * @param[in] capability Name of the capability
352      */
353     void serverCapAdded(const QString& capability);
354
355     /**
356      * Indicates a capability was acknowledged (enabled by the IRC server).
357      *
358      * @see Network::acknowledgeCap()
359      *
360      * @param[in] capability Name of the capability
361      */
362     void serverCapAcknowledged(const QString& capability);
363
364     /**
365      * Indicates a capability was removed from the list of available capabilities.
366      *
367      * @see Network::removeCap()
368      *
369      * @param[in] capability Name of the capability
370      */
371     void serverCapRemoved(const QString& capability);
372
373     /**
374      * Sends the next capability from the queue.
375      *
376      * During nick registration if any capabilities remain queued, this will take the next and
377      * request it.  When no capabilities remain, capability negotiation is ended.
378      */
379     void sendNextCap();
380
381     void setAutoWhoEnabled(bool enabled);
382     void setAutoWhoInterval(int interval);
383     void setAutoWhoDelay(int delay);
384
385     /**
386      * Appends the given channel/nick to the front of the AutoWho queue.
387      *
388      * When 'away-notify' is enabled, this will trigger an immediate AutoWho since regular
389      * who-cycles are disabled as per IRCv3 specifications.
390      *
391      * @param[in] name Channel or nickname
392      */
393     void queueAutoWhoOneshot(const QString& name);
394
395     /**
396      * Checks if the given target has an automatic WHO in progress, and sets it as done if so
397      *
398      * @param name Channel or nickname
399      * @return True if an automatic WHO is in progress (and should be silenced), otherwise false
400      */
401     bool setAutoWhoDone(const QString& name);
402
403     void updateIssuedModes(const QString& requestedModes);
404     void updatePersistentModes(QString addModes, QString removeModes);
405     void resetPersistentModes();
406
407     Server usedServer() const;
408
409     inline void resetPingTimeout() { _pingCount = 0; }
410
411     /**
412      * Marks the network as no longer having a pending reply to an automated PING
413      */
414     inline void resetPongReplyPending() { _pongReplyPending = false; }
415
416     void onDisplayMsg(const NetworkInternalMessage& msg)
417     {
418         emit displayMsg(RawMessage(networkId(), msg));
419     }
420
421 signals:
422     void recvRawServerMsg(const QString&);
423     void displayStatusMsg(const QString&);
424     void displayMsg(const RawMessage& msg);
425     void disconnected(NetworkId networkId);
426     void connectionError(const QString& errorMsg);
427
428     void quitRequested(NetworkId networkId);
429     void sslErrors(const QVariant& errorData);
430
431     void newEvent(Event* event);
432     void socketInitialized(const CoreIdentity* identity,
433                            const QHostAddress& localAddress,
434                            quint16 localPort,
435                            const QHostAddress& peerAddress,
436                            quint16 peerPort,
437                            qint64 socketId);
438     void socketDisconnected(const CoreIdentity* identity,
439                             const QHostAddress& localAddress,
440                             quint16 localPort,
441                             const QHostAddress& peerAddress,
442                             quint16 peerPort,
443                             qint64 socketId);
444
445 protected:
446     inline IrcChannel* ircChannelFactory(const QString& channelname) override { return new CoreIrcChannel(channelname, this); }
447     inline IrcUser* ircUserFactory(const QString& hostmask) override { return new CoreIrcUser(hostmask, this); }
448
449 protected slots:
450     // TODO: remove cached cipher keys, when appropriate
451     // virtual void removeIrcUser(IrcUser *ircuser);
452     // virtual void removeIrcChannel(IrcChannel *ircChannel);
453     // virtual void removeChansAndUsers();
454
455 private slots:
456     void onSocketHasData();
457     void onSocketError(QAbstractSocket::SocketError);
458     void onSocketInitialized();
459     void onSocketCloseTimeout();
460     void onSocketDisconnected();
461     void onSocketStateChanged(QAbstractSocket::SocketState);
462
463     void networkInitialized();
464
465     void sendPerform();
466     void restoreUserModes();
467     void doAutoReconnect();
468     void sendPing();
469     void enablePingTimeout(bool enable = true);
470     void disablePingTimeout();
471     void sendAutoWho();
472     void startAutoWhoCycle();
473
474     void onSslErrors(const QList<QSslError>& errors);
475
476     /**
477      * Check the message token bucket
478      *
479      * If rate limiting is disabled and the message queue is empty, this disables the token bucket
480      * timer.  Otherwise, a queued message will be sent.
481      *
482      * @see CoreNetwork::fillBucketAndProcessQueue()
483      */
484     void checkTokenBucket();
485
486     /**
487      * Top up token bucket and send as many queued messages as possible
488      *
489      * If there's any room for more tokens, add to the token bucket.  Separately, if there's any
490      * messages to send, send until there's no more tokens or the queue is empty, whichever comes
491      * first.
492      */
493     void fillBucketAndProcessQueue();
494
495     void writeToSocket(const QByteArray& data);
496
497 private:
498     void showMessage(const NetworkInternalMessage& msg)
499     {
500         emit displayMsg(RawMessage(networkId(), msg));
501     }
502
503 private:
504     CoreSession* _coreSession;
505
506     bool _debugLogRawIrc;      ///< If true, include raw IRC socket messages in the debug log
507     qint32 _debugLogRawNetId;  ///< Network ID for logging raw IRC socket messages, or -1 for all
508
509     QSslSocket socket;
510     qint64 _socketId{0};
511
512     CoreUserInputHandler* _userInputHandler;
513     MetricsServer* _metricsServer;
514
515     QHash<QString, QString> _channelKeys;  // stores persistent channels and their passwords, if any
516
517     QTimer _autoReconnectTimer;
518     int _autoReconnectCount;
519
520     QTimer _socketCloseTimer;
521
522     /* this flag triggers quitRequested() once the socket is closed
523      * it is needed to determine whether or not the connection needs to be
524      * in the automatic session restore. */
525     bool _quitRequested;
526     QString _quitReason;
527
528     bool _disconnectExpected;  /// If true, connection is quitting, expect a socket close
529     // This avoids logging a spurious RemoteHostClosedError whenever disconnect is called without
530     // specifying a permanent (saved to core session) disconnect.
531
532     bool _shuttingDown{false};  ///< If true, we're shutting down and ignore requests to (dis)connect networks
533
534     bool _previousConnectionAttemptFailed;
535     int _lastUsedServerIndex;
536
537     QTimer _pingTimer;
538     qint64 _lastPingTime = 0;          ///< Unix time of most recently sent automatic ping
539     uint _pingCount = 0;               ///< Unacknowledged automatic pings
540     bool _sendPings = false;           ///< If true, pings should be periodically sent to server
541     bool _pongTimestampValid = false;  ///< If true, IRC server responds to PING by quoting in PONG
542     // This tracks whether or not a server responds to PING with a PONG of what was sent, or if it
543     // does something else.  If false, PING reply hiding should be more aggressive.
544     bool _pongReplyPending = false;  ///< If true, at least one PING sent without a PONG reply
545
546     QStringList _autoWhoQueue;
547     QHash<QString, int> _autoWhoPending;
548     QTimer _autoWhoTimer, _autoWhoCycleTimer;
549
550     // Maintain a list of CAPs that are being checked; if empty, negotiation finished
551     // See http://ircv3.net/specs/core/capability-negotiation-3.2.html
552     QStringList _capsQueuedIndividual;  /// Capabilities to check that require one at a time requests
553     QStringList _capsQueuedBundled;     /// Capabilities to check that can be grouped together
554     QStringList _capsQueuedLastBundle;  /// Most recent capability bundle requested (no individuals)
555     // Some capabilities, such as SASL, require follow-up messages to be fully enabled.  These
556     // capabilities should not be grouped with others to avoid requesting new capabilities while the
557     // previous capability is still being set up.
558     // Additionally, IRC servers can choose to send a 'NAK' to any set of requested capabilities.
559     // If this happens, we need a way to retry each capability individually in order to avoid having
560     // one failing capability (e.g. SASL) block all other capabilities.
561
562     bool _capNegotiationActive;  /// Whether or not full capability negotiation was started
563     // Avoid displaying repeat "negotiation finished" messages
564     bool _capInitialNegotiationEnded;  /// Whether or not initial capability negotiation finished
565     // Avoid sending repeat "CAP END" replies when registration is already ended
566
567     /**
568      * Gets the next set of capabilities to request, removing them from the queue.
569      *
570      * May return one or multiple space-separated capabilities, depending on queue.
571      *
572      * @returns Space-separated names of capabilities to request, or empty string if none remain
573      */
574     QString takeQueuedCaps();
575
576     /**
577      * Maximum length of a single 'CAP REQ' command.
578      *
579      * To be safe, 100 chars.  Higher numbers should be possible; this is following the conservative
580      * minimum number of characters that IRC servers must return in CAP NAK replies.  This also
581      * means CAP NAK replies will contain the full list of denied capabilities.
582      *
583      * See: http://ircv3.net/specs/core/capability-negotiation-3.1.html
584      */
585     const int maxCapRequestLength = 100;
586
587     QTimer _tokenBucketTimer;
588     // No need for int type as one cannot travel into the past (at least not yet, Doc)
589     quint32 _messageDelay;        /// Token refill speed in ms
590     quint32 _burstSize;           /// Size of the token bucket
591     quint32 _tokenBucket;         /// The virtual bucket that holds the tokens
592     QList<QByteArray> _msgQueue;  /// Queue of messages waiting to be sent
593     bool _skipMessageRates;       /// If true, skip all message rate limits
594
595     QString _requestedUserModes;  // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
596
597     // List of blowfish keys for channels
598     QHash<QString, QByteArray> _cipherKeys;
599 };