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