1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
40 #include "logmessage.h"
45 #include "syncableobject.h"
50 # include "posixsignalwatcher.h"
52 # include "windowssignalwatcher.h"
56 : Singleton<Quassel>{this}
57 , _logger{new Logger{this}}
60 Q_INIT_RESOURCE(i18n);
65 void Quassel::init(RunMode runMode)
69 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
71 setupSignalHandling();
75 // Initial translation (may be overridden in UI settings)
76 loadTranslation(QLocale::system());
80 // Don't keep a debug log on the core
81 logger()->setup(runMode != RunMode::CoreOnly);
83 Network::setDefaultCodecForServer("UTF-8");
84 Network::setDefaultCodecForEncoding("UTF-8");
85 Network::setDefaultCodecForDecoding("ISO-8859-15");
89 Logger *Quassel::logger() const
95 void Quassel::registerQuitHandler(QuitHandler handler)
97 instance()->_quitHandlers.emplace_back(std::move(handler));
102 // Protect against multiple invocations (e.g. triggered by MainWin::closeEvent())
105 quInfo() << "Quitting...";
106 if (_quitHandlers.empty()) {
107 QCoreApplication::quit();
110 // Note: We expect one of the registered handlers to call QCoreApplication::quit()
111 for (auto &&handler : _quitHandlers) {
119 void Quassel::registerReloadHandler(ReloadHandler handler)
121 instance()->_reloadHandlers.emplace_back(std::move(handler));
125 bool Quassel::reloadConfig()
128 for (auto &&handler : _reloadHandlers) {
129 result = result && handler();
135 //! Register our custom types with Qt's Meta Object System.
136 /** This makes them available for QVariant and in signals/slots, among other things.
139 void Quassel::registerMetaTypes()
142 qRegisterMetaType<Message>("Message");
143 qRegisterMetaType<BufferInfo>("BufferInfo");
144 qRegisterMetaType<NetworkInfo>("NetworkInfo");
145 qRegisterMetaType<Network::Server>("Network::Server");
146 qRegisterMetaType<Identity>("Identity");
148 qRegisterMetaTypeStreamOperators<Message>("Message");
149 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
150 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
151 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
152 qRegisterMetaTypeStreamOperators<Identity>("Identity");
154 qRegisterMetaType<IdentityId>("IdentityId");
155 qRegisterMetaType<BufferId>("BufferId");
156 qRegisterMetaType<NetworkId>("NetworkId");
157 qRegisterMetaType<UserId>("UserId");
158 qRegisterMetaType<AccountId>("AccountId");
159 qRegisterMetaType<MsgId>("MsgId");
161 qRegisterMetaType<QHostAddress>("QHostAddress");
162 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
163 qRegisterMetaType<QUuid>("QUuid");
164 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
166 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
167 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
168 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
169 qRegisterMetaTypeStreamOperators<UserId>("UserId");
170 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
171 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
173 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
174 qRegisterMetaType<PeerPtr>("PeerPtr");
175 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
177 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
178 if (!QMetaType::type("QVariant")) {
179 qRegisterMetaType<QVariant>("QVariant");
180 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
185 void Quassel::setupEnvironment()
187 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
188 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
189 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
190 // hack extra search paths into various places.
192 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
193 if (xdgDataVar.isEmpty())
194 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
196 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
198 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
199 QString appDir = QCoreApplication::applicationDirPath();
200 int binpos = appDir.lastIndexOf("/bin");
202 appDir.replace(binpos, 4, "/share");
203 xdgDirs.append(appDir);
204 // Also append apps/quassel, this is only for QIconLoader to find icons there
205 xdgDirs.append(appDir + "/apps/quassel");
207 xdgDirs.append(appDir); // build directory is always the last fallback
209 xdgDirs.removeDuplicates();
211 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
216 void Quassel::setupBuildInfo()
219 buildInfo.applicationName = "quassel";
220 buildInfo.coreApplicationName = "quasselcore";
221 buildInfo.clientApplicationName = "quasselclient";
222 buildInfo.organizationName = "Quassel Project";
223 buildInfo.organizationDomain = "quassel-irc.org";
225 buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
227 buildInfo.baseVersion = QUASSEL_VERSION_STRING;
228 buildInfo.generatedVersion = GIT_DESCRIBE;
230 // Check if we got a commit hash
231 if (!QString(GIT_HEAD).isEmpty()) {
232 buildInfo.commitHash = GIT_HEAD;
233 // Set to Unix epoch, wrapped as a string for backwards-compatibility
234 buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
236 else if (!QString(DIST_HASH).contains("Format")) {
237 buildInfo.commitHash = DIST_HASH;
238 // Leave as Unix epoch if set as Unix epoch, but don't force this for
239 // backwards-compatibility with existing packaging/release tools that might set strings.
240 buildInfo.commitDate = QString(DIST_DATE);
243 // create a nice version string
244 if (buildInfo.generatedVersion.isEmpty()) {
245 if (!buildInfo.commitHash.isEmpty()) {
247 buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
248 .arg(buildInfo.baseVersion)
249 .arg(buildInfo.commitHash.left(7));
250 buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
251 .arg(buildInfo.baseVersion)
252 .arg(buildInfo.commitHash.left(7))
253 .arg(buildInfo.commitHash);
256 // we only have a base version :(
257 buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
261 // analyze what we got from git-describe
262 static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
263 if (rx.exactMatch(buildInfo.generatedVersion)) {
264 QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
265 buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
266 if (!buildInfo.commitHash.isEmpty()) {
267 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
268 .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
272 buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
275 if (buildInfo.fancyVersionString.isEmpty()) {
276 buildInfo.fancyVersionString = buildInfo.plainVersionString;
279 instance()->_buildInfo = std::move(buildInfo);
283 const Quassel::BuildInfo &Quassel::buildInfo()
285 return instance()->_buildInfo;
289 void Quassel::setupSignalHandling()
292 _signalWatcher = new PosixSignalWatcher(this);
294 _signalWatcher = new WindowsSignalWatcher(this);
296 connect(_signalWatcher, &AbstractSignalWatcher::handleSignal, this, &Quassel::handleSignal);
300 void Quassel::handleSignal(AbstractSignalWatcher::Action action)
303 case AbstractSignalWatcher::Action::Reload:
304 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for graceful reloading of processes.
305 if (!_reloadHandlers.empty()) {
306 quInfo() << "Reloading configuration";
307 if (reloadConfig()) {
308 quInfo() << "Successfully reloaded configuration";
312 case AbstractSignalWatcher::Action::Terminate:
317 quInfo() << "Already shutting down, ignoring signal";
320 case AbstractSignalWatcher::Action::HandleCrash:
321 logBacktrace(instance()->coreDumpFileName());
327 Quassel::RunMode Quassel::runMode() {
328 return instance()->_runMode;
332 void Quassel::setupCliParser()
334 QList<QCommandLineOption> options;
337 /// @todo Bring back --datadir to specify the database location independent of config
338 if (runMode() == RunMode::ClientOnly) {
339 options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")};
342 options += {{"c", "configdir"}, tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."), tr("path")};
346 if (runMode() != RunMode::CoreOnly) {
348 {"icontheme", tr("Override the system icon theme ('breeze' is recommended)."), tr("theme")},
349 {"qss", tr("Load a custom application stylesheet."), tr("file.qss")},
350 {"hidewindow", tr("Start the client minimized to the system tray.")},
355 if (runMode() != RunMode::ClientOnly) {
357 {"listen", tr("The address(es) quasselcore will listen on."), tr("<address>[,<address>[,...]]"), "::,0.0.0.0"},
358 {{"p", "port"}, tr("The port quasselcore will listen at."), tr("port"), "4242"},
359 {{"n", "norestore"}, tr("Don't restore last core's state.")},
360 {"config-from-environment", tr("Load configuration from environment variables.")},
361 {"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")},
362 {"select-authenticator", tr("Select authentication backend."), tr("authidentifier")},
363 {"add-user", tr("Starts an interactive session to add a new core user.")},
364 {"change-userpass", tr("Starts an interactive session to change the password of the user identified by <username>."), tr("username")},
365 {"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")},
366 {"ident-daemon", tr("Enable internal ident daemon.")},
367 {"ident-port", tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."), tr("port"), "10113"},
368 {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")},
369 {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")},
371 {"require-ssl", tr("Require SSL for remote (non-loopback) client connections.")},
372 {"ssl-cert", tr("Specify the path to the SSL certificate."), tr("path"), "configdir/quasselCert.pem"},
373 {"ssl-key", tr("Specify the path to the SSL key."), tr("path"), "ssl-cert-path"},
380 {{"L", "loglevel"}, tr("Supports one of Debug|Info|Warning|Error; default is Info."), tr("level"), "Info"},
381 {{"l", "logfile"}, tr("Log to a file."), "path"},
383 {"syslog", tr("Log to syslog.")},
388 options += {{"d", "debug"}, tr("Enable debug output.")};
389 if (runMode() != RunMode::CoreOnly) {
391 {"debugbufferswitches", tr("Enables debugging for bufferswitches.")},
392 {"debugmodel", tr("Enables debugging for models.")},
395 if (runMode() != RunMode::ClientOnly) {
397 {"debug-irc", tr("Enable logging of all raw IRC messages to debug log, including passwords! In most cases you should also set --loglevel Debug")},
398 {"debug-irc-id", tr("Limit raw IRC logging to this network ID. Implies --debug-irc"), tr("database network ID"), "-1"},
402 _cliParser.addOptions(options);
403 _cliParser.addHelpOption();
404 _cliParser.addVersionOption();
405 _cliParser.setApplicationDescription(tr("Quassel IRC is a modern, distributed IRC client."));
407 // This will call ::exit() for --help, --version and in case of errors
408 _cliParser.process(*QCoreApplication::instance());
412 QString Quassel::optionValue(const QString &key)
414 return instance()->_cliParser.value(key);
418 bool Quassel::isOptionSet(const QString &key)
420 return instance()->_cliParser.isSet(key);
424 const QString &Quassel::coreDumpFileName()
426 if (_coreDumpFileName.isEmpty()) {
427 QDir configDir(configDirPath());
428 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
429 QFile dumpFile(_coreDumpFileName);
430 dumpFile.open(QIODevice::Append);
431 QTextStream dumpStream(&dumpFile);
432 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
433 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
437 return _coreDumpFileName;
441 QString Quassel::configDirPath()
443 if (!instance()->_configDirPath.isEmpty())
444 return instance()->_configDirPath;
447 if (isOptionSet("configdir")) {
448 path = Quassel::optionValue("configdir");
452 // On Mac, the path is always the same
453 path = QDir::homePath() + "/Library/Application Support/Quassel/";
455 // We abuse QSettings to find us a sensible path on the other platforms
457 // don't use the registry
458 QSettings::Format format = QSettings::IniFormat;
460 QSettings::Format format = QSettings::NativeFormat;
462 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
463 QFileInfo fileInfo(s.fileName());
464 path = fileInfo.dir().absolutePath();
465 #endif /* Q_OS_MAC */
468 path = QFileInfo{path}.absoluteFilePath();
470 if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
471 path += QDir::separator();
474 if (!qDir.exists(path)) {
475 if (!qDir.mkpath(path)) {
476 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
481 instance()->_configDirPath = path;
486 QStringList Quassel::dataDirPaths()
488 if (!instance()->_dataDirPaths.isEmpty())
489 return instance()->_dataDirPaths;
491 // TODO: Migrate to QStandardPaths (will require moving of the sqlite database,
492 // or a fallback for it being in the config dir)
494 QStringList dataDirNames;
496 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
497 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
498 << QCoreApplication::applicationDirPath();
499 #elif defined Q_OS_MAC
500 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
501 << QCoreApplication::applicationDirPath();
505 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
506 // This should thus come first.
507 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
508 if (xdgDataHome.isEmpty())
509 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
510 dataDirNames << xdgDataHome;
512 // Now whatever is configured through XDG_DATA_DIRS
513 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
514 if (xdgDataDirs.isEmpty())
515 dataDirNames << "/usr/local/share" << "/usr/share";
517 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
519 // Just in case, also check our install prefix
520 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
522 // Normalize and append our application name
523 for (int i = 0; i < dataDirNames.count(); i++)
524 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
528 // Add resource path and workdir just in case.
529 // Workdir should have precedence
530 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
531 dataDirNames.append(":/data/");
533 // Append trailing '/' and check for existence
534 auto iter = dataDirNames.begin();
535 while (iter != dataDirNames.end()) {
536 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
537 iter->append(QDir::separator());
538 if (!QFile::exists(*iter))
539 iter = dataDirNames.erase(iter);
544 dataDirNames.removeDuplicates();
546 instance()->_dataDirPaths = dataDirNames;
551 QString Quassel::findDataFilePath(const QString &fileName)
553 QStringList dataDirs = dataDirPaths();
554 foreach(QString dataDir, dataDirs) {
555 QString path = dataDir + fileName;
556 if (QFile::exists(path))
563 QStringList Quassel::scriptDirPaths()
565 QStringList res(configDirPath() + "scripts/");
566 foreach(QString path, dataDirPaths())
567 res << path + "scripts/";
572 QString Quassel::translationDirPath()
574 if (instance()->_translationDirPath.isEmpty()) {
575 // We support only one translation dir; fallback mechanisms wouldn't work else.
576 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
577 foreach(const QString &dir, dataDirPaths()) {
578 if (QFile::exists(dir + "translations/")) {
579 instance()->_translationDirPath = dir + "translations/";
583 if (instance()->_translationDirPath.isEmpty())
584 instance()->_translationDirPath = ":/i18n/";
586 return instance()->_translationDirPath;
590 void Quassel::loadTranslation(const QLocale &locale)
592 auto *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
593 auto *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
596 qApp->removeTranslator(qtTranslator);
597 if (quasselTranslator)
598 qApp->removeTranslator(quasselTranslator);
600 // We use QLocale::C to indicate that we don't want a translation
601 if (locale.language() == QLocale::C)
604 qtTranslator = new QTranslator(qApp);
605 qtTranslator->setObjectName("QtTr");
607 quasselTranslator = new QTranslator(qApp);
608 quasselTranslator->setObjectName("QuasselTr");
611 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
613 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
614 quasselTranslator->load(locale, QString(""), translationDirPath());
616 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
618 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
619 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
622 qApp->installTranslator(quasselTranslator);
623 qApp->installTranslator(qtTranslator);
627 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
629 Quassel::Features::Features()
631 QStringList features;
633 // TODO Qt5: Use QMetaEnum::fromType()
634 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
635 _features.resize(featureEnum.keyCount(), true); // enable all known features to true
639 Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
641 // TODO Qt5: Use QMetaEnum::fromType()
642 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
643 _features.resize(featureEnum.keyCount(), false);
645 for (auto &&feature : features) {
646 int i = featureEnum.keyToValue(qPrintable(feature));
651 _unknownFeatures << feature;
655 if (legacyFeatures) {
656 // TODO Qt5: Use QMetaEnum::fromType()
657 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
658 for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
659 if (static_cast<quint32>(legacyFeatures) & mask) {
660 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
670 bool Quassel::Features::isEnabled(Feature feature) const
672 auto i = static_cast<size_t>(feature);
673 return i < _features.size() ? _features[i] : false;
677 QStringList Quassel::Features::toStringList(bool enabled) const
679 // Check if any feature is enabled
680 if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
681 return QStringList{} << "NoFeatures";
686 // TODO Qt5: Use QMetaEnum::fromType()
687 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
688 for (quint32 i = 0; i < _features.size(); ++i) {
689 if (_features[i] == enabled) {
690 result << featureEnum.key(i);
697 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
699 // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
701 // TODO Qt5: Use QMetaEnum::fromType()
702 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
703 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
705 for (quint32 i = 0; i < _features.size(); ++i) {
707 int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
713 return static_cast<LegacyFeatures>(result);
717 QStringList Quassel::Features::unknownFeatures() const
719 return _unknownFeatures;