Point to github in Core Info
[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 <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     qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
203     qRegisterMetaType<QUuid>("QUuid");
204     qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
205
206     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
207     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
208     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
209     qRegisterMetaTypeStreamOperators<UserId>("UserId");
210     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
211     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
212
213     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
214     qRegisterMetaType<PeerPtr>("PeerPtr");
215     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
216
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");
221     }
222 }
223
224
225 void Quassel::setupEnvironment()
226 {
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.
231 #ifdef Q_OS_UNIX
232     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
233     if (xdgDataVar.isEmpty())
234         xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
235
236     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
237
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");
241     if (binpos >= 0) {
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");
246     } else
247         xdgDirs.append(appDir);  // build directory is always the last fallback
248
249     xdgDirs.removeDuplicates();
250
251     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
252 #endif
253 }
254
255
256 void Quassel::setupBuildInfo()
257 {
258     _buildInfo.applicationName = "quassel";
259     _buildInfo.coreApplicationName = "quasselcore";
260     _buildInfo.clientApplicationName = "quasselclient";
261     _buildInfo.organizationName = "Quassel Project";
262     _buildInfo.organizationDomain = "quassel-irc.org";
263
264     _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
265
266     _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
267     _buildInfo.generatedVersion = GIT_DESCRIBE;
268
269     // Check if we got a commit hash
270     if (!QString(GIT_HEAD).isEmpty()) {
271         _buildInfo.commitHash = GIT_HEAD;
272         QDateTime date;
273         date.setTime_t(GIT_COMMIT_DATE);
274         _buildInfo.commitDate = date.toString();
275     }
276     else if (!QString(DIST_HASH).contains("Format")) {
277         _buildInfo.commitHash = DIST_HASH;
278         _buildInfo.commitDate = QString(DIST_DATE);
279     }
280
281     // create a nice version string
282     if (_buildInfo.generatedVersion.isEmpty()) {
283         if (!_buildInfo.commitHash.isEmpty()) {
284             // dist version
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=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)")
289                                             .arg(_buildInfo.baseVersion)
290                                             .arg(_buildInfo.commitHash.left(7))
291                                             .arg(_buildInfo.commitHash);
292         }
293         else {
294             // we only have a base version :(
295             _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
296         }
297     }
298     else {
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=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)")
307                                                 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
308             }
309         }
310         else {
311             _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
312         }
313     }
314     if (_buildInfo.fancyVersionString.isEmpty())
315         _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
316 }
317
318
319 //! Signal handler for graceful shutdown.
320 void Quassel::handleSignal(int sig)
321 {
322     switch (sig) {
323     case SIGTERM:
324     case SIGINT:
325         qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
326         if (_instance)
327             _instance->quit();
328         else
329             QCoreApplication::quit();
330         break;
331 #ifndef Q_OS_WIN
332 // Windows does not support SIGHUP
333     case SIGHUP:
334         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
335         // graceful reloading of processes.
336         if (_instance) {
337             // If the instance exists, reload the configuration
338             quInfo() << "Caught signal" << SIGHUP <<"- reloading configuration";
339             if (_instance->reloadConfig()) {
340                 quInfo() << "Successfully reloaded configuration";
341             }
342         }
343         break;
344 #endif
345     case SIGABRT:
346     case SIGSEGV:
347 #ifndef Q_OS_WIN
348     case SIGBUS:
349 #endif
350         logBacktrace(coreDumpFileName());
351         exit(EXIT_FAILURE);
352         break;
353     default:
354         break;
355     }
356 }
357
358
359 void Quassel::logFatalMessage(const char *msg)
360 {
361 #ifdef Q_OS_MAC
362     Q_UNUSED(msg)
363 #else
364     QFile dumpFile(coreDumpFileName());
365     dumpFile.open(QIODevice::Append);
366     QTextStream dumpStream(&dumpFile);
367
368     dumpStream << "Fatal: " << msg << '\n';
369     dumpStream.flush();
370     dumpFile.close();
371 #endif
372 }
373
374
375 Quassel::Features Quassel::features()
376 {
377     Features feats = 0;
378     for (int i = 1; i <= NumFeatures; i <<= 1)
379         feats |= (Feature)i;
380
381     return feats;
382 }
383
384
385 const QString &Quassel::coreDumpFileName()
386 {
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;
395         dumpStream.flush();
396         dumpFile.close();
397     }
398     return _coreDumpFileName;
399 }
400
401
402 QString Quassel::configDirPath()
403 {
404     if (!_configDirPath.isEmpty())
405         return _configDirPath;
406
407     if (Quassel::isOptionSet("datadir")) {
408         qWarning() << "Obsolete option --datadir used!";
409         _configDirPath = Quassel::optionValue("datadir");
410     }
411     else if (Quassel::isOptionSet("configdir")) {
412         _configDirPath = Quassel::optionValue("configdir");
413     }
414     else {
415 #ifdef Q_OS_MAC
416         // On Mac, the path is always the same
417         _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
418 #else
419         // We abuse QSettings to find us a sensible path on the other platforms
420 #  ifdef Q_OS_WIN
421         // don't use the registry
422         QSettings::Format format = QSettings::IniFormat;
423 #  else
424         QSettings::Format format = QSettings::NativeFormat;
425 #  endif
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 */
430     }
431
432     if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
433         _configDirPath += QDir::separator();
434
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());
439             return QString();
440         }
441     }
442
443     return _configDirPath;
444 }
445
446
447 QStringList Quassel::dataDirPaths()
448 {
449     return _dataDirPaths;
450 }
451
452
453 QStringList Quassel::findDataDirPaths() const
454 {
455     // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
456     // want to stay consistent.
457
458     QStringList dataDirNames;
459 #ifdef Q_OS_WIN
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();
466 #else
467     // Linux et al
468
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;
475
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";
480     else
481         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
482
483     // Just in case, also check our install prefix
484     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
485
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/";
489
490 #endif
491
492     // Add resource path and workdir just in case.
493     // Workdir should have precedence
494     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
495     dataDirNames.append(":/data/");
496
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);
504         else
505             ++iter;
506     }
507
508     dataDirNames.removeDuplicates();
509
510     return dataDirNames;
511 }
512
513
514 QString Quassel::findDataFilePath(const QString &fileName)
515 {
516     QStringList dataDirs = dataDirPaths();
517     foreach(QString dataDir, dataDirs) {
518         QString path = dataDir + fileName;
519         if (QFile::exists(path))
520             return path;
521     }
522     return QString();
523 }
524
525
526 QStringList Quassel::scriptDirPaths()
527 {
528     QStringList res(configDirPath() + "scripts/");
529     foreach(QString path, dataDirPaths())
530     res << path + "scripts/";
531     return res;
532 }
533
534
535 QString Quassel::translationDirPath()
536 {
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/";
543                 break;
544             }
545         }
546         if (_translationDirPath.isEmpty())
547             _translationDirPath = ":/i18n/";
548     }
549     return _translationDirPath;
550 }
551
552
553 void Quassel::loadTranslation(const QLocale &locale)
554 {
555     QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
556     QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
557
558     if (qtTranslator)
559         qApp->removeTranslator(qtTranslator);
560     if (quasselTranslator)
561         qApp->removeTranslator(quasselTranslator);
562
563     // We use QLocale::C to indicate that we don't want a translation
564     if (locale.language() == QLocale::C)
565         return;
566
567     qtTranslator = new QTranslator(qApp);
568     qtTranslator->setObjectName("QtTr");
569     qApp->installTranslator(qtTranslator);
570
571     quasselTranslator = new QTranslator(qApp);
572     quasselTranslator->setObjectName("QuasselTr");
573     qApp->installTranslator(quasselTranslator);
574
575 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
576     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
577     if (!success)
578         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
579     quasselTranslator->load(locale, QString(""), translationDirPath());
580 #else
581     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
582     if (!success)
583         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
584     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
585 #endif
586 }