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