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