fixes #391 - appending underscores if all nicknames of the identity are unavailable
[quassel.git] / src / core / core.cpp
index 233157b..e1a5360 100644 (file)
@@ -1,5 +1,5 @@
 /***************************************************************************
- *   Copyright (C) 2005-08 by the Quassel Project                          *
+ *   Copyright (C) 2005-09 by the Quassel Project                          *
  *   devel@quassel-irc.org                                                 *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
@@ -18,8 +18,6 @@
  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
  ***************************************************************************/
 
-#include <QMetaObject>
-#include <QMetaMethod>
 #include <QCoreApplication>
 
 #include "core.h"
@@ -33,6 +31,9 @@
 
 #include "util.h"
 
+// migration related
+#include <QFile>
+
 Core *Core::instanceptr = 0;
 
 Core *Core::instance() {
@@ -47,43 +48,108 @@ void Core::destroy() {
   instanceptr = 0;
 }
 
-Core::Core() : storage(0) {
+Core::Core()
+  : _storage(0)
+{
   _startTime = QDateTime::currentDateTime().toUTC();  // for uptime :)
 
-  loadTranslation(QLocale::system());
+  Quassel::loadTranslation(QLocale::system());
+
+  // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
+  // Move settings, note this does not delete the old files
+#ifdef Q_WS_MAC
+    QSettings newSettings("quassel-irc.org", "quasselcore");
+#else
+
+# ifdef Q_WS_WIN
+    QSettings::Format format = QSettings::IniFormat;
+# else
+    QSettings::Format format = QSettings::NativeFormat;
+# endif
+    QString newFilePath = Quassel::configDirPath() + "quasselcore"
+    + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
+    QSettings newSettings(newFilePath, format);
+#endif /* Q_WS_MAC */
+
+  if(newSettings.value("Config/Version").toUInt() == 0) {
+#   ifdef Q_WS_MAC
+    QString org = "quassel-irc.org";
+#   else
+    QString org = "Quassel Project";
+#   endif
+    QSettings oldSettings(org, "Quassel Core");
+    if(oldSettings.allKeys().count()) {
+      qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
+      foreach(QString key, oldSettings.allKeys())
+        newSettings.setValue(key, oldSettings.value(key));
+      newSettings.setValue("Config/Version", 1);
+      qWarning() << "*   Your core settings have been migrated to" << newSettings.fileName();
+
+#ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
+#ifdef Q_OS_WIN32
+      QString quasselDir = qgetenv("APPDATA") + "/quassel/";
+#elif defined Q_WS_MAC
+      QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
+#else
+      QString quasselDir = QDir::homePath() + "/.quassel/";
+#endif
+
+      QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
+      if(!info.exists()) {
+      // move database, if we found it
+        QFile oldDb(quasselDir + "quassel-storage.sqlite");
+        if(oldDb.exists()) {
+          bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
+          if(success)
+            qWarning() << "*   Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
+          else
+            qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
+        }
+      }
+      // move certificate
+      QFileInfo certInfo(quasselDir + "quasselCert.pem");
+      if(certInfo.exists()) {
+        QFile cert(quasselDir + "quasselCert.pem");
+        bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
+        if(success)
+          qWarning() << "*   Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
+        else
+          qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
+      }
+#endif /* !Q_WS_MAC */
+      qWarning() << "*** Migration completed.\n\n";
+    }
+  }
+  // MIGRATION end
+
+  // check settings version
+  // so far, we only have 1
+  CoreSettings s;
+  if(s.version() != 1) {
+    qCritical() << "Invalid core settings version, terminating!";
+    exit(EXIT_FAILURE);
+  }
 
   // Register storage backends here!
   registerStorageBackend(new SqliteStorage(this));
 
-  if(!_storageBackends.count()) {
-    qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
-    qWarning() << 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()));
   _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
 }
 
 void Core::init() {
-  configured = false;
-
   CoreSettings cs;
-
-  if(!(configured = initStorage(cs.storageSettings().toMap()))) {
-    qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
-
-    // try to migrate old settings
-    QVariantMap old = cs.oldDbSettings().toMap();
-    if(old.count() && old["Type"].toString().toUpper() == "SQLITE") {
-      QVariantMap newSettings;
-      newSettings["Backend"] = "SQLite";
-      if((configured = initStorage(newSettings))) {
-        qWarning() << "...but thankfully I found some old settings to migrate!";
-        cs.setStorageSettings(newSettings);
-      }
+  _configured = initStorage(cs.storageSettings().toMap());
+
+  if(!_configured) {
+    if(!_storageBackends.count()) {
+      qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
+      qWarning() << 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)
     }
+    qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
   }
 
   connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
@@ -112,7 +178,7 @@ void Core::saveState() {
 }
 
 void Core::restoreState() {
-  if(!instance()->configured) {
+  if(!instance()->_configured) {
     // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
     return;
   }
@@ -160,13 +226,14 @@ QString Core::setupCore(QVariantMap setupData) {
   if(user.isEmpty() || password.isEmpty()) {
     return tr("Admin user or password not set.");
   }
-  if(!initStorage(setupData, true)) {
+  _configured = initStorage(setupData, true);
+  if(!_configured) {
     return tr("Could not setup storage!");
   }
   CoreSettings s;
   s.setStorageSettings(setupData);
   quInfo() << qPrintable(tr("Creating admin user..."));
-  storage->addUser(user, password);
+  _storage->addUser(user, password);
   startListening();  // TODO check when we need this
   return QString();
 }
@@ -191,42 +258,55 @@ void Core::unregisterStorageBackend(Storage *backend) {
 // old db settings:
 // "Type" => "sqlite"
 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
+  _storage = 0;
+
   QString backend = dbSettings["Backend"].toString();
   if(backend.isEmpty()) {
-    //qWarning() << "No storage backend selected!";
-    return configured = false;
+    return false;
   }
 
+  Storage *storage = 0;
   if(_storageBackends.contains(backend)) {
     storage = _storageBackends[backend];
   } else {
     qCritical() << "Selected storage backend is not available:" << backend;
-    return configured = false;
+    return false;
   }
-  if(!storage->init(dbSettings)) {
-    if(!setup || !(storage->setup(dbSettings) && storage->init(dbSettings))) {
-      qCritical() << "Could not init storage!";
-      storage = 0;
-      return configured = false;
+
+  Storage::State storageState = storage->init(dbSettings);
+  switch(storageState) {
+  case Storage::NeedsSetup:
+    if(!setup)
+      return false; // trigger setup process
+    if(storage->setup(dbSettings))
+      return initStorage(dbSettings, false);
+    // if setup wasn't successfull we mark the backend as unavailable
+  case Storage::NotAvailable:
+    qCritical() << "Selected storage backend is not available:" << backend;
+    storage->deleteLater();
+    _storageBackends.remove(backend);
+    storage = 0;
+    return false;
+  case Storage::IsReady:
+    // delete all other backends
+    foreach(Storage *s, _storageBackends.values()) {
+      if(s != storage) s->deleteLater();
     }
+    _storageBackends.clear();
+    connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
   }
-  // delete all other backends
-  foreach(Storage *s, _storageBackends.values()) {
-    if(s != storage) s->deleteLater();
-  }
-  _storageBackends.clear();
-
-  connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
-  return configured = true;
+  _storage = storage;
+  return true;
 }
 
 void Core::syncStorage() {
-  if(storage) storage->sync();
+  if(_storage)
+    _storage->sync();
 }
 
 /*** Storage Access ***/
 bool Core::createNetwork(UserId user, NetworkInfo &info) {
-  NetworkId networkId = instance()->storage->createNetwork(user, info);
+  NetworkId networkId = instance()->_storage->createNetwork(user, info);
   if(!networkId.isValid())
     return false;
 
@@ -244,20 +324,66 @@ bool Core::startListening() {
   bool success = false;
   uint port = Quassel::optionValue("port").toUInt();
 
-  if(_server.listen(QHostAddress::Any, port)) {
-    quInfo() << "Listening for GUI clients on IPv4 port" << _server.serverPort()
-             << "using protocol version" << Quassel::buildInfo().protocolVersion;
-    success = true;
-  }
-  if(_v6server.listen(QHostAddress::AnyIPv6, port)) {
-    quInfo() << "Listening for GUI clients on IPv6 port" << _v6server.serverPort()
-             << "using protocol version" << Quassel::buildInfo().protocolVersion;
-    success = true;
-  }
-
-  if(!success) {
-    qCritical() << qPrintable(QString("Could not open GUI client port %1: %2").arg(port).arg(_server.errorString()));
+  const QString listen = Quassel::optionValue("listen");
+  const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
+  if(listen_list.size() > 0) {
+    foreach (const QString listen_term, listen_list) {  // TODO: handle multiple interfaces for same TCP version gracefully
+      QHostAddress addr;
+      if(!addr.setAddress(listen_term)) {
+        qCritical() << qPrintable(
+          tr("Invalid listen address %1")
+            .arg(listen_term)
+        );
+      } else {
+        switch(addr.protocol()) {
+          case QAbstractSocket::IPv4Protocol:
+            if(_server.listen(addr, port)) {
+              quInfo() << qPrintable(
+                tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
+                  .arg(addr.toString())
+                  .arg(_server.serverPort())
+                  .arg(Quassel::buildInfo().protocolVersion)
+              );
+              success = true;
+            } else
+              quWarning() << qPrintable(
+                tr("Could not open IPv4 interface %1:%2: %3")
+                  .arg(addr.toString())
+                  .arg(port)
+                  .arg(_server.errorString()));
+            break;
+          case QAbstractSocket::IPv6Protocol:
+            if(_v6server.listen(addr, port)) {
+              quInfo() << qPrintable(
+                tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
+                  .arg(addr.toString())
+                  .arg(_v6server.serverPort())
+                  .arg(Quassel::buildInfo().protocolVersion)
+              );
+              success = true;
+            } else {
+              // if v4 succeeded on Any, the port will be already in use - don't display the error then
+              // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
+              if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
+                quWarning() << qPrintable(
+                  tr("Could not open IPv6 interface %1:%2: %3")
+                  .arg(addr.toString())
+                  .arg(port)
+                  .arg(_v6server.errorString()));
+            }
+            break;
+          default:
+            qCritical() << qPrintable(
+              tr("Invalid listen address %1, unknown network protocol")
+                  .arg(listen_term)
+            );
+            break;
+        }
+      }
+    }
   }
+  if(!success)
+    quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
 
   return success;
 }
@@ -293,7 +419,7 @@ void Core::incomingConnection() {
     blocksizes.insert(socket, (quint32)0);
     quInfo() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
 
-    if(!configured) {
+    if(!_configured) {
       stopListening(tr("Closing server for basic setup."));
     }
   }
@@ -350,7 +476,7 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
 #ifdef HAVE_SSL
     SslServer *sslServer = qobject_cast<SslServer *>(&_server);
     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
-    bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->certIsValid();
+    bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
 #else
     bool supportSsl = false;
 #endif
@@ -368,7 +494,7 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
     reply["LoginEnabled"] = true;
 
     // check if we are configured, start wizard otherwise
-    if(!configured) {
+    if(!_configured) {
       reply["Configured"] = false;
       QList<QVariant> backends;
       foreach(Storage *backend, _storageBackends.values()) {
@@ -424,7 +550,7 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
       SignalProxy::writeDataToDevice(socket, reply);
     } else if(msg["MsgType"] == "ClientLogin") {
       QVariantMap reply;
-      UserId uid = storage->validateUser(msg["User"].toString(), msg["Password"].toString());
+      UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
       if(uid == 0) {
         reply["MsgType"] = "ClientLoginReject";
         reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
@@ -458,23 +584,25 @@ void Core::clientDisconnected() {
     QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
     while(blockSizeIter != blocksizes.end()) {
       if(blockSizeIter.key() == socket) {
-       blocksizes.erase(blockSizeIter);
+       blockSizeIter = blocksizes.erase(blockSizeIter);
+      } else {
+       blockSizeIter++;
       }
-      blockSizeIter++;
     }
 
     QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
     while(clientInfoIter != clientInfo.end()) {
       if(clientInfoIter.key() == socket) {
-       clientInfo.erase(clientInfoIter);
+       clientInfoIter = clientInfo.erase(clientInfoIter);
+      } else {
+       clientInfoIter++;
       }
-      clientInfoIter++;
     }
   }
 
 
   // make server listen again if still not configured
-  if (!configured) {
+  if (!_configured) {
     startListening();
   }
 
@@ -499,12 +627,12 @@ void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
 }
 
 void Core::setupInternalClientSession(SignalProxy *proxy) {
-  if(!configured) {
+  if(!_configured) {
     stopListening();
     setupCoreForInternalUsage();
   }
 
-  UserId uid = storage->internalUser();
+  UserId uid = _storage->internalUser();
 
   // Find or create session for validated user
   SessionThread *sess;