Default to sqlite backend in core creation wizard
[quassel.git] / src / core / core.cpp
index 2b158ab..11db682 100644 (file)
@@ -1,5 +1,5 @@
 /***************************************************************************
- *   Copyright (C) 2005-2014 by the Quassel Project                        *
+ *   Copyright (C) 2005-2016 by the Quassel Project                        *
  *   devel@quassel-irc.org                                                 *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
 #include "sqlitestorage.h"
 #include "util.h"
 
-#include "protocols/legacy/legacypeer.h"
-
 // migration related
 #include <QFile>
-#ifdef Q_OS_WIN32
+#ifdef Q_OS_WIN
 #  include <windows.h>
 #else
 #  include <unistd.h>
 #  include <termios.h>
-#endif /* Q_OS_WIN32 */
+#endif /* Q_OS_WIN */
 
 #ifdef HAVE_UMASK
 #  include <sys/types.h>
@@ -96,11 +94,11 @@ Core::Core()
 
     // 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
+#ifdef Q_OS_MAC
     QSettings newSettings("quassel-irc.org", "quasselcore");
 #else
 
-# ifdef Q_WS_WIN
+# ifdef Q_OS_WIN
     QSettings::Format format = QSettings::IniFormat;
 # else
     QSettings::Format format = QSettings::NativeFormat;
@@ -108,10 +106,10 @@ Core::Core()
     QString newFilePath = Quassel::configDirPath() + "quasselcore"
                           + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
     QSettings newSettings(newFilePath, format);
-#endif /* Q_WS_MAC */
+#endif /* Q_OS_MAC */
 
     if (newSettings.value("Config/Version").toUInt() == 0) {
-#   ifdef Q_WS_MAC
+#   ifdef Q_OS_MAC
         QString org = "quassel-irc.org";
 #   else
         QString org = "Quassel Project";
@@ -124,10 +122,10 @@ Core::Core()
             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
+#ifndef Q_OS_MAC /* we don't need to move the db and cert for mac */
+#ifdef Q_OS_WIN
             QString quasselDir = qgetenv("APPDATA") + "/quassel/";
-#elif defined Q_WS_MAC
+#elif defined Q_OS_MAC
             QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
 #else
             QString quasselDir = QDir::homePath() + "/.quassel/";
@@ -155,7 +153,7 @@ Core::Core()
                 else
                     qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
             }
-#endif /* !Q_WS_MAC */
+#endif /* !Q_OS_MAC */
             qWarning() << "*** Migration completed.\n\n";
         }
     }
@@ -200,13 +198,13 @@ void Core::init()
     }
 
     if (Quassel::isOptionSet("add-user")) {
-        createUser();
-        exit(0);
+        exit(createUser() ? EXIT_SUCCESS : EXIT_FAILURE);
+
     }
 
     if (Quassel::isOptionSet("change-userpass")) {
-        changeUserPass(Quassel::optionValue("change-userpass"));
-        exit(0);
+        exit(changeUserPass(Quassel::optionValue("change-userpass")) ?
+                       EXIT_SUCCESS : EXIT_FAILURE);
     }
 
     connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
@@ -224,7 +222,7 @@ Core::~Core()
     foreach(CoreAuthHandler *handler, _connectingClients) {
         handler->deleteLater(); // disconnect non authed clients
     }
-    qDeleteAll(sessions);
+    qDeleteAll(_sessions);
     qDeleteAll(_storageBackends);
 }
 
@@ -236,7 +234,8 @@ void Core::saveState()
     CoreSettings s;
     QVariantMap state;
     QVariantList activeSessions;
-    foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
+    foreach(UserId user, instance()->_sessions.keys())
+        activeSessions << QVariant::fromValue<UserId>(user);
     state["CoreStateVersion"] = 1;
     state["ActiveSessions"] = activeSessions;
     s.setCoreState(state);
@@ -249,7 +248,7 @@ void Core::restoreState()
         // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
         return;
     }
-    if (instance()->sessions.count()) {
+    if (instance()->_sessions.count()) {
         qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
         return;
     }
@@ -267,7 +266,7 @@ void Core::restoreState()
         quInfo() << "Restoring previous core state...";
         foreach(QVariant v, activeSessions) {
             UserId user = v.value<UserId>();
-            instance()->createSession(user, true);
+            instance()->sessionForUser(user, true);
         }
     }
 }
@@ -382,13 +381,10 @@ bool Core::initStorage(const QString &backend, const QVariantMap &settings, bool
             return false;  // trigger setup process
         if (storage->setup(settings))
             return initStorage(backend, settings, false);
-    // if setup wasn't successfull we mark the backend as unavailable
+    // if initialization wasn't successful, we quit to keep from coming up unconfigured
     case Storage::NotAvailable:
-        qCritical() << "Selected storage backend is not available:" << backend;
-        storage->deleteLater();
-        _storageBackends.remove(backend);
-        storage = 0;
-        return false;
+        qCritical() << "FATAL: Selected storage backend is not available:" << backend;
+        exit(EXIT_FAILURE);
     case Storage::IsReady:
         // delete all other backends
         _storageBackends.remove(backend);
@@ -432,6 +428,18 @@ bool Core::sslSupported()
 }
 
 
+bool Core::reloadCerts()
+{
+#ifdef HAVE_SSL
+    SslServer *sslServer = qobject_cast<SslServer *>(&instance()->_server);
+    return sslServer->reloadCerts();
+#else
+    // SSL not supported, don't mark configuration reload as failed
+    return true;
+#endif
+}
+
+
 bool Core::startListening()
 {
     // in mono mode we only start a local port if a port is specified in the cli call
@@ -582,19 +590,7 @@ void Core::setupClientSession(RemotePeer *peer, UserId uid)
     handler->deleteLater();
 
     // 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(peer->description());
-            peer->close();
-            peer->deleteLater();
-            return;
-        }
-    }
+    sessionForUser(uid);
 
     // 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.
@@ -615,14 +611,7 @@ void Core::customEvent(QEvent *event)
 void Core::addClientHelper(RemotePeer *peer, UserId uid)
 {
     // Find or create session for validated user
-    if (!sessions.contains(uid)) {
-        qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(peer->description());
-        peer->close();
-        peer->deleteLater();
-        return;
-    }
-
-    SessionThread *session = sessions[uid];
+    SessionThread *session = sessionForUser(uid);
     session->addClient(peer);
 }
 
@@ -648,26 +637,20 @@ void Core::setupInternalClientSession(InternalPeer *clientPeer)
     clientPeer->setPeer(corePeer);
 
     // Find or create session for validated user
-    SessionThread *sessionThread;
-    if (sessions.contains(uid))
-        sessionThread = sessions[uid];
-    else
-        sessionThread = createSession(uid);
-
+    SessionThread *sessionThread = sessionForUser(uid);
     sessionThread->addClient(corePeer);
 }
 
 
-SessionThread *Core::createSession(UserId uid, bool restore)
+SessionThread *Core::sessionForUser(UserId uid, bool restore)
 {
-    if (sessions.contains(uid)) {
-        qWarning() << "Calling createSession() when a session for the user already exists!";
-        return 0;
-    }
-    SessionThread *sess = new SessionThread(uid, restore, this);
-    sessions[uid] = sess;
-    sess->start();
-    return sess;
+    if (_sessions.contains(uid))
+        return _sessions[uid];
+
+    SessionThread *session = new SessionThread(uid, restore, this);
+    _sessions[uid] = session;
+    session->start();
+    return session;
 }
 
 
@@ -686,6 +669,7 @@ QVariantList Core::backendInfo()
         v["Description"] = backend->description();
         v["SetupKeys"] = backend->setupKeys();
         v["SetupDefaults"] = backend->setupDefaults();
+        v["IsDefault"] = isStorageBackendDefault(backend);
         backends.append(v);
     }
     return backends;
@@ -768,7 +752,7 @@ bool Core::selectBackend(const QString &backend)
 }
 
 
-void Core::createUser()
+bool Core::createUser()
 {
     QTextStream out(stdout);
     QTextStream in(stdin);
@@ -790,30 +774,32 @@ void Core::createUser()
 
     if (password != password2) {
         qWarning() << "Passwords don't match!";
-        return;
+        return false;
     }
     if (password.isEmpty()) {
         qWarning() << "Password is empty!";
-        return;
+        return false;
     }
 
     if (_configured && _storage->addUser(username, password).isValid()) {
         out << "Added user " << username << " successfully!" << endl;
+        return true;
     }
     else {
         qWarning() << "Unable to add user:" << qPrintable(username);
+        return false;
     }
 }
 
 
-void Core::changeUserPass(const QString &username)
+bool 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;
+        return false;
     }
 
     out << "Change password for user: " << username << endl;
@@ -831,22 +817,33 @@ void Core::changeUserPass(const QString &username)
 
     if (password != password2) {
         qWarning() << "Passwords don't match!";
-        return;
+        return false;
     }
     if (password.isEmpty()) {
         qWarning() << "Password is empty!";
-        return;
+        return false;
     }
 
     if (_configured && _storage->updateUser(userId, password)) {
         out << "Password changed successfully!" << endl;
+        return true;
     }
     else {
         qWarning() << "Failed to change password!";
+        return false;
     }
 }
 
 
+bool Core::changeUserPassword(UserId userId, const QString &password)
+{
+    if (!isConfigured() || !userId.isValid())
+        return false;
+
+    return instance()->_storage->updateUser(userId, password);
+}
+
+
 AbstractSqlMigrationReader *Core::getMigrationReader(Storage *storage)
 {
     if (!storage)
@@ -937,7 +934,7 @@ QVariantMap Core::promptForSettings(const Storage *storage)
 }
 
 
-#ifdef Q_OS_WIN32
+#ifdef Q_OS_WIN
 void Core::stdInEcho(bool on)
 {
     HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
@@ -964,4 +961,4 @@ void Core::stdInEcho(bool on)
 }
 
 
-#endif /* Q_OS_WIN32 */
+#endif /* Q_OS_WIN */