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