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