1 /***************************************************************************
2 * Copyright (C) 2005-2019 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
26 #include <QCoreApplication>
30 #include <QHostAddress>
31 #include <QLibraryInfo>
34 #include <QTranslator>
37 #include "bufferinfo.h"
44 #include "syncableobject.h"
49 # include "posixsignalwatcher.h"
51 # include "windowssignalwatcher.h"
55 : Singleton<Quassel>{this}
56 , _logger{new Logger{this}}
59 Q_INIT_RESOURCE(i18n);
63 void Quassel::init(RunMode runMode)
67 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
69 setupSignalHandling();
73 // Initial translation (may be overridden in UI settings)
74 loadTranslation(QLocale::system());
78 // Don't keep a debug log on the core
79 logger()->setup(runMode != RunMode::CoreOnly);
81 Network::setDefaultCodecForServer("UTF-8");
82 Network::setDefaultCodecForEncoding("UTF-8");
83 Network::setDefaultCodecForDecoding("ISO-8859-15");
86 Logger* Quassel::logger() const
91 void Quassel::registerQuitHandler(QuitHandler handler)
93 instance()->_quitHandlers.emplace_back(std::move(handler));
98 // Protect against multiple invocations (e.g. triggered by MainWin::closeEvent())
101 qInfo() << "Quitting...";
102 if (_quitHandlers.empty()) {
103 QCoreApplication::quit();
106 // Note: We expect one of the registered handlers to call QCoreApplication::quit()
107 for (auto&& handler : _quitHandlers) {
114 void Quassel::registerReloadHandler(ReloadHandler handler)
116 instance()->_reloadHandlers.emplace_back(std::move(handler));
119 bool Quassel::reloadConfig()
122 for (auto&& handler : _reloadHandlers) {
123 result = result && handler();
128 //! Register our custom types with Qt's Meta Object System.
129 /** This makes them available for QVariant and in signals/slots, among other things.
132 void Quassel::registerMetaTypes()
135 qRegisterMetaType<Message>("Message");
136 qRegisterMetaType<BufferInfo>("BufferInfo");
137 qRegisterMetaType<NetworkInfo>("NetworkInfo");
138 qRegisterMetaType<Network::Server>("Network::Server");
139 qRegisterMetaType<Identity>("Identity");
141 qRegisterMetaTypeStreamOperators<Message>("Message");
142 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
143 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
144 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
145 qRegisterMetaTypeStreamOperators<Identity>("Identity");
147 qRegisterMetaType<IdentityId>("IdentityId");
148 qRegisterMetaType<BufferId>("BufferId");
149 qRegisterMetaType<NetworkId>("NetworkId");
150 qRegisterMetaType<UserId>("UserId");
151 qRegisterMetaType<AccountId>("AccountId");
152 qRegisterMetaType<MsgId>("MsgId");
154 qRegisterMetaType<QHostAddress>("QHostAddress");
155 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
156 qRegisterMetaType<QUuid>("QUuid");
157 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
159 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
160 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
161 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
162 qRegisterMetaTypeStreamOperators<UserId>("UserId");
163 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
164 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
166 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
167 qRegisterMetaType<PeerPtr>("PeerPtr");
168 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
170 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
171 if (!QMetaType::type("QVariant")) {
172 qRegisterMetaType<QVariant>("QVariant");
173 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
177 void Quassel::setupEnvironment()
179 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
180 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
181 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
182 // hack extra search paths into various places.
184 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
185 if (xdgDataVar.isEmpty())
186 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
188 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
190 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
191 QString appDir = QCoreApplication::applicationDirPath();
192 int binpos = appDir.lastIndexOf("/bin");
194 appDir.replace(binpos, 4, "/share");
195 xdgDirs.append(appDir);
196 // Also append apps/quassel, this is only for QIconLoader to find icons there
197 xdgDirs.append(appDir + "/apps/quassel");
200 xdgDirs.append(appDir); // build directory is always the last fallback
202 xdgDirs.removeDuplicates();
204 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
208 void Quassel::setupBuildInfo()
211 buildInfo.applicationName = "quassel";
212 buildInfo.coreApplicationName = "quasselcore";
213 buildInfo.clientApplicationName = "quasselclient";
214 buildInfo.organizationName = "Quassel Project";
215 buildInfo.organizationDomain = "quassel-irc.org";
217 buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
219 buildInfo.baseVersion = QUASSEL_VERSION_STRING;
220 buildInfo.generatedVersion = GIT_DESCRIBE;
222 // Check if we got a commit hash
223 if (!QString(GIT_HEAD).isEmpty()) {
224 buildInfo.commitHash = GIT_HEAD;
225 // Set to Unix epoch, wrapped as a string for backwards-compatibility
226 buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
228 else if (!QString(DIST_HASH).contains("Format")) {
229 buildInfo.commitHash = DIST_HASH;
230 // Leave as Unix epoch if set as Unix epoch, but don't force this for
231 // backwards-compatibility with existing packaging/release tools that might set strings.
232 buildInfo.commitDate = QString(DIST_DATE);
235 // create a nice version string
236 if (buildInfo.generatedVersion.isEmpty()) {
237 if (!buildInfo.commitHash.isEmpty()) {
239 buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}.arg(buildInfo.baseVersion).arg(buildInfo.commitHash.left(7));
240 buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
241 .arg(buildInfo.baseVersion)
242 .arg(buildInfo.commitHash.left(7))
243 .arg(buildInfo.commitHash);
246 // we only have a base version :(
247 buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
251 // analyze what we got from git-describe
252 static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
253 if (rx.exactMatch(buildInfo.generatedVersion)) {
254 QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
255 buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
256 if (!buildInfo.commitHash.isEmpty()) {
257 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
258 .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
262 buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
265 if (buildInfo.fancyVersionString.isEmpty()) {
266 buildInfo.fancyVersionString = buildInfo.plainVersionString;
269 instance()->_buildInfo = std::move(buildInfo);
272 const Quassel::BuildInfo& Quassel::buildInfo()
274 return instance()->_buildInfo;
277 void Quassel::setupSignalHandling()
280 _signalWatcher = new PosixSignalWatcher(this);
282 _signalWatcher = new WindowsSignalWatcher(this);
284 connect(_signalWatcher, &AbstractSignalWatcher::handleSignal, this, &Quassel::handleSignal);
287 void Quassel::handleSignal(AbstractSignalWatcher::Action action)
290 case AbstractSignalWatcher::Action::Reload:
291 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for graceful reloading of processes.
292 if (!_reloadHandlers.empty()) {
293 qInfo() << "Reloading configuration";
294 if (reloadConfig()) {
295 qInfo() << "Successfully reloaded configuration";
299 case AbstractSignalWatcher::Action::Terminate:
304 qInfo() << "Already shutting down, ignoring signal";
307 case AbstractSignalWatcher::Action::HandleCrash:
308 logBacktrace(instance()->coreDumpFileName());
313 Quassel::RunMode Quassel::runMode()
315 return instance()->_runMode;
318 void Quassel::setupCliParser()
320 QList<QCommandLineOption> options;
323 /// @todo Bring back --datadir to specify the database location independent of config
324 if (runMode() == RunMode::ClientOnly) {
325 options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")};
328 options += {{"c", "configdir"},
329 tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."),
334 if (runMode() != RunMode::CoreOnly) {
336 {"icontheme", tr("Override the system icon theme ('breeze' is recommended)."), tr("theme")},
337 {"qss", tr("Load a custom application stylesheet."), tr("file.qss")},
338 {"hidewindow", tr("Start the client minimized to the system tray.")},
339 {"account", tr("Account id to connect to on startup."), tr("account"), "0"},
344 if (runMode() != RunMode::ClientOnly) {
346 {"listen", tr("The address(es) quasselcore will listen on."), tr("<address>[,<address>[,...]]"), "::,0.0.0.0"},
347 {{"p", "port"}, tr("The port quasselcore will listen at."), tr("port"), "4242"},
348 {{"n", "norestore"}, tr("Don't restore last core's state.")},
349 {"config-from-environment", tr("Load configuration from environment variables.")},
350 {"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")},
351 {"select-authenticator", tr("Select authentication backend."), tr("authidentifier")},
352 {"add-user", tr("Starts an interactive session to add a new core user.")},
354 tr("Starts an interactive session to change the password of the user identified by <username>."),
356 {"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")},
357 {"ident-daemon", tr("Enable internal ident daemon.")},
359 tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."),
362 {"ident-listen", tr("The address(es) quasselcore will listen on for ident requests. Same format as --listen."), tr("<address>[,...]"), "::1,127.0.0.1"},
363 {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")},
364 {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")},
366 {"require-ssl", tr("Require SSL for remote (non-loopback) client connections.")},
367 {"ssl-cert", tr("Specify the path to the SSL certificate."), tr("path"), "configdir/quasselCert.pem"},
368 {"ssl-key", tr("Specify the path to the SSL key."), tr("path"), "ssl-cert-path"},
375 {{"L", "loglevel"}, tr("Supports one of Debug|Info|Warning|Error; default is Info."), tr("level"), "Info"},
376 {{"l", "logfile"}, tr("Log to a file."), "path"},
378 {"syslog", tr("Log to syslog.")},
383 options += {{"d", "debug"}, tr("Enable debug output.")};
384 if (runMode() != RunMode::CoreOnly) {
386 {"debugbufferswitches", tr("Enables debugging for bufferswitches.")},
387 {"debugmodel", tr("Enables debugging for models.")},
390 if (runMode() != RunMode::ClientOnly) {
392 {"debug-irc", tr("Enable logging of all raw IRC messages to debug log, including passwords! In most cases you should also set --loglevel Debug")},
393 {"debug-irc-id", tr("Limit raw IRC logging to this network ID. Implies --debug-irc"), tr("database network ID"), "-1"},
394 {"debug-irc-parsed", tr("Enable logging of all parsed IRC messages to debug log, including passwords! In most cases you should also set --loglevel Debug")},
395 {"debug-irc-parsed-id", tr("Limit parsed IRC logging to this network ID. Implies --debug-irc-parsed"), tr("database network ID"), "-1"},
399 _cliParser.addOptions(options);
400 _cliParser.addHelpOption();
401 _cliParser.addVersionOption();
402 _cliParser.setApplicationDescription(tr("Quassel IRC is a modern, distributed IRC client."));
404 // This will call ::exit() for --help, --version and in case of errors
405 _cliParser.process(*QCoreApplication::instance());
408 QString Quassel::optionValue(const QString& key)
410 return instance()->_cliParser.value(key);
413 bool Quassel::isOptionSet(const QString& key)
415 return instance()->_cliParser.isSet(key);
418 const QString& Quassel::coreDumpFileName()
420 if (_coreDumpFileName.isEmpty()) {
421 QDir configDir(configDirPath());
422 _coreDumpFileName = configDir.absoluteFilePath(
423 QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
424 QFile dumpFile(_coreDumpFileName);
425 dumpFile.open(QIODevice::Append);
426 QTextStream dumpStream(&dumpFile);
427 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
428 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
432 return _coreDumpFileName;
435 QString Quassel::configDirPath()
437 if (!instance()->_configDirPath.isEmpty())
438 return instance()->_configDirPath;
441 if (isOptionSet("configdir")) {
442 path = Quassel::optionValue("configdir");
446 // On Mac, the path is always the same
447 path = QDir::homePath() + "/Library/Application Support/Quassel/";
449 // We abuse QSettings to find us a sensible path on the other platforms
451 // don't use the registry
452 QSettings::Format format = QSettings::IniFormat;
454 QSettings::Format format = QSettings::NativeFormat;
456 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
457 QFileInfo fileInfo(s.fileName());
458 path = fileInfo.dir().absolutePath();
459 #endif /* Q_OS_MAC */
462 path = QFileInfo{path}.absoluteFilePath();
464 if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
465 path += QDir::separator();
468 if (!qDir.exists(path)) {
469 if (!qDir.mkpath(path)) {
470 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
475 instance()->_configDirPath = path;
479 QStringList Quassel::dataDirPaths()
481 if (!instance()->_dataDirPaths.isEmpty())
482 return instance()->_dataDirPaths;
484 // TODO: Migrate to QStandardPaths (will require moving of the sqlite database,
485 // or a fallback for it being in the config dir)
487 QStringList dataDirNames;
489 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
490 << qgetenv("APPDATA") + QCoreApplication::organizationDomain() << QCoreApplication::applicationDirPath();
491 #elif defined Q_OS_MAC
492 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" << QCoreApplication::applicationDirPath();
496 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
497 // This should thus come first.
498 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
499 if (xdgDataHome.isEmpty())
500 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
501 dataDirNames << xdgDataHome;
503 // Now whatever is configured through XDG_DATA_DIRS
504 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
505 if (xdgDataDirs.isEmpty())
506 dataDirNames << "/usr/local/share"
509 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
511 // Just in case, also check our install prefix
512 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
514 // Normalize and append our application name
515 for (int i = 0; i < dataDirNames.count(); i++)
516 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
520 // Add resource path and workdir just in case.
521 // Workdir should have precedence
522 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
523 dataDirNames.append(":/data/");
525 // Append trailing '/' and check for existence
526 auto iter = dataDirNames.begin();
527 while (iter != dataDirNames.end()) {
528 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
529 iter->append(QDir::separator());
530 if (!QFile::exists(*iter))
531 iter = dataDirNames.erase(iter);
536 dataDirNames.removeDuplicates();
538 instance()->_dataDirPaths = dataDirNames;
542 QString Quassel::findDataFilePath(const QString& fileName)
544 QStringList dataDirs = dataDirPaths();
545 foreach (QString dataDir, dataDirs) {
546 QString path = dataDir + fileName;
547 if (QFile::exists(path))
553 QStringList Quassel::scriptDirPaths()
555 QStringList res(configDirPath() + "scripts/");
556 foreach (QString path, dataDirPaths())
557 res << path + "scripts/";
561 QString Quassel::translationDirPath()
563 if (instance()->_translationDirPath.isEmpty()) {
564 // We support only one translation dir; fallback mechanisms wouldn't work else.
565 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
566 foreach (const QString& dir, dataDirPaths()) {
567 if (QFile::exists(dir + "translations/")) {
568 instance()->_translationDirPath = dir + "translations/";
572 if (instance()->_translationDirPath.isEmpty())
573 instance()->_translationDirPath = ":/i18n/";
575 return instance()->_translationDirPath;
578 void Quassel::loadTranslation(const QLocale& locale)
580 auto* qtTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QtTr");
581 auto* quasselTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QuasselTr");
584 qApp->removeTranslator(qtTranslator);
585 if (quasselTranslator)
586 qApp->removeTranslator(quasselTranslator);
588 // We use QLocale::C to indicate that we don't want a translation
589 if (locale.language() == QLocale::C)
592 qtTranslator = new QTranslator(qApp);
593 qtTranslator->setObjectName("QtTr");
595 quasselTranslator = new QTranslator(qApp);
596 quasselTranslator->setObjectName("QuasselTr");
599 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
601 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
602 quasselTranslator->load(locale, QString(""), translationDirPath());
604 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
606 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
607 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
610 qApp->installTranslator(quasselTranslator);
611 qApp->installTranslator(qtTranslator);
614 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
616 Quassel::Features::Features()
618 QStringList features;
620 // TODO Qt5: Use QMetaEnum::fromType()
621 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
622 _features.resize(featureEnum.keyCount(), true); // enable all known features to true
625 Quassel::Features::Features(const QStringList& features, LegacyFeatures legacyFeatures)
627 // TODO Qt5: Use QMetaEnum::fromType()
628 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
629 _features.resize(featureEnum.keyCount(), false);
631 for (auto&& feature : features) {
632 int i = featureEnum.keyToValue(qPrintable(feature));
637 _unknownFeatures << feature;
641 if (legacyFeatures) {
642 // TODO Qt5: Use QMetaEnum::fromType()
643 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
644 for (quint32 mask = 0x0001; mask <= 0x8000; mask <<= 1) {
645 if (static_cast<quint32>(legacyFeatures) & mask) {
646 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
655 bool Quassel::Features::isEnabled(Feature feature) const
657 auto i = static_cast<size_t>(feature);
658 return i < _features.size() ? _features[i] : false;
661 QStringList Quassel::Features::toStringList(bool enabled) const
663 // Check if any feature is enabled
664 if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
665 return QStringList{} << "NoFeatures";
670 // TODO Qt5: Use QMetaEnum::fromType()
671 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
672 for (quint32 i = 0; i < _features.size(); ++i) {
673 if (_features[i] == enabled) {
674 result << featureEnum.key(i);
680 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
682 // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
684 // TODO Qt5: Use QMetaEnum::fromType()
685 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
686 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
688 for (quint32 i = 0; i < _features.size(); ++i) {
690 int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
696 return static_cast<LegacyFeatures>(result);
699 QStringList Quassel::Features::unknownFeatures() const
701 return _unknownFeatures;