first version of core info dialog
[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   bool success = false;
344
345   // let's see if ipv6 is available
346   success = server.listen(QHostAddress::AnyIPv6, port);
347
348   if(!success && server.serverError() == QAbstractSocket::UnsupportedSocketOperationError) {
349     // fall back to v4
350     success = server.listen(QHostAddress::Any, port);
351   }
352
353   if(!success) {
354     qWarning("%s", qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())));
355   } else {
356     qDebug() << "Listening for GUI clients on port" << server.serverPort();
357   }
358   
359   return success;
360 }
361
362 void Core::stopListening() {
363   server.close();
364   qDebug() << "No longer listening for GUI clients.";
365 }
366
367 void Core::incomingConnection() {
368   while(server.hasPendingConnections()) {
369     QTcpSocket *socket = server.nextPendingConnection();
370     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
371     connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
372     connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
373     
374     QVariantMap clientInfo;
375     blocksizes.insert(socket, (quint32)0);
376     qDebug() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
377
378     if (!configured) {
379       server.close();
380       qDebug() << "Closing server for basic setup.";
381     }
382   }
383 }
384
385 void Core::clientHasData() {
386   QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
387   Q_ASSERT(socket && blocksizes.contains(socket));
388   QVariant item;
389   while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
390     QVariantMap msg = item.toMap();
391     processClientMessage(socket, msg);
392     if(!blocksizes.contains(socket)) break;  // this socket is no longer ours to handle!
393   }
394 }
395
396 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
397   if(!msg.contains("MsgType")) {
398     // Client is way too old, does not even use the current init format
399     qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
400     socket->close();
401     return;
402   }
403   // OK, so we have at least an init message format we can understand
404   if(msg["MsgType"] == "ClientInit") {
405     QVariantMap reply;
406
407     // Just version information -- check it!
408     uint ver = 0;
409     if(!msg.contains("ProtocolVersion") && msg["ClientBuild"].toUInt() >= 732) ver = 1; // FIXME legacy
410     if(msg.contains("ProtocolVersion")) ver = msg["ProtocolVersion"].toUInt();
411     if(ver < Global::coreNeedsProtocol) {
412       reply["MsgType"] = "ClientInitReject";
413       reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
414       "This core needs at least client/core protocol version %1.<br>"
415       "Please consider upgrading your client.").arg(Global::coreNeedsProtocol);
416       SignalProxy::writeDataToDevice(socket, reply);
417       qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
418       socket->close(); return;
419     }
420
421     reply["CoreVersion"] = Global::quasselVersion;
422     reply["CoreDate"] = Global::quasselBuildDate;
423     reply["CoreBuild"] = 860; // FIXME legacy
424     reply["ProtocolVersion"] = Global::protocolVersion;
425     // TODO: Make the core info configurable
426     int uptime = startTime().secsTo(QDateTime::currentDateTime());
427     int updays = uptime / 86400; uptime %= 86400;
428     int uphours = uptime / 3600; uptime %= 3600;
429     int upmins = uptime / 60;
430     reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
431                            "Built: %2<br>"
432                            "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuildDate)
433       .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
434
435 #ifndef QT_NO_OPENSSL
436     SslServer *sslServer = qobject_cast<SslServer *>(&server);
437     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
438     bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
439 #else
440     bool supportSsl = false;
441 #endif
442
443 #ifndef QT_NO_COMPRESS
444     bool supportsCompression = true;
445 #else
446     bool supportsCompression = false;
447 #endif
448
449     reply["SupportSsl"] = supportSsl;
450     reply["SupportsCompression"] = supportsCompression;
451     // switch to ssl/compression after client has been informed about our capabilities (see below)
452
453     reply["LoginEnabled"] = true;
454
455     // check if we are configured, start wizard otherwise
456     if(!configured) {
457       reply["Configured"] = false;
458       QList<QVariant> backends;
459       foreach(Storage *backend, _storageBackends.values()) {
460         QVariantMap v;
461         v["DisplayName"] = backend->displayName();
462         v["Description"] = backend->description();
463         backends.append(v);
464       }
465       reply["StorageBackends"] = backends;
466       reply["LoginEnabled"] = false;
467     } else {
468       reply["Configured"] = true;
469     }
470     clientInfo[socket] = msg; // store for future reference
471     reply["MsgType"] = "ClientInitAck";
472     SignalProxy::writeDataToDevice(socket, reply);
473
474 #ifndef QT_NO_OPENSSL
475     // after we told the client that we are ssl capable we switch to ssl mode
476     if(supportSsl && msg["UseSsl"].toBool()) {
477       qDebug() << qPrintable(tr("Starting TLS for Client:"))  << qPrintable(socket->peerAddress().toString());
478       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
479       sslSocket->startServerEncryption();
480     }
481 #endif
482
483 #ifndef QT_NO_COMPRESS
484     if(supportsCompression && msg["UseCompression"].toBool()) {
485       socket->setProperty("UseCompression", true);
486       qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
487     }
488 #endif
489     
490   } else {
491     // for the rest, we need an initialized connection
492     if(!clientInfo.contains(socket)) {
493       QVariantMap reply;
494       reply["MsgType"] = "ClientLoginReject";
495       reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
496       SignalProxy::writeDataToDevice(socket, reply);
497       qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
498       socket->close(); return;
499     }
500     if(msg["MsgType"] == "CoreSetupData") {
501       QVariantMap reply;
502       QString result = setupCore(msg["SetupData"]);
503       if(!result.isEmpty()) {
504         reply["MsgType"] = "CoreSetupReject";
505         reply["Error"] = result;
506       } else {
507         reply["MsgType"] = "CoreSetupAck";
508       }
509       SignalProxy::writeDataToDevice(socket, reply);
510     } else if(msg["MsgType"] == "ClientLogin") {
511       QVariantMap reply;
512       mutex.lock();
513       UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
514       mutex.unlock();
515       if(uid == 0) {
516         reply["MsgType"] = "ClientLoginReject";
517         reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
518         SignalProxy::writeDataToDevice(socket, reply);
519         return;
520       }
521       reply["MsgType"] = "ClientLoginAck";
522       SignalProxy::writeDataToDevice(socket, reply);
523       qDebug() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("initialized and authenticated successfully as \"%1\" (UserId: %2).").arg(msg["User"].toString()).arg(uid.toInt()));
524       setupClientSession(socket, uid);
525     }
526   }
527 }
528
529 // Potentially called during the initialization phase (before handing the connection off to the session)
530 void Core::clientDisconnected() {
531   QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
532   if(socket) {
533     // here it's safe to call methods on socket!
534     qDebug() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
535     blocksizes.remove(socket);
536     clientInfo.remove(socket);
537     socket->deleteLater();
538   } else {
539     // we have to crawl through the hashes and see if we find a victim to remove
540     qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
541
542     // DO NOT CALL ANY METHODS ON socket!!
543     socket = static_cast<QTcpSocket *>(sender());
544     
545     QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
546     while(blockSizeIter != blocksizes.end()) {
547       if(blockSizeIter.key() == socket) {
548         blocksizes.erase(blockSizeIter);
549       }
550       blockSizeIter++;
551     }
552
553     QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
554     while(clientInfoIter != clientInfo.end()) {
555       if(clientInfoIter.key() == socket) {
556         clientInfo.erase(clientInfoIter);
557       }
558       clientInfoIter++;
559     }
560   }
561
562
563   // make server listen again if still not configured
564   if (!configured) {
565     startListening();
566   }
567
568   // TODO remove unneeded sessions - if necessary/possible...
569   // Suggestion: kill sessions if they are not connected to any network and client.
570 }
571
572 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
573   // Find or create session for validated user
574   SessionThread *sess;
575   if(sessions.contains(uid)) sess = sessions[uid];
576   else sess = createSession(uid);
577   // Hand over socket, session then sends state itself
578   disconnect(socket, 0, this, 0);
579   blocksizes.remove(socket);
580   clientInfo.remove(socket);
581   if(!sess) {
582     qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
583     socket->close();
584   }
585   sess->addClient(socket);
586 }
587
588 SessionThread *Core::createSession(UserId uid, bool restore) {
589   if(sessions.contains(uid)) {
590     qWarning() << "Calling createSession() when a session for the user already exists!";
591     return 0;
592   }
593   SessionThread *sess = new SessionThread(uid, restore, this);
594   sessions[uid] = sess;
595   sess->start();
596   return sess;
597 }
598
599 #ifndef QT_NO_OPENSSL
600 void Core::sslErrors(const QList<QSslError> &errors) {
601   Q_UNUSED(errors);
602   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
603   if(socket)
604     socket->ignoreSslErrors();
605 }
606 #endif
607
608 void Core::socketError(QAbstractSocket::SocketError err) {
609   QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
610   if(socket && err != QAbstractSocket::RemoteHostClosedError)
611     qDebug() << "Core::socketError()" << socket << err << socket->errorString();
612 }