Adding users and changing passwords needs a configured core.
[quassel.git] / src / core / core.cpp
index d859c2a..29174b6 100644 (file)
 
 // migration related
 #include <QFile>
-
+#ifdef Q_OS_WIN32
+#  include <windows.h>
+#else
+#  include <unistd.h>
+#  include <termios.h>
+#endif /* Q_OS_WIN32 */
+
+// umask
+#ifndef Q_OS_WIN32
+#  include <sys/types.h>
+#  include <sys/stat.h>
+#endif /* Q_OS_WIN32 */
+
+// ==============================
+//  Custom Events
+// ==============================
+const int Core::AddClientEventId = QEvent::registerEventType();
+
+class AddClientEvent : public QEvent {
+public:
+  AddClientEvent(QTcpSocket *socket, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), socket(socket), userId(uid) {}
+  QTcpSocket *socket;
+  UserId userId;
+};
+
+
+// ==============================
+//  Core
+// ==============================
 Core *Core::instanceptr = 0;
 
 Core *Core::instance() {
@@ -52,6 +80,9 @@ void Core::destroy() {
 Core::Core()
   : _storage(0)
 {
+#ifndef Q_OS_WIN32
+  umask(S_IRWXG | S_IRWXO);
+#endif /* Q_OS_WIN32 */
   _startTime = QDateTime::currentDateTime().toUTC();  // for uptime :)
 
   Quassel::loadTranslation(QLocale::system());
@@ -138,27 +169,32 @@ Core::Core()
 }
 
 void Core::init() {
-  if(Quassel::isOptionSet("switch-backend")) {
-    switchBackend(Quassel::optionValue("switch-backend"));
-    exit(0);
-  }
-
   CoreSettings cs;
   _configured = initStorage(cs.storageSettings().toMap());
 
+  if(Quassel::isOptionSet("select-backend")) {
+    selectBackend(Quassel::optionValue("select-backend"));
+    exit(0);
+  }
+
   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"
+      qWarning() << qPrintable(tr("Currently, Quassel supports SQLite3 and PostgreSQL. You need to build your\n"
+                                 "Qt library with the sqlite or postgres 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.";
   }
 
-  if(Quassel::isOptionSet("migrate-backend")) {
-    migrateBackend(Quassel::optionValue("migrate-backend"));
+  if(Quassel::isOptionSet("add-user")) {
+    createUser();
+    exit(0);
+  }
+
+  if(Quassel::isOptionSet("change-userpass")) {
+    changeUserPass(Quassel::optionValue("change-userpass"));
     exit(0);
   }
 
@@ -483,10 +519,15 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
       socket->close(); return;
     }
 
+    reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
     reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
     reply["CoreDate"] = Quassel::buildInfo().buildDate;
-    reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
-    // TODO: Make the core info configurable
+    reply["CoreStartTime"] = startTime(); // v10 clients don't necessarily parse this, see below
+
+    // FIXME: newer clients no longer use the hardcoded CoreInfo (for now), since it gets the
+    //        time zone wrong. With the next protocol bump (10 -> 11), we should remove this
+    //        or make it properly configurable.
+
     int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
     int updays = uptime / 86400; uptime %= 86400;
     int uphours = uptime / 3600; uptime %= 3600;
@@ -497,6 +538,8 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
                                                      .arg(Quassel::buildInfo().buildDate)
       .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
 
+    reply["CoreFeatures"] = (int)Quassel::features();
+
 #ifdef HAVE_SSL
     SslServer *sslServer = qobject_cast<SslServer *>(&_server);
     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
@@ -525,8 +568,8 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
         QVariantMap v;
         v["DisplayName"] = backend->displayName();
         v["Description"] = backend->description();
-       v["ConnectionProperties"] = backend->setupKeys();
-       qDebug() << backend->setupKeys();
+       v["SetupKeys"] = backend->setupKeys();
+       v["SetupDefaults"] = backend->setupDefaults();
         backends.append(v);
       }
       reply["StorageBackends"] = backends;
@@ -537,6 +580,7 @@ void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
     clientInfo[socket] = msg; // store for future reference
     reply["MsgType"] = "ClientInitAck";
     SignalProxy::writeDataToDevice(socket, reply);
+    socket->flush(); // ensure that the write cache is flushed before we switch to ssl
 
 #ifdef HAVE_SSL
     // after we told the client that we are ssl capable we switch to ssl mode
@@ -637,19 +681,48 @@ void Core::clientDisconnected() {
 }
 
 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
-  // Find or create session for validated user
-  SessionThread *sess;
-  if(sessions.contains(uid)) sess = sessions[uid];
-  else sess = createSession(uid);
-  // Hand over socket, session then sends state itself
+  // From now on everything is handled by the client session
   disconnect(socket, 0, this, 0);
+  socket->flush();
   blocksizes.remove(socket);
   clientInfo.remove(socket);
-  if(!sess) {
-    qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
+
+  // Find or create session for validated user
+  SessionThread *session;
+  if(sessions.contains(uid)) {
+    session = sessions[uid];
+  } else {
+    session = createSession(uid);
+    if(!session) {
+      qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
+      socket->close();
+      return;
+    }
+  }
+
+  // as we are currently handling an event triggered by incoming data on this socket
+  // it is unsafe to directly move the socket to the client thread.
+  QCoreApplication::postEvent(this, new AddClientEvent(socket, uid));
+}
+
+void Core::customEvent(QEvent *event) {
+  if(event->type() == AddClientEventId) {
+    AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
+    addClientHelper(addClientEvent->socket, addClientEvent->userId);
+    return;
+  }
+}
+
+void Core::addClientHelper(QTcpSocket *socket, UserId uid) {
+  // Find or create session for validated user
+  if(!sessions.contains(uid)) {
+    qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(socket->peerAddress().toString());
     socket->close();
+    return;
   }
-  sess->addClient(socket);
+
+  SessionThread *session = sessions[uid];
+  session->addClient(socket);
 }
 
 void Core::setupInternalClientSession(SignalProxy *proxy) {
@@ -658,7 +731,13 @@ void Core::setupInternalClientSession(SignalProxy *proxy) {
     setupCoreForInternalUsage();
   }
 
-  UserId uid = _storage->internalUser();
+  UserId uid;
+  if(_storage) {
+    uid = _storage->internalUser();
+  } else {
+    qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
+    return;
+  }
 
   // Find or create session for validated user
   SessionThread *sess;
@@ -695,95 +774,176 @@ void Core::socketError(QAbstractSocket::SocketError err) {
     qWarning() << "Core::socketError()" << socket << err << socket->errorString();
 }
 
-bool Core::migrateBackend(const QString &backend) {
-  AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(_storage);
-  if(!sqlStorage) {
-    qWarning() << "Core::migrateDb(): only SQL based backends can be migrated!";
-    return false;
-  }
-
-  AbstractSqlMigrationReader *reader = sqlStorage->createMigrationReader();
-  if(!reader) {
-    qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration reader for %1)").arg(sqlStorage->displayName()));
-    return false;
-  }
-
-
+// migration / backend selection
+bool Core::selectBackend(const QString &backend) {
   // reregister all storage backends
   registerStorageBackends();
-  if(_storageBackends.contains(sqlStorage->displayName())) {
-    unregisterStorageBackend(_storageBackends[sqlStorage->displayName()]);
-  }
   if(!_storageBackends.contains(backend)) {
-    qWarning() << qPrintable(QString("Core::migrateBackend(): unsupported migration target: %1").arg(backend));
-    qWarning() << "    supported Targets:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
+    qWarning() << qPrintable(QString("Core::selectBackend(): unsupported backend: %1").arg(backend));
+    qWarning() << "    supported backends are:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
     return false;
   }
 
   Storage *storage = _storageBackends[backend];
-  QVariantMap settings = promptForSettings(storage->setupKeys());
+  QVariantMap settings = promptForSettings(storage);
 
   Storage::State storageState = storage->init(settings);
   switch(storageState) {
+  case Storage::IsReady:
+    saveBackendSettings(backend, settings);
+    qWarning() << "Switched backend to:" << qPrintable(backend);
+    qWarning() << "Backend already initialized. Skipping Migration";
+    return true;
   case Storage::NotAvailable:
-    qCritical() << "Core::migrateBackend(): selected storage backend is not available:" << backend;
+    qCritical() << "Backend is not available:" << qPrintable(backend);
     return false;
   case Storage::NeedsSetup:
     if(!storage->setup(settings)) {
-      qWarning() << qPrintable(QString("Core::migrateBackend(): unable to setup target: %1").arg(backend));
+      qWarning() << qPrintable(QString("Core::selectBackend(): unable to setup backend: %1").arg(backend));
       return false;
     }
 
     if(storage->init(settings) != Storage::IsReady) {
-      qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize target: %1").arg(backend));
+      qWarning() << qPrintable(QString("Core::migrateBackend(): unable to initialize backend: %1").arg(backend));
       return false;
     }
-  case Storage::IsReady:
+
+    saveBackendSettings(backend, settings);
+    qWarning() << "Switched backend to:" << qPrintable(backend);
     break;
   }
 
-  sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
-  if(!sqlStorage) {
-    qWarning() << "Core::migrateDb(): only SQL based backends can be migrated!";
+  // let's see if we have a current storage object we can migrate from
+  AbstractSqlMigrationReader *reader = getMigrationReader(_storage);
+  AbstractSqlMigrationWriter *writer = getMigrationWriter(storage);
+  if(reader && writer) {
+    qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
+    delete _storage;
+    _storage = 0;
+    delete storage;
+    storage = 0;
+    if(reader->migrateTo(writer)) {
+      qDebug() << "Migration finished!";
+      saveBackendSettings(backend, settings);
+      return true;
+    }
     return false;
-  }
-  AbstractSqlMigrationWriter *writer = sqlStorage->createMigrationWriter();
-  if(!writer) {
     qWarning() << qPrintable(QString("Core::migrateDb(): unable to migrate storage backend! (No migration writer for %1)").arg(backend));
-    return false;
   }
 
-  qDebug() << qPrintable(QString("Migrating Storage backend %1 to %2...").arg(_storage->displayName(), storage->displayName()));
-  delete _storage;
-  _storage = 0;
-  delete storage;
-  storage = 0;
-  if(reader->migrateTo(writer)) {
-    qDebug() << "Migration finished!";
-    saveBackendSettings(backend, settings);
-    return true;
+  // inform the user why we cannot merge
+  if(!_storage) {
+    qWarning() << "No currently active backend. Skipping migration.";
+  } else if(!reader) {
+    qWarning() << "Currently active backend does not support migration:" << qPrintable(_storage->displayName());
   }
-  return false;
+  if(writer) {
+    qWarning() << "New backend does not support migration:" << qPrintable(backend);
+  }
+
+  // so we were unable to merge, but let's create a user \o/
+  _storage = storage;
+  createUser();
+  return true;
 }
 
-bool Core::switchBackend(const QString &backend) {
-  if(!_storageBackends.contains(backend)) {
-    qWarning() << qPrintable(QString("Core::switchBackend(): unsupported backend: %1").arg(backend));
-    qWarning() << "    supported backends:" << qPrintable(QStringList(_storageBackends.keys()).join(", "));
-    return false;
+void Core::createUser() {
+  QTextStream out(stdout);
+  QTextStream in(stdin);
+  out << "Add a new user:" << endl;
+  out << "Username: ";
+  out.flush();
+  QString username = in.readLine().trimmed();
+
+  disableStdInEcho();
+  out << "Password: ";
+  out.flush();
+  QString password = in.readLine().trimmed();
+  out << endl;
+  out << "Repeat Password: ";
+  out.flush();
+  QString password2 = in.readLine().trimmed();
+  out << endl;
+  enableStdInEcho();
+
+  if(password != password2) {
+    qWarning() << "Passwords don't match!";
+    return;
+  }
+  if(password.isEmpty()) {
+    qWarning() << "Password is empty!";
+    return;
   }
 
-  Storage *storage = _storageBackends[backend];
-  QVariantMap settings = promptForSettings(storage->setupKeys());
+  if(_configured && _storage->addUser(username, password).isValid()) {
+    out << "Added user " << username << " successfully!" << endl;
+  } else {
+    qWarning() << "Unable to add user:" << qPrintable(username);
+  }
+}
 
-  bool ok = initStorage(backend, settings, true /* initial setup is allowed */);
-  if(ok) {
-    saveBackendSettings(backend, settings);
-    qWarning() << "Switched backend to:" << qPrintable(backend);
+void Core::changeUserPass(const QString &username) {
+  QTextStream out(stdout);
+  QTextStream in(stdin);
+  UserId userId = _storage->getUserId(username);
+  if(!userId.isValid()) {
+    out << "User " << username << " does not exist." << endl;
+    return;
+  }
+
+  out << "Change password for user: " << username << endl;
+
+  disableStdInEcho();
+  out << "New Password: ";
+  out.flush();
+  QString password = in.readLine().trimmed();
+  out << endl;
+  out << "Repeat Password: ";
+  out.flush();
+  QString password2 = in.readLine().trimmed();
+  out << endl;
+  enableStdInEcho();
+
+  if(password != password2) {
+    qWarning() << "Passwords don't match!";
+    return;
+  }
+  if(password.isEmpty()) {
+    qWarning() << "Password is empty!";
+    return;
+  }
+
+  if(_configured && _storage->updateUser(userId, password)) {
+    out << "Password changed successfuly!" << endl;
   } else {
-    qWarning() << "Failed to switch backend to:" << qPrintable(backend);
+    qWarning() << "Failed to change password!";
+  }
+}
+
+AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage) {
+  if(!storage)
+    return 0;
+
+  AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
+  if(!sqlStorage) {
+    qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
+    return 0;
   }
-  return ok;
+
+  return sqlStorage->createMigrationReader();
+}
+
+AbstractSqlMigrationWriter *Core::getMigrationWriter(Storage *storage) {
+  if(!storage)
+    return 0;
+
+  AbstractSqlStorage *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
+  if(!sqlStorage) {
+    qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
+    return 0;
+  }
+
+  return sqlStorage->createMigrationWriter();
 }
 
 void Core::saveBackendSettings(const QString &backend, const QVariantMap &settings) {
@@ -793,36 +953,75 @@ void Core::saveBackendSettings(const QString &backend, const QVariantMap &settin
   CoreSettings().setStorageSettings(dbsettings);
 }
 
-QVariantMap Core::promptForSettings(const QVariantMap &map) {
+QVariantMap Core::promptForSettings(const Storage *storage) {
   QVariantMap settings;
-  if(map.isEmpty())
+
+  QStringList keys = storage->setupKeys();
+  if(keys.isEmpty())
     return settings;
 
   QTextStream out(stdout);
   QTextStream in(stdin);
-  out << "!!!Warning: echo mode is always on even if asked for a password!!!" << endl;
+  out << "Default values are in brackets" << endl;
 
-  QVariantMap::const_iterator iter;
+  QVariantMap defaults = storage->setupDefaults();
   QString value;
-  for(iter = map.constBegin(); iter != map.constEnd(); iter++) {
-    out << iter.key() << " (" << iter.value().toString() << "): ";
+  foreach(QString key, keys) {
+    QVariant val;
+    if(defaults.contains(key)) {
+      val = defaults[key];
+    }
+    out << key;
+    if(!val.toString().isEmpty()) {
+      out << " (" << val.toString() << ")";
+    }
+    out << ": ";
     out.flush();
-    value = in.readLine();
 
-    if(value.isEmpty()) {
-      settings[iter.key()] = iter.value();
-    } else {
-      value = value.trimmed();
-      QVariant val;
-      switch(iter.value().type()) {
+    bool noEcho = QString("password").toLower().startsWith(key.toLower());
+    if(noEcho) {
+      disableStdInEcho();
+    }
+    value = in.readLine().trimmed();
+    if(noEcho) {
+      out << endl;
+      enableStdInEcho();
+    }
+
+    if(!value.isEmpty()) {
+      switch(defaults[key].type()) {
       case QVariant::Int:
        val = QVariant(value.toInt());
        break;
       default:
        val = QVariant(value);
       }
-      settings[iter.key()] = val;
     }
+    settings[key] = val;
   }
   return settings;
 }
+
+
+#ifdef Q_OS_WIN32
+void Core::stdInEcho(bool on) {
+  HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
+  DWORD mode = 0;
+  GetConsoleMode(hStdin, &mode);
+  if(on)
+    mode |= ENABLE_ECHO_INPUT;
+  else
+    mode &= ~ENABLE_ECHO_INPUT;
+  SetConsoleMode(hStdin, mode);
+}
+#else
+void Core::stdInEcho(bool on) {
+  termios t;
+  tcgetattr(STDIN_FILENO, &t);
+  if(on)
+    t.c_lflag |= ECHO;
+  else
+    t.c_lflag &= ~ECHO;
+  tcsetattr(STDIN_FILENO, TCSANOW, &t);
+}
+#endif /* Q_OS_WIN32 */