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