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"
51 #include "syncableobject.h"
54 #include "../../version.h"
56 Quassel *Quassel::instance()
58 static Quassel instance;
65 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
66 signal(SIGTERM, handleSignal);
67 signal(SIGINT, handleSignal);
69 // SIGHUP is used to reload configuration (i.e. SSL certificates)
70 // Windows does not support SIGHUP
71 signal(SIGHUP, handleSignal);
78 if (instance()->_initialized)
79 return true; // allow multiple invocations because of MonolithicApplication
81 if (instance()->_handleCrashes) {
82 // we have crashhandler for win32 and unix (based on execinfo).
83 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
85 // we only handle crashes ourselves if coredumps are disabled
86 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
87 int rc = getrlimit(RLIMIT_CORE, limit);
89 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
90 # endif /* Q_OS_WIN */
91 signal(SIGABRT, handleSignal);
92 signal(SIGSEGV, handleSignal);
94 signal(SIGBUS, handleSignal);
97 # endif /* Q_OS_WIN */
98 #endif /* Q_OS_WIN || HAVE_EXECINFO */
101 instance()->_initialized = true;
102 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
104 instance()->setupEnvironment();
105 instance()->registerMetaTypes();
107 Network::setDefaultCodecForServer("UTF-8");
108 Network::setDefaultCodecForEncoding("UTF-8");
109 Network::setDefaultCodecForDecoding("ISO-8859-15");
111 if (isOptionSet("help")) {
112 instance()->_cliParser->usage();
116 if (isOptionSet("version")) {
117 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
122 if (isOptionSet("loglevel")) {
123 QString level = optionValue("loglevel").toLower();
125 if (level == "debug")
126 setLogLevel(DebugLevel);
127 else if (level == "info")
128 setLogLevel(InfoLevel);
129 else if (level == "warning")
130 setLogLevel(WarningLevel);
131 else if (level == "error")
132 setLogLevel(ErrorLevel);
134 qWarning() << qPrintable(tr("Invalid log level %1; supported are Debug|Info|Warning|Error").arg(level));
139 QString logfilename = optionValue("logfile");
140 if (!logfilename.isEmpty()) {
141 instance()->_logFile.reset(new QFile{logfilename});
142 if (!logFile()->open(QIODevice::Append | QIODevice::Text)) {
143 qWarning() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, logFile()->errorString()));
144 instance()->_logFile.reset();
148 instance()->_logToSyslog = isOptionSet("syslog");
151 #if QT_VERSION < 0x050000
152 qInstallMsgHandler(Logger::logMessage);
154 qInstallMessageHandler(Logger::logMessage);
161 void Quassel::destroy()
165 instance()->_logFile.reset();
170 void Quassel::registerQuitHandler(QuitHandler handler)
172 instance()->_quitHandlers.emplace_back(std::move(handler));
177 if (_quitHandlers.empty()) {
178 QCoreApplication::quit();
181 for (auto &&handler : _quitHandlers) {
188 void Quassel::registerReloadHandler(ReloadHandler handler)
190 instance()->_reloadHandlers.emplace_back(std::move(handler));
194 bool Quassel::reloadConfig()
197 for (auto &&handler : _reloadHandlers) {
198 result = result && handler();
204 //! Register our custom types with Qt's Meta Object System.
205 /** This makes them available for QVariant and in signals/slots, among other things.
208 void Quassel::registerMetaTypes()
211 qRegisterMetaType<Message>("Message");
212 qRegisterMetaType<BufferInfo>("BufferInfo");
213 qRegisterMetaType<NetworkInfo>("NetworkInfo");
214 qRegisterMetaType<Network::Server>("Network::Server");
215 qRegisterMetaType<Identity>("Identity");
217 qRegisterMetaTypeStreamOperators<Message>("Message");
218 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
219 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
220 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
221 qRegisterMetaTypeStreamOperators<Identity>("Identity");
223 qRegisterMetaType<IdentityId>("IdentityId");
224 qRegisterMetaType<BufferId>("BufferId");
225 qRegisterMetaType<NetworkId>("NetworkId");
226 qRegisterMetaType<UserId>("UserId");
227 qRegisterMetaType<AccountId>("AccountId");
228 qRegisterMetaType<MsgId>("MsgId");
230 qRegisterMetaType<QHostAddress>("QHostAddress");
231 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
232 qRegisterMetaType<QUuid>("QUuid");
233 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
235 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
236 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
237 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
238 qRegisterMetaTypeStreamOperators<UserId>("UserId");
239 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
240 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
242 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
243 qRegisterMetaType<PeerPtr>("PeerPtr");
244 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
246 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
247 if (!QMetaType::type("QVariant")) {
248 qRegisterMetaType<QVariant>("QVariant");
249 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
254 void Quassel::setupEnvironment()
256 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
257 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
258 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
259 // hack extra search paths into various places.
261 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
262 if (xdgDataVar.isEmpty())
263 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
265 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
267 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
268 QString appDir = QCoreApplication::applicationDirPath();
269 int binpos = appDir.lastIndexOf("/bin");
271 appDir.replace(binpos, 4, "/share");
272 xdgDirs.append(appDir);
273 // Also append apps/quassel, this is only for QIconLoader to find icons there
274 xdgDirs.append(appDir + "/apps/quassel");
276 xdgDirs.append(appDir); // build directory is always the last fallback
278 xdgDirs.removeDuplicates();
280 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
285 void Quassel::setupBuildInfo()
288 buildInfo.applicationName = "quassel";
289 buildInfo.coreApplicationName = "quasselcore";
290 buildInfo.clientApplicationName = "quasselclient";
291 buildInfo.organizationName = "Quassel Project";
292 buildInfo.organizationDomain = "quassel-irc.org";
294 buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
296 buildInfo.baseVersion = QUASSEL_VERSION_STRING;
297 buildInfo.generatedVersion = GIT_DESCRIBE;
299 // Check if we got a commit hash
300 if (!QString(GIT_HEAD).isEmpty()) {
301 buildInfo.commitHash = GIT_HEAD;
302 // Set to Unix epoch, wrapped as a string for backwards-compatibility
303 buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
305 else if (!QString(DIST_HASH).contains("Format")) {
306 buildInfo.commitHash = DIST_HASH;
307 // Leave as Unix epoch if set as Unix epoch, but don't force this for
308 // backwards-compatibility with existing packaging/release tools that might set strings.
309 buildInfo.commitDate = QString(DIST_DATE);
312 // create a nice version string
313 if (buildInfo.generatedVersion.isEmpty()) {
314 if (!buildInfo.commitHash.isEmpty()) {
316 buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
317 .arg(buildInfo.baseVersion)
318 .arg(buildInfo.commitHash.left(7));
319 buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
320 .arg(buildInfo.baseVersion)
321 .arg(buildInfo.commitHash.left(7))
322 .arg(buildInfo.commitHash);
325 // we only have a base version :(
326 buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
330 // analyze what we got from git-describe
331 static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
332 if (rx.exactMatch(buildInfo.generatedVersion)) {
333 QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
334 buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
335 if (!buildInfo.commitHash.isEmpty()) {
336 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
337 .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
341 buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
344 if (buildInfo.fancyVersionString.isEmpty()) {
345 buildInfo.fancyVersionString = buildInfo.plainVersionString;
348 instance()->_buildInfo = std::move(buildInfo);
352 const Quassel::BuildInfo &Quassel::buildInfo()
354 return instance()->_buildInfo;
358 //! Signal handler for graceful shutdown.
359 void Quassel::handleSignal(int sig)
364 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
368 // Windows does not support SIGHUP
370 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
371 // graceful reloading of processes.
372 quInfo() << "Caught signal" << SIGHUP << "- reloading configuration";
373 if (instance()->reloadConfig()) {
374 quInfo() << "Successfully reloaded configuration";
383 instance()->logBacktrace(instance()->coreDumpFileName());
391 void Quassel::disableCrashHandler()
393 instance()->_handleCrashes = false;
397 Quassel::RunMode Quassel::runMode() {
398 return instance()->_runMode;
402 void Quassel::setRunMode(RunMode runMode)
404 instance()->_runMode = runMode;
408 void Quassel::setCliParser(std::shared_ptr<AbstractCliParser> parser)
410 instance()->_cliParser = std::move(parser);
414 QString Quassel::optionValue(const QString &key)
416 return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{};
420 bool Quassel::isOptionSet(const QString &key)
422 return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false;
426 Quassel::LogLevel Quassel::logLevel()
428 return instance()->_logLevel;
432 void Quassel::setLogLevel(LogLevel logLevel)
434 instance()->_logLevel = logLevel;
438 QFile *Quassel::logFile() {
439 return instance()->_logFile.get();
443 bool Quassel::logToSyslog()
445 return instance()->_logToSyslog;
449 void Quassel::logFatalMessage(const char *msg)
454 QFile dumpFile(instance()->coreDumpFileName());
455 dumpFile.open(QIODevice::Append);
456 QTextStream dumpStream(&dumpFile);
458 dumpStream << "Fatal: " << msg << '\n';
465 const QString &Quassel::coreDumpFileName()
467 if (_coreDumpFileName.isEmpty()) {
468 QDir configDir(configDirPath());
469 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
470 QFile dumpFile(_coreDumpFileName);
471 dumpFile.open(QIODevice::Append);
472 QTextStream dumpStream(&dumpFile);
473 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
474 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
478 return _coreDumpFileName;
482 QString Quassel::configDirPath()
484 if (!instance()->_configDirPath.isEmpty())
485 return instance()->_configDirPath;
488 if (isOptionSet("datadir")) {
489 qWarning() << "Obsolete option --datadir used!";
490 path = Quassel::optionValue("datadir");
492 else if (isOptionSet("configdir")) {
493 path = Quassel::optionValue("configdir");
497 // On Mac, the path is always the same
498 path = QDir::homePath() + "/Library/Application Support/Quassel/";
500 // We abuse QSettings to find us a sensible path on the other platforms
502 // don't use the registry
503 QSettings::Format format = QSettings::IniFormat;
505 QSettings::Format format = QSettings::NativeFormat;
507 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
508 QFileInfo fileInfo(s.fileName());
509 path = fileInfo.dir().absolutePath();
510 #endif /* Q_OS_MAC */
513 path = QFileInfo{path}.absoluteFilePath();
515 if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
516 path += QDir::separator();
519 if (!qDir.exists(path)) {
520 if (!qDir.mkpath(path)) {
521 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
526 instance()->_configDirPath = path;
531 void Quassel::setDataDirPaths(const QStringList &paths) {
532 instance()->_dataDirPaths = paths;
536 QStringList Quassel::dataDirPaths()
538 return instance()->_dataDirPaths;
542 QStringList Quassel::findDataDirPaths()
545 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
546 // want to stay consistent.
548 QStringList dataDirNames;
550 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
551 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
552 << QCoreApplication::applicationDirPath();
553 #elif defined Q_OS_MAC
554 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
555 << QCoreApplication::applicationDirPath();
559 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
560 // This should thus come first.
561 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
562 if (xdgDataHome.isEmpty())
563 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
564 dataDirNames << xdgDataHome;
566 // Now whatever is configured through XDG_DATA_DIRS
567 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
568 if (xdgDataDirs.isEmpty())
569 dataDirNames << "/usr/local/share" << "/usr/share";
571 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
573 // Just in case, also check our install prefix
574 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
576 // Normalize and append our application name
577 for (int i = 0; i < dataDirNames.count(); i++)
578 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
582 // Add resource path and workdir just in case.
583 // Workdir should have precedence
584 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
585 dataDirNames.append(":/data/");
587 // Append trailing '/' and check for existence
588 auto iter = dataDirNames.begin();
589 while (iter != dataDirNames.end()) {
590 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
591 iter->append(QDir::separator());
592 if (!QFile::exists(*iter))
593 iter = dataDirNames.erase(iter);
598 dataDirNames.removeDuplicates();
604 QString Quassel::findDataFilePath(const QString &fileName)
606 QStringList dataDirs = dataDirPaths();
607 foreach(QString dataDir, dataDirs) {
608 QString path = dataDir + fileName;
609 if (QFile::exists(path))
616 QStringList Quassel::scriptDirPaths()
618 QStringList res(configDirPath() + "scripts/");
619 foreach(QString path, dataDirPaths())
620 res << path + "scripts/";
625 QString Quassel::translationDirPath()
627 if (instance()->_translationDirPath.isEmpty()) {
628 // We support only one translation dir; fallback mechanisms wouldn't work else.
629 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
630 foreach(const QString &dir, dataDirPaths()) {
631 if (QFile::exists(dir + "translations/")) {
632 instance()->_translationDirPath = dir + "translations/";
636 if (instance()->_translationDirPath.isEmpty())
637 instance()->_translationDirPath = ":/i18n/";
639 return instance()->_translationDirPath;
643 void Quassel::loadTranslation(const QLocale &locale)
645 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
646 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
649 qApp->removeTranslator(qtTranslator);
650 if (quasselTranslator)
651 qApp->removeTranslator(quasselTranslator);
653 // We use QLocale::C to indicate that we don't want a translation
654 if (locale.language() == QLocale::C)
657 qtTranslator = new QTranslator(qApp);
658 qtTranslator->setObjectName("QtTr");
659 qApp->installTranslator(qtTranslator);
661 quasselTranslator = new QTranslator(qApp);
662 quasselTranslator->setObjectName("QuasselTr");
663 qApp->installTranslator(quasselTranslator);
665 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
666 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
668 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
669 quasselTranslator->load(locale, QString(""), translationDirPath());
671 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
673 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
674 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
679 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
681 Quassel::Features::Features()
683 QStringList features;
685 // TODO Qt5: Use QMetaEnum::fromType()
686 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
687 _features.resize(featureEnum.keyCount(), true); // enable all known features to true
691 Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
693 // TODO Qt5: Use QMetaEnum::fromType()
694 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
695 _features.resize(featureEnum.keyCount(), false);
697 for (auto &&feature : features) {
698 int i = featureEnum.keyToValue(qPrintable(feature));
703 _unknownFeatures << feature;
707 if (legacyFeatures) {
708 // TODO Qt5: Use QMetaEnum::fromType()
709 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
710 for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
711 if (static_cast<quint32>(legacyFeatures) & mask) {
712 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
722 bool Quassel::Features::isEnabled(Feature feature) const
724 size_t i = static_cast<size_t>(feature);
725 return i < _features.size() ? _features[i] : false;
729 QStringList Quassel::Features::toStringList(bool enabled) const
731 // Check if any feature is enabled
732 if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
733 return QStringList{} << "NoFeatures";
738 // TODO Qt5: Use QMetaEnum::fromType()
739 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
740 for (quint32 i = 0; i < _features.size(); ++i) {
741 if (_features[i] == enabled) {
742 result << featureEnum.key(i);
749 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
751 // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
753 // TODO Qt5: Use QMetaEnum::fromType()
754 auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
755 auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
757 for (quint32 i = 0; i < _features.size(); ++i) {
759 int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
765 return static_cast<LegacyFeatures>(result);
769 QStringList Quassel::Features::unknownFeatures() const
771 return _unknownFeatures;