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>
35 #include <QHostAddress>
36 #include <QLibraryInfo>
38 #include <QTranslator>
41 #include "bufferinfo.h"
48 #include "syncableobject.h"
51 #include "../../version.h"
53 Quassel::BuildInfo Quassel::_buildInfo;
54 AbstractCliParser *Quassel::_cliParser = 0;
55 Quassel::RunMode Quassel::_runMode;
56 QString Quassel::_configDirPath;
57 QString Quassel::_translationDirPath;
58 QStringList Quassel::_dataDirPaths;
59 bool Quassel::_initialized = false;
60 bool Quassel::DEBUG = false;
61 QString Quassel::_coreDumpFileName;
62 Quassel *Quassel::_instance = 0;
63 bool Quassel::_handleCrashes = true;
64 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
65 QFile *Quassel::_logFile = 0;
66 bool Quassel::_logToSyslog = false;
73 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
74 signal(SIGTERM, handleSignal);
75 signal(SIGINT, handleSignal);
77 // SIGHUP is used to reload configuration (i.e. SSL certificates)
78 // Windows does not support SIGHUP
79 signal(SIGHUP, handleSignal);
88 logFile()->deleteLater();
97 return true; // allow multiple invocations because of MonolithicApplication
100 // we have crashhandler for win32 and unix (based on execinfo).
101 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
103 // we only handle crashes ourselves if coredumps are disabled
104 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
105 int rc = getrlimit(RLIMIT_CORE, limit);
107 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
108 # endif /* Q_OS_WIN */
109 signal(SIGABRT, handleSignal);
110 signal(SIGSEGV, handleSignal);
112 signal(SIGBUS, handleSignal);
115 # endif /* Q_OS_WIN */
116 #endif /* Q_OS_WIN || HAVE_EXECINFO */
120 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
125 Network::setDefaultCodecForServer("ISO-8859-1");
126 Network::setDefaultCodecForEncoding("UTF-8");
127 Network::setDefaultCodecForDecoding("ISO-8859-15");
129 if (isOptionSet("help")) {
130 cliParser()->usage();
134 if (isOptionSet("version")) {
135 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
139 DEBUG = isOptionSet("debug");
142 if (Quassel::runMode() != Quassel::ClientOnly) {
143 if (isOptionSet("loglevel")) {
144 QString level = optionValue("loglevel");
146 if (level == "Debug") _logLevel = DebugLevel;
147 else if (level == "Info") _logLevel = InfoLevel;
148 else if (level == "Warning") _logLevel = WarningLevel;
149 else if (level == "Error") _logLevel = ErrorLevel;
152 QString logfilename = optionValue("logfile");
153 if (!logfilename.isEmpty()) {
154 _logFile = new QFile(logfilename);
155 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
156 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
157 _logFile->deleteLater();
162 _logToSyslog = isOptionSet("syslog");
172 QCoreApplication::quit();
176 //! Register our custom types with Qt's Meta Object System.
177 /** This makes them available for QVariant and in signals/slots, among other things.
180 void Quassel::registerMetaTypes()
183 qRegisterMetaType<Message>("Message");
184 qRegisterMetaType<BufferInfo>("BufferInfo");
185 qRegisterMetaType<NetworkInfo>("NetworkInfo");
186 qRegisterMetaType<Network::Server>("Network::Server");
187 qRegisterMetaType<Identity>("Identity");
189 qRegisterMetaTypeStreamOperators<Message>("Message");
190 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
191 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
192 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
193 qRegisterMetaTypeStreamOperators<Identity>("Identity");
195 qRegisterMetaType<IdentityId>("IdentityId");
196 qRegisterMetaType<BufferId>("BufferId");
197 qRegisterMetaType<NetworkId>("NetworkId");
198 qRegisterMetaType<UserId>("UserId");
199 qRegisterMetaType<AccountId>("AccountId");
200 qRegisterMetaType<MsgId>("MsgId");
202 qRegisterMetaType<QHostAddress>("QHostAddress");
203 qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
204 qRegisterMetaType<QUuid>("QUuid");
205 qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
207 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
208 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
209 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
210 qRegisterMetaTypeStreamOperators<UserId>("UserId");
211 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
212 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
214 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
215 qRegisterMetaType<PeerPtr>("PeerPtr");
216 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
218 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
219 if (!QMetaType::type("QVariant")) {
220 qRegisterMetaType<QVariant>("QVariant");
221 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
226 void Quassel::setupEnvironment()
228 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
229 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
230 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
231 // hack extra search paths into various places.
233 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
234 if (xdgDataVar.isEmpty())
235 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
237 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
239 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
240 QString appDir = QCoreApplication::applicationDirPath();
241 int binpos = appDir.lastIndexOf("/bin");
243 appDir.replace(binpos, 4, "/share");
244 xdgDirs.append(appDir);
245 // Also append apps/quassel, this is only for QIconLoader to find icons there
246 xdgDirs.append(appDir + "/apps/quassel");
248 xdgDirs.append(appDir); // build directory is always the last fallback
250 xdgDirs.removeDuplicates();
252 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
257 void Quassel::setupBuildInfo()
259 _buildInfo.applicationName = "quassel";
260 _buildInfo.coreApplicationName = "quasselcore";
261 _buildInfo.clientApplicationName = "quasselclient";
262 _buildInfo.organizationName = "Quassel Project";
263 _buildInfo.organizationDomain = "quassel-irc.org";
265 _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
267 _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
268 _buildInfo.generatedVersion = GIT_DESCRIBE;
270 // Check if we got a commit hash
271 if (!QString(GIT_HEAD).isEmpty()) {
272 _buildInfo.commitHash = GIT_HEAD;
274 date.setTime_t(GIT_COMMIT_DATE);
275 _buildInfo.commitDate = date.toString();
277 else if (!QString(DIST_HASH).contains("Format")) {
278 _buildInfo.commitHash = DIST_HASH;
279 _buildInfo.commitDate = QString(DIST_DATE);
282 // create a nice version string
283 if (_buildInfo.generatedVersion.isEmpty()) {
284 if (!_buildInfo.commitHash.isEmpty()) {
286 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
287 .arg(_buildInfo.baseVersion)
288 .arg(_buildInfo.commitHash.left(7));
289 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)")
290 .arg(_buildInfo.baseVersion)
291 .arg(_buildInfo.commitHash.left(7))
292 .arg(_buildInfo.commitHash);
295 // we only have a base version :(
296 _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
300 // analyze what we got from git-describe
301 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$");
302 if (rx.exactMatch(_buildInfo.generatedVersion)) {
303 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
304 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
305 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
306 if (!_buildInfo.commitHash.isEmpty()) {
307 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)")
308 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
312 _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
315 if (_buildInfo.fancyVersionString.isEmpty())
316 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
320 //! Signal handler for graceful shutdown.
321 void Quassel::handleSignal(int sig)
326 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
330 QCoreApplication::quit();
333 // Windows does not support SIGHUP
335 // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
336 // graceful reloading of processes.
338 // If the instance exists, reload the configuration
339 quInfo() << "Caught signal" << SIGHUP <<"- reloading configuration";
340 if (_instance->reloadConfig()) {
341 quInfo() << "Successfully reloaded configuration";
351 logBacktrace(coreDumpFileName());
360 void Quassel::logFatalMessage(const char *msg)
365 QFile dumpFile(coreDumpFileName());
366 dumpFile.open(QIODevice::Append);
367 QTextStream dumpStream(&dumpFile);
369 dumpStream << "Fatal: " << msg << '\n';
376 Quassel::Features Quassel::features()
379 for (int i = 1; i <= NumFeatures; i <<= 1)
386 const QString &Quassel::coreDumpFileName()
388 if (_coreDumpFileName.isEmpty()) {
389 QDir configDir(configDirPath());
390 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
391 QFile dumpFile(_coreDumpFileName);
392 dumpFile.open(QIODevice::Append);
393 QTextStream dumpStream(&dumpFile);
394 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
395 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
399 return _coreDumpFileName;
403 QString Quassel::configDirPath()
405 if (!_configDirPath.isEmpty())
406 return _configDirPath;
408 if (Quassel::isOptionSet("datadir")) {
409 qWarning() << "Obsolete option --datadir used!";
410 _configDirPath = Quassel::optionValue("datadir");
412 else if (Quassel::isOptionSet("configdir")) {
413 _configDirPath = Quassel::optionValue("configdir");
417 // On Mac, the path is always the same
418 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
420 // We abuse QSettings to find us a sensible path on the other platforms
422 // don't use the registry
423 QSettings::Format format = QSettings::IniFormat;
425 QSettings::Format format = QSettings::NativeFormat;
427 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
428 QFileInfo fileInfo(s.fileName());
429 _configDirPath = fileInfo.dir().absolutePath();
430 #endif /* Q_OS_MAC */
433 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
434 _configDirPath += QDir::separator();
436 QDir qDir(_configDirPath);
437 if (!qDir.exists(_configDirPath)) {
438 if (!qDir.mkpath(_configDirPath)) {
439 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
444 return _configDirPath;
448 QStringList Quassel::dataDirPaths()
450 return _dataDirPaths;
454 QStringList Quassel::findDataDirPaths() const
456 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
457 // want to stay consistent.
459 QStringList dataDirNames;
461 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
462 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
463 << QCoreApplication::applicationDirPath();
464 #elif defined Q_OS_MAC
465 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
466 << QCoreApplication::applicationDirPath();
470 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
471 // This should thus come first.
472 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
473 if (xdgDataHome.isEmpty())
474 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
475 dataDirNames << xdgDataHome;
477 // Now whatever is configured through XDG_DATA_DIRS
478 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
479 if (xdgDataDirs.isEmpty())
480 dataDirNames << "/usr/local/share" << "/usr/share";
482 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
484 // Just in case, also check our install prefix
485 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
487 // Normalize and append our application name
488 for (int i = 0; i < dataDirNames.count(); i++)
489 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
493 // Add resource path and workdir just in case.
494 // Workdir should have precedence
495 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
496 dataDirNames.append(":/data/");
498 // Append trailing '/' and check for existence
499 auto iter = dataDirNames.begin();
500 while (iter != dataDirNames.end()) {
501 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
502 iter->append(QDir::separator());
503 if (!QFile::exists(*iter))
504 iter = dataDirNames.erase(iter);
509 dataDirNames.removeDuplicates();
515 QString Quassel::findDataFilePath(const QString &fileName)
517 QStringList dataDirs = dataDirPaths();
518 foreach(QString dataDir, dataDirs) {
519 QString path = dataDir + fileName;
520 if (QFile::exists(path))
527 QStringList Quassel::scriptDirPaths()
529 QStringList res(configDirPath() + "scripts/");
530 foreach(QString path, dataDirPaths())
531 res << path + "scripts/";
536 QString Quassel::translationDirPath()
538 if (_translationDirPath.isEmpty()) {
539 // We support only one translation dir; fallback mechanisms wouldn't work else.
540 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
541 foreach(const QString &dir, dataDirPaths()) {
542 if (QFile::exists(dir + "translations/")) {
543 _translationDirPath = dir + "translations/";
547 if (_translationDirPath.isEmpty())
548 _translationDirPath = ":/i18n/";
550 return _translationDirPath;
554 void Quassel::loadTranslation(const QLocale &locale)
556 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
557 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
560 qApp->removeTranslator(qtTranslator);
561 if (quasselTranslator)
562 qApp->removeTranslator(quasselTranslator);
564 // We use QLocale::C to indicate that we don't want a translation
565 if (locale.language() == QLocale::C)
568 qtTranslator = new QTranslator(qApp);
569 qtTranslator->setObjectName("QtTr");
570 qApp->installTranslator(qtTranslator);
572 quasselTranslator = new QTranslator(qApp);
573 quasselTranslator->setObjectName("QuasselTr");
574 qApp->installTranslator(quasselTranslator);
576 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
577 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
579 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
580 quasselTranslator->load(locale, QString(""), translationDirPath());
582 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
584 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
585 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());