32b34f53c08e48698b01865b574d10fc6d342457
[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 Core *Core::instanceptr = 0;
34 QMutex Core::mutex;
35
36 Core *Core::instance() {
37   if(instanceptr) return instanceptr;
38   instanceptr = new Core();
39   instanceptr->init();
40   return instanceptr;
41 }
42
43 void Core::destroy() {
44   delete instanceptr;
45   instanceptr = 0;
46 }
47
48 Core::Core() : storage(0) {
49   startTime = QDateTime::currentDateTime();  // for uptime :)
50
51   // Register storage backends here!
52   registerStorageBackend(new SqliteStorage(this));
53
54   if(!_storageBackends.count()) {
55     qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
56     exit(1); // TODO make this less brutal (especially for mono client -> popup)
57   }
58   connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
59   _storageSyncTimer.start(10 * 60 * 1000); // in msecs
60 }
61
62 void Core::init() {
63   configured = false;
64
65   CoreSettings cs;
66
67   // TODO migrate old db settings
68
69   if(!(configured = initStorage(cs.storageSettings().toMap()))) {
70     qWarning("Core is currently not configured!");
71
72     // try to migrate old settings
73     QVariantMap old = cs.oldDbSettings().toMap();
74     if(old.count() && old["Type"].toString() == "SQlite") {
75       QVariantMap newSettings;
76       newSettings["Backend"] = "SQLite";
77       if((configured = initStorage(newSettings))) {
78         qWarning("...but thankfully I found some old settings to migrate!");
79         cs.setStorageSettings(newSettings);
80       }
81     }
82   }
83
84   connect(&server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
85   if(!startListening(cs.port())) exit(1); // TODO make this less brutal
86 }
87
88 Core::~Core() {
89   foreach(QTcpSocket *socket, blocksizes.keys()) {
90     socket->disconnectFromHost();  // disconnect local (i.e. non-authed) clients
91   }
92   qDeleteAll(sessions);
93   qDeleteAll(_storageBackends);
94 }
95
96 /*** Session Restore ***/
97
98 void Core::saveState() {
99   CoreSettings s;
100   QVariantMap state;
101   QVariantList activeSessions;
102   foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
103   state["CoreBuild"] = Global::quasselBuild;
104   state["ActiveSessions"] = activeSessions;
105   s.setCoreState(state);
106 }
107
108 void Core::restoreState() {
109   if(instance()->sessions.count()) {
110     qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
111     return;
112   }
113   CoreSettings s;
114   uint build = s.coreState().toMap()["CoreBuild"].toUInt();
115   if(build < 362) {
116     qWarning() << qPrintable(tr("Core state too old, ignoring..."));
117     return;
118   }
119   QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
120   if(activeSessions.count() > 0) {
121     qDebug() << "Restoring previous core state...";
122     foreach(QVariant v, activeSessions) {
123       UserId user = v.value<UserId>();
124       instance()->createSession(user, true);
125     }
126   }
127 }
128
129 /*** Core Setup ***/
130
131 QString Core::setupCore(const QVariant &setupData_) {
132   QVariantMap setupData = setupData_.toMap();
133   QString user = setupData.take("AdminUser").toString();
134   QString password = setupData.take("AdminPasswd").toString();
135   if(user.isEmpty() || password.isEmpty()) {
136     return tr("Admin user or password not set.");
137   }
138   if(!initStorage(setupData, true)) {
139     return tr("Could not setup storage!");
140   }
141   CoreSettings s;
142   //s.setStorageSettings(msg);
143   qDebug() << qPrintable(tr("Creating admin user..."));
144   mutex.lock();
145   storage->addUser(user, password);
146   mutex.unlock();
147   startListening();  // TODO check when we need this
148   return QString();
149 }
150
151 /*** Storage Handling ***/
152
153 bool Core::registerStorageBackend(Storage *backend) {
154   if(backend->isAvailable()) {
155     _storageBackends[backend->displayName()] = backend;
156     return true;
157   } else {
158     backend->deleteLater();
159     return false;
160   }
161 }
162
163 void Core::unregisterStorageBackend(Storage *backend) {
164   _storageBackends.remove(backend->displayName());
165   backend->deleteLater();
166 }
167
168 // old db settings:
169 // "Type" => "sqlite"
170 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
171   QString backend = dbSettings["Backend"].toString();
172   if(backend.isEmpty()) {
173     //qWarning() << "No storage backend selected!";
174     return configured = false;
175   }
176
177   if(_storageBackends.contains(backend)) {
178     storage = _storageBackends[backend];
179   } else {
180     qWarning() << "Selected storage backend is not available:" << backend;
181     return configured = false;
182   }
183   if(!storage->init(dbSettings)) {
184     if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
185       qWarning() << "Could not init storage!";
186       storage = 0;
187       return configured = false;
188     }
189   }
190   // delete all other backends
191   foreach(Storage *s, _storageBackends.values()) {
192     if(s != storage) s->deleteLater();
193   }
194   _storageBackends.clear();
195
196   connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
197   return configured = true;
198 }
199
200 void Core::syncStorage() {
201   QMutexLocker locker(&mutex);
202   if(storage) storage->sync();
203 }
204
205 /*** Storage Access ***/
206 bool Core::createNetworkId(UserId user, NetworkInfo &info) {
207   QMutexLocker locker(&mutex);
208   NetworkId networkId = instance()->storage->createNetworkId(user, info);
209   if(!networkId.isValid())
210     return false;
211
212   info.networkId = networkId;
213   return true;
214 }
215
216 NetworkId Core::networkId(UserId user, const QString &network) {
217   QMutexLocker locker(&mutex);
218   return instance()->storage->getNetworkId(user, network);
219 }
220
221 BufferInfo Core::bufferInfo(UserId user, const NetworkId &networkId, const QString &buffer) {
222   QMutexLocker locker(&mutex);
223   return instance()->storage->getBufferInfo(user, networkId, buffer);
224 }
225
226 MsgId Core::storeMessage(const Message &message) {
227   QMutexLocker locker(&mutex);
228   return instance()->storage->logMessage(message);
229 }
230
231 QList<Message> Core::requestMsgs(BufferInfo buffer, int lastmsgs, int offset) {
232   QMutexLocker locker(&mutex);
233   return instance()->storage->requestMsgs(buffer, lastmsgs, offset);
234 }
235
236 QList<Message> Core::requestMsgs(BufferInfo buffer, QDateTime since, int offset) {
237   QMutexLocker locker(&mutex);
238   return instance()->storage->requestMsgs(buffer, since, offset);
239 }
240
241 QList<Message> Core::requestMsgRange(BufferInfo buffer, int first, int last) {
242   QMutexLocker locker(&mutex);
243   return instance()->storage->requestMsgRange(buffer, first, last);
244 }
245
246 QList<BufferInfo> Core::requestBuffers(UserId user, QDateTime since) {
247   QMutexLocker locker(&mutex);
248   return instance()->storage->requestBuffers(user, since);
249 }
250
251 /*** Network Management ***/
252
253 bool Core::startListening(uint port) {
254   if(!server.listen(QHostAddress::Any, port)) {
255     qWarning(qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())));
256     return false;
257   }
258   qDebug() << "Listening for GUI clients on port" << server.serverPort();
259   return true;
260 }
261
262 void Core::stopListening() {
263   server.close();
264   qDebug() << "No longer listening for GUI clients.";
265 }
266
267 void Core::incomingConnection() {
268   // TODO implement SSL
269   while(server.hasPendingConnections()) {
270     QTcpSocket *socket = server.nextPendingConnection();
271     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
272     connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
273     QVariantMap clientInfo;
274     blocksizes.insert(socket, (quint32)0);
275     qDebug() << "Client connected from"  << qPrintable(socket->peerAddress().toString());
276
277     if (!configured) {
278       server.close();
279       qDebug() << "Closing server for basic setup.";
280     }
281   }
282 }
283
284 void Core::clientHasData() {
285   QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
286   Q_ASSERT(socket && blocksizes.contains(socket));
287   QVariant item;
288   while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
289     QVariantMap msg = item.toMap();
290     processClientMessage(socket, msg);
291   }
292 }
293
294 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
295   if(!msg.contains("MsgType")) {
296     // Client is way too old, does not even use the current init format
297     qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
298     socket->close();
299     return;
300   }
301   // OK, so we have at least an init message format we can understand
302   if(msg["MsgType"] == "ClientInit") {
303     QVariantMap reply;
304     reply["CoreVersion"] = Global::quasselVersion;
305     reply["CoreDate"] = Global::quasselDate;
306     reply["CoreBuild"] = Global::quasselBuild;
307     // TODO: Make the core info configurable
308     int uptime = startTime.secsTo(QDateTime::currentDateTime());
309     int updays = uptime / 86400; uptime %= 86400;
310     int uphours = uptime / 3600; uptime %= 3600;
311     int upmins = uptime / 60;
312     reply["CoreInfo"] = tr("<b>Quassel Core Version %1 (Build >= %2)</b><br>"
313                             "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuild)
314                             .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime.toString(Qt::TextDate));
315
316     reply["SupportSsl"] = false;
317     reply["LoginEnabled"] = true;
318
319     // Just version information -- check it!
320     if(msg["ClientBuild"].toUInt() < Global::clientBuildNeeded) {
321       reply["MsgType"] = "ClientInitReject";
322       reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
323                           "This core needs at least client version %1 (Build >= %2).<br>"
324                           "Please consider upgrading your client.").arg(Global::quasselVersion).arg(Global::quasselBuild);
325       SignalProxy::writeDataToDevice(socket, reply);
326       qWarning() << qPrintable(tr("Client %1 too old, rejecting.").arg(socket->peerAddress().toString()));
327       socket->close(); return;
328     }
329     // check if we are configured, start wizard otherwise
330     if(!configured) {
331       reply["Configured"] = false;
332       QList<QVariant> backends;
333       foreach(Storage *backend, _storageBackends.values()) {
334         QVariantMap v;
335         v["DisplayName"] = backend->displayName();
336         v["Description"] = backend->description();
337         backends.append(v);
338       }
339       reply["StorageBackends"] = backends;
340       reply["LoginEnabled"] = false;
341     } else {
342       reply["Configured"] = true;
343     }
344     clientInfo[socket] = msg; // store for future reference
345     reply["MsgType"] = "ClientInitAck";
346     SignalProxy::writeDataToDevice(socket, reply);
347   } else {
348     // for the rest, we need an initialized connection
349     if(!clientInfo.contains(socket)) {
350       QVariantMap reply;
351       reply["MsgType"] = "ClientLoginReject";
352       reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
353       SignalProxy::writeDataToDevice(socket, reply);
354       qWarning() << qPrintable(tr("Client %1 did not send an init message before trying to login, rejecting.").arg(socket->peerAddress().toString()));
355       socket->close(); return;
356     }
357     if(msg["MsgType"] == "CoreSetupData") {
358       QVariantMap reply;
359       QString result = setupCore(msg["SetupData"]);
360       if(!result.isEmpty()) {
361         reply["MsgType"] = "CoreSetupReject";
362         reply["Error"] = result;
363       } else {
364         reply["MsgType"] = "CoreSetupAck";
365       }
366       SignalProxy::writeDataToDevice(socket, reply);
367     } else if(msg["MsgType"] == "ClientLogin") {
368       QVariantMap reply;
369       mutex.lock();
370       UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
371       mutex.unlock();
372       if(uid == 0) {
373         reply["MsgType"] = "ClientLoginReject";
374         reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
375         SignalProxy::writeDataToDevice(socket, reply);
376         return;
377       }
378       reply["MsgType"] = "ClientLoginAck";
379       SignalProxy::writeDataToDevice(socket, reply);
380       qDebug() << qPrintable(tr("Client %1 initialized and authentificated successfully as \"%2\".").arg(socket->peerAddress().toString(), msg["User"].toString()));
381       setupClientSession(socket, uid);
382     }
383   }
384 }
385
386 // Potentially called during the initialization phase (before handing the connection off to the session)
387 void Core::clientDisconnected() {
388   QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());  // Note: This might be a QObject* already (if called by ~Core())!
389   Q_ASSERT(socket);
390   blocksizes.remove(socket);
391   clientInfo.remove(socket);
392   qDebug() << qPrintable(tr("Non-authed client disconnected."));
393   socket->deleteLater();
394   socket = 0;
395
396   // make server listen again if still not configured
397   if (!configured) {
398     startListening();
399   }
400
401   // TODO remove unneeded sessions - if necessary/possible...
402   // Suggestion: kill sessions if they are not connected to any network and client.
403 }
404
405 /*
406 void Core::processCoreSetup(QTcpSocket *socket, QVariantMap &msg) {
407   if(msg["HasSettings"].toBool()) {
408     QVariantMap auth;
409     auth["User"] = msg["User"];
410     auth["Password"] = msg["Password"];
411     msg.remove("User");
412     msg.remove("Password");
413     qDebug() << "Initializing storage provider" << msg["Type"].toString();
414
415     if(!initStorage(msg, true)) {
416       // notify client to start wizard again
417       qWarning("Core is currently not configured!");
418       QVariantMap reply;
419       reply["StartWizard"] = true;
420       reply["StorageProviders"] = availableStorageProviders();
421       SignalProxy::writeDataToDevice(socket, reply);
422     } else {
423       // write coresettings
424       CoreSettings s;
425       s.setDatabaseSettings(msg);
426       // write admin user to database & make the core listen again to connections
427       storage->addUser(auth["User"].toString(), auth["Password"].toString());
428       startListening();
429       // continue the normal procedure
430       //processClientInit(socket, auth);
431     }
432   } else {
433     // notify client to start wizard
434     QVariantMap reply;
435     reply["StartWizard"] = true;
436     reply["StorageProviders"] = availableStorageProviders();
437     SignalProxy::writeDataToDevice(socket, reply);
438   }
439 }
440 */
441
442 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
443   // Find or create session for validated user
444   SessionThread *sess;
445   if(sessions.contains(uid)) sess = sessions[uid];
446   else sess = createSession(uid);
447   // Hand over socket, session then sends state itself
448   disconnect(socket, 0, this, 0);
449   blocksizes.remove(socket);
450   clientInfo.remove(socket);
451   if(!sess) {
452     qWarning() << qPrintable(tr("Could not initialize session for client %1!").arg(socket->peerAddress().toString()));
453     socket->close();
454   }
455   sess->addClient(socket);
456 }
457
458 SessionThread *Core::createSession(UserId uid, bool restore) {
459   if(sessions.contains(uid)) {
460     qWarning() << "Calling createSession() when a session for the user already exists!";
461     return 0;
462   }
463   SessionThread *sess = new SessionThread(uid, restore, this);
464   sessions[uid] = sess;
465   sess->start();
466   return sess;
467 }