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