Monolithic build features now zero setup configuration: click and run
[quassel.git] / src / core / core.cpp
index f413bbf..bf611aa 100644 (file)
 #include "core.h"
 #include "coresession.h"
 #include "coresettings.h"
+#include "quassel.h"
 #include "signalproxy.h"
 #include "sqlitestorage.h"
 #include "network.h"
+#include "logger.h"
 
 #include "util.h"
 
@@ -48,13 +50,16 @@ void Core::destroy() {
 }
 
 Core::Core() : storage(0) {
-  startTime = QDateTime::currentDateTime();  // for uptime :)
+  _startTime = QDateTime::currentDateTime().toUTC();  // for uptime :)
 
   // Register storage backends here!
   registerStorageBackend(new SqliteStorage(this));
 
   if(!_storageBackends.count()) {
-    qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
+    quWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
+    quWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
+                                "Qt library with the sqlite plugin enabled in order for quasselcore\n"
+                                "to work."));
     exit(1); // TODO make this less brutal (especially for mono client -> popup)
   }
   connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
@@ -67,7 +72,7 @@ void Core::init() {
   CoreSettings cs;
 
   if(!(configured = initStorage(cs.storageSettings().toMap()))) {
-    qWarning("Core is currently not configured! Please connect with a Quassel Client for basic setup.");
+    quWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
 
     // try to migrate old settings
     QVariantMap old = cs.oldDbSettings().toMap();
@@ -75,19 +80,20 @@ void Core::init() {
       QVariantMap newSettings;
       newSettings["Backend"] = "SQLite";
       if((configured = initStorage(newSettings))) {
-        qWarning("...but thankfully I found some old settings to migrate!");
+        quWarning() << "...but thankfully I found some old settings to migrate!";
         cs.setStorageSettings(newSettings);
       }
     }
   }
 
-  connect(&server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
-  if(!startListening(cs.port())) exit(1); // TODO make this less brutal
+  connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
+  connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
+  if(!startListening()) exit(1); // TODO make this less brutal
 }
 
 Core::~Core() {
-  foreach(QTcpSocket *socket, blocksizes.keys()) { qDebug() << "disconnecting" << socket << blocksizes.keys();
-    socket->disconnectFromHost();  // disconnect local (i.e. non-authed) clients
+  foreach(QTcpSocket *socket, blocksizes.keys()) {
+    socket->disconnectFromHost();  // disconnect non authed clients
   }
   qDeleteAll(sessions);
   qDeleteAll(_storageBackends);
@@ -100,7 +106,7 @@ void Core::saveState() {
   QVariantMap state;
   QVariantList activeSessions;
   foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
-  state["CoreBuild"] = Global::quasselBuild;
+  state["CoreStateVersion"] = 1;
   state["ActiveSessions"] = activeSessions;
   s.setCoreState(state);
 }
@@ -111,18 +117,20 @@ void Core::restoreState() {
     return;
   }
   if(instance()->sessions.count()) {
-    qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
+    quWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
     return;
   }
   CoreSettings s;
-  uint build = s.coreState().toMap()["CoreBuild"].toUInt();
-  if(build < 362) {
+  /* We don't check, since we are at the first version since switching to Git
+  uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
+  if(statever < 1) {
     qWarning() << qPrintable(tr("Core state too old, ignoring..."));
     return;
   }
+  */
   QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
   if(activeSessions.count() > 0) {
-    qDebug() << "Restoring previous core state...";
+    quInfo() << "Restoring previous core state...";
     foreach(QVariant v, activeSessions) {
       UserId user = v.value<UserId>();
       instance()->createSession(user, true);
@@ -131,9 +139,22 @@ void Core::restoreState() {
 }
 
 /*** Core Setup ***/
+QString Core::setupCoreForInternalUsage() {
+  Q_ASSERT(!_storageBackends.isEmpty());
+  QVariantMap setupData;
+  qsrand(QDateTime::currentDateTime().toTime_t());
+  int pass = 0;
+  for(int i = 0; i < 10; i++) {
+    pass *= 10;
+    pass += qrand() % 10;
+  }
+  setupData["AdminUser"] = "AdminUser";
+  setupData["AdminPasswd"] = QString::number(pass);
+  setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
+  return setupCore(setupData);
+}
 
-QString Core::setupCore(const QVariant &setupData_) {
-  QVariantMap setupData = setupData_.toMap();
+QString Core::setupCore(QVariantMap setupData) {
   QString user = setupData.take("AdminUser").toString();
   QString password = setupData.take("AdminPasswd").toString();
   if(user.isEmpty() || password.isEmpty()) {
@@ -144,7 +165,7 @@ QString Core::setupCore(const QVariant &setupData_) {
   }
   CoreSettings s;
   s.setStorageSettings(setupData);
-  qDebug() << qPrintable(tr("Creating admin user..."));
+  quInfo() << qPrintable(tr("Creating admin user..."));
   mutex.lock();
   storage->addUser(user, password);
   mutex.unlock();
@@ -181,12 +202,12 @@ bool Core::initStorage(QVariantMap dbSettings, bool setup) {
   if(_storageBackends.contains(backend)) {
     storage = _storageBackends[backend];
   } else {
-    qWarning() << "Selected storage backend is not available:" << backend;
+    quError() << "Selected storage backend is not available:" << backend;
     return configured = false;
   }
   if(!storage->init(dbSettings)) {
     if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
-      qWarning() << "Could not init storage!";
+      quError() << "Could not init storage!";
       storage = 0;
       return configured = false;
     }
@@ -307,6 +328,11 @@ QList<BufferInfo> Core::requestBuffers(UserId user) {
   return instance()->storage->requestBuffers(user);
 }
 
+QList<BufferId> Core::requestBufferIdsForNetwork(UserId user, NetworkId networkId) {
+  QMutexLocker locker(&mutex);
+  return instance()->storage->requestBufferIdsForNetwork(user, networkId);
+}
+
 bool Core::removeBuffer(const UserId &user, const BufferId &bufferId) {
   QMutexLocker locker(&mutex);
   return instance()->storage->removeBuffer(user, bufferId);
@@ -329,34 +355,65 @@ QHash<BufferId, MsgId> Core::bufferLastSeenMsgIds(UserId user) {
 
 /*** Network Management ***/
 
-bool Core::startListening(uint port) {
-  if(!server.listen(QHostAddress::Any, port)) {
-    qWarning(qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(server.errorString())));
-    return false;
+bool Core::startListening() {
+  // in mono mode we only start a local port if a port is specified in the cli call
+  if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
+    return true;
+  
+  bool success = false;
+  uint port = Quassel::optionValue("port").toUInt();
+
+  if(_server.listen(QHostAddress::Any, port)) {
+    quInfo() << "Listening for GUI clients on IPv6 port" << _server.serverPort()
+             << "using protocol version" << Quassel::buildInfo().protocolVersion;
+    success = true;
   }
-  qDebug() << "Listening for GUI clients on port" << server.serverPort();
-  return true;
+  if(_v6server.listen(QHostAddress::AnyIPv6, port)) {
+    quInfo() << "Listening for GUI clients on IPv4 port" << _v6server.serverPort()
+             << "using protocol version" << Quassel::buildInfo().protocolVersion;
+    success = true;
+  }
+
+  if(!success) {
+    quError() << qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(_server.errorString()));
+  }
+
+  return success;
 }
 
-void Core::stopListening() {
-  server.close();
-  qDebug() << "No longer listening for GUI clients.";
+void Core::stopListening(const QString &reason) {
+  bool wasListening = false;
+  if(_server.isListening()) {
+    wasListening = true;
+    _server.close();
+  }
+  if(_v6server.isListening()) {
+    wasListening = true;
+    _v6server.close();
+  }
+  if(wasListening) {
+    if(reason.isEmpty())
+      quInfo() << "No longer listening for GUI clients.";
+    else
+      quInfo() << qPrintable(reason);
+  }
 }
 
 void Core::incomingConnection() {
-  while(server.hasPendingConnections()) {
-    QTcpSocket *socket = server.nextPendingConnection();
+  QTcpServer *server = qobject_cast<QTcpServer *>(sender());
+  Q_ASSERT(server);
+  while(server->hasPendingConnections()) {
+    QTcpSocket *socket = server->nextPendingConnection();
     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
     connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
     connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
-    
+
     QVariantMap clientInfo;
     blocksizes.insert(socket, (quint32)0);
-    qDebug() << "Client connected from"  << qPrintable(socket->peerAddress().toString());
+    quInfo() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
 
-    if (!configured) {
-      server.close();
-      qDebug() << "Closing server for basic setup.";
+    if(!configured) {
+      stopListening(tr("Closing server for basic setup."));
     }
   }
 }
@@ -375,27 +432,42 @@ void Core::clientHasData() {
 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
   if(!msg.contains("MsgType")) {
     // Client is way too old, does not even use the current init format
-    qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
+    quWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
     socket->close();
     return;
   }
   // OK, so we have at least an init message format we can understand
   if(msg["MsgType"] == "ClientInit") {
     QVariantMap reply;
-    reply["CoreVersion"] = Global::quasselVersion;
-    reply["CoreDate"] = Global::quasselDate;
-    reply["CoreBuild"] = Global::quasselBuild;
+
+    // Just version information -- check it!
+    uint ver = msg["ProtocolVersion"].toUInt();
+    if(ver < Quassel::buildInfo().coreNeedsProtocol) {
+      reply["MsgType"] = "ClientInitReject";
+      reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
+      "This core needs at least client/core protocol version %1.<br>"
+      "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
+      SignalProxy::writeDataToDevice(socket, reply);
+      quWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
+      socket->close(); return;
+    }
+
+    reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
+    reply["CoreDate"] = Quassel::buildInfo().buildDate;
+    reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
     // TODO: Make the core info configurable
-    int uptime = startTime.secsTo(QDateTime::currentDateTime());
+    int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
     int updays = uptime / 86400; uptime %= 86400;
     int uphours = uptime / 3600; uptime %= 3600;
     int upmins = uptime / 60;
-    reply["CoreInfo"] = tr("<b>Quassel Core Version %1 (Build &ge; %2)</b><br>"
-                            "Up %3d%4h%5m (since %6)").arg(Global::quasselVersion).arg(Global::quasselBuild)
-                            .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime.toString(Qt::TextDate));
-
-#ifndef QT_NO_OPENSSL
-    SslServer *sslServer = qobject_cast<SslServer *>(&server);
+    reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
+                          "Built: %2<br>"
+                          "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
+                                                     .arg(Quassel::buildInfo().buildDate)
+      .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
+
+#ifdef HAVE_SSL
+    SslServer *sslServer = qobject_cast<SslServer *>(&_server);
     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
     bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
 #else
@@ -407,23 +479,13 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
 #else
     bool supportsCompression = false;
 #endif
-    
+
     reply["SupportSsl"] = supportSsl;
     reply["SupportsCompression"] = supportsCompression;
     // switch to ssl/compression after client has been informed about our capabilities (see below)
 
     reply["LoginEnabled"] = true;
 
-    // Just version information -- check it!
-    if(msg["ClientBuild"].toUInt() < Global::clientBuildNeeded) {
-      reply["MsgType"] = "ClientInitReject";
-      reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
-                          "This core needs at least client version %1 (Build >= %2).<br>"
-                          "Please consider upgrading your client.").arg(Global::quasselVersion).arg(Global::quasselBuild);
-      SignalProxy::writeDataToDevice(socket, reply);
-      qWarning() << qPrintable(tr("Client %1 too old, rejecting.").arg(socket->peerAddress().toString()));
-      socket->close(); return;
-    }
     // check if we are configured, start wizard otherwise
     if(!configured) {
       reply["Configured"] = false;
@@ -443,10 +505,10 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
     reply["MsgType"] = "ClientInitAck";
     SignalProxy::writeDataToDevice(socket, reply);
 
-#ifndef QT_NO_OPENSSL
+#ifdef HAVE_SSL
     // after we told the client that we are ssl capable we switch to ssl mode
     if(supportSsl && msg["UseSsl"].toBool()) {
-      qDebug() << "Starting TLS for Client:" << qPrintable(socket->peerAddress().toString());
+      quDebug() << qPrintable(tr("Starting TLS for Client:"))  << qPrintable(socket->peerAddress().toString());
       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
       sslSocket->startServerEncryption();
     }
@@ -455,10 +517,10 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
 #ifndef QT_NO_COMPRESS
     if(supportsCompression && msg["UseCompression"].toBool()) {
       socket->setProperty("UseCompression", true);
-      qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
+      quDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
     }
 #endif
-    
+
   } else {
     // for the rest, we need an initialized connection
     if(!clientInfo.contains(socket)) {
@@ -466,12 +528,12 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
       reply["MsgType"] = "ClientLoginReject";
       reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
       SignalProxy::writeDataToDevice(socket, reply);
-      qWarning() << qPrintable(tr("Client %1 did not send an init message before trying to login, rejecting.").arg(socket->peerAddress().toString()));
+      quWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
       socket->close(); return;
     }
     if(msg["MsgType"] == "CoreSetupData") {
       QVariantMap reply;
-      QString result = setupCore(msg["SetupData"]);
+      QString result = setupCore(msg["SetupData"].toMap());
       if(!result.isEmpty()) {
         reply["MsgType"] = "CoreSetupReject";
         reply["Error"] = result;
@@ -492,7 +554,7 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
       }
       reply["MsgType"] = "ClientLoginAck";
       SignalProxy::writeDataToDevice(socket, reply);
-      qDebug() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).").arg(socket->peerAddress().toString(), msg["User"].toString()).arg(uid.toInt()));
+      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()));
       setupClientSession(socket, uid);
     }
   }
@@ -500,13 +562,37 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
 
 // Potentially called during the initialization phase (before handing the connection off to the session)
 void Core::clientDisconnected() {
-  QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());  // Note: This might be a QObject* already (if called by ~Core())!
-  Q_ASSERT(socket);
-  blocksizes.remove(socket);
-  clientInfo.remove(socket);
-  qDebug() << qPrintable(tr("Non-authed client disconnected."));
-  socket->deleteLater();
-  socket = 0;
+  QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
+  if(socket) {
+    // here it's safe to call methods on socket!
+    quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
+    blocksizes.remove(socket);
+    clientInfo.remove(socket);
+    socket->deleteLater();
+  } else {
+    // we have to crawl through the hashes and see if we find a victim to remove
+    quDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
+
+    // DO NOT CALL ANY METHODS ON socket!!
+    socket = static_cast<QTcpSocket *>(sender());
+
+    QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
+    while(blockSizeIter != blocksizes.end()) {
+      if(blockSizeIter.key() == socket) {
+       blocksizes.erase(blockSizeIter);
+      }
+      blockSizeIter++;
+    }
+
+    QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
+    while(clientInfoIter != clientInfo.end()) {
+      if(clientInfoIter.key() == socket) {
+       clientInfo.erase(clientInfoIter);
+      }
+      clientInfoIter++;
+    }
+  }
+
 
   // make server listen again if still not configured
   if (!configured) {
@@ -527,15 +613,31 @@ void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
   blocksizes.remove(socket);
   clientInfo.remove(socket);
   if(!sess) {
-    qWarning() << qPrintable(tr("Could not initialize session for client %1!").arg(socket->peerAddress().toString()));
+    quWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
     socket->close();
   }
   sess->addClient(socket);
 }
 
+void Core::setupInternalClientSession(SignalProxy *proxy) {
+  if(!configured) {
+    stopListening();
+    setupCoreForInternalUsage();
+  }
+
+  UserId uid = 3; // FIXME!!!11
+  // Find or create session for validated user
+  SessionThread *sess;
+  if(sessions.contains(uid))
+    sess = sessions[uid];
+  else
+    sess = createSession(uid);
+  sess->addClient(proxy);
+}
+
 SessionThread *Core::createSession(UserId uid, bool restore) {
   if(sessions.contains(uid)) {
-    qWarning() << "Calling createSession() when a session for the user already exists!";
+    quWarning() << "Calling createSession() when a session for the user already exists!";
     return 0;
   }
   SessionThread *sess = new SessionThread(uid, restore, this);
@@ -544,7 +646,7 @@ SessionThread *Core::createSession(UserId uid, bool restore) {
   return sess;
 }
 
-#ifndef QT_NO_OPENSSL
+#ifdef HAVE_SSL
 void Core::sslErrors(const QList<QSslError> &errors) {
   Q_UNUSED(errors);
   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
@@ -556,5 +658,5 @@ void Core::sslErrors(const QList<QSslError> &errors) {
 void Core::socketError(QAbstractSocket::SocketError err) {
   QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
   if(socket && err != QAbstractSocket::RemoteHostClosedError)
-    qDebug() << "Core::socketError()" << socket << err << socket->errorString();
+    quWarning() << "Core::socketError()" << socket << err << socket->errorString();
 }