Persist Blowfish keys in the database
[quassel.git] / src / core / coresession.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "coresession.h"
22
23 #include <QtScript>
24
25 #include "core.h"
26 #include "coreuserinputhandler.h"
27 #include "corebuffersyncer.h"
28 #include "corebacklogmanager.h"
29 #include "corebufferviewmanager.h"
30 #include "coredccconfig.h"
31 #include "coreeventmanager.h"
32 #include "coreidentity.h"
33 #include "coreignorelistmanager.h"
34 #include "coreirclisthelper.h"
35 #include "corenetwork.h"
36 #include "corenetworkconfig.h"
37 #include "coresessioneventprocessor.h"
38 #include "coretransfermanager.h"
39 #include "coreusersettings.h"
40 #include "ctcpparser.h"
41 #include "eventstringifier.h"
42 #include "internalpeer.h"
43 #include "ircchannel.h"
44 #include "ircparser.h"
45 #include "ircuser.h"
46 #include "logger.h"
47 #include "messageevent.h"
48 #include "remotepeer.h"
49 #include "storage.h"
50 #include "util.h"
51
52
53 class ProcessMessagesEvent : public QEvent
54 {
55 public:
56     ProcessMessagesEvent() : QEvent(QEvent::User) {}
57 };
58
59
60 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
61     : QObject(parent),
62     _user(uid),
63     _signalProxy(new SignalProxy(SignalProxy::Server, this)),
64     _aliasManager(this),
65     _bufferSyncer(new CoreBufferSyncer(this)),
66     _backlogManager(new CoreBacklogManager(this)),
67     _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
68     _dccConfig(new CoreDccConfig(this)),
69     _ircListHelper(new CoreIrcListHelper(this)),
70     _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
71     _coreInfo(this),
72     _transferManager(new CoreTransferManager(this)),
73     _eventManager(new CoreEventManager(this)),
74     _eventStringifier(new EventStringifier(this)),
75     _sessionEventProcessor(new CoreSessionEventProcessor(this)),
76     _ctcpParser(new CtcpParser(this)),
77     _ircParser(new IrcParser(this)),
78     scriptEngine(new QScriptEngine(this)),
79     _processMessages(false),
80     _ignoreListManager(this),
81     _highlightRuleManager(this)
82 {
83     SignalProxy *p = signalProxy();
84     p->setHeartBeatInterval(30);
85     p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
86
87     connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
88
89     connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
90     connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
91
92     p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
93     p->attachSignal(this, SIGNAL(displayMsg(Message)));
94     p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
95
96     p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
97     p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
98     p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
99     p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
100
101     p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
102     p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
103     p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
104     p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
105
106     p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
107     p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
108
109     p->attachSlot(SIGNAL(kickClient(int)), this, SLOT(kickClient(int)));
110     p->attachSignal(this, SIGNAL(disconnectFromCore()));
111
112     loadSettings();
113     initScriptEngine();
114
115     eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
116     eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
117     eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
118     eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
119     eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
120     // some events need to be handled after msg generation
121     eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
122     eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
123
124     // periodically save our session state
125     connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
126
127     p->synchronize(_bufferSyncer);
128     p->synchronize(&aliasManager());
129     p->synchronize(_backlogManager);
130     p->synchronize(dccConfig());
131     p->synchronize(ircListHelper());
132     p->synchronize(networkConfig());
133     p->synchronize(&_coreInfo);
134     p->synchronize(&_ignoreListManager);
135     p->synchronize(&_highlightRuleManager);
136     p->synchronize(transferManager());
137     // Restore session state
138     if (restoreState)
139         restoreSessionState();
140
141     emit initialized();
142 }
143
144
145 CoreSession::~CoreSession()
146 {
147     saveSessionState();
148
149     /* Why partially duplicate CoreNetwork destructor?  When each CoreNetwork quits in the
150      * destructor, disconnections are processed in sequence for each object.  For many IRC servers
151      * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
152      *
153      * Here, CoreSession first calls disconnect on all networks, letting them all start
154      * disconnecting before beginning to sequentially wait for each network.  Ideally, after the
155      * first network is disconnected, the other networks will have already closed.  Worst-case may
156      * still wait [msecs wait time * num. of networks], but the risk should be much lower.
157      *
158      * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
159      * outside of deleting the whole CoreSession.
160      *
161      * If this proves to be problematic in the future, there's an alternative Qt signal-based system
162      * implemented in another pull request that guarentees a maximum amount of time to disconnect,
163      * but at the cost of more complex code.
164      *
165      * See https://github.com/quassel/quassel/pull/203
166      */
167
168     foreach(CoreNetwork *net, _networks.values()) {
169         // Request each network properly disconnect, but don't count as user-requested disconnect
170         if (net->socketConnected()) {
171             // Only try if the socket's fully connected (not initializing or disconnecting).
172             // Force an immediate disconnect, jumping the command queue.  Ensures the proper QUIT is
173             // shown even if other messages are queued.
174             net->disconnectFromIrc(false, QString(), false, true);
175         }
176     }
177
178     // Process the putCmd events that trigger the quit.  Without this, shutting down the core
179     // results in abrubtly closing the socket rather than sending the QUIT as expected.
180     QCoreApplication::processEvents();
181
182     foreach(CoreNetwork *net, _networks.values()) {
183         // Wait briefly for each network to disconnect.  Sometimes it takes a little while to send.
184         if (!net->forceDisconnect()) {
185             qWarning() << "Timed out quitting network" << net->networkName() <<
186                           "(user ID " << net->userId() << ")";
187         }
188         // Delete the network now that it's closed
189         delete net;
190     }
191 }
192
193
194 CoreNetwork *CoreSession::network(NetworkId id) const
195 {
196     if (_networks.contains(id)) return _networks[id];
197     return 0;
198 }
199
200
201 CoreIdentity *CoreSession::identity(IdentityId id) const
202 {
203     if (_identities.contains(id)) return _identities[id];
204     return 0;
205 }
206
207
208 void CoreSession::loadSettings()
209 {
210     CoreUserSettings s(user());
211
212     // migrate to db
213     QList<IdentityId> ids = s.identityIds();
214     QList<NetworkInfo> networkInfos = Core::networks(user());
215     foreach(IdentityId id, ids) {
216         CoreIdentity identity(s.identity(id));
217         IdentityId newId = Core::createIdentity(user(), identity);
218         QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
219         while (networkIter != networkInfos.end()) {
220             if (networkIter->identity == id) {
221                 networkIter->identity = newId;
222                 Core::updateNetwork(user(), *networkIter);
223                 networkIter = networkInfos.erase(networkIter);
224             }
225             else {
226                 ++networkIter;
227             }
228         }
229         s.removeIdentity(id);
230     }
231     // end of migration
232
233     foreach(CoreIdentity identity, Core::identities(user())) {
234         createIdentity(identity);
235     }
236
237     foreach(NetworkInfo info, Core::networks(user())) {
238         createNetwork(info);
239     }
240 }
241
242
243 void CoreSession::saveSessionState() const
244 {
245     _bufferSyncer->storeDirtyIds();
246     _bufferViewManager->saveBufferViews();
247     _networkConfig->save();
248 }
249
250
251 void CoreSession::restoreSessionState()
252 {
253     QList<NetworkId> nets = Core::connectedNetworks(user());
254     CoreNetwork *net = 0;
255     foreach(NetworkId id, nets) {
256         net = network(id);
257         Q_ASSERT(net);
258         net->connectToIrc();
259     }
260 }
261
262
263 void CoreSession::addClient(RemotePeer *peer)
264 {
265     peer->dispatch(sessionState());
266     signalProxy()->addPeer(peer);
267 }
268
269
270 void CoreSession::addClient(InternalPeer *peer)
271 {
272     signalProxy()->addPeer(peer);
273     emit sessionState(sessionState());
274 }
275
276
277 void CoreSession::removeClient(Peer *peer)
278 {
279     RemotePeer *p = qobject_cast<RemotePeer *>(peer);
280     if (p)
281         quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
282 }
283
284
285 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
286 {
287     return Core::persistentChannels(user(), id);
288 }
289
290
291 QHash<QString, QByteArray> CoreSession::bufferCiphers(NetworkId id) const
292 {
293     return Core::bufferCiphers(user(), id);
294 }
295
296 void CoreSession::setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const
297 {
298     Core::setBufferCipher(user(), id, bufferName, cipher);
299 }
300
301
302 // FIXME switch to BufferId
303 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
304 {
305     CoreNetwork *net = network(bufinfo.networkId());
306     if (net) {
307         net->userInput(bufinfo, msg);
308     }
309     else {
310         qWarning() << "Trying to send to unconnected network:" << msg;
311     }
312 }
313
314
315 // ALL messages coming pass through these functions before going to the GUI.
316 // So this is the perfect place for storing the backlog and log stuff.
317 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
318     const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
319 {
320     // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
321     // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
322     // KDE's notifications), hence we remove those just to be safe.
323     QString text = text_;
324     text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
325     RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
326
327     // check for HardStrictness ignore
328     CoreNetwork *currentNetwork = network(networkId);
329     QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
330     if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
331         return;
332
333     if (_highlightRuleManager.match(rawMsg, currentNetwork->myNick(), currentNetwork->identityPtr()->nicks()))
334         rawMsg.flags |= Message::Flag::Highlight;
335
336     _messageQueue << rawMsg;
337     if (!_processMessages) {
338         _processMessages = true;
339         QCoreApplication::postEvent(this, new ProcessMessagesEvent());
340     }
341 }
342
343
344 void CoreSession::recvStatusMsgFromServer(QString msg)
345 {
346     CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
347     Q_ASSERT(net);
348     emit displayStatusMsg(net->networkName(), msg);
349 }
350
351
352 void CoreSession::processMessageEvent(MessageEvent *event)
353 {
354     recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
355         event->target().isNull() ? "" : event->target(),
356         event->text().isNull() ? "" : event->text(),
357         event->sender().isNull() ? "" : event->sender(),
358         event->msgFlags());
359 }
360
361
362 QList<BufferInfo> CoreSession::buffers() const
363 {
364     return Core::requestBuffers(user());
365 }
366
367
368 void CoreSession::customEvent(QEvent *event)
369 {
370     if (event->type() != QEvent::User)
371         return;
372
373     processMessages();
374     event->accept();
375 }
376
377
378 void CoreSession::processMessages()
379 {
380     if (_messageQueue.count() == 1) {
381         const RawMessage &rawMsg = _messageQueue.first();
382         bool createBuffer = !(rawMsg.flags & Message::Redirected);
383         BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
384         if (!bufferInfo.isValid()) {
385             Q_ASSERT(!createBuffer);
386             bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
387         }
388         Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
389                     senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
390         if(Core::storeMessage(msg))
391             emit displayMsg(msg);
392     }
393     else {
394         QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
395         MessageList messages;
396         QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
397         BufferInfo bufferInfo;
398         for (int i = 0; i < _messageQueue.count(); i++) {
399             const RawMessage &rawMsg = _messageQueue.at(i);
400             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
401                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
402             }
403             else {
404                 bool createBuffer = !(rawMsg.flags & Message::Redirected);
405                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
406                 if (!bufferInfo.isValid()) {
407                     Q_ASSERT(!createBuffer);
408                     redirectedMessages << rawMsg;
409                     continue;
410                 }
411                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
412             }
413             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
414                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
415             messages << msg;
416         }
417
418         // recheck if there exists a buffer to store a redirected message in
419         for (int i = 0; i < redirectedMessages.count(); i++) {
420             const RawMessage &rawMsg = redirectedMessages.at(i);
421             if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
422                 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
423             }
424             else {
425                 // no luck -> we store them in the StatusBuffer
426                 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
427                 // add the StatusBuffer to the Cache in case there are more Messages for the original target
428                 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
429             }
430             Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
431                         senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
432             messages << msg;
433         }
434
435         if(Core::storeMessages(messages)) {
436             // FIXME: extend protocol to a displayMessages(MessageList)
437             for (int i = 0; i < messages.count(); i++) {
438                 emit displayMsg(messages[i]);
439             }
440         }
441     }
442     _processMessages = false;
443     _messageQueue.clear();
444 }
445
446 QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
447 {
448     CoreNetwork *currentNetwork = network(bufferInfo.networkId());
449     if (!currentNetwork) {
450         return {};
451     }
452
453     if (bufferInfo.type() != BufferInfo::ChannelBuffer) {
454         return {};
455     }
456
457     IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
458     if (!currentChannel) {
459         return {};
460     }
461
462     const QString modes = currentChannel->userModes(nickFromMask(sender).toLower());
463     return currentNetwork->modesToPrefixes(modes);
464 }
465
466 Protocol::SessionState CoreSession::sessionState() const
467 {
468     QVariantList bufferInfos;
469     QVariantList networkIds;
470     QVariantList identities;
471
472     foreach(const BufferInfo &id, buffers())
473         bufferInfos << QVariant::fromValue(id);
474     foreach(const NetworkId &id, _networks.keys())
475         networkIds << QVariant::fromValue(id);
476     foreach(const Identity *i, _identities.values())
477         identities << QVariant::fromValue(*i);
478
479     return Protocol::SessionState(identities, bufferInfos, networkIds);
480 }
481
482
483 void CoreSession::initScriptEngine()
484 {
485     signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
486     signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
487
488     // FIXME
489     //QScriptValue storage_ = scriptEngine->newQObject(storage);
490     //scriptEngine->globalObject().setProperty("storage", storage_);
491 }
492
493
494 void CoreSession::scriptRequest(QString script)
495 {
496     emit scriptResult(scriptEngine->evaluate(script).toString());
497 }
498
499
500 /*** Identity Handling ***/
501 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
502 {
503 #ifndef HAVE_SSL
504     Q_UNUSED(additional)
505 #endif
506
507     CoreIdentity coreIdentity(identity);
508 #ifdef HAVE_SSL
509     if (additional.contains("KeyPem"))
510         coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
511     if (additional.contains("CertPem"))
512         coreIdentity.setSslCert(additional["CertPem"].toByteArray());
513 #endif
514     qDebug() << Q_FUNC_INFO;
515     IdentityId id = Core::createIdentity(user(), coreIdentity);
516     if (!id.isValid())
517         return;
518     else
519         createIdentity(coreIdentity);
520 }
521
522 const QString CoreSession::strictSysident() {
523     return Core::instance()->strictSysIdent(_user);
524 }
525
526 void CoreSession::createIdentity(const CoreIdentity &identity)
527 {
528     CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
529     _identities[identity.id()] = coreIdentity;
530     // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
531     coreIdentity->synchronize(signalProxy());
532     connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
533     emit identityCreated(*coreIdentity);
534 }
535
536
537 void CoreSession::updateIdentityBySender()
538 {
539     CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
540     if (!identity)
541         return;
542     Core::updateIdentity(user(), *identity);
543 }
544
545
546 void CoreSession::removeIdentity(IdentityId id)
547 {
548     CoreIdentity *identity = _identities.take(id);
549     if (identity) {
550         emit identityRemoved(id);
551         Core::removeIdentity(user(), id);
552         identity->deleteLater();
553     }
554 }
555
556
557 /*** Network Handling ***/
558
559 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
560 {
561     NetworkInfo info = info_;
562     int id;
563
564     if (!info.networkId.isValid())
565         Core::createNetwork(user(), info);
566
567     if (!info.networkId.isValid()) {
568         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
569         return;
570     }
571
572     id = info.networkId.toInt();
573     if (!_networks.contains(id)) {
574         // create persistent chans
575         QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
576         foreach(QString channel, persistentChans) {
577             if (!rx.exactMatch(channel)) {
578                 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
579                 continue;
580             }
581             Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
582             Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
583             if (!rx.cap(2).isEmpty())
584                 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
585         }
586
587         CoreNetwork *net = new CoreNetwork(id, this);
588         connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
589             SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
590         connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
591         connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
592
593         net->setNetworkInfo(info);
594         net->setProxy(signalProxy());
595         _networks[id] = net;
596         signalProxy()->synchronize(net);
597         emit networkCreated(id);
598     }
599     else {
600         qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
601         _networks[info.networkId]->requestSetNetworkInfo(info);
602     }
603 }
604
605
606 void CoreSession::removeNetwork(NetworkId id)
607 {
608     // Make sure the network is disconnected!
609     CoreNetwork *net = network(id);
610     if (!net)
611         return;
612
613     if (net->connectionState() != Network::Disconnected) {
614         // make sure we no longer receive data from the tcp buffer
615         disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
616         disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
617         connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
618         net->disconnectFromIrc();
619     }
620     else {
621         destroyNetwork(id);
622     }
623 }
624
625
626 void CoreSession::destroyNetwork(NetworkId id)
627 {
628     QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
629     Network *net = _networks.take(id);
630     if (net && Core::removeNetwork(user(), id)) {
631         // make sure that all unprocessed RawMessages from this network are removed
632         QList<RawMessage>::iterator messageIter = _messageQueue.begin();
633         while (messageIter != _messageQueue.end()) {
634             if (messageIter->networkId == id) {
635                 messageIter = _messageQueue.erase(messageIter);
636             }
637             else {
638                 ++messageIter;
639             }
640         }
641         // remove buffers from syncer
642         foreach(BufferId bufferId, removedBuffers) {
643             _bufferSyncer->removeBuffer(bufferId);
644         }
645         emit networkRemoved(id);
646         net->deleteLater();
647     }
648 }
649
650
651 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
652 {
653     BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
654     if (bufferInfo.isValid()) {
655         _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
656     }
657 }
658
659
660 void CoreSession::clientsConnected()
661 {
662     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
663     Identity *identity = 0;
664     CoreNetwork *net = 0;
665     IrcUser *me = 0;
666     while (netIter != _networks.end()) {
667         net = *netIter;
668         ++netIter;
669
670         if (!net->isConnected())
671             continue;
672         identity = net->identityPtr();
673         if (!identity)
674             continue;
675         me = net->me();
676         if (!me)
677             continue;
678
679         if (identity->detachAwayEnabled() && me->isAway()) {
680             net->userInputHandler()->handleAway(BufferInfo(), QString());
681         }
682     }
683 }
684
685
686 void CoreSession::clientsDisconnected()
687 {
688     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
689     Identity *identity = 0;
690     CoreNetwork *net = 0;
691     IrcUser *me = 0;
692     QString awayReason;
693     while (netIter != _networks.end()) {
694         net = *netIter;
695         ++netIter;
696
697         if (!net->isConnected())
698             continue;
699
700         identity = net->identityPtr();
701         if (!identity)
702             continue;
703         me = net->me();
704         if (!me)
705             continue;
706
707         if (identity->detachAwayEnabled() && !me->isAway()) {
708             if (!identity->detachAwayReason().isEmpty())
709                 awayReason = identity->detachAwayReason();
710             net->setAutoAwayActive(true);
711             // Allow handleAway() to format the current date/time in the string.
712             net->userInputHandler()->handleAway(BufferInfo(), awayReason);
713         }
714     }
715 }
716
717
718 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
719 {
720     QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
721     CoreNetwork *net = 0;
722     while (netIter != _networks.end()) {
723         net = *netIter;
724         ++netIter;
725
726         if (!net->isConnected())
727             continue;
728
729         net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
730     }
731 }
732
733 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword) {
734     Q_UNUSED(peer);
735
736     bool success = false;
737     UserId uid = Core::validateUser(userName, oldPassword);
738     if (uid.isValid() && uid == user())
739         success = Core::changeUserPassword(uid, newPassword);
740
741     signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&]{
742         emit passwordChanged(nullptr, success);
743     });
744 }
745
746 void CoreSession::kickClient(int peerId) {
747     auto peer = signalProxy()->peerById(peerId);
748     if (peer == nullptr) {
749         qWarning() << "Invalid peer Id: " << peerId;
750         return;
751     }
752     signalProxy()->restrictTargetPeers(peer, [&]{
753         emit disconnectFromCore();
754     });
755 }