X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fcommon%2Fquassel.cpp;h=03cf739ad146cfe02ec357e735a4555e8cd45b26;hp=4e24ff0abfce51f15ace099c2ae5e059cdcb6cac;hb=8582c2ad5708a1972c85bea1cf8d81ad3ece4814;hpb=4e3b9ea041c45aba5eaea14e4aafd46ee3ed044a diff --git a/src/common/quassel.cpp b/src/common/quassel.cpp index 4e24ff0a..03cf739a 100644 --- a/src/common/quassel.cpp +++ b/src/common/quassel.cpp @@ -23,13 +23,6 @@ #include #include -#include -#if !defined Q_OS_WIN && !defined Q_OS_MAC -# include -# include -# include -#endif - #include #include #include @@ -44,126 +37,58 @@ #include "bufferinfo.h" #include "identity.h" #include "logger.h" +#include "logmessage.h" #include "message.h" #include "network.h" #include "peer.h" #include "protocol.h" #include "syncableobject.h" #include "types.h" +#include "version.h" -#include "../../version.h" - -Quassel *Quassel::instance() -{ - static Quassel instance; - return &instance; -} - +#ifndef Q_OS_WIN +# include "posixsignalwatcher.h" +#else +# include "windowssignalwatcher.h" +#endif Quassel::Quassel() + : Singleton{this} + , _logger{new Logger{this}} { - // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel. - signal(SIGTERM, handleSignal); - signal(SIGINT, handleSignal); -#ifndef Q_OS_WIN - // SIGHUP is used to reload configuration (i.e. SSL certificates) - // Windows does not support SIGHUP - signal(SIGHUP, handleSignal); +#ifdef EMBED_DATA + Q_INIT_RESOURCE(i18n); #endif } -bool Quassel::init() +void Quassel::init(RunMode runMode) { - if (instance()->_initialized) - return true; // allow multiple invocations because of MonolithicApplication - - if (instance()->_handleCrashes) { - // we have crashhandler for win32 and unix (based on execinfo). -#if defined(Q_OS_WIN) || defined(HAVE_EXECINFO) -# ifndef Q_OS_WIN - // we only handle crashes ourselves if coredumps are disabled - struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit)); - int rc = getrlimit(RLIMIT_CORE, limit); - - if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) { -# endif /* Q_OS_WIN */ - signal(SIGABRT, handleSignal); - signal(SIGSEGV, handleSignal); -# ifndef Q_OS_WIN - signal(SIGBUS, handleSignal); - } - free(limit); -# endif /* Q_OS_WIN */ -#endif /* Q_OS_WIN || HAVE_EXECINFO */ - } + _runMode = runMode; - instance()->_initialized = true; qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); - instance()->setupEnvironment(); - instance()->registerMetaTypes(); - - Network::setDefaultCodecForServer("ISO-8859-1"); - Network::setDefaultCodecForEncoding("UTF-8"); - Network::setDefaultCodecForDecoding("ISO-8859-15"); + setupSignalHandling(); + setupEnvironment(); + registerMetaTypes(); - if (isOptionSet("help")) { - instance()->_cliParser->usage(); - return false; - } + // Initial translation (may be overridden in UI settings) + loadTranslation(QLocale::system()); - if (isOptionSet("version")) { - std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl; - return false; - } + setupCliParser(); - // Set up logging - if (isOptionSet("loglevel")) { - QString level = optionValue("loglevel").toLower(); - - if (level == "debug") - setLogLevel(DebugLevel); - else if (level == "info") - setLogLevel(InfoLevel); - else if (level == "warning") - setLogLevel(WarningLevel); - else if (level == "error") - setLogLevel(ErrorLevel); - else { - qWarning() << qPrintable(tr("Invalid log level %1; supported are Debug|Info|Warning|Error").arg(level)); - return false; - } - } + // Don't keep a debug log on the core + logger()->setup(runMode != RunMode::CoreOnly); - QString logfilename = optionValue("logfile"); - if (!logfilename.isEmpty()) { - instance()->_logFile.reset(new QFile{logfilename}); - if (!logFile()->open(QIODevice::Append | QIODevice::Text)) { - qWarning() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, logFile()->errorString())); - instance()->_logFile.reset(); - } - } -#ifdef HAVE_SYSLOG - instance()->_logToSyslog = isOptionSet("syslog"); -#endif - -#if QT_VERSION < 0x050000 - qInstallMsgHandler(Logger::logMessage); -#else - qInstallMessageHandler(Logger::logMessage); -#endif - - return true; + Network::setDefaultCodecForServer("UTF-8"); + Network::setDefaultCodecForEncoding("UTF-8"); + Network::setDefaultCodecForDecoding("ISO-8859-15"); } -void Quassel::destroy() +Logger *Quassel::logger() const { - if (logFile()) { - logFile()->close(); - instance()->_logFile.reset(); - } + return _logger; } @@ -174,12 +99,18 @@ void Quassel::registerQuitHandler(QuitHandler handler) void Quassel::quit() { - if (_quitHandlers.empty()) { - QCoreApplication::quit(); - } - else { - for (auto &&handler : _quitHandlers) { - handler(); + // Protect against multiple invocations (e.g. triggered by MainWin::closeEvent()) + if (!_quitting) { + _quitting = true; + quInfo() << "Quitting..."; + if (_quitHandlers.empty()) { + QCoreApplication::quit(); + } + else { + // Note: We expect one of the registered handlers to call QCoreApplication::quit() + for (auto &&handler : _quitHandlers) { + handler(); + } } } } @@ -299,19 +230,13 @@ void Quassel::setupBuildInfo() // Check if we got a commit hash if (!QString(GIT_HEAD).isEmpty()) { buildInfo.commitHash = GIT_HEAD; - QDateTime date; -#if QT_VERSION >= 0x050800 - date.setSecsSinceEpoch(GIT_COMMIT_DATE); -#else - // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now. - // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch - // Warning generated if not converting the 1000 to a qint64 first. - date.setMSecsSinceEpoch(GIT_COMMIT_DATE * (qint64)1000); -#endif - buildInfo.commitDate = date.toString(); + // Set to Unix epoch, wrapped as a string for backwards-compatibility + buildInfo.commitDate = QString::number(GIT_COMMIT_DATE); } else if (!QString(DIST_HASH).contains("Format")) { buildInfo.commitHash = DIST_HASH; + // Leave as Unix epoch if set as Unix epoch, but don't force this for + // backwards-compatibility with existing packaging/release tools that might set strings. buildInfo.commitDate = QString(DIST_DATE); } @@ -361,42 +286,41 @@ const Quassel::BuildInfo &Quassel::buildInfo() } -//! Signal handler for graceful shutdown. -void Quassel::handleSignal(int sig) +void Quassel::setupSignalHandling() { - switch (sig) { - case SIGTERM: - case SIGINT: - qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig))); - instance()->quit(); - break; #ifndef Q_OS_WIN -// Windows does not support SIGHUP - case SIGHUP: - // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for - // graceful reloading of processes. - quInfo() << "Caught signal" << SIGHUP << "- reloading configuration"; - if (instance()->reloadConfig()) { - quInfo() << "Successfully reloaded configuration"; - } - break; -#endif - case SIGABRT: - case SIGSEGV: -#ifndef Q_OS_WIN - case SIGBUS: + _signalWatcher = new PosixSignalWatcher(this); +#else + _signalWatcher = new WindowsSignalWatcher(this); #endif - instance()->logBacktrace(instance()->coreDumpFileName()); - exit(EXIT_FAILURE); - default: - ; - } + connect(_signalWatcher, SIGNAL(handleSignal(AbstractSignalWatcher::Action)), this, SLOT(handleSignal(AbstractSignalWatcher::Action))); } -void Quassel::disableCrashHandler() +void Quassel::handleSignal(AbstractSignalWatcher::Action action) { - instance()->_handleCrashes = false; + switch (action) { + case AbstractSignalWatcher::Action::Reload: + // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for graceful reloading of processes. + if (!_reloadHandlers.empty()) { + quInfo() << "Reloading configuration"; + if (reloadConfig()) { + quInfo() << "Successfully reloaded configuration"; + } + } + break; + case AbstractSignalWatcher::Action::Terminate: + if (!_quitting) { + quit(); + } + else { + quInfo() << "Already shutting down, ignoring signal"; + } + break; + case AbstractSignalWatcher::Action::HandleCrash: + logBacktrace(instance()->coreDumpFileName()); + exit(EXIT_FAILURE); + } } @@ -405,66 +329,95 @@ Quassel::RunMode Quassel::runMode() { } -void Quassel::setRunMode(RunMode runMode) -{ - instance()->_runMode = runMode; -} - - -void Quassel::setCliParser(std::shared_ptr parser) -{ - instance()->_cliParser = std::move(parser); -} - - -QString Quassel::optionValue(const QString &key) -{ - return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{}; -} - - -bool Quassel::isOptionSet(const QString &key) +void Quassel::setupCliParser() { - return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false; -} + QList options; + // General options + /// @todo Bring back --datadir to specify the database location independent of config + if (runMode() == RunMode::ClientOnly) { + options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")}; + } + else { + options += {{"c", "configdir"}, tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."), tr("path")}; + } -Quassel::LogLevel Quassel::logLevel() -{ - return instance()->_logLevel; -} + // Client options + if (runMode() != RunMode::CoreOnly) { + options += { + {"icontheme", tr("Override the system icon theme ('breeze' is recommended)."), tr("theme")}, + {"qss", tr("Load a custom application stylesheet."), tr("file.qss")}, + {"hidewindow", tr("Start the client minimized to the system tray.")}, + }; + } + // Core options + if (runMode() != RunMode::ClientOnly) { + options += { + {"listen", tr("The address(es) quasselcore will listen on."), tr("
[,
[,...]]"), "::,0.0.0.0"}, + {{"p", "port"}, tr("The port quasselcore will listen at."), tr("port"), "4242"}, + {{"n", "norestore"}, tr("Don't restore last core's state.")}, + {"config-from-environment", tr("Load configuration from environment variables.")}, + {"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")}, + {"select-authenticator", tr("Select authentication backend."), tr("authidentifier")}, + {"add-user", tr("Starts an interactive session to add a new core user.")}, + {"change-userpass", tr("Starts an interactive session to change the password of the user identified by ."), tr("username")}, + {"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")}, + {"ident-daemon", tr("Enable internal ident daemon.")}, + {"ident-port", tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."), tr("port"), "10113"}, + {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")}, + {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")}, +#ifdef HAVE_SSL + {"require-ssl", tr("Require SSL for remote (non-loopback) client connections.")}, + {"ssl-cert", tr("Specify the path to the SSL certificate."), tr("path"), "configdir/quasselCert.pem"}, + {"ssl-key", tr("Specify the path to the SSL key."), tr("path"), "ssl-cert-path"}, +#endif + }; + } -void Quassel::setLogLevel(LogLevel logLevel) -{ - instance()->_logLevel = logLevel; -} + // Logging options + options += { + {{"L", "loglevel"}, tr("Supports one of Debug|Info|Warning|Error; default is Info."), tr("level"), "Info"}, + {{"l", "logfile"}, tr("Log to a file."), "path"}, +#ifdef HAVE_SYSLOG + {"syslog", tr("Log to syslog.")}, +#endif + }; + + // Debug options + options += {{"d", "debug"}, tr("Enable debug output.")}; + if (runMode() != RunMode::CoreOnly) { + options += { + {"debugbufferswitches", tr("Enables debugging for bufferswitches.")}, + {"debugmodel", tr("Enables debugging for models.")}, + }; + } + if (runMode() != RunMode::ClientOnly) { + options += { + {"debug-irc", tr("Enable logging of all raw IRC messages to debug log, including passwords! In most cases you should also set --loglevel Debug")}, + {"debug-irc-id", tr("Limit raw IRC logging to this network ID. Implies --debug-irc"), tr("database network ID"), "-1"}, + }; + } + _cliParser.addOptions(options); + _cliParser.addHelpOption(); + _cliParser.addVersionOption(); + _cliParser.setApplicationDescription(tr("Quassel IRC is a modern, distributed IRC client.")); -QFile *Quassel::logFile() { - return instance()->_logFile.get(); + // This will call ::exit() for --help, --version and in case of errors + _cliParser.process(*QCoreApplication::instance()); } -bool Quassel::logToSyslog() +QString Quassel::optionValue(const QString &key) { - return instance()->_logToSyslog; + return instance()->_cliParser.value(key); } -void Quassel::logFatalMessage(const char *msg) +bool Quassel::isOptionSet(const QString &key) { -#ifdef Q_OS_MAC - Q_UNUSED(msg) -#else - QFile dumpFile(instance()->coreDumpFileName()); - dumpFile.open(QIODevice::Append); - QTextStream dumpStream(&dumpFile); - - dumpStream << "Fatal: " << msg << '\n'; - dumpStream.flush(); - dumpFile.close(); -#endif + return instance()->_cliParser.isSet(key); } @@ -491,11 +444,7 @@ QString Quassel::configDirPath() return instance()->_configDirPath; QString path; - if (isOptionSet("datadir")) { - qWarning() << "Obsolete option --datadir used!"; - path = Quassel::optionValue("datadir"); - } - else if (isOptionSet("configdir")) { + if (isOptionSet("configdir")) { path = Quassel::optionValue("configdir"); } else { @@ -534,22 +483,13 @@ QString Quassel::configDirPath() } -void Quassel::setDataDirPaths(const QStringList &paths) { - instance()->_dataDirPaths = paths; -} - - QStringList Quassel::dataDirPaths() { - return instance()->_dataDirPaths; -} - + if (!instance()->_dataDirPaths.isEmpty()) + return instance()->_dataDirPaths; -QStringList Quassel::findDataDirPaths() -{ - // TODO Qt5 - // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and - // want to stay consistent. + // TODO: Migrate to QStandardPaths (will require moving of the sqlite database, + // or a fallback for it being in the config dir) QStringList dataDirNames; #ifdef Q_OS_WIN @@ -603,6 +543,7 @@ QStringList Quassel::findDataDirPaths() dataDirNames.removeDuplicates(); + instance()->_dataDirPaths = dataDirNames; return dataDirNames; } @@ -648,8 +589,8 @@ QString Quassel::translationDirPath() void Quassel::loadTranslation(const QLocale &locale) { - QTranslator *qtTranslator = QCoreApplication::instance()->findChild("QtTr"); - QTranslator *quasselTranslator = QCoreApplication::instance()->findChild("QuasselTr"); + auto *qtTranslator = QCoreApplication::instance()->findChild("QtTr"); + auto *quasselTranslator = QCoreApplication::instance()->findChild("QuasselTr"); if (qtTranslator) qApp->removeTranslator(qtTranslator); @@ -662,13 +603,11 @@ void Quassel::loadTranslation(const QLocale &locale) qtTranslator = new QTranslator(qApp); qtTranslator->setObjectName("QtTr"); - qApp->installTranslator(qtTranslator); quasselTranslator = new QTranslator(qApp); quasselTranslator->setObjectName("QuasselTr"); - qApp->installTranslator(quasselTranslator); -#if QT_VERSION >= 0x040800 && !defined Q_OS_MAC +#ifndef Q_OS_MAC bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath()); if (!success) qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); @@ -679,6 +618,9 @@ void Quassel::loadTranslation(const QLocale &locale) qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath()); #endif + + qApp->installTranslator(quasselTranslator); + qApp->installTranslator(qtTranslator); } @@ -727,7 +669,7 @@ Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFe bool Quassel::Features::isEnabled(Feature feature) const { - size_t i = static_cast(feature); + auto i = static_cast(feature); return i < _features.size() ? _features[i] : false; }