common: Make frequently called util methods more efficient
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "quassel.h"
22
23 #include <iostream>
24 #include <signal.h>
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>
29 #endif
30
31 #include <QCoreApplication>
32 #include <QDateTime>
33 #include <QDir>
34 #include <QFileInfo>
35 #include <QHostAddress>
36 #include <QLibraryInfo>
37 #include <QSettings>
38 #include <QTranslator>
39 #include <QUuid>
40
41 #include "bufferinfo.h"
42 #include "identity.h"
43 #include "logger.h"
44 #include "message.h"
45 #include "network.h"
46 #include "peer.h"
47 #include "protocol.h"
48 #include "syncableobject.h"
49 #include "types.h"
50
51 #include "../../version.h"
52
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;
67
68 Quassel::Quassel()
69 {
70     Q_ASSERT(!_instance);
71     _instance = this;
72
73     // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
74     signal(SIGTERM, handleSignal);
75     signal(SIGINT, handleSignal);
76 #ifndef Q_OS_WIN
77     // SIGHUP is used to reload configuration (i.e. SSL certificates)
78     // Windows does not support SIGHUP
79     signal(SIGHUP, handleSignal);
80 #endif
81 }
82
83
84 Quassel::~Quassel()
85 {
86     if (logFile()) {
87         logFile()->close();
88         logFile()->deleteLater();
89     }
90     delete _cliParser;
91 }
92
93
94 bool Quassel::init()
95 {
96     if (_initialized)
97         return true;  // allow multiple invocations because of MonolithicApplication
98
99     if (_handleCrashes) {
100         // we have crashhandler for win32 and unix (based on execinfo).
101 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
102 # ifndef Q_OS_WIN
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);
106
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);
111 # ifndef Q_OS_WIN
112         signal(SIGBUS, handleSignal);
113     }
114     free(limit);
115 # endif /* Q_OS_WIN */
116 #endif /* Q_OS_WIN || HAVE_EXECINFO */
117     }
118
119     _initialized = true;
120     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
121
122     setupEnvironment();
123     registerMetaTypes();
124
125     Network::setDefaultCodecForServer("ISO-8859-1");
126     Network::setDefaultCodecForEncoding("UTF-8");
127     Network::setDefaultCodecForDecoding("ISO-8859-15");
128
129     if (isOptionSet("help")) {
130         cliParser()->usage();
131         return false;
132     }
133
134     if (isOptionSet("version")) {
135         std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
136         return false;
137     }
138
139     DEBUG = isOptionSet("debug");
140
141     // set up logging
142     if (Quassel::runMode() != Quassel::ClientOnly) {
143         if (isOptionSet("loglevel")) {
144             QString level = optionValue("loglevel");
145
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;
150         }
151
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();
158                 _logFile = 0;
159             }
160         }
161 #ifdef HAVE_SYSLOG
162         _logToSyslog = isOptionSet("syslog");
163 #endif
164     }
165
166     return true;
167 }
168
169
170 void Quassel::quit()
171 {
172     QCoreApplication::quit();
173 }
174
175
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.
178 *
179 */
180 void Quassel::registerMetaTypes()
181 {
182     // Complex types
183     qRegisterMetaType<Message>("Message");
184     qRegisterMetaType<BufferInfo>("BufferInfo");
185     qRegisterMetaType<NetworkInfo>("NetworkInfo");
186     qRegisterMetaType<Network::Server>("Network::Server");
187     qRegisterMetaType<Identity>("Identity");
188
189     qRegisterMetaTypeStreamOperators<Message>("Message");
190     qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
191     qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
192     qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
193     qRegisterMetaTypeStreamOperators<Identity>("Identity");
194
195     qRegisterMetaType<IdentityId>("IdentityId");
196     qRegisterMetaType<BufferId>("BufferId");
197     qRegisterMetaType<NetworkId>("NetworkId");
198     qRegisterMetaType<UserId>("UserId");
199     qRegisterMetaType<AccountId>("AccountId");
200     qRegisterMetaType<MsgId>("MsgId");
201
202     qRegisterMetaType<QHostAddress>("QHostAddress");
203     qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
204     qRegisterMetaType<QUuid>("QUuid");
205     qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
206
207     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
208     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
209     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
210     qRegisterMetaTypeStreamOperators<UserId>("UserId");
211     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
212     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
213
214     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
215     qRegisterMetaType<PeerPtr>("PeerPtr");
216     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
217
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");
222     }
223 }
224
225
226 void Quassel::setupEnvironment()
227 {
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.
232 #ifdef Q_OS_UNIX
233     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
234     if (xdgDataVar.isEmpty())
235         xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
236
237     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
238
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");
242     if (binpos >= 0) {
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");
247     } else
248         xdgDirs.append(appDir);  // build directory is always the last fallback
249
250     xdgDirs.removeDuplicates();
251
252     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
253 #endif
254 }
255
256
257 void Quassel::setupBuildInfo()
258 {
259     _buildInfo.applicationName = "quassel";
260     _buildInfo.coreApplicationName = "quasselcore";
261     _buildInfo.clientApplicationName = "quasselclient";
262     _buildInfo.organizationName = "Quassel Project";
263     _buildInfo.organizationDomain = "quassel-irc.org";
264
265     _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
266
267     _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
268     _buildInfo.generatedVersion = GIT_DESCRIBE;
269
270     // Check if we got a commit hash
271     if (!QString(GIT_HEAD).isEmpty()) {
272         _buildInfo.commitHash = GIT_HEAD;
273         QDateTime date;
274         date.setTime_t(GIT_COMMIT_DATE);
275         _buildInfo.commitDate = date.toString();
276     }
277     else if (!QString(DIST_HASH).contains("Format")) {
278         _buildInfo.commitHash = DIST_HASH;
279         _buildInfo.commitDate = QString(DIST_DATE);
280     }
281
282     // create a nice version string
283     if (_buildInfo.generatedVersion.isEmpty()) {
284         if (!_buildInfo.commitHash.isEmpty()) {
285             // dist version
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);
293         }
294         else {
295             // we only have a base version :(
296             _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
297         }
298     }
299     else {
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);
309             }
310         }
311         else {
312             _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
313         }
314     }
315     if (_buildInfo.fancyVersionString.isEmpty())
316         _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
317 }
318
319
320 //! Signal handler for graceful shutdown.
321 void Quassel::handleSignal(int sig)
322 {
323     switch (sig) {
324     case SIGTERM:
325     case SIGINT:
326         qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
327         if (_instance)
328             _instance->quit();
329         else
330             QCoreApplication::quit();
331         break;
332 #ifndef Q_OS_WIN
333 // Windows does not support SIGHUP
334     case SIGHUP:
335         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
336         // graceful reloading of processes.
337         if (_instance) {
338             // If the instance exists, reload the configuration
339             quInfo() << "Caught signal" << SIGHUP <<"- reloading configuration";
340             if (_instance->reloadConfig()) {
341                 quInfo() << "Successfully reloaded configuration";
342             }
343         }
344         break;
345 #endif
346     case SIGABRT:
347     case SIGSEGV:
348 #ifndef Q_OS_WIN
349     case SIGBUS:
350 #endif
351         logBacktrace(coreDumpFileName());
352         exit(EXIT_FAILURE);
353         break;
354     default:
355         break;
356     }
357 }
358
359
360 void Quassel::logFatalMessage(const char *msg)
361 {
362 #ifdef Q_OS_MAC
363     Q_UNUSED(msg)
364 #else
365     QFile dumpFile(coreDumpFileName());
366     dumpFile.open(QIODevice::Append);
367     QTextStream dumpStream(&dumpFile);
368
369     dumpStream << "Fatal: " << msg << '\n';
370     dumpStream.flush();
371     dumpFile.close();
372 #endif
373 }
374
375
376 Quassel::Features Quassel::features()
377 {
378     Features feats = 0;
379     for (int i = 1; i <= NumFeatures; i <<= 1)
380         feats |= (Feature)i;
381
382     return feats;
383 }
384
385
386 const QString &Quassel::coreDumpFileName()
387 {
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;
396         dumpStream.flush();
397         dumpFile.close();
398     }
399     return _coreDumpFileName;
400 }
401
402
403 QString Quassel::configDirPath()
404 {
405     if (!_configDirPath.isEmpty())
406         return _configDirPath;
407
408     if (Quassel::isOptionSet("datadir")) {
409         qWarning() << "Obsolete option --datadir used!";
410         _configDirPath = Quassel::optionValue("datadir");
411     }
412     else if (Quassel::isOptionSet("configdir")) {
413         _configDirPath = Quassel::optionValue("configdir");
414     }
415     else {
416 #ifdef Q_OS_MAC
417         // On Mac, the path is always the same
418         _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
419 #else
420         // We abuse QSettings to find us a sensible path on the other platforms
421 #  ifdef Q_OS_WIN
422         // don't use the registry
423         QSettings::Format format = QSettings::IniFormat;
424 #  else
425         QSettings::Format format = QSettings::NativeFormat;
426 #  endif
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 */
431     }
432
433     if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
434         _configDirPath += QDir::separator();
435
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());
440             return QString();
441         }
442     }
443
444     return _configDirPath;
445 }
446
447
448 QStringList Quassel::dataDirPaths()
449 {
450     return _dataDirPaths;
451 }
452
453
454 QStringList Quassel::findDataDirPaths() const
455 {
456     // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
457     // want to stay consistent.
458
459     QStringList dataDirNames;
460 #ifdef Q_OS_WIN
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();
467 #else
468     // Linux et al
469
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;
476
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";
481     else
482         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
483
484     // Just in case, also check our install prefix
485     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
486
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/";
490
491 #endif
492
493     // Add resource path and workdir just in case.
494     // Workdir should have precedence
495     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
496     dataDirNames.append(":/data/");
497
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);
505         else
506             ++iter;
507     }
508
509     dataDirNames.removeDuplicates();
510
511     return dataDirNames;
512 }
513
514
515 QString Quassel::findDataFilePath(const QString &fileName)
516 {
517     QStringList dataDirs = dataDirPaths();
518     foreach(QString dataDir, dataDirs) {
519         QString path = dataDir + fileName;
520         if (QFile::exists(path))
521             return path;
522     }
523     return QString();
524 }
525
526
527 QStringList Quassel::scriptDirPaths()
528 {
529     QStringList res(configDirPath() + "scripts/");
530     foreach(QString path, dataDirPaths())
531     res << path + "scripts/";
532     return res;
533 }
534
535
536 QString Quassel::translationDirPath()
537 {
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/";
544                 break;
545             }
546         }
547         if (_translationDirPath.isEmpty())
548             _translationDirPath = ":/i18n/";
549     }
550     return _translationDirPath;
551 }
552
553
554 void Quassel::loadTranslation(const QLocale &locale)
555 {
556     QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
557     QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
558
559     if (qtTranslator)
560         qApp->removeTranslator(qtTranslator);
561     if (quasselTranslator)
562         qApp->removeTranslator(quasselTranslator);
563
564     // We use QLocale::C to indicate that we don't want a translation
565     if (locale.language() == QLocale::C)
566         return;
567
568     qtTranslator = new QTranslator(qApp);
569     qtTranslator->setObjectName("QtTr");
570     qApp->installTranslator(qtTranslator);
571
572     quasselTranslator = new QTranslator(qApp);
573     quasselTranslator->setObjectName("QuasselTr");
574     qApp->installTranslator(quasselTranslator);
575
576 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
577     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
578     if (!success)
579         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
580     quasselTranslator->load(locale, QString(""), translationDirPath());
581 #else
582     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
583     if (!success)
584         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
585     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
586 #endif
587 }