Fixes #682 - Core crashes on client connection
[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 <QCoreApplication>
22
23 #include "core.h"
24 #include "coresession.h"
25 #include "coresettings.h"
26 #include "quassel.h"
27 #include "signalproxy.h"
28 #include "sqlitestorage.h"
29 #include "network.h"
30 #include "logger.h"
31
32 #include "util.h"
33
34 // migration related
35 #include <QFile>
36
37 // ==============================
38 //  Custom Events
39 // ==============================
40 const int Core::AddClientEventId = QEvent::registerEventType();
41
42 class AddClientEvent : public QEvent {
43 public:
44   AddClientEvent(QTcpSocket *socket, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), socket(socket), userId(uid) {}
45   QTcpSocket *socket;
46   UserId userId;
47 };
48
49
50 // ==============================
51 //  Core
52 // ==============================
53 Core *Core::instanceptr = 0;
54
55 Core *Core::instance() {
56   if(instanceptr) return instanceptr;
57   instanceptr = new Core();
58   instanceptr->init();
59   return instanceptr;
60 }
61
62 void Core::destroy() {
63   delete instanceptr;
64   instanceptr = 0;
65 }
66
67 Core::Core()
68   : _storage(0)
69 {
70   _startTime = QDateTime::currentDateTime().toUTC();  // for uptime :)
71
72   Quassel::loadTranslation(QLocale::system());
73
74   // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
75   // Move settings, note this does not delete the old files
76 #ifdef Q_WS_MAC
77     QSettings newSettings("quassel-irc.org", "quasselcore");
78 #else
79
80 # ifdef Q_WS_WIN
81     QSettings::Format format = QSettings::IniFormat;
82 # else
83     QSettings::Format format = QSettings::NativeFormat;
84 # endif
85     QString newFilePath = Quassel::configDirPath() + "quasselcore"
86     + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
87     QSettings newSettings(newFilePath, format);
88 #endif /* Q_WS_MAC */
89
90   if(newSettings.value("Config/Version").toUInt() == 0) {
91 #   ifdef Q_WS_MAC
92     QString org = "quassel-irc.org";
93 #   else
94     QString org = "Quassel Project";
95 #   endif
96     QSettings oldSettings(org, "Quassel Core");
97     if(oldSettings.allKeys().count()) {
98       qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your core settings...";
99       foreach(QString key, oldSettings.allKeys())
100         newSettings.setValue(key, oldSettings.value(key));
101       newSettings.setValue("Config/Version", 1);
102       qWarning() << "*   Your core settings have been migrated to" << newSettings.fileName();
103
104 #ifndef Q_WS_MAC /* we don't need to move the db and cert for mac */
105 #ifdef Q_OS_WIN32
106       QString quasselDir = qgetenv("APPDATA") + "/quassel/";
107 #elif defined Q_WS_MAC
108       QString quasselDir = QDir::homePath() + "/Library/Application Support/Quassel/";
109 #else
110       QString quasselDir = QDir::homePath() + "/.quassel/";
111 #endif
112
113       QFileInfo info(Quassel::configDirPath() + "quassel-storage.sqlite");
114       if(!info.exists()) {
115       // move database, if we found it
116         QFile oldDb(quasselDir + "quassel-storage.sqlite");
117         if(oldDb.exists()) {
118           bool success = oldDb.rename(Quassel::configDirPath() + "quassel-storage.sqlite");
119           if(success)
120             qWarning() << "*   Your database has been moved to" << Quassel::configDirPath() + "quassel-storage.sqlite";
121           else
122             qWarning() << "!!! Moving your database has failed. Please move it manually into" << Quassel::configDirPath();
123         }
124       }
125       // move certificate
126       QFileInfo certInfo(quasselDir + "quasselCert.pem");
127       if(certInfo.exists()) {
128         QFile cert(quasselDir + "quasselCert.pem");
129         bool success = cert.rename(Quassel::configDirPath() + "quasselCert.pem");
130         if(success)
131           qWarning() << "*   Your certificate has been moved to" << Quassel::configDirPath() + "quasselCert.pem";
132         else
133           qWarning() << "!!! Moving your certificate has failed. Please move it manually into" << Quassel::configDirPath();
134       }
135 #endif /* !Q_WS_MAC */
136       qWarning() << "*** Migration completed.\n\n";
137     }
138   }
139   // MIGRATION end
140
141   // check settings version
142   // so far, we only have 1
143   CoreSettings s;
144   if(s.version() != 1) {
145     qCritical() << "Invalid core settings version, terminating!";
146     exit(EXIT_FAILURE);
147   }
148
149   // Register storage backends here!
150   registerStorageBackend(new SqliteStorage(this));
151
152   connect(&_storageSyncTimer, SIGNAL(timeout()), this, SLOT(syncStorage()));
153   _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
154 }
155
156 void Core::init() {
157   CoreSettings cs;
158   _configured = initStorage(cs.storageSettings().toMap());
159
160   if(!_configured) {
161     if(!_storageBackends.count()) {
162       qWarning() << qPrintable(tr("Could not initialize any storage backend! Exiting..."));
163       qWarning() << qPrintable(tr("Currently, Quassel only supports SQLite3. You need to build your\n"
164                                   "Qt library with the sqlite plugin enabled in order for quasselcore\n"
165                                   "to work."));
166       exit(1); // TODO make this less brutal (especially for mono client -> popup)
167     }
168     qWarning() << "Core is currently not configured! Please connect with a Quassel Client for basic setup.";
169   }
170
171   connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
172   connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
173   if(!startListening()) exit(1); // TODO make this less brutal
174 }
175
176 Core::~Core() {
177   foreach(QTcpSocket *socket, blocksizes.keys()) {
178     socket->disconnectFromHost();  // disconnect non authed clients
179   }
180   qDeleteAll(sessions);
181   qDeleteAll(_storageBackends);
182 }
183
184 /*** Session Restore ***/
185
186 void Core::saveState() {
187   CoreSettings s;
188   QVariantMap state;
189   QVariantList activeSessions;
190   foreach(UserId user, instance()->sessions.keys()) activeSessions << QVariant::fromValue<UserId>(user);
191   state["CoreStateVersion"] = 1;
192   state["ActiveSessions"] = activeSessions;
193   s.setCoreState(state);
194 }
195
196 void Core::restoreState() {
197   if(!instance()->_configured) {
198     // qWarning() << qPrintable(tr("Cannot restore a state for an unconfigured core!"));
199     return;
200   }
201   if(instance()->sessions.count()) {
202     qWarning() << qPrintable(tr("Calling restoreState() even though active sessions exist!"));
203     return;
204   }
205   CoreSettings s;
206   /* We don't check, since we are at the first version since switching to Git
207   uint statever = s.coreState().toMap()["CoreStateVersion"].toUInt();
208   if(statever < 1) {
209     qWarning() << qPrintable(tr("Core state too old, ignoring..."));
210     return;
211   }
212   */
213   QVariantList activeSessions = s.coreState().toMap()["ActiveSessions"].toList();
214   if(activeSessions.count() > 0) {
215     quInfo() << "Restoring previous core state...";
216     foreach(QVariant v, activeSessions) {
217       UserId user = v.value<UserId>();
218       instance()->createSession(user, true);
219     }
220   }
221 }
222
223 /*** Core Setup ***/
224 QString Core::setupCoreForInternalUsage() {
225   Q_ASSERT(!_storageBackends.isEmpty());
226   QVariantMap setupData;
227   qsrand(QDateTime::currentDateTime().toTime_t());
228   int pass = 0;
229   for(int i = 0; i < 10; i++) {
230     pass *= 10;
231     pass += qrand() % 10;
232   }
233   setupData["AdminUser"] = "AdminUser";
234   setupData["AdminPasswd"] = QString::number(pass);
235   setupData["Backend"] = _storageBackends[_storageBackends.keys().first()]->displayName();
236   return setupCore(setupData);
237 }
238
239 QString Core::setupCore(QVariantMap setupData) {
240   QString user = setupData.take("AdminUser").toString();
241   QString password = setupData.take("AdminPasswd").toString();
242   if(user.isEmpty() || password.isEmpty()) {
243     return tr("Admin user or password not set.");
244   }
245   _configured = initStorage(setupData, true);
246   if(!_configured) {
247     return tr("Could not setup storage!");
248   }
249   CoreSettings s;
250   s.setStorageSettings(setupData);
251   quInfo() << qPrintable(tr("Creating admin user..."));
252   _storage->addUser(user, password);
253   startListening();  // TODO check when we need this
254   return QString();
255 }
256
257 /*** Storage Handling ***/
258
259 bool Core::registerStorageBackend(Storage *backend) {
260   if(backend->isAvailable()) {
261     _storageBackends[backend->displayName()] = backend;
262     return true;
263   } else {
264     backend->deleteLater();
265     return false;
266   }
267 }
268
269 void Core::unregisterStorageBackend(Storage *backend) {
270   _storageBackends.remove(backend->displayName());
271   backend->deleteLater();
272 }
273
274 // old db settings:
275 // "Type" => "sqlite"
276 bool Core::initStorage(QVariantMap dbSettings, bool setup) {
277   _storage = 0;
278
279   QString backend = dbSettings["Backend"].toString();
280   if(backend.isEmpty()) {
281     return false;
282   }
283
284   Storage *storage = 0;
285   if(_storageBackends.contains(backend)) {
286     storage = _storageBackends[backend];
287   } else {
288     qCritical() << "Selected storage backend is not available:" << backend;
289     return false;
290   }
291
292   Storage::State storageState = storage->init(dbSettings);
293   switch(storageState) {
294   case Storage::NeedsSetup:
295     if(!setup)
296       return false; // trigger setup process
297     if(storage->setup(dbSettings))
298       return initStorage(dbSettings, false);
299     // if setup wasn't successfull we mark the backend as unavailable
300   case Storage::NotAvailable:
301     qCritical() << "Selected storage backend is not available:" << backend;
302     storage->deleteLater();
303     _storageBackends.remove(backend);
304     storage = 0;
305     return false;
306   case Storage::IsReady:
307     // delete all other backends
308     foreach(Storage *s, _storageBackends.values()) {
309       if(s != storage) s->deleteLater();
310     }
311     _storageBackends.clear();
312     connect(storage, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)), this, SIGNAL(bufferInfoUpdated(UserId, const BufferInfo &)));
313   }
314   _storage = storage;
315   return true;
316 }
317
318 void Core::syncStorage() {
319   if(_storage)
320     _storage->sync();
321 }
322
323 /*** Storage Access ***/
324 bool Core::createNetwork(UserId user, NetworkInfo &info) {
325   NetworkId networkId = instance()->_storage->createNetwork(user, info);
326   if(!networkId.isValid())
327     return false;
328
329   info.networkId = networkId;
330   return true;
331 }
332
333 /*** Network Management ***/
334
335 bool Core::startListening() {
336   // in mono mode we only start a local port if a port is specified in the cli call
337   if(Quassel::runMode() == Quassel::Monolithic && !Quassel::isOptionSet("port"))
338     return true;
339
340   bool success = false;
341   uint port = Quassel::optionValue("port").toUInt();
342
343   const QString listen = Quassel::optionValue("listen");
344   const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
345   if(listen_list.size() > 0) {
346     foreach (const QString listen_term, listen_list) {  // TODO: handle multiple interfaces for same TCP version gracefully
347       QHostAddress addr;
348       if(!addr.setAddress(listen_term)) {
349         qCritical() << qPrintable(
350           tr("Invalid listen address %1")
351             .arg(listen_term)
352         );
353       } else {
354         switch(addr.protocol()) {
355           case QAbstractSocket::IPv4Protocol:
356             if(_server.listen(addr, port)) {
357               quInfo() << qPrintable(
358                 tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
359                   .arg(addr.toString())
360                   .arg(_server.serverPort())
361                   .arg(Quassel::buildInfo().protocolVersion)
362               );
363               success = true;
364             } else
365               quWarning() << qPrintable(
366                 tr("Could not open IPv4 interface %1:%2: %3")
367                   .arg(addr.toString())
368                   .arg(port)
369                   .arg(_server.errorString()));
370             break;
371           case QAbstractSocket::IPv6Protocol:
372             if(_v6server.listen(addr, port)) {
373               quInfo() << qPrintable(
374                 tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
375                   .arg(addr.toString())
376                   .arg(_v6server.serverPort())
377                   .arg(Quassel::buildInfo().protocolVersion)
378               );
379               success = true;
380             } else {
381               // if v4 succeeded on Any, the port will be already in use - don't display the error then
382               // FIXME: handle this more sanely, make sure we can listen to both v4 and v6 by default!
383               if(!success || _v6server.serverError() != QAbstractSocket::AddressInUseError)
384                 quWarning() << qPrintable(
385                   tr("Could not open IPv6 interface %1:%2: %3")
386                   .arg(addr.toString())
387                   .arg(port)
388                   .arg(_v6server.errorString()));
389             }
390             break;
391           default:
392             qCritical() << qPrintable(
393               tr("Invalid listen address %1, unknown network protocol")
394                   .arg(listen_term)
395             );
396             break;
397         }
398       }
399     }
400   }
401   if(!success)
402     quError() << qPrintable(tr("Could not open any network interfaces to listen on!"));
403
404   return success;
405 }
406
407 void Core::stopListening(const QString &reason) {
408   bool wasListening = false;
409   if(_server.isListening()) {
410     wasListening = true;
411     _server.close();
412   }
413   if(_v6server.isListening()) {
414     wasListening = true;
415     _v6server.close();
416   }
417   if(wasListening) {
418     if(reason.isEmpty())
419       quInfo() << "No longer listening for GUI clients.";
420     else
421       quInfo() << qPrintable(reason);
422   }
423 }
424
425 void Core::incomingConnection() {
426   QTcpServer *server = qobject_cast<QTcpServer *>(sender());
427   Q_ASSERT(server);
428   while(server->hasPendingConnections()) {
429     QTcpSocket *socket = server->nextPendingConnection();
430     connect(socket, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
431     connect(socket, SIGNAL(readyRead()), this, SLOT(clientHasData()));
432     connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
433
434     QVariantMap clientInfo;
435     blocksizes.insert(socket, (quint32)0);
436     quInfo() << qPrintable(tr("Client connected from"))  << qPrintable(socket->peerAddress().toString());
437
438     if(!_configured) {
439       stopListening(tr("Closing server for basic setup."));
440     }
441   }
442 }
443
444 void Core::clientHasData() {
445   QTcpSocket *socket = dynamic_cast<QTcpSocket*>(sender());
446   Q_ASSERT(socket && blocksizes.contains(socket));
447   QVariant item;
448   while(SignalProxy::readDataFromDevice(socket, blocksizes[socket], item)) {
449     QVariantMap msg = item.toMap();
450     processClientMessage(socket, msg);
451     if(!blocksizes.contains(socket)) break;  // this socket is no longer ours to handle!
452   }
453 }
454
455 void Core::processClientMessage(QTcpSocket *socket, const QVariantMap &msg) {
456   if(!msg.contains("MsgType")) {
457     // Client is way too old, does not even use the current init format
458     qWarning() << qPrintable(tr("Antique client trying to connect... refusing."));
459     socket->close();
460     return;
461   }
462   // OK, so we have at least an init message format we can understand
463   if(msg["MsgType"] == "ClientInit") {
464     QVariantMap reply;
465
466     // Just version information -- check it!
467     uint ver = msg["ProtocolVersion"].toUInt();
468     if(ver < Quassel::buildInfo().coreNeedsProtocol) {
469       reply["MsgType"] = "ClientInitReject";
470       reply["Error"] = tr("<b>Your Quassel Client is too old!</b><br>"
471       "This core needs at least client/core protocol version %1.<br>"
472       "Please consider upgrading your client.").arg(Quassel::buildInfo().coreNeedsProtocol);
473       SignalProxy::writeDataToDevice(socket, reply);
474       qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("too old, rejecting."));
475       socket->close(); return;
476     }
477
478     reply["CoreVersion"] = Quassel::buildInfo().fancyVersionString;
479     reply["CoreDate"] = Quassel::buildInfo().buildDate;
480     reply["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
481     // TODO: Make the core info configurable
482     int uptime = startTime().secsTo(QDateTime::currentDateTime().toUTC());
483     int updays = uptime / 86400; uptime %= 86400;
484     int uphours = uptime / 3600; uptime %= 3600;
485     int upmins = uptime / 60;
486     reply["CoreInfo"] = tr("<b>Quassel Core Version %1</b><br>"
487                            "Built: %2<br>"
488                            "Up %3d%4h%5m (since %6)").arg(Quassel::buildInfo().fancyVersionString)
489                                                      .arg(Quassel::buildInfo().buildDate)
490       .arg(updays).arg(uphours,2,10,QChar('0')).arg(upmins,2,10,QChar('0')).arg(startTime().toString(Qt::TextDate));
491
492 #ifdef HAVE_SSL
493     SslServer *sslServer = qobject_cast<SslServer *>(&_server);
494     QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket);
495     bool supportSsl = (bool)sslServer && (bool)sslSocket && sslServer->isCertValid();
496 #else
497     bool supportSsl = false;
498 #endif
499
500 #ifndef QT_NO_COMPRESS
501     bool supportsCompression = true;
502 #else
503     bool supportsCompression = false;
504 #endif
505
506     reply["SupportSsl"] = supportSsl;
507     reply["SupportsCompression"] = supportsCompression;
508     // switch to ssl/compression after client has been informed about our capabilities (see below)
509
510     reply["LoginEnabled"] = true;
511
512     // check if we are configured, start wizard otherwise
513     if(!_configured) {
514       reply["Configured"] = false;
515       QList<QVariant> backends;
516       foreach(Storage *backend, _storageBackends.values()) {
517         QVariantMap v;
518         v["DisplayName"] = backend->displayName();
519         v["Description"] = backend->description();
520         backends.append(v);
521       }
522       reply["StorageBackends"] = backends;
523       reply["LoginEnabled"] = false;
524     } else {
525       reply["Configured"] = true;
526     }
527     clientInfo[socket] = msg; // store for future reference
528     reply["MsgType"] = "ClientInitAck";
529     SignalProxy::writeDataToDevice(socket, reply);
530
531 #ifdef HAVE_SSL
532     // after we told the client that we are ssl capable we switch to ssl mode
533     if(supportSsl && msg["UseSsl"].toBool()) {
534       qDebug() << qPrintable(tr("Starting TLS for Client:"))  << qPrintable(socket->peerAddress().toString());
535       connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
536       sslSocket->startServerEncryption();
537     }
538 #endif
539
540 #ifndef QT_NO_COMPRESS
541     if(supportsCompression && msg["UseCompression"].toBool()) {
542       socket->setProperty("UseCompression", true);
543       qDebug() << "Using compression for Client:" << qPrintable(socket->peerAddress().toString());
544     }
545 #endif
546
547   } else {
548     // for the rest, we need an initialized connection
549     if(!clientInfo.contains(socket)) {
550       QVariantMap reply;
551       reply["MsgType"] = "ClientLoginReject";
552       reply["Error"] = tr("<b>Client not initialized!</b><br>You need to send an init message before trying to login.");
553       SignalProxy::writeDataToDevice(socket, reply);
554       qWarning() << qPrintable(tr("Client")) << qPrintable(socket->peerAddress().toString()) << qPrintable(tr("did not send an init message before trying to login, rejecting."));
555       socket->close(); return;
556     }
557     if(msg["MsgType"] == "CoreSetupData") {
558       QVariantMap reply;
559       QString result = setupCore(msg["SetupData"].toMap());
560       if(!result.isEmpty()) {
561         reply["MsgType"] = "CoreSetupReject";
562         reply["Error"] = result;
563       } else {
564         reply["MsgType"] = "CoreSetupAck";
565       }
566       SignalProxy::writeDataToDevice(socket, reply);
567     } else if(msg["MsgType"] == "ClientLogin") {
568       QVariantMap reply;
569       UserId uid = _storage->validateUser(msg["User"].toString(), msg["Password"].toString());
570       if(uid == 0) {
571         reply["MsgType"] = "ClientLoginReject";
572         reply["Error"] = tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.");
573         SignalProxy::writeDataToDevice(socket, reply);
574         return;
575       }
576       reply["MsgType"] = "ClientLoginAck";
577       SignalProxy::writeDataToDevice(socket, reply);
578       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()));
579       setupClientSession(socket, uid);
580     }
581   }
582 }
583
584 // Potentially called during the initialization phase (before handing the connection off to the session)
585 void Core::clientDisconnected() {
586   QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
587   if(socket) {
588     // here it's safe to call methods on socket!
589     quInfo() << qPrintable(tr("Non-authed client disconnected.")) << qPrintable(socket->peerAddress().toString());
590     blocksizes.remove(socket);
591     clientInfo.remove(socket);
592     socket->deleteLater();
593   } else {
594     // we have to crawl through the hashes and see if we find a victim to remove
595     qDebug() << qPrintable(tr("Non-authed client disconnected. (socket allready destroyed)"));
596
597     // DO NOT CALL ANY METHODS ON socket!!
598     socket = static_cast<QTcpSocket *>(sender());
599
600     QHash<QTcpSocket *, quint32>::iterator blockSizeIter = blocksizes.begin();
601     while(blockSizeIter != blocksizes.end()) {
602       if(blockSizeIter.key() == socket) {
603         blockSizeIter = blocksizes.erase(blockSizeIter);
604       } else {
605         blockSizeIter++;
606       }
607     }
608
609     QHash<QTcpSocket *, QVariantMap>::iterator clientInfoIter = clientInfo.begin();
610     while(clientInfoIter != clientInfo.end()) {
611       if(clientInfoIter.key() == socket) {
612         clientInfoIter = clientInfo.erase(clientInfoIter);
613       } else {
614         clientInfoIter++;
615       }
616     }
617   }
618
619
620   // make server listen again if still not configured
621   if (!_configured) {
622     startListening();
623   }
624
625   // TODO remove unneeded sessions - if necessary/possible...
626   // Suggestion: kill sessions if they are not connected to any network and client.
627 }
628
629 void Core::setupClientSession(QTcpSocket *socket, UserId uid) {
630   // From now on everything is handled by the client session
631   disconnect(socket, 0, this, 0);
632   socket->flush();
633   blocksizes.remove(socket);
634   clientInfo.remove(socket);
635
636   // Find or create session for validated user
637   SessionThread *session;
638   if(sessions.contains(uid)) {
639     session = sessions[uid];
640   } else {
641     session = createSession(uid);
642     if(!session) {
643       qWarning() << qPrintable(tr("Could not initialize session for client:")) << qPrintable(socket->peerAddress().toString());
644       socket->close();
645       return;
646     }
647   }
648
649   // as we are currently handling an event triggered by incoming data on this socket
650   // it is unsafe to directly move the socket to the client thread.
651   QCoreApplication::postEvent(this, new AddClientEvent(socket, uid));
652 }
653
654 void Core::customEvent(QEvent *event) {
655   if(event->type() == AddClientEventId) {
656     AddClientEvent *addClientEvent = static_cast<AddClientEvent *>(event);
657     addClientHelper(addClientEvent->socket, addClientEvent->userId);
658     return;
659   }
660 }
661
662 void Core::addClientHelper(QTcpSocket *socket, UserId uid) {
663   // Find or create session for validated user
664   if(!sessions.contains(uid)) {
665     qWarning() << qPrintable(tr("Could not find a session for client:")) << qPrintable(socket->peerAddress().toString());
666     socket->close();
667     return;
668   }
669
670   SessionThread *session = sessions[uid];
671   session->addClient(socket);
672 }
673
674 void Core::setupInternalClientSession(SignalProxy *proxy) {
675   if(!_configured) {
676     stopListening();
677     setupCoreForInternalUsage();
678   }
679
680   UserId uid;
681   if(_storage) {
682     uid = _storage->internalUser();
683   } else {
684     qWarning() << "Core::setupInternalClientSession(): You're trying to run monolithic Quassel with an unusable Backend! Go fix it!";
685     return;
686   }
687
688   // Find or create session for validated user
689   SessionThread *sess;
690   if(sessions.contains(uid))
691     sess = sessions[uid];
692   else
693     sess = createSession(uid);
694   sess->addClient(proxy);
695 }
696
697 SessionThread *Core::createSession(UserId uid, bool restore) {
698   if(sessions.contains(uid)) {
699     qWarning() << "Calling createSession() when a session for the user already exists!";
700     return 0;
701   }
702   SessionThread *sess = new SessionThread(uid, restore, this);
703   sessions[uid] = sess;
704   sess->start();
705   return sess;
706 }
707
708 #ifdef HAVE_SSL
709 void Core::sslErrors(const QList<QSslError> &errors) {
710   Q_UNUSED(errors);
711   QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
712   if(socket)
713     socket->ignoreSslErrors();
714 }
715 #endif
716
717 void Core::socketError(QAbstractSocket::SocketError err) {
718   QAbstractSocket *socket = qobject_cast<QAbstractSocket *>(sender());
719   if(socket && err != QAbstractSocket::RemoteHostClosedError)
720     qWarning() << "Core::socketError()" << socket << err << socket->errorString();
721 }