1 /***************************************************************************
2 * Copyright (C) 2005-08 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QMetaObject>
22 #include <QMetaMethod>
23 #include <QMutexLocker>
24 #include <QCoreApplication>
27 #include "coresession.h"
28 #include "coresettings.h"
29 #include "signalproxy.h"
30 #include "sqlitestorage.h"
33 Core *Core::instanceptr = 0;
36 Core *Core::instance() {
37 if(instanceptr) return instanceptr;
38 instanceptr = new Core();
43 void Core::destroy() {
51 startTime = QDateTime::currentDateTime(); // for uptime :)
53 connect(&_storageSyncTimer, SIGNAL(timeout()),
54 this, SLOT(syncStorage()));
55 _storageSyncTimer.start(10 * 60 * 1000); // in msecs
62 if(!(configured = initStorage(cs.databaseSettings().toMap()))) {
63 qWarning("Core is currently not configured!");
66 connect(&server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
67 startListening(cs.port());
72 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
73 QString engine = dbSettings["Type"].toString().toLower();
76 qDebug() << "Deleting old storage object.";
77 storage->deleteLater();
81 // FIXME register new storageProviders here
82 if(engine == "sqlite" && SqliteStorage::isAvailable()) {
83 storage = new SqliteStorage(this);
84 connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
86 qWarning() << "Selected StorageBackend is not available:" << dbSettings["Type"].toString();
87 return configured = false;
90 if(setup && !storage->setup(dbSettings)) {
91 return configured = false;
94 return configured = storage->init(dbSettings);
98 // FIXME properly shutdown the sessions
102 void Core::syncStorage() {
103 QMutexLocker locker(&mutex);
104 return instance()->storage->sync();
107 void Core::restoreState() {
108 if(instance()->sessions.count()) {
109 qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
113 uint build = s.coreState().toMap()["CoreBuild"].toUInt();
115 qWarning() << qPrintable(tr("Core state too old, ignoring..."));
118 QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
119 if(activeSessions.count() > 0) {
120 qDebug() << "Restoring previous core state...";
121 foreach(QVariant v, activeSessions) {
122 UserId user = v.value<UserId>();
123 instance()->createSession(user, true);
125 qDebug() << "...done.";
129 void Core::saveState() {
132 QVariantList activeSessions;
133 foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
134 state["CoreBuild"] = Global::quasselBuild;
135 state["ActiveSessions"] = activeSessions;
136 s.setCoreState(state);
139 /*** Storage Access ***/
140 bool Core::createNetworkId(UserId user, NetworkInfo &info) {
141 QMutexLocker locker(&mutex);
142 NetworkId networkId = instance()->storage->createNetworkId(user, info);
143 if(!networkId.isValid())
146 info.networkId = networkId;
150 NetworkId Core::networkId(UserId user, const QString &network) {
151 QMutexLocker locker(&mutex);
152 return instance()->storage->getNetworkId(user, network);
155 BufferInfo Core::bufferInfo(UserId user, const NetworkId &networkId, const QString &buffer) {
156 QMutexLocker locker(&mutex);
157 return instance()->storage->getBufferInfo(user, networkId, buffer);
160 MsgId Core::storeMessage(const Message &message) {
161 QMutexLocker locker(&mutex);
162 return instance()->storage->logMessage(message);
165 QList<Message> Core::requestMsgs(BufferInfo buffer, int lastmsgs, int offset) {
166 QMutexLocker locker(&mutex);
167 return instance()->storage->requestMsgs(buffer, lastmsgs, offset);
170 QList<Message> Core::requestMsgs(BufferInfo buffer, QDateTime since, int offset) {
171 QMutexLocker locker(&mutex);
172 return instance()->storage->requestMsgs(buffer, since, offset);
175 QList<Message> Core::requestMsgRange(BufferInfo buffer, int first, int last) {
176 QMutexLocker locker(&mutex);
177 return instance()->storage->requestMsgRange(buffer, first, last);
180 QList<BufferInfo> Core::requestBuffers(UserId user, QDateTime since) {
181 QMutexLocker locker(&mutex);
182 return instance()->storage->requestBuffers(user, since);
185 /*** Network Management ***/
187 bool Core::startListening(uint port) {
188 if(!server.listen(QHostAddress::Any, port)) {
189 qWarning(QString(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())).toAscii());
192 qDebug() << "Listening for GUI clients on port" << server.serverPort();
196 void Core::stopListening() {
198 qDebug() << "No longer listening for GUI clients.";
201 void Core::incomingConnection() {
202 // TODO implement SSL
203 while (server.hasPendingConnections()) {
204 QTcpSocket *socket = server.nextPendingConnection();
205 connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
206 connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
207 QVariantMap clientInfo;
208 blocksizes.insert(socket, (quint32)0);
209 qDebug() << "Client connected from" << qPrintable(socket->peerAddress().toString());
213 qDebug() << "Closing server for basic setup.";
218 void Core::clientHasData() {
219 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
220 Q_ASSERT(socket && blocksizes.contains(socket));
222 while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
223 QVariantMap msg = item.toMap();
224 if(!msg.contains("MsgType")) {
225 // Client is way too old, does not even use the current init format
226 qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
230 // OK, so we have at least an init message format we can understand
231 if(msg["MsgType"] == "ClientInit") {
233 reply["CoreVersion"] = Global::quasselVersion;
234 reply["CoreDate"] = Global::quasselDate;
235 reply["CoreBuild"] = Global::quasselBuild;
236 // TODO: Make the core info configurable
237 int uptime = startTime.secsTo(QDateTime::currentDateTime());
238 int updays = uptime / 86400; uptime %= 86400;
239 int uphours = uptime / 3600; uptime %= 3600;
240 int upmins = uptime / 60;
241 reply["CoreInfo"] = tr("<b>Quassel Core Version %1 (Build >= %2)</b><br>"
242 "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuild)
243 .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime.toString(Qt::TextDate));
245 reply["SupportSsl"] = false;
246 reply["LoginEnabled"] = true;
247 // TODO: check if we are configured, start wizard otherwise
249 // Just version information -- check it!
250 if(msg["ClientBuild"].toUInt() < Global::clientBuildNeeded) {
251 reply["MsgType"] = "ClientInitReject";
252 reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
253 "This core needs at least client version %1 (Build >= %2).<br>"
254 "Please consider upgrading your client.").arg(Global::quasselVersion).arg(Global::quasselBuild);
255 SignalProxy::writeDataToDevice(socket, reply);
256 qWarning() << qPrintable(tr("Client %1 too old, rejecting.").arg(socket->peerAddress().toString()));
257 socket->close(); return;
259 clientInfo[socket] = msg; // store for future reference
260 reply["MsgType"] = "ClientInitAck";
261 SignalProxy::writeDataToDevice(socket, reply);
262 } else if(msg["MsgType"] == "ClientLogin") {
264 if(!clientInfo.contains(socket)) {
265 reply["MsgType"] = "ClientLoginReject";
266 reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
267 SignalProxy::writeDataToDevice(socket, reply);
268 qWarning() << qPrintable(tr("Client %1 did not send an init message before trying to login, rejecting.").arg(socket->peerAddress().toString()));
269 socket->close(); return;
272 UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
275 reply["MsgType"] = "ClientLoginReject";
276 reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
277 SignalProxy::writeDataToDevice(socket, reply);
280 reply["MsgType"] = "ClientLoginAck";
281 SignalProxy::writeDataToDevice(socket, reply);
282 qDebug() << qPrintable(tr("Client %1 initialized and authentificated successfully as \"%2\".").arg(socket->peerAddress().toString(), msg["User"].toString()));
283 setupClientSession(socket, uid);
285 //socket->close(); return;
287 // we need to auth the client
289 QVariantMap msg = item.toMap();
290 if (msg["GuiProtocol"].toUInt() != GUI_PROTOCOL) {
291 throw Exception("GUI client version mismatch");
294 processClientInit(socket, msg);
296 processCoreSetup(socket, msg);
298 } catch(Storage::AuthError) {
299 qWarning() << "Authentification error!"; // FIXME: send auth error to client
302 } catch(Exception e) {
303 qWarning() << "Client init error:" << e.msg();
310 // Potentially called during the initialization phase (before handing the connection off to the session)
311 void Core::clientDisconnected() {
312 QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
313 blocksizes.remove(socket);
314 clientInfo.remove(socket);
315 qDebug() << qPrintable(tr("Client %1 disconnected.").arg(socket->peerAddress().toString()));
316 socket->deleteLater();
319 // make server listen again if still not configured FIXME
324 // TODO remove unneeded sessions - if necessary/possible...
325 // Suggestion: kill sessions if they are not connected to any network and client.
328 void Core::processCoreSetup(QTcpSocket *socket, QVariantMap &msg) {
329 if(msg["HasSettings"].toBool()) {
331 auth["User"] = msg["User"];
332 auth["Password"] = msg["Password"];
334 msg.remove("Password");
335 qDebug() << "Initializing storage provider" << msg["Type"].toString();
337 if(!initStorage(msg, true)) {
338 // notify client to start wizard again
339 qWarning("Core is currently not configured!");
341 reply["StartWizard"] = true;
342 reply["StorageProviders"] = availableStorageProviders();
343 SignalProxy::writeDataToDevice(socket, reply);
345 // write coresettings
347 s.setDatabaseSettings(msg);
348 // write admin user to database & make the core listen again to connections
349 storage->addUser(auth["User"].toString(), auth["Password"].toString());
351 // continue the normal procedure
352 //processClientInit(socket, auth);
355 // notify client to start wizard
357 reply["StartWizard"] = true;
358 reply["StorageProviders"] = availableStorageProviders();
359 SignalProxy::writeDataToDevice(socket, reply);
363 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
364 // Find or create session for validated user
366 if(sessions.contains(uid)) sess = sessions[uid];
367 else sess = createSession(uid);
368 // Hand over socket, session then sends state itself
369 disconnect(socket, 0, this, 0);
371 qWarning() << qPrintable(tr("Could not initialize session for client %1!").arg(socket->peerAddress().toString()));
374 sess->addClient(socket);
377 SessionThread *Core::createSession(UserId uid, bool restore) {
378 if(sessions.contains(uid)) {
379 qWarning() << "Calling createSession() when a session for the user already exists!";
382 SessionThread *sess = new SessionThread(uid, restore, this);
383 sessions[uid] = sess;
388 QStringList Core::availableStorageProviders() {
389 QStringList storageProviders;
390 if (SqliteStorage::isAvailable()) {
391 storageProviders.append(SqliteStorage::displayName());
394 // storageProviders.append("MySQL");
396 return storageProviders;