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