Semi-yearly copyright bump
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 <QFileInfo>
34 #include <QHostAddress>
35 #include <QLibraryInfo>
36 #include <QSettings>
37 #include <QTranslator>
38 #include <QUuid>
39
40 #include "bufferinfo.h"
41 #include "identity.h"
42 #include "logger.h"
43 #include "message.h"
44 #include "network.h"
45 #include "peer.h"
46 #include "protocol.h"
47 #include "syncableobject.h"
48 #include "types.h"
49
50 #include "../../version.h"
51
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;
66
67 Quassel::Quassel()
68 {
69     Q_ASSERT(!_instance);
70     _instance = this;
71
72     // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
73     signal(SIGTERM, handleSignal);
74     signal(SIGINT, handleSignal);
75 #ifndef Q_OS_WIN
76     // SIGHUP is used to reload configuration (i.e. SSL certificates)
77     // Windows does not support SIGHUP
78     signal(SIGHUP, handleSignal);
79 #endif
80 }
81
82
83 Quassel::~Quassel()
84 {
85     if (logFile()) {
86         logFile()->close();
87         logFile()->deleteLater();
88     }
89     delete _cliParser;
90 }
91
92
93 bool Quassel::init()
94 {
95     if (_initialized)
96         return true;  // allow multiple invocations because of MonolithicApplication
97
98     if (_handleCrashes) {
99         // we have crashhandler for win32 and unix (based on execinfo).
100 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
101 # ifndef Q_OS_WIN
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);
105
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);
110 # ifndef Q_OS_WIN
111         signal(SIGBUS, handleSignal);
112     }
113     free(limit);
114 # endif /* Q_OS_WIN */
115 #endif /* Q_OS_WIN || HAVE_EXECINFO */
116     }
117
118     _initialized = true;
119     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
120
121     setupEnvironment();
122     registerMetaTypes();
123
124     Network::setDefaultCodecForServer("ISO-8859-1");
125     Network::setDefaultCodecForEncoding("UTF-8");
126     Network::setDefaultCodecForDecoding("ISO-8859-15");
127
128     if (isOptionSet("help")) {
129         cliParser()->usage();
130         return false;
131     }
132
133     if (isOptionSet("version")) {
134         std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
135         return false;
136     }
137
138     DEBUG = isOptionSet("debug");
139
140     // set up logging
141     if (Quassel::runMode() != Quassel::ClientOnly) {
142         if (isOptionSet("loglevel")) {
143             QString level = optionValue("loglevel");
144
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;
149         }
150
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();
157                 _logFile = 0;
158             }
159         }
160 #ifdef HAVE_SYSLOG
161         _logToSyslog = isOptionSet("syslog");
162 #endif
163     }
164
165     return true;
166 }
167
168
169 void Quassel::quit()
170 {
171     QCoreApplication::quit();
172 }
173
174
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.
177 *
178 */
179 void Quassel::registerMetaTypes()
180 {
181     // Complex types
182     qRegisterMetaType<Message>("Message");
183     qRegisterMetaType<BufferInfo>("BufferInfo");
184     qRegisterMetaType<NetworkInfo>("NetworkInfo");
185     qRegisterMetaType<Network::Server>("Network::Server");
186     qRegisterMetaType<Identity>("Identity");
187
188     qRegisterMetaTypeStreamOperators<Message>("Message");
189     qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
190     qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
191     qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
192     qRegisterMetaTypeStreamOperators<Identity>("Identity");
193
194     qRegisterMetaType<IdentityId>("IdentityId");
195     qRegisterMetaType<BufferId>("BufferId");
196     qRegisterMetaType<NetworkId>("NetworkId");
197     qRegisterMetaType<UserId>("UserId");
198     qRegisterMetaType<AccountId>("AccountId");
199     qRegisterMetaType<MsgId>("MsgId");
200
201     qRegisterMetaType<QHostAddress>("QHostAddress");
202     qRegisterMetaType<QUuid>("QUuid");
203
204     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
205     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
206     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
207     qRegisterMetaTypeStreamOperators<UserId>("UserId");
208     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
209     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
210
211     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
212     qRegisterMetaType<PeerPtr>("PeerPtr");
213     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
214
215     // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
216     if (!QMetaType::type("QVariant")) {
217         qRegisterMetaType<QVariant>("QVariant");
218         qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
219     }
220 }
221
222
223 void Quassel::setupEnvironment()
224 {
225     // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
226     // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
227     // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
228     // hack extra search paths into various places.
229 #ifdef Q_OS_UNIX
230     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
231     if (xdgDataVar.isEmpty())
232         xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
233
234     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
235
236     // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
237     QString appDir = QCoreApplication::applicationDirPath();
238     int binpos = appDir.lastIndexOf("/bin");
239     if (binpos >= 0) {
240         appDir.replace(binpos, 4, "/share");
241         xdgDirs.append(appDir);
242         // Also append apps/quassel, this is only for QIconLoader to find icons there
243         xdgDirs.append(appDir + "/apps/quassel");
244     } else
245         xdgDirs.append(appDir);  // build directory is always the last fallback
246
247     xdgDirs.removeDuplicates();
248
249     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
250 #endif
251 }
252
253
254 void Quassel::setupBuildInfo()
255 {
256     _buildInfo.applicationName = "quassel";
257     _buildInfo.coreApplicationName = "quasselcore";
258     _buildInfo.clientApplicationName = "quasselclient";
259     _buildInfo.organizationName = "Quassel Project";
260     _buildInfo.organizationDomain = "quassel-irc.org";
261
262     _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
263
264     _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
265     _buildInfo.generatedVersion = GIT_DESCRIBE;
266
267     // Check if we got a commit hash
268     if (!QString(GIT_HEAD).isEmpty()) {
269         _buildInfo.commitHash = GIT_HEAD;
270         QDateTime date;
271         date.setTime_t(GIT_COMMIT_DATE);
272         _buildInfo.commitDate = date.toString();
273     }
274     else if (!QString(DIST_HASH).contains("Format")) {
275         _buildInfo.commitHash = DIST_HASH;
276         _buildInfo.commitDate = QString(DIST_DATE);
277     }
278
279     // create a nice version string
280     if (_buildInfo.generatedVersion.isEmpty()) {
281         if (!_buildInfo.commitHash.isEmpty()) {
282             // dist version
283             _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
284                                             .arg(_buildInfo.baseVersion)
285                                             .arg(_buildInfo.commitHash.left(7));
286             _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)")
287                                             .arg(_buildInfo.baseVersion)
288                                             .arg(_buildInfo.commitHash.left(7))
289                                             .arg(_buildInfo.commitHash);
290         }
291         else {
292             // we only have a base version :(
293             _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
294         }
295     }
296     else {
297         // analyze what we got from git-describe
298         QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$");
299         if (rx.exactMatch(_buildInfo.generatedVersion)) {
300             QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
301             _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
302                                             .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
303             if (!_buildInfo.commitHash.isEmpty()) {
304                 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)")
305                                                 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
306             }
307         }
308         else {
309             _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
310         }
311     }
312     if (_buildInfo.fancyVersionString.isEmpty())
313         _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
314 }
315
316
317 //! Signal handler for graceful shutdown.
318 void Quassel::handleSignal(int sig)
319 {
320     switch (sig) {
321     case SIGTERM:
322     case SIGINT:
323         qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
324         if (_instance)
325             _instance->quit();
326         else
327             QCoreApplication::quit();
328         break;
329 #ifndef Q_OS_WIN
330 // Windows does not support SIGHUP
331     case SIGHUP:
332         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
333         // graceful reloading of processes.
334         if (_instance) {
335             // If the instance exists, reload the configuration
336             quInfo() << "Caught signal" << SIGHUP <<"- reloading configuration";
337             if (_instance->reloadConfig()) {
338                 quInfo() << "Successfully reloaded configuration";
339             }
340         }
341         break;
342 #endif
343     case SIGABRT:
344     case SIGSEGV:
345 #ifndef Q_OS_WIN
346     case SIGBUS:
347 #endif
348         logBacktrace(coreDumpFileName());
349         exit(EXIT_FAILURE);
350         break;
351     default:
352         break;
353     }
354 }
355
356
357 void Quassel::logFatalMessage(const char *msg)
358 {
359 #ifdef Q_OS_MAC
360     Q_UNUSED(msg)
361 #else
362     QFile dumpFile(coreDumpFileName());
363     dumpFile.open(QIODevice::Append);
364     QTextStream dumpStream(&dumpFile);
365
366     dumpStream << "Fatal: " << msg << '\n';
367     dumpStream.flush();
368     dumpFile.close();
369 #endif
370 }
371
372
373 Quassel::Features Quassel::features()
374 {
375     Features feats = 0;
376     for (int i = 1; i <= NumFeatures; i <<= 1)
377         feats |= (Feature)i;
378
379     return feats;
380 }
381
382
383 const QString &Quassel::coreDumpFileName()
384 {
385     if (_coreDumpFileName.isEmpty()) {
386         QDir configDir(configDirPath());
387         _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
388         QFile dumpFile(_coreDumpFileName);
389         dumpFile.open(QIODevice::Append);
390         QTextStream dumpStream(&dumpFile);
391         dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
392         qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
393         dumpStream.flush();
394         dumpFile.close();
395     }
396     return _coreDumpFileName;
397 }
398
399
400 QString Quassel::configDirPath()
401 {
402     if (!_configDirPath.isEmpty())
403         return _configDirPath;
404
405     if (Quassel::isOptionSet("datadir")) {
406         qWarning() << "Obsolete option --datadir used!";
407         _configDirPath = Quassel::optionValue("datadir");
408     }
409     else if (Quassel::isOptionSet("configdir")) {
410         _configDirPath = Quassel::optionValue("configdir");
411     }
412     else {
413 #ifdef Q_OS_MAC
414         // On Mac, the path is always the same
415         _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
416 #else
417         // We abuse QSettings to find us a sensible path on the other platforms
418 #  ifdef Q_OS_WIN
419         // don't use the registry
420         QSettings::Format format = QSettings::IniFormat;
421 #  else
422         QSettings::Format format = QSettings::NativeFormat;
423 #  endif
424         QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
425         QFileInfo fileInfo(s.fileName());
426         _configDirPath = fileInfo.dir().absolutePath();
427 #endif /* Q_OS_MAC */
428     }
429
430     if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
431         _configDirPath += QDir::separator();
432
433     QDir qDir(_configDirPath);
434     if (!qDir.exists(_configDirPath)) {
435         if (!qDir.mkpath(_configDirPath)) {
436             qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
437             return QString();
438         }
439     }
440
441     return _configDirPath;
442 }
443
444
445 QStringList Quassel::dataDirPaths()
446 {
447     return _dataDirPaths;
448 }
449
450
451 QStringList Quassel::findDataDirPaths() const
452 {
453     // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
454     // want to stay consistent.
455
456     QStringList dataDirNames;
457 #ifdef Q_OS_WIN
458     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
459                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
460                  << QCoreApplication::applicationDirPath();
461 #elif defined Q_OS_MAC
462     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
463                  << QCoreApplication::applicationDirPath();
464 #else
465     // Linux et al
466
467     // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
468     // This should thus come first.
469     QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
470     if (xdgDataHome.isEmpty())
471         xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
472     dataDirNames << xdgDataHome;
473
474     // Now whatever is configured through XDG_DATA_DIRS
475     QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
476     if (xdgDataDirs.isEmpty())
477         dataDirNames << "/usr/local/share" << "/usr/share";
478     else
479         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
480
481     // Just in case, also check our install prefix
482     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
483
484     // Normalize and append our application name
485     for (int i = 0; i < dataDirNames.count(); i++)
486         dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
487
488 #endif
489
490     // Add resource path and workdir just in case.
491     // Workdir should have precedence
492     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
493     dataDirNames.append(":/data/");
494
495     // Append trailing '/' and check for existence
496     auto iter = dataDirNames.begin();
497     while (iter != dataDirNames.end()) {
498         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
499             iter->append(QDir::separator());
500         if (!QFile::exists(*iter))
501             iter = dataDirNames.erase(iter);
502         else
503             ++iter;
504     }
505
506     dataDirNames.removeDuplicates();
507
508     return dataDirNames;
509 }
510
511
512 QString Quassel::findDataFilePath(const QString &fileName)
513 {
514     QStringList dataDirs = dataDirPaths();
515     foreach(QString dataDir, dataDirs) {
516         QString path = dataDir + fileName;
517         if (QFile::exists(path))
518             return path;
519     }
520     return QString();
521 }
522
523
524 QStringList Quassel::scriptDirPaths()
525 {
526     QStringList res(configDirPath() + "scripts/");
527     foreach(QString path, dataDirPaths())
528     res << path + "scripts/";
529     return res;
530 }
531
532
533 QString Quassel::translationDirPath()
534 {
535     if (_translationDirPath.isEmpty()) {
536         // We support only one translation dir; fallback mechanisms wouldn't work else.
537         // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
538         foreach(const QString &dir, dataDirPaths()) {
539             if (QFile::exists(dir + "translations/")) {
540                 _translationDirPath = dir + "translations/";
541                 break;
542             }
543         }
544         if (_translationDirPath.isEmpty())
545             _translationDirPath = ":/i18n/";
546     }
547     return _translationDirPath;
548 }
549
550
551 void Quassel::loadTranslation(const QLocale &locale)
552 {
553     QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
554     QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
555
556     if (qtTranslator)
557         qApp->removeTranslator(qtTranslator);
558     if (quasselTranslator)
559         qApp->removeTranslator(quasselTranslator);
560
561     // We use QLocale::C to indicate that we don't want a translation
562     if (locale.language() == QLocale::C)
563         return;
564
565     qtTranslator = new QTranslator(qApp);
566     qtTranslator->setObjectName("QtTr");
567     qApp->installTranslator(qtTranslator);
568
569     quasselTranslator = new QTranslator(qApp);
570     quasselTranslator->setObjectName("QuasselTr");
571     qApp->installTranslator(quasselTranslator);
572
573 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
574     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
575     if (!success)
576         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
577     quasselTranslator->load(locale, QString(""), translationDirPath());
578 #else
579     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
580     if (!success)
581         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
582     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
583 #endif
584 }