1 /***************************************************************************
2 * Copyright (C) 2005-2016 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 ***************************************************************************/
25 #if !defined Q_OS_WIN && !defined Q_OS_MAC
26 # include <sys/types.h>
27 # include <sys/time.h>
28 # include <sys/resource.h>
31 #include <QCoreApplication>
34 #include <QHostAddress>
35 #include <QLibraryInfo>
37 #include <QTranslator>
40 #include "bufferinfo.h"
47 #include "syncableobject.h"
50 #include "../../version.h"
52 Quassel::BuildInfo Quassel::_buildInfo;
53 AbstractCliParser *Quassel::_cliParser = 0;
54 Quassel::RunMode Quassel::_runMode;
55 QString Quassel::_configDirPath;
56 QString Quassel::_translationDirPath;
57 QStringList Quassel::_dataDirPaths;
58 bool Quassel::_initialized = false;
59 bool Quassel::DEBUG = false;
60 QString Quassel::_coreDumpFileName;
61 Quassel *Quassel::_instance = 0;
62 bool Quassel::_handleCrashes = true;
63 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
64 QFile *Quassel::_logFile = 0;
65 bool Quassel::_logToSyslog = false;
72 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
73 signal(SIGTERM, handleSignal);
74 signal(SIGINT, handleSignal);
76 // SIGHUP is used to reload configuration (i.e. SSL certificates)
77 // Windows does not support SIGHUP
78 signal(SIGHUP, handleSignal);
87 logFile()->deleteLater();
96 return true; // allow multiple invocations because of MonolithicApplication
99 // we have crashhandler for win32 and unix (based on execinfo).
100 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
102 // we only handle crashes ourselves if coredumps are disabled
103 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
104 int rc = getrlimit(RLIMIT_CORE, limit);
106 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
107 # endif /* Q_OS_WIN */
108 signal(SIGABRT, handleSignal);
109 signal(SIGSEGV, handleSignal);
111 signal(SIGBUS, handleSignal);
114 # endif /* Q_OS_WIN */
115 #endif /* Q_OS_WIN || HAVE_EXECINFO */
119 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
124 Network::setDefaultCodecForServer("ISO-8859-1");
125 Network::setDefaultCodecForEncoding("UTF-8");
126 Network::setDefaultCodecForDecoding("ISO-8859-15");
128 if (isOptionSet("help")) {
129 cliParser()->usage();
133 if (isOptionSet("version")) {
134 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
138 DEBUG = isOptionSet("debug");
141 if (Quassel::runMode() != Quassel::ClientOnly) {
142 if (isOptionSet("loglevel")) {
143 QString level = optionValue("loglevel");
145 if (level == "Debug") _logLevel = DebugLevel;
146 else if (level == "Info") _logLevel = InfoLevel;
147 else if (level == "Warning") _logLevel = WarningLevel;
148 else if (level == "Error") _logLevel = ErrorLevel;
151 QString logfilename = optionValue("logfile");
152 if (!logfilename.isEmpty()) {
153 _logFile = new QFile(logfilename);
154 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
155 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
156 _logFile->deleteLater();
161 _logToSyslog = isOptionSet("syslog");
171 QCoreApplication::quit();
175 //! Register our custom types with Qt's Meta Object System.
176 /** This makes them available for QVariant and in signals/slots, among other things.
179 void Quassel::registerMetaTypes()
182 qRegisterMetaType<Message>("Message");
183 qRegisterMetaType<BufferInfo>("BufferInfo");
184 qRegisterMetaType<NetworkInfo>("NetworkInfo");
185 qRegisterMetaType<Network::Server>("Network::Server");
186 qRegisterMetaType<Identity>("Identity");
188 qRegisterMetaTypeStreamOperators<Message>("Message");
189 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
190 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
191 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
192 qRegisterMetaTypeStreamOperators<Identity>("Identity");
194 qRegisterMetaType<IdentityId>("IdentityId");
195 qRegisterMetaType<BufferId>("BufferId");
196 qRegisterMetaType<NetworkId>("NetworkId");
197 qRegisterMetaType<UserId>("UserId");
198 qRegisterMetaType<AccountId>("AccountId");
199 qRegisterMetaType<MsgId>("MsgId");
201 qRegisterMetaType<QHostAddress>("QHostAddress");
202 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
203 qRegisterMetaType<QUuid>("QUuid");
204 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
206 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
207 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
208 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
209 qRegisterMetaTypeStreamOperators<UserId>("UserId");
210 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
211 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
213 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
214 qRegisterMetaType<PeerPtr>("PeerPtr");
215 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
217 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
218 if (!QMetaType::type("QVariant")) {
219 qRegisterMetaType<QVariant>("QVariant");
220 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
225 void Quassel::setupEnvironment()
227 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
228 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
229 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
230 // hack extra search paths into various places.
232 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
233 if (xdgDataVar.isEmpty())
234 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
236 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
238 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
239 QString appDir = QCoreApplication::applicationDirPath();
240 int binpos = appDir.lastIndexOf("/bin");
242 appDir.replace(binpos, 4, "/share");
243 xdgDirs.append(appDir);
244 // Also append apps/quassel, this is only for QIconLoader to find icons there
245 xdgDirs.append(appDir + "/apps/quassel");
247 xdgDirs.append(appDir); // build directory is always the last fallback
249 xdgDirs.removeDuplicates();
251 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
256 void Quassel::setupBuildInfo()
258 _buildInfo.applicationName = "quassel";
259 _buildInfo.coreApplicationName = "quasselcore";
260 _buildInfo.clientApplicationName = "quasselclient";
261 _buildInfo.organizationName = "Quassel Project";
262 _buildInfo.organizationDomain = "quassel-irc.org";
264 _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
266 _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
267 _buildInfo.generatedVersion = GIT_DESCRIBE;
269 // Check if we got a commit hash
270 if (!QString(GIT_HEAD).isEmpty()) {
271 _buildInfo.commitHash = GIT_HEAD;
273 date.setTime_t(GIT_COMMIT_DATE);
274 _buildInfo.commitDate = date.toString();
276 else if (!QString(DIST_HASH).contains("Format")) {
277 _buildInfo.commitHash = DIST_HASH;
278 _buildInfo.commitDate = QString(DIST_DATE);
281 // create a nice version string
282 if (_buildInfo.generatedVersion.isEmpty()) {
283 if (!_buildInfo.commitHash.isEmpty()) {
285 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
286 .arg(_buildInfo.baseVersion)
287 .arg(_buildInfo.commitHash.left(7));
288 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
289 .arg(_buildInfo.baseVersion)
290 .arg(_buildInfo.commitHash.left(7))
291 .arg(_buildInfo.commitHash);
294 // we only have a base version :(
295 _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
299 // analyze what we got from git-describe
300 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$");
301 if (rx.exactMatch(_buildInfo.generatedVersion)) {
302 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
303 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
304 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
305 if (!_buildInfo.commitHash.isEmpty()) {
306 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
307 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
311 _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
314 if (_buildInfo.fancyVersionString.isEmpty())
315 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
319 //! Signal handler for graceful shutdown.
320 void Quassel::handleSignal(int sig)
325 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
329 QCoreApplication::quit();
332 // Windows does not support SIGHUP
334 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
335 // graceful reloading of processes.
337 // If the instance exists, reload the configuration
338 quInfo() << "Caught signal" << SIGHUP <<"- reloading configuration";
339 if (_instance->reloadConfig()) {
340 quInfo() << "Successfully reloaded configuration";
350 logBacktrace(coreDumpFileName());
359 void Quassel::logFatalMessage(const char *msg)
364 QFile dumpFile(coreDumpFileName());
365 dumpFile.open(QIODevice::Append);
366 QTextStream dumpStream(&dumpFile);
368 dumpStream << "Fatal: " << msg << '\n';
375 Quassel::Features Quassel::features()
378 for (int i = 1; i <= NumFeatures; i <<= 1)
385 const QString &Quassel::coreDumpFileName()
387 if (_coreDumpFileName.isEmpty()) {
388 QDir configDir(configDirPath());
389 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
390 QFile dumpFile(_coreDumpFileName);
391 dumpFile.open(QIODevice::Append);
392 QTextStream dumpStream(&dumpFile);
393 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
394 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
398 return _coreDumpFileName;
402 QString Quassel::configDirPath()
404 if (!_configDirPath.isEmpty())
405 return _configDirPath;
407 if (Quassel::isOptionSet("datadir")) {
408 qWarning() << "Obsolete option --datadir used!";
409 _configDirPath = Quassel::optionValue("datadir");
411 else if (Quassel::isOptionSet("configdir")) {
412 _configDirPath = Quassel::optionValue("configdir");
416 // On Mac, the path is always the same
417 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
419 // We abuse QSettings to find us a sensible path on the other platforms
421 // don't use the registry
422 QSettings::Format format = QSettings::IniFormat;
424 QSettings::Format format = QSettings::NativeFormat;
426 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
427 QFileInfo fileInfo(s.fileName());
428 _configDirPath = fileInfo.dir().absolutePath();
429 #endif /* Q_OS_MAC */
432 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
433 _configDirPath += QDir::separator();
435 QDir qDir(_configDirPath);
436 if (!qDir.exists(_configDirPath)) {
437 if (!qDir.mkpath(_configDirPath)) {
438 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
443 return _configDirPath;
447 QStringList Quassel::dataDirPaths()
449 return _dataDirPaths;
453 QStringList Quassel::findDataDirPaths() const
455 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
456 // want to stay consistent.
458 QStringList dataDirNames;
460 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
461 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
462 << QCoreApplication::applicationDirPath();
463 #elif defined Q_OS_MAC
464 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
465 << QCoreApplication::applicationDirPath();
469 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
470 // This should thus come first.
471 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
472 if (xdgDataHome.isEmpty())
473 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
474 dataDirNames << xdgDataHome;
476 // Now whatever is configured through XDG_DATA_DIRS
477 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
478 if (xdgDataDirs.isEmpty())
479 dataDirNames << "/usr/local/share" << "/usr/share";
481 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
483 // Just in case, also check our install prefix
484 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
486 // Normalize and append our application name
487 for (int i = 0; i < dataDirNames.count(); i++)
488 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
492 // Add resource path and workdir just in case.
493 // Workdir should have precedence
494 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
495 dataDirNames.append(":/data/");
497 // Append trailing '/' and check for existence
498 auto iter = dataDirNames.begin();
499 while (iter != dataDirNames.end()) {
500 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
501 iter->append(QDir::separator());
502 if (!QFile::exists(*iter))
503 iter = dataDirNames.erase(iter);
508 dataDirNames.removeDuplicates();
514 QString Quassel::findDataFilePath(const QString &fileName)
516 QStringList dataDirs = dataDirPaths();
517 foreach(QString dataDir, dataDirs) {
518 QString path = dataDir + fileName;
519 if (QFile::exists(path))
526 QStringList Quassel::scriptDirPaths()
528 QStringList res(configDirPath() + "scripts/");
529 foreach(QString path, dataDirPaths())
530 res << path + "scripts/";
535 QString Quassel::translationDirPath()
537 if (_translationDirPath.isEmpty()) {
538 // We support only one translation dir; fallback mechanisms wouldn't work else.
539 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
540 foreach(const QString &dir, dataDirPaths()) {
541 if (QFile::exists(dir + "translations/")) {
542 _translationDirPath = dir + "translations/";
546 if (_translationDirPath.isEmpty())
547 _translationDirPath = ":/i18n/";
549 return _translationDirPath;
553 void Quassel::loadTranslation(const QLocale &locale)
555 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
556 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
559 qApp->removeTranslator(qtTranslator);
560 if (quasselTranslator)
561 qApp->removeTranslator(quasselTranslator);
563 // We use QLocale::C to indicate that we don't want a translation
564 if (locale.language() == QLocale::C)
567 qtTranslator = new QTranslator(qApp);
568 qtTranslator->setObjectName("QtTr");
569 qApp->installTranslator(qtTranslator);
571 quasselTranslator = new QTranslator(qApp);
572 quasselTranslator->setObjectName("QuasselTr");
573 qApp->installTranslator(quasselTranslator);
575 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
576 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
578 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
579 quasselTranslator->load(locale, QString(""), translationDirPath());
581 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
583 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
584 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());