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