common: Don't use unsafe functions when handling POSIX signals
[quassel.git] / src / common / quassel.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 #include <memory>
25 #include <vector>
26
27 #include <QCoreApplication>
28 #include <QFile>
29 #include <QObject>
30 #include <QLocale>
31 #include <QString>
32 #include <QStringList>
33
34 #include "abstractcliparser.h"
35 #include "abstractsignalwatcher.h"
36 #include "singleton.h"
37
38 class QFile;
39
40 class Logger;
41
42 class Quassel : public QObject, public Singleton<Quassel>
43 {
44     // TODO Qt5: Use Q_GADGET
45     Q_OBJECT
46
47 public:
48     enum RunMode {
49         Monolithic,
50         ClientOnly,
51         CoreOnly
52     };
53
54     struct BuildInfo {
55         QString fancyVersionString; // clickable rev
56         QString plainVersionString; // no <a> tag
57
58         QString baseVersion;
59         QString generatedVersion;
60         QString commitHash;
61         QString commitDate;
62
63         uint protocolVersion; // deprecated
64
65         QString applicationName;
66         QString coreApplicationName;
67         QString clientApplicationName;
68         QString organizationName;
69         QString organizationDomain;
70     };
71
72     /**
73      * This enum defines the optional features supported by cores/clients prior to version 0.13.
74      *
75      * Since the number of features declared this way is limited to 16 (due to the enum not having a defined
76      * width in cores/clients prior to 0.13), and for more robustness when negotiating features on connect,
77      * the bitfield-based representation was replaced by a string-based representation in 0.13, support for
78      * which is indicated by having the ExtendedFeatures flag set. Extended features are defined in the Feature
79      * enum.
80      *
81      * @warning Do not alter this enum; new features must be added (only) to the @a Feature enum.
82      *
83      * @sa Feature
84      */
85     enum class LegacyFeature : quint32 {
86         SynchronizedMarkerLine = 0x0001,
87         SaslAuthentication     = 0x0002,
88         SaslExternal           = 0x0004,
89         HideInactiveNetworks   = 0x0008,
90         PasswordChange         = 0x0010,
91         CapNegotiation         = 0x0020,
92         VerifyServerSSL        = 0x0040,
93         CustomRateLimits       = 0x0080,
94         // DccFileTransfer     = 0x0100,  // never in use
95         AwayFormatTimestamp    = 0x0200,
96         Authenticators         = 0x0400,
97         BufferActivitySync     = 0x0800,
98         CoreSideHighlights     = 0x1000,
99         SenderPrefixes         = 0x2000,
100         RemoteDisconnect       = 0x4000,
101         ExtendedFeatures       = 0x8000,
102     };
103     Q_FLAGS(LegacyFeature)
104     Q_DECLARE_FLAGS(LegacyFeatures, LegacyFeature)
105
106     /**
107      * A list of features that are optional in core and/or client, but need runtime checking.
108      *
109      * Some features require an uptodate counterpart, but don't justify a protocol break.
110      * This is what we use this enum for. Add such features to it and check at runtime on the other
111      * side for their existence.
112      *
113      * For feature negotiation, these enum values are serialized as strings, so order does not matter. However,
114      * do not rename existing enum values to avoid breaking compatibility.
115      *
116      * This list should be cleaned up after every protocol break, as we can assume them to be present then.
117      */
118     #if QT_VERSION >= 0x050000
119     enum class Feature : uint32_t {
120     #else
121     enum Feature {
122     #endif
123         SynchronizedMarkerLine,
124         SaslAuthentication,
125         SaslExternal,
126         HideInactiveNetworks,
127         PasswordChange,           ///< Remote password change
128         CapNegotiation,           ///< IRCv3 capability negotiation, account tracking
129         VerifyServerSSL,          ///< IRC server SSL validation
130         CustomRateLimits,         ///< IRC server custom message rate limits
131         AwayFormatTimestamp,      ///< Timestamp formatting in away (e.g. %%hh:mm%%)
132         Authenticators,           ///< Whether or not the core supports auth backends
133         BufferActivitySync,       ///< Sync buffer activity status
134         CoreSideHighlights,       ///< Core-Side highlight configuration and matching
135         SenderPrefixes,           ///< Show prefixes for senders in backlog
136         RemoteDisconnect,         ///< Allow this peer to be remotely disconnected
137         ExtendedFeatures,         ///< Extended features
138         LongTime,                 ///< Serialize time as 64-bit values
139         RichMessages,             ///< Real Name and Avatar URL in backlog
140         BacklogFilterType,        ///< BacklogManager supports filtering backlog by MessageType
141 #if QT_VERSION >= 0x050500
142         EcdsaCertfpKeys,          ///< ECDSA keys for CertFP in identities
143 #endif
144         LongMessageId,            ///< 64-bit IDs for messages
145         SyncedCoreInfo,           ///< CoreInfo dynamically updated using signals
146     };
147     Q_ENUMS(Feature)
148
149     class Features;
150
151     Quassel();
152
153     /**
154      * Provides access to the Logger instance.
155      *
156      * @returns The Logger instance
157      */
158     Logger *logger() const;
159
160     static void setupBuildInfo();
161     static const BuildInfo &buildInfo();
162     static RunMode runMode();
163
164     static QString configDirPath();
165
166     //! Returns a list of data directory paths
167     /** There are several locations for applications to install their data files in. On Unix,
168     *  a common location is /usr/share; others include $PREFIX/share and additional directories
169     *  specified in the env variable XDG_DATA_DIRS.
170     *  \return A list of directory paths to look for data files in
171     */
172     static QStringList dataDirPaths();
173
174     //! Searches for a data file in the possible data directories
175     /** Data files can reside in $DATA_DIR/apps/quassel, where $DATA_DIR is one of the directories
176     *  returned by \sa dataDirPaths().
177     *  \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs.
178     *  \return The full path to the data file if found; a null QString else
179     */
180     static QString findDataFilePath(const QString &filename);
181
182     static QString translationDirPath();
183
184     //! Returns a list of directories we look for scripts in
185     /** We look for a subdirectory named "scripts" in the configdir and in all datadir paths.
186     *   \return A list of directory paths containing executable scripts for /exec
187     */
188     static QStringList scriptDirPaths();
189
190     static void loadTranslation(const QLocale &locale);
191
192     static void setCliParser(std::shared_ptr<AbstractCliParser> cliParser);
193     static QString optionValue(const QString &option);
194     static bool isOptionSet(const QString &option);
195
196     using ReloadHandler = std::function<bool()>;
197
198     static void registerReloadHandler(ReloadHandler handler);
199
200     using QuitHandler = std::function<void()>;
201
202     /**
203      * Registers a handler that is called when the application is supposed to quit.
204      *
205      * @note If multiple handlers are registered, they are processed in order of registration.
206      * @note If any handler is registered, quit() will not call QCoreApplication::quit(). It relies
207      *       on one of the handlers doing so, instead.
208      * @param quitHandler Handler to register
209      */
210     static void registerQuitHandler(QuitHandler quitHandler);
211
212     const QString &coreDumpFileName();
213
214 public slots:
215     /**
216      * Requests to quit the application.
217      *
218      * Calls any registered quit handlers. If no handlers are registered, calls QCoreApplication::quit().
219      */
220     void quit();
221
222 signals:
223     void messageLogged(const QDateTime &timeStamp, const QString &msg);
224
225 protected:
226     static bool init();
227
228     static void setRunMode(Quassel::RunMode runMode);
229
230     static void setDataDirPaths(const QStringList &paths);
231     static QStringList findDataDirPaths();
232
233     friend class CoreApplication;
234     friend class QtUiApplication;
235     friend class MonolithicApplication;
236
237 private:
238     void setupEnvironment();
239     void registerMetaTypes();
240     void setupSignalHandling();
241
242     /**
243      * Requests a reload of relevant runtime configuration.
244      *
245      * Calls any registered reload handlers, and returns the cumulative result. If no handlers are registered,
246      * does nothing and returns true.
247      *
248      * @returns True if configuration reload successful, otherwise false
249      */
250     bool reloadConfig();
251
252     void logBacktrace(const QString &filename);
253
254 private slots:
255     void handleSignal(AbstractSignalWatcher::Action action);
256
257 private:
258     BuildInfo _buildInfo;
259     RunMode _runMode;
260     bool _initialized{false};
261     bool _quitting{false};
262
263     QString _coreDumpFileName;
264     QString _configDirPath;
265     QStringList _dataDirPaths;
266     QString _translationDirPath;
267
268     std::shared_ptr<AbstractCliParser> _cliParser;
269
270     Logger *_logger;
271     AbstractSignalWatcher *_signalWatcher{nullptr};
272
273     std::vector<ReloadHandler> _reloadHandlers;
274     std::vector<QuitHandler> _quitHandlers;
275 };
276
277 // --------------------------------------------------------------------------------------------------------------------
278
279 /**
280  * Class representing a set of supported core/client features.
281  *
282  * @sa Quassel::Feature
283  */
284 class Quassel::Features
285 {
286 public:
287     /**
288      * Default constructor.
289      *
290      * Creates a Feature instance with all known features (i.e., all values declared in the Quassel::Feature enum) set.
291      * This is useful for easily creating a Feature instance that represent the current version's capabilities.
292      */
293     Features();
294
295     /**
296      * Constructs a Feature instance holding the given list of features.
297      *
298      * Both the @a features and the @a legacyFeatures arguments are considered (additively).
299      * This is useful when receiving a list of features from another peer.
300      *
301      * @param features       A list of strings matching values in the Quassel::Feature enum. Strings that don't match are
302      *                       can be accessed after construction via unknownFeatures(), but are otherwise ignored.
303      * @param legacyFeatures Holds a bit-wise combination of LegacyFeature flag values, which are each added to the list of
304      *                       features represented by this Features instance.
305      */
306     Features(const QStringList &features, LegacyFeatures legacyFeatures);
307
308     /**
309      * Check if a given feature is marked as enabled in this Features instance.
310      *
311      * @param feature The feature to be queried
312      * @returns Whether the given feature is marked as enabled
313      */
314     bool isEnabled(Feature feature) const;
315
316     /**
317      * Provides a list of all features marked as either enabled or disabled (as indicated by the @a enabled argument) as strings.
318      *
319      * @param enabled Whether to return the enabled or the disabled features
320      * @return A string list containing all enabled or disabled features
321      */
322     QStringList toStringList(bool enabled = true) const;
323
324     /**
325      * Provides a list of all enabled legacy features (i.e. features defined prior to v0.13) as bit-wise combination in a
326      * LegacyFeatures type.
327      *
328      * @note Extended features cannot be represented this way, and are thus ignored even if set.
329      * @return A LegacyFeatures type holding the bit-wise combination of all legacy features enabled in this Features instance
330      */
331     LegacyFeatures toLegacyFeatures() const;
332
333     /**
334      * Provides the list of strings that could not be mapped to Quassel::Feature enum values on construction.
335      *
336      * Useful for debugging/logging purposes.
337      *
338      * @returns A list of strings that could not be mapped to the Feature enum on construction of this Features instance, if any
339      */
340     QStringList unknownFeatures() const;
341
342 private:
343     std::vector<bool> _features;
344     QStringList _unknownFeatures;
345 };