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