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 ***************************************************************************/
27 #if !defined Q_OS_WIN && !defined Q_OS_MAC
28 # include <sys/types.h>
29 # include <sys/time.h>
30 # include <sys/resource.h>
33 #include <QCoreApplication>
37 #include <QHostAddress>
38 #include <QLibraryInfo>
41 #include <QTranslator>
44 #include "bufferinfo.h"
47 #include "logmessage.h"
52 #include "syncableobject.h"
55 #include "../../version.h"
57 Quassel *Quassel::instance()
59 static Quassel instance;
65 : _logger{new Logger{this}}
72 if (instance()->_initialized)
73 return true; // allow multiple invocations because of MonolithicApplication
75 // Setup signal handling
76 // TODO: Don't use unsafe methods, see handleSignal()
78 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
79 signal(SIGTERM, handleSignal);
80 signal(SIGINT, handleSignal);
82 // SIGHUP is used to reload configuration (i.e. SSL certificates)
83 // Windows does not support SIGHUP
84 signal(SIGHUP, handleSignal);
87 if (instance()->_handleCrashes) {
88 // we have crashhandler for win32 and unix (based on execinfo).
89 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
91 // we only handle crashes ourselves if coredumps are disabled
92 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
93 int rc = getrlimit(RLIMIT_CORE, limit);
95 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
96 # endif /* Q_OS_WIN */
97 signal(SIGABRT, handleSignal);
98 signal(SIGSEGV, handleSignal);
100 signal(SIGBUS, handleSignal);
103 # endif /* Q_OS_WIN */
104 #endif /* Q_OS_WIN || HAVE_EXECINFO */
107 instance()->_initialized = true;
108 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
110 instance()->setupEnvironment();
111 instance()->registerMetaTypes();
113 Network::setDefaultCodecForServer("UTF-8");
114 Network::setDefaultCodecForEncoding("UTF-8");
115 Network::setDefaultCodecForDecoding("ISO-8859-15");
117 if (isOptionSet("help")) {
118 instance()->_cliParser->usage();
122 if (isOptionSet("version")) {
123 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
127 // Don't keep a debug log on the core
128 return instance()->logger()->setup(runMode() != RunMode::CoreOnly);
132 void Quassel::destroy()
137 Logger *Quassel::logger() const
143 void Quassel::registerQuitHandler(QuitHandler handler)
145 instance()->_quitHandlers.emplace_back(std::move(handler));
150 if (_quitHandlers.empty()) {
151 QCoreApplication::quit();
154 for (auto &&handler : _quitHandlers) {
161 void Quassel::registerReloadHandler(ReloadHandler handler)
163 instance()->_reloadHandlers.emplace_back(std::move(handler));
167 bool Quassel::reloadConfig()
170 for (auto &&handler : _reloadHandlers) {
171 result = result && handler();
177 //! Register our custom types with Qt's Meta Object System.
178 /** This makes them available for QVariant and in signals/slots, among other things.
181 void Quassel::registerMetaTypes()
184 qRegisterMetaType<Message>("Message");
185 qRegisterMetaType<BufferInfo>("BufferInfo");
186 qRegisterMetaType<NetworkInfo>("NetworkInfo");
187 qRegisterMetaType<Network::Server>("Network::Server");
188 qRegisterMetaType<Identity>("Identity");
190 qRegisterMetaTypeStreamOperators<Message>("Message");
191 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
192 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
193 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
194 qRegisterMetaTypeStreamOperators<Identity>("Identity");
196 qRegisterMetaType<IdentityId>("IdentityId");
197 qRegisterMetaType<BufferId>("BufferId");
198 qRegisterMetaType<NetworkId>("NetworkId");
199 qRegisterMetaType<UserId>("UserId");
200 qRegisterMetaType<AccountId>("AccountId");
201 qRegisterMetaType<MsgId>("MsgId");
203 qRegisterMetaType<QHostAddress>("QHostAddress");
204 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
205 qRegisterMetaType<QUuid>("QUuid");
206 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
208 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
209 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
210 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
211 qRegisterMetaTypeStreamOperators<UserId>("UserId");
212 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
213 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
215 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
216 qRegisterMetaType<PeerPtr>("PeerPtr");
217 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
219 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
220 if (!QMetaType::type("QVariant")) {
221 qRegisterMetaType<QVariant>("QVariant");
222 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
227 void Quassel::setupEnvironment()
229 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
230 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
231 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
232 // hack extra search paths into various places.
234 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
235 if (xdgDataVar.isEmpty())
236 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
238 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
240 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
241 QString appDir = QCoreApplication::applicationDirPath();
242 int binpos = appDir.lastIndexOf("/bin");
244 appDir.replace(binpos, 4, "/share");
245 xdgDirs.append(appDir);
246 // Also append apps/quassel, this is only for QIconLoader to find icons there
247 xdgDirs.append(appDir + "/apps/quassel");
249 xdgDirs.append(appDir); // build directory is always the last fallback
251 xdgDirs.removeDuplicates();
253 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
258 void Quassel::setupBuildInfo()
261 buildInfo.applicationName = "quassel";
262 buildInfo.coreApplicationName = "quasselcore";
263 buildInfo.clientApplicationName = "quasselclient";
264 buildInfo.organizationName = "Quassel Project";
265 buildInfo.organizationDomain = "quassel-irc.org";
267 buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
269 buildInfo.baseVersion = QUASSEL_VERSION_STRING;
270 buildInfo.generatedVersion = GIT_DESCRIBE;
272 // Check if we got a commit hash
273 if (!QString(GIT_HEAD).isEmpty()) {
274 buildInfo.commitHash = GIT_HEAD;
275 // Set to Unix epoch, wrapped as a string for backwards-compatibility
276 buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
278 else if (!QString(DIST_HASH).contains("Format")) {
279 buildInfo.commitHash = DIST_HASH;
280 // Leave as Unix epoch if set as Unix epoch, but don't force this for
281 // backwards-compatibility with existing packaging/release tools that might set strings.
282 buildInfo.commitDate = QString(DIST_DATE);
285 // create a nice version string
286 if (buildInfo.generatedVersion.isEmpty()) {
287 if (!buildInfo.commitHash.isEmpty()) {
289 buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
290 .arg(buildInfo.baseVersion)
291 .arg(buildInfo.commitHash.left(7));
292 buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
293 .arg(buildInfo.baseVersion)
294 .arg(buildInfo.commitHash.left(7))
295 .arg(buildInfo.commitHash);
298 // we only have a base version :(
299 buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
303 // analyze what we got from git-describe
304 static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
305 if (rx.exactMatch(buildInfo.generatedVersion)) {
306 QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
307 buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
308 if (!buildInfo.commitHash.isEmpty()) {
309 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
310 .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
314 buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
317 if (buildInfo.fancyVersionString.isEmpty()) {
318 buildInfo.fancyVersionString = buildInfo.plainVersionString;
321 instance()->_buildInfo = std::move(buildInfo);
325 const Quassel::BuildInfo &Quassel::buildInfo()
327 return instance()->_buildInfo;
331 //! Signal handler for graceful shutdown.
332 //! @todo: Ensure this doesn't use unsafe methods (it does currently)
333 //! cf. QSocketNotifier, UnixSignalWatcher
334 void Quassel::handleSignal(int sig)
339 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
343 // Windows does not support SIGHUP
345 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
346 // graceful reloading of processes.
347 quInfo() << "Caught signal" << SIGHUP << "- reloading configuration";
348 if (instance()->reloadConfig()) {
349 quInfo() << "Successfully reloaded configuration";
358 instance()->logBacktrace(instance()->coreDumpFileName());
366 void Quassel::disableCrashHandler()
368 instance()->_handleCrashes = false;
372 Quassel::RunMode Quassel::runMode() {
373 return instance()->_runMode;
377 void Quassel::setRunMode(RunMode runMode)
379 instance()->_runMode = runMode;
383 void Quassel::setCliParser(std::shared_ptr<AbstractCliParser> parser)
385 instance()->_cliParser = std::move(parser);
389 QString Quassel::optionValue(const QString &key)
391 return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{};
395 bool Quassel::isOptionSet(const QString &key)
397 return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false;
401 const QString &Quassel::coreDumpFileName()
403 if (_coreDumpFileName.isEmpty()) {
404 QDir configDir(configDirPath());
405 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
406 QFile dumpFile(_coreDumpFileName);
407 dumpFile.open(QIODevice::Append);
408 QTextStream dumpStream(&dumpFile);
409 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
410 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
414 return _coreDumpFileName;
418 QString Quassel::configDirPath()
420 if (!instance()->_configDirPath.isEmpty())
421 return instance()->_configDirPath;
424 if (isOptionSet("datadir")) {
425 qWarning() << "Obsolete option --datadir used!";
426 path = Quassel::optionValue("datadir");
428 else if (isOptionSet("configdir")) {
429 path = Quassel::optionValue("configdir");
433 // On Mac, the path is always the same
434 path = QDir::homePath() + "/Library/Application Support/Quassel/";
436 // We abuse QSettings to find us a sensible path on the other platforms
438 // don't use the registry
439 QSettings::Format format = QSettings::IniFormat;
441 QSettings::Format format = QSettings::NativeFormat;
443 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
444 QFileInfo fileInfo(s.fileName());
445 path = fileInfo.dir().absolutePath();
446 #endif /* Q_OS_MAC */
449 path = QFileInfo{path}.absoluteFilePath();
451 if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
452 path += QDir::separator();
455 if (!qDir.exists(path)) {
456 if (!qDir.mkpath(path)) {
457 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
462 instance()->_configDirPath = path;
467 void Quassel::setDataDirPaths(const QStringList &paths) {
468 instance()->_dataDirPaths = paths;
472 QStringList Quassel::dataDirPaths()
474 return instance()->_dataDirPaths;
478 QStringList Quassel::findDataDirPaths()
481 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
482 // want to stay consistent.
484 QStringList dataDirNames;
486 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
487 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
488 << QCoreApplication::applicationDirPath();
489 #elif defined Q_OS_MAC
490 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
491 << QCoreApplication::applicationDirPath();
495 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
496 // This should thus come first.
497 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
498 if (xdgDataHome.isEmpty())
499 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
500 dataDirNames << xdgDataHome;
502 // Now whatever is configured through XDG_DATA_DIRS
503 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
504 if (xdgDataDirs.isEmpty())
505 dataDirNames << "/usr/local/share" << "/usr/share";
507 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
509 // Just in case, also check our install prefix
510 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
512 // Normalize and append our application name
513 for (int i = 0; i < dataDirNames.count(); i++)
514 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
518 // Add resource path and workdir just in case.
519 // Workdir should have precedence
520 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
521 dataDirNames.append(":/data/");
523 // Append trailing '/' and check for existence
524 auto iter = dataDirNames.begin();
525 while (iter != dataDirNames.end()) {
526 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
527 iter->append(QDir::separator());
528 if (!QFile::exists(*iter))
529 iter = dataDirNames.erase(iter);
534 dataDirNames.removeDuplicates();
540 QString Quassel::findDataFilePath(const QString &fileName)
542 QStringList dataDirs = dataDirPaths();
543 foreach(QString dataDir, dataDirs) {
544 QString path = dataDir + fileName;
545 if (QFile::exists(path))
552 QStringList Quassel::scriptDirPaths()
554 QStringList res(configDirPath() + "scripts/");
555 foreach(QString path, dataDirPaths())
556 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;
579 void Quassel::loadTranslation(const QLocale &locale)
581 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
582 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
585 qApp->removeTranslator(qtTranslator);
586 if (quasselTranslator)
587 qApp->removeTranslator(quasselTranslator);
589 // We use QLocale::C to indicate that we don't want a translation
590 if (locale.language() == QLocale::C)
593 qtTranslator = new QTranslator(qApp);
594 qtTranslator->setObjectName("QtTr");
595 qApp->installTranslator(qtTranslator);
597 quasselTranslator = new QTranslator(qApp);
598 quasselTranslator->setObjectName("QuasselTr");
599 qApp->installTranslator(quasselTranslator);
601 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
602 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
604 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
605 quasselTranslator->load(locale, QString(""), translationDirPath());
607 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
609 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
610 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
615 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
617 Quassel::Features::Features()
619 QStringList features;
621 // TODO Qt5: Use QMetaEnum::fromType()
622 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
623 _features.resize(featureEnum.keyCount(), true); // enable all known features to true
627 Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
629 // TODO Qt5: Use QMetaEnum::fromType()
630 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
631 _features.resize(featureEnum.keyCount(), false);
633 for (auto &&feature : features) {
634 int i = featureEnum.keyToValue(qPrintable(feature));
639 _unknownFeatures << feature;
643 if (legacyFeatures) {
644 // TODO Qt5: Use QMetaEnum::fromType()
645 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
646 for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
647 if (static_cast<quint32>(legacyFeatures) & mask) {
648 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
658 bool Quassel::Features::isEnabled(Feature feature) const
660 size_t i = static_cast<size_t>(feature);
661 return i < _features.size() ? _features[i] : false;
665 QStringList Quassel::Features::toStringList(bool enabled) const
667 // Check if any feature is enabled
668 if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
669 return QStringList{} << "NoFeatures";
674 // TODO Qt5: Use QMetaEnum::fromType()
675 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
676 for (quint32 i = 0; i < _features.size(); ++i) {
677 if (_features[i] == enabled) {
678 result << featureEnum.key(i);
685 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
687 // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
689 // TODO Qt5: Use QMetaEnum::fromType()
690 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
691 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
693 for (quint32 i = 0; i < _features.size(); ++i) {
695 int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
701 return static_cast<LegacyFeatures>(result);
705 QStringList Quassel::Features::unknownFeatures() const
707 return _unknownFeatures;