fixing corecrash on exit when non-authed clients were connected
[quassel.git] / src / core / core.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 <QMetaObject>
22 #include <QMetaMethod>
23 #include <QMutexLocker>
24 #include <QCoreApplication>
25
26 #include "core.h"
27 #include "coresession.h"
28 #include "coresettings.h"
29 #include "signalproxy.h"
30 #include "sqlitestorage.h"
31 #include "network.h"
32
33 #include "util.h"
34
35 Core *Core::instanceptr = 0;
36 QMutex Core::mutex;
37
38 Core *Core::instance() {
39   if(instanceptr) return instanceptr;
40   instanceptr = new Core();
41   instanceptr->init();
42   return instanceptr;
43 }
44
45 void Core::destroy() {
46   delete instanceptr;
47   instanceptr = 0;
48 }
49
50 Core::Core() : storage(0) {
51   startTime = QDateTime::currentDateTime();  // for uptime :)
52
53   // Register storage backends here!
54   registerStorageBackend(new SqliteStorage(this));
55
56   if(!_storageBackends.count()) {
57     qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
58     qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
59                                 "Qt library with the sqlite plugin enabled in order for quasselcore\n"
60                                 "to work."));
61     exit(1); // TODO make this less brutal (especially for mono client -> popup)
62   }
63   connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
64   _storageSyncTimer.start(10 * 60 * 1000); // in msecs
65 }
66
67 void Core::init() {
68   configured = false;
69
70   CoreSettings cs;
71
72   if(!(configured = initStorage(cs.storageSettings().toMap()))) {
73     qWarning("Core is currently not configured! Please connect with a Quassel Client for basic setup.");
74
75     // try to migrate old settings
76     QVariantMap old = cs.oldDbSettings().toMap();
77     if(old.count() && old["Type"].toString().toUpper() == "SQLITE") {
78       QVariantMap newSettings;
79       newSettings["Backend"] = "SQLite";
80       if((configured = initStorage(newSettings))) {
81         qWarning("...but thankfully I found some old settings to migrate!");
82         cs.setStorageSettings(newSettings);
83       }
84     }
85   }
86
87   connect(&server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
88   if(!startListening(cs.port())) exit(1); // TODO make this less brutal
89 }
90
91 Core::~Core() {
92   foreach(QTcpSocket *socket, blocksizes.keys()) {
93     socket->disconnectFromHost();  // disconnect non authed clients
94   }
95   qDeleteAll(sessions);
96   qDeleteAll(_storageBackends);
97 }
98
99 /*** Session Restore ***/
100
101 void Core::saveState() {
102   CoreSettings s;
103   QVariantMap state;
104   QVariantList activeSessions;
105   foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
106   state["CoreStateVersion"] = 1;
107   state["ActiveSessions"] = activeSessions;
108   s.setCoreState(state);
109 }
110
111 void Core::restoreState() {
112   if(!instance()->configured) {
113     // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
114     return;
115   }
116   if(instance()->sessions.count()) {
117     qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
118     return;
119   }
120   CoreSettings s;
121   /* We don't check, since we are at the first version since switching to Git
122   uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
123   if(statever < 1) {
124     qWarning() << qPrintable(tr("Core state too old, ignoring..."));
125     return;
126   }
127   */
128   QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
129   if(activeSessions.count() > 0) {
130     qDebug() << "Restoring previous core state...";
131     foreach(QVariant v, activeSessions) {
132       UserId user = v.value<UserId>();
133       instance()->createSession(user, true);
134     }
135   }
136 }
137
138 /*** Core Setup ***/
139
140 QString Core::setupCore(const QVariant &setupData_) {
141   QVariantMap setupData = setupData_.toMap();
142   QString user = setupData.take("AdminUser").toString();
143   QString password = setupData.take("AdminPasswd").toString();
144   if(user.isEmpty() || password.isEmpty()) {
145     return tr("Admin user or password not set.");
146   }
147   if(!initStorage(setupData, true)) {
148     return tr("Could not setup storage!");
149   }
150   CoreSettings s;
151   s.setStorageSettings(setupData);
152   qDebug() << qPrintable(tr("Creating admin user..."));
153   mutex.lock();
154   storage->addUser(user, password);
155   mutex.unlock();
156   startListening();  // TODO check when we need this
157   return QString();
158 }
159
160 /*** Storage Handling ***/
161
162 bool Core::registerStorageBackend(Storage *backend) {
163   if(backend->isAvailable()) {
164     _storageBackends[backend->displayName()] = backend;
165     return true;
166   } else {
167     backend->deleteLater();
168     return false;
169   }
170 }
171
172 void Core::unregisterStorageBackend(Storage *backend) {
173   _storageBackends.remove(backend->displayName());
174   backend->deleteLater();
175 }
176
177 // old db settings:
178 // "Type" => "sqlite"
179 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
180   QString backend = dbSettings["Backend"].toString();
181   if(backend.isEmpty()) {
182     //qWarning() << "No storage backend selected!";
183     return configured = false;
184   }
185
186   if(_storageBackends.contains(backend)) {
187     storage = _storageBackends[backend];
188   } else {
189     qWarning() << "Selected storage backend is not available:" << backend;
190     return configured = false;
191   }
192   if(!storage->init(dbSettings)) {
193     if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
194       qWarning() << "Could not init storage!";
195       storage = 0;
196       return configured = false;
197     }
198   }
199   // delete all other backends
200   foreach(Storage *s, _storageBackends.values()) {
201     if(s != storage) s->deleteLater();
202   }
203   _storageBackends.clear();
204
205   connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
206   return configured = true;
207 }
208
209 void Core::syncStorage() {
210   QMutexLocker locker(&mutex);
211   if(storage) storage->sync();
212 }
213
214 /*** Storage Access ***/
215 void Core::setUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
216   QMutexLocker locker(&mutex);
217   instance()->storage->setUserSetting(userId, settingName, data);
218 }
219
220 QVariant Core::getUserSetting(UserId userId, const QString &settingName, const QVariant &data) {
221   QMutexLocker locker(&mutex);
222   return instance()->storage->getUserSetting(userId, settingName, data);
223 }
224
225 bool Core::createNetwork(UserId user, NetworkInfo &info) {
226   QMutexLocker locker(&mutex);
227   NetworkId networkId = instance()->storage->createNetwork(user, info);
228   if(!networkId.isValid())
229     return false;
230
231   info.networkId = networkId;
232   return true;
233 }
234
235 bool Core::updateNetwork(UserId user, const NetworkInfo &info) {
236   QMutexLocker locker(&mutex);
237   return instance()->storage->updateNetwork(user, info);
238 }
239
240 bool Core::removeNetwork(UserId user, const NetworkId &networkId) {
241   QMutexLocker locker(&mutex);
242   return instance()->storage->removeNetwork(user, networkId);
243 }
244
245 QList<NetworkInfo> Core::networks(UserId user) {
246   QMutexLocker locker(&mutex);
247   return instance()->storage->networks(user);
248 }
249
250 NetworkId Core::networkId(UserId user, const QString &network) {
251   QMutexLocker locker(&mutex);
252   return instance()->storage->getNetworkId(user, network);
253 }
254
255 QList<NetworkId> Core::connectedNetworks(UserId user) {
256   QMutexLocker locker(&mutex);
257   return instance()->storage->connectedNetworks(user);
258 }
259
260 void Core::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) {
261   QMutexLocker locker(&mutex);
262   return instance()->storage->setNetworkConnected(user, networkId, isConnected);
263 }
264
265 QHash<QString, QString> Core::persistentChannels(UserId user, const NetworkId &networkId) {
266   QMutexLocker locker(&mutex);
267   return instance()->storage->persistentChannels(user, networkId);
268 }
269
270 void Core::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) {
271   QMutexLocker locker(&mutex);
272   return instance()->storage->setChannelPersistent(user, networkId, channel, isJoined);
273 }
274
275 void Core::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) {
276   QMutexLocker locker(&mutex);
277   return instance()->storage->setPersistentChannelKey(user, networkId, channel, key);
278 }
279
280 BufferInfo Core::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer) {
281   QMutexLocker locker(&mutex);
282   return instance()->storage->getBufferInfo(user, networkId, type, buffer);
283 }
284
285 BufferInfo Core::getBufferInfo(UserId user, const BufferId &bufferId) {
286   QMutexLocker locker(&mutex);
287   return instance()->storage->getBufferInfo(user, bufferId);
288 }
289
290 MsgId Core::storeMessage(const Message &message) {
291   QMutexLocker locker(&mutex);
292   return instance()->storage->logMessage(message);
293 }
294
295 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, int lastmsgs, int offset) {
296   QMutexLocker locker(&mutex);
297   return instance()->storage->requestMsgs(user, buffer, lastmsgs, offset);
298 }
299
300 QList<Message> Core::requestMsgs(UserId user, BufferId buffer, QDateTime since, int offset) {
301   QMutexLocker locker(&mutex);
302   return instance()->storage->requestMsgs(user, buffer, since, offset);
303 }
304
305 QList<Message> Core::requestMsgRange(UserId user, BufferId buffer, int first, int last) {
306   QMutexLocker locker(&mutex);
307   return instance()->storage->requestMsgRange(user, buffer, first, last);
308 }
309
310 QList<BufferInfo> Core::requestBuffers(UserId user) {
311   QMutexLocker locker(&mutex);
312   return instance()->storage->requestBuffers(user);
313 }
314
315 QList<BufferId> Core::requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
316   QMutexLocker locker(&mutex);
317   return instance()->storage->requestBufferIdsForNetwork(user, networkId);
318 }
319
320 bool Core::removeBuffer(const UserId &user, const BufferId &bufferId) {
321   QMutexLocker locker(&mutex);
322   return instance()->storage->removeBuffer(user, bufferId);
323 }
324
325 BufferId Core::renameBuffer(const UserId &user, const NetworkId &networkId, const QString &newName, const QString &oldName) {
326   QMutexLocker locker(&mutex);
327   return instance()->storage->renameBuffer(user, networkId, newName, oldName);
328 }
329
330 void Core::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) {
331   QMutexLocker locker(&mutex);
332   return instance()->storage->setBufferLastSeenMsg(user, bufferId, msgId);
333 }
334
335 QHash<BufferId, MsgId> Core::bufferLastSeenMsgIds(UserId user) {
336   QMutexLocker locker(&mutex);
337   return instance()->storage->bufferLastSeenMsgIds(user);
338 }
339
340 /*** Network Management ***/
341
342 bool Core::startListening(uint port) {
343   if(!server.listen(QHostAddress::Any, port)) {
344     qWarning("%s", qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())));
345     return false;
346   }
347   qDebug() << "Listening for GUI clients on port" << server.serverPort();
348   return true;
349 }
350
351 void Core::stopListening() {
352   server.close();
353   qDebug() << "No longer listening for GUI clients.";
354 }
355
356 void Core::incomingConnection() {
357   while(server.hasPendingConnections()) {
358     QTcpSocket *socket = server.nextPendingConnection();
359     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
360     connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
361     connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
362     
363     QVariantMap clientInfo;
364     blocksizes.insert(socket, (quint32)0);
365     qDebug() << "Client connected from"  << qPrintable(socket->peerAddress().toString());
366
367     if (!configured) {
368       server.close();
369       qDebug() << "Closing server for basic setup.";
370     }
371   }
372 }
373
374 void Core::clientHasData() {
375   QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
376   Q_ASSERT(socket && blocksizes.contains(socket));
377   QVariant item;
378   while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
379     QVariantMap msg = item.toMap();
380     processClientMessage(socket, msg);
381     if(!blocksizes.contains(socket)) break;  // this socket is no longer ours to handle!
382   }
383 }
384
385 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
386   if(!msg.contains("MsgType")) {
387     // Client is way too old, does not even use the current init format
388     qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
389     socket->close();
390     return;
391   }
392   // OK, so we have at least an init message format we can understand
393   if(msg["MsgType"] == "ClientInit") {
394     QVariantMap reply;
395
396     // Just version information -- check it!
397     if((msg.contains("ClientBuild") && msg["ClientBuild"].toUInt() < 732)
398        || (!msg.contains("ClientBuild") && msg["ProtocolVersion"].toUInt() < Global::coreNeedsProtocol)) {
399       reply["MsgType"] = "ClientInitReject";
400       reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
401       "This core needs at least client/core protocol version %1.<br>"
402       "Please consider upgrading your client.").arg(Global::coreNeedsProtocol);
403       SignalProxy::writeDataToDevice(socket, reply);
404       qWarning() << qPrintable(tr("Client %1 too old, rejecting.").arg(socket->peerAddress().toString()));
405       socket->close(); return;
406     }
407
408     reply["CoreVersion"] = Global::quasselVersion;
409     reply["CoreDate"] = Global::quasselBuildDate;
410     reply["CoreBuild"] = 860; // FIXME legacy
411     reply["ProtocolVersion"] = Global::protocolVersion;
412     // TODO: Make the core info configurable
413     int uptime = startTime.secsTo(QDateTime::currentDateTime());
414     int updays = uptime / 86400; uptime %= 86400;
415     int uphours = uptime / 3600; uptime %= 3600;
416     int upmins = uptime / 60;
417     reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
418                             "Built: %2<br>"
419                             "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuildDate)
420                             .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime.toString(Qt::TextDate));
421
422 #ifndef QT_NO_OPENSSL
423     SslServer *sslServer = qobject_cast<SslServer *>(&server);
424     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
425     bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
426 #else
427     bool supportSsl = false;
428 #endif
429
430 #ifndef QT_NO_COMPRESS
431     bool supportsCompression = true;
432 #else
433     bool supportsCompression = false;
434 #endif
435
436     reply["SupportSsl"] = supportSsl;
437     reply["SupportsCompression"] = supportsCompression;
438     // switch to ssl/compression after client has been informed about our capabilities (see below)
439
440     reply["LoginEnabled"] = true;
441
442     // check if we are configured, start wizard otherwise
443     if(!configured) {
444       reply["Configured"] = false;
445       QList<QVariant> backends;
446       foreach(Storage *backend, _storageBackends.values()) {
447         QVariantMap v;
448         v["DisplayName"] = backend->displayName();
449         v["Description"] = backend->description();
450         backends.append(v);
451       }
452       reply["StorageBackends"] = backends;
453       reply["LoginEnabled"] = false;
454     } else {
455       reply["Configured"] = true;
456     }
457     clientInfo[socket] = msg; // store for future reference
458     reply["MsgType"] = "ClientInitAck";
459     SignalProxy::writeDataToDevice(socket, reply);
460
461 #ifndef QT_NO_OPENSSL
462     // after we told the client that we are ssl capable we switch to ssl mode
463     if(supportSsl && msg["UseSsl"].toBool()) {
464       qDebug() << "Starting TLS for Client:" << qPrintable(socket->peerAddress().toString());
465       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
466       sslSocket->startServerEncryption();
467     }
468 #endif
469
470 #ifndef QT_NO_COMPRESS
471     if(supportsCompression && msg["UseCompression"].toBool()) {
472       socket->setProperty("UseCompression", true);
473       qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
474     }
475 #endif
476     
477   } else {
478     // for the rest, we need an initialized connection
479     if(!clientInfo.contains(socket)) {
480       QVariantMap reply;
481       reply["MsgType"] = "ClientLoginReject";
482       reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
483       SignalProxy::writeDataToDevice(socket, reply);
484       qWarning() << qPrintable(tr("Client %1 did not send an init message before trying to login, rejecting.").arg(socket->peerAddress().toString()));
485       socket->close(); return;
486     }
487     if(msg["MsgType"] == "CoreSetupData") {
488       QVariantMap reply;
489       QString result = setupCore(msg["SetupData"]);
490       if(!result.isEmpty()) {
491         reply["MsgType"] = "CoreSetupReject";
492         reply["Error"] = result;
493       } else {
494         reply["MsgType"] = "CoreSetupAck";
495       }
496       SignalProxy::writeDataToDevice(socket, reply);
497     } else if(msg["MsgType"] == "ClientLogin") {
498       QVariantMap reply;
499       mutex.lock();
500       UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
501       mutex.unlock();
502       if(uid == 0) {
503         reply["MsgType"] = "ClientLoginReject";
504         reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
505         SignalProxy::writeDataToDevice(socket, reply);
506         return;
507       }
508       reply["MsgType"] = "ClientLoginAck";
509       SignalProxy::writeDataToDevice(socket, reply);
510       qDebug() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).").arg(socket->peerAddress().toString(), msg["User"].toString()).arg(uid.toInt()));
511       setupClientSession(socket, uid);
512     }
513   }
514 }
515
516 // Potentially called during the initialization phase (before handing the connection off to the session)
517 void Core::clientDisconnected() {
518   QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
519   if(socket) {
520     // here it's safe to call methods on socket!
521     qDebug() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
522     socket->deleteLater();
523   } else {
524     // we have to crawl through the hashes and see if we find a victim to remove
525
526     // DO NOT CALL ANY METHODS ON socket!!
527     socket = static_cast<QTcpSocket *>(sender());
528     
529     QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
530     while(blockSizeIter != blocksizes.end()) {
531       if(blockSizeIter.key() == socket) {
532         blocksizes.erase(blockSizeIter);
533       }
534       blockSizeIter++;
535     }
536
537     QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
538     while(clientInfoIter != clientInfo.end()) {
539       if(clientInfoIter.key() == socket) {
540         clientInfo.erase(clientInfoIter);
541       }
542       clientInfoIter++;
543     }
544   }
545
546
547   // make server listen again if still not configured
548   if (!configured) {
549     startListening();
550   }
551
552   // TODO remove unneeded sessions - if necessary/possible...
553   // Suggestion: kill sessions if they are not connected to any network and client.
554 }
555
556 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
557   // Find or create session for validated user
558   SessionThread *sess;
559   if(sessions.contains(uid)) sess = sessions[uid];
560   else sess = createSession(uid);
561   // Hand over socket, session then sends state itself
562   disconnect(socket, 0, this, 0);
563   blocksizes.remove(socket);
564   clientInfo.remove(socket);
565   if(!sess) {
566     qWarning() << qPrintable(tr("Could not initialize session for client %1!").arg(socket->peerAddress().toString()));
567     socket->close();
568   }
569   sess->addClient(socket);
570 }
571
572 SessionThread *Core::createSession(UserId uid, bool restore) {
573   if(sessions.contains(uid)) {
574     qWarning() << "Calling createSession() when a session for the user already exists!";
575     return 0;
576   }
577   SessionThread *sess = new SessionThread(uid, restore, this);
578   sessions[uid] = sess;
579   sess->start();
580   return sess;
581 }
582
583 #ifndef QT_NO_OPENSSL
584 void Core::sslErrors(const QList<QSslError> &errors) {
585   Q_UNUSED(errors);
586   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
587   if(socket)
588     socket->ignoreSslErrors();
589 }
590 #endif
591
592 void Core::socketError(QAbstractSocket::SocketError err) {
593   QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
594   if(socket && err != QAbstractSocket::RemoteHostClosedError)
595     qDebug() << "Core::socketError()" << socket << err << socket->errorString();
596 }