1 /***************************************************************************
2 * Copyright (C) 2005-2016 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "coresession.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"
47 #include "messageevent.h"
48 #include "remotepeer.h"
53 class ProcessMessagesEvent : public QEvent
56 ProcessMessagesEvent() : QEvent(QEvent::User) {}
60 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
63 _signalProxy(new SignalProxy(SignalProxy::Server, 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)),
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)
82 SignalProxy *p = signalProxy();
83 p->setHeartBeatInterval(30);
84 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
86 connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
88 connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
89 connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
91 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
92 p->attachSignal(this, SIGNAL(displayMsg(Message)));
93 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
95 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
96 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
97 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
98 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
100 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
101 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
102 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
103 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
105 p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
106 p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
108 p->attachSlot(SIGNAL(kickClient(int)), this, SLOT(kickClient(int)));
113 eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
114 eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
115 eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
116 eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
117 eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
118 // some events need to be handled after msg generation
119 eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
120 eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
122 // periodically save our session state
123 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
125 p->synchronize(_bufferSyncer);
126 p->synchronize(&aliasManager());
127 p->synchronize(_backlogManager);
128 p->synchronize(dccConfig());
129 p->synchronize(ircListHelper());
130 p->synchronize(networkConfig());
131 p->synchronize(&_coreInfo);
132 p->synchronize(&_ignoreListManager);
133 p->synchronize(transferManager());
134 // Restore session state
136 restoreSessionState();
142 CoreSession::~CoreSession()
146 /* Why partially duplicate CoreNetwork destructor? When each CoreNetwork quits in the
147 * destructor, disconnections are processed in sequence for each object. For many IRC servers
148 * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
150 * Here, CoreSession first calls disconnect on all networks, letting them all start
151 * disconnecting before beginning to sequentially wait for each network. Ideally, after the
152 * first network is disconnected, the other networks will have already closed. Worst-case may
153 * still wait [msecs wait time * num. of networks], but the risk should be much lower.
155 * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
156 * outside of deleting the whole CoreSession.
158 * If this proves to be problematic in the future, there's an alternative Qt signal-based system
159 * implemented in another pull request that guarentees a maximum amount of time to disconnect,
160 * but at the cost of more complex code.
162 * See https://github.com/quassel/quassel/pull/203
165 foreach(CoreNetwork *net, _networks.values()) {
166 // Request each network properly disconnect, but don't count as user-requested disconnect
167 if (net->socketConnected()) {
168 // Only try if the socket's fully connected (not initializing or disconnecting).
169 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
170 // shown even if other messages are queued.
171 net->disconnectFromIrc(false, QString(), false, true);
175 // Process the putCmd events that trigger the quit. Without this, shutting down the core
176 // results in abrubtly closing the socket rather than sending the QUIT as expected.
177 QCoreApplication::processEvents();
179 foreach(CoreNetwork *net, _networks.values()) {
180 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
181 if (!net->forceDisconnect()) {
182 qWarning() << "Timed out quitting network" << net->networkName() <<
183 "(user ID " << net->userId() << ")";
185 // Delete the network now that it's closed
191 CoreNetwork *CoreSession::network(NetworkId id) const
193 if (_networks.contains(id)) return _networks[id];
198 CoreIdentity *CoreSession::identity(IdentityId id) const
200 if (_identities.contains(id)) return _identities[id];
205 void CoreSession::loadSettings()
207 CoreUserSettings s(user());
210 QList<IdentityId> ids = s.identityIds();
211 QList<NetworkInfo> networkInfos = Core::networks(user());
212 foreach(IdentityId id, ids) {
213 CoreIdentity identity(s.identity(id));
214 IdentityId newId = Core::createIdentity(user(), identity);
215 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
216 while (networkIter != networkInfos.end()) {
217 if (networkIter->identity == id) {
218 networkIter->identity = newId;
219 Core::updateNetwork(user(), *networkIter);
220 networkIter = networkInfos.erase(networkIter);
226 s.removeIdentity(id);
230 foreach(CoreIdentity identity, Core::identities(user())) {
231 createIdentity(identity);
234 foreach(NetworkInfo info, Core::networks(user())) {
240 void CoreSession::saveSessionState() const
242 _bufferSyncer->storeDirtyIds();
243 _bufferViewManager->saveBufferViews();
244 _networkConfig->save();
248 void CoreSession::restoreSessionState()
250 QList<NetworkId> nets = Core::connectedNetworks(user());
251 CoreNetwork *net = 0;
252 foreach(NetworkId id, nets) {
260 void CoreSession::addClient(RemotePeer *peer)
262 peer->dispatch(sessionState());
263 signalProxy()->addPeer(peer);
267 void CoreSession::addClient(InternalPeer *peer)
269 signalProxy()->addPeer(peer);
270 emit sessionState(sessionState());
274 void CoreSession::removeClient(Peer *peer)
276 RemotePeer *p = qobject_cast<RemotePeer *>(peer);
278 quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
282 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
284 return Core::persistentChannels(user(), id);
288 // FIXME switch to BufferId
289 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
291 CoreNetwork *net = network(bufinfo.networkId());
293 net->userInput(bufinfo, msg);
296 qWarning() << "Trying to send to unconnected network:" << msg;
301 // ALL messages coming pass through these functions before going to the GUI.
302 // So this is the perfect place for storing the backlog and log stuff.
303 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
304 const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
306 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
307 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
308 // KDE's notifications), hence we remove those just to be safe.
309 QString text = text_;
310 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
311 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
313 // check for HardStrictness ignore
314 CoreNetwork *currentNetwork = network(networkId);
315 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
316 if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
319 _messageQueue << rawMsg;
320 if (!_processMessages) {
321 _processMessages = true;
322 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
327 void CoreSession::recvStatusMsgFromServer(QString msg)
329 CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
331 emit displayStatusMsg(net->networkName(), msg);
335 void CoreSession::processMessageEvent(MessageEvent *event)
337 recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
338 event->target().isNull() ? "" : event->target(),
339 event->text().isNull() ? "" : event->text(),
340 event->sender().isNull() ? "" : event->sender(),
345 QList<BufferInfo> CoreSession::buffers() const
347 return Core::requestBuffers(user());
351 void CoreSession::customEvent(QEvent *event)
353 if (event->type() != QEvent::User)
361 void CoreSession::processMessages()
363 if (_messageQueue.count() == 1) {
364 const RawMessage &rawMsg = _messageQueue.first();
365 bool createBuffer = !(rawMsg.flags & Message::Redirected);
366 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
367 if (!bufferInfo.isValid()) {
368 Q_ASSERT(!createBuffer);
369 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
371 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
372 senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
373 if(Core::storeMessage(msg))
374 emit displayMsg(msg);
377 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
378 MessageList messages;
379 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
380 BufferInfo bufferInfo;
381 for (int i = 0; i < _messageQueue.count(); i++) {
382 const RawMessage &rawMsg = _messageQueue.at(i);
383 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
384 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
387 bool createBuffer = !(rawMsg.flags & Message::Redirected);
388 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
389 if (!bufferInfo.isValid()) {
390 Q_ASSERT(!createBuffer);
391 redirectedMessages << rawMsg;
394 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
396 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
397 senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
401 // recheck if there exists a buffer to store a redirected message in
402 for (int i = 0; i < redirectedMessages.count(); i++) {
403 const RawMessage &rawMsg = redirectedMessages.at(i);
404 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
405 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
408 // no luck -> we store them in the StatusBuffer
409 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
410 // add the StatusBuffer to the Cache in case there are more Messages for the original target
411 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
413 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender,
414 senderPrefixes(rawMsg.sender, bufferInfo), rawMsg.flags);
418 if(Core::storeMessages(messages)) {
419 // FIXME: extend protocol to a displayMessages(MessageList)
420 for (int i = 0; i < messages.count(); i++) {
421 emit displayMsg(messages[i]);
425 _processMessages = false;
426 _messageQueue.clear();
429 QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
431 CoreNetwork *currentNetwork = network(bufferInfo.networkId());
432 if (!currentNetwork) {
436 if (bufferInfo.type() != BufferInfo::ChannelBuffer) {
440 IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
441 if (!currentChannel) {
445 const QString modes = currentChannel->userModes(nickFromMask(sender).toLower());
446 return currentNetwork->modesToPrefixes(modes);
449 Protocol::SessionState CoreSession::sessionState() const
451 QVariantList bufferInfos;
452 QVariantList networkIds;
453 QVariantList identities;
455 foreach(const BufferInfo &id, buffers())
456 bufferInfos << QVariant::fromValue(id);
457 foreach(const NetworkId &id, _networks.keys())
458 networkIds << QVariant::fromValue(id);
459 foreach(const Identity *i, _identities.values())
460 identities << QVariant::fromValue(*i);
462 return Protocol::SessionState(identities, bufferInfos, networkIds);
466 void CoreSession::initScriptEngine()
468 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
469 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
472 //QScriptValue storage_ = scriptEngine->newQObject(storage);
473 //scriptEngine->globalObject().setProperty("storage", storage_);
477 void CoreSession::scriptRequest(QString script)
479 emit scriptResult(scriptEngine->evaluate(script).toString());
483 /*** Identity Handling ***/
484 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
490 CoreIdentity coreIdentity(identity);
492 if (additional.contains("KeyPem"))
493 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
494 if (additional.contains("CertPem"))
495 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
497 qDebug() << Q_FUNC_INFO;
498 IdentityId id = Core::createIdentity(user(), coreIdentity);
502 createIdentity(coreIdentity);
506 void CoreSession::createIdentity(const CoreIdentity &identity)
508 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
509 _identities[identity.id()] = coreIdentity;
510 // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
511 coreIdentity->synchronize(signalProxy());
512 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
513 emit identityCreated(*coreIdentity);
517 void CoreSession::updateIdentityBySender()
519 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
522 Core::updateIdentity(user(), *identity);
526 void CoreSession::removeIdentity(IdentityId id)
528 CoreIdentity *identity = _identities.take(id);
530 emit identityRemoved(id);
531 Core::removeIdentity(user(), id);
532 identity->deleteLater();
537 /*** Network Handling ***/
539 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
541 NetworkInfo info = info_;
544 if (!info.networkId.isValid())
545 Core::createNetwork(user(), info);
547 if (!info.networkId.isValid()) {
548 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
552 id = info.networkId.toInt();
553 if (!_networks.contains(id)) {
554 // create persistent chans
555 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
556 foreach(QString channel, persistentChans) {
557 if (!rx.exactMatch(channel)) {
558 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
561 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
562 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
563 if (!rx.cap(2).isEmpty())
564 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
567 CoreNetwork *net = new CoreNetwork(id, this);
568 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
569 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
570 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
571 connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
573 net->setNetworkInfo(info);
574 net->setProxy(signalProxy());
576 signalProxy()->synchronize(net);
577 emit networkCreated(id);
580 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
581 _networks[info.networkId]->requestSetNetworkInfo(info);
586 void CoreSession::removeNetwork(NetworkId id)
588 // Make sure the network is disconnected!
589 CoreNetwork *net = network(id);
593 if (net->connectionState() != Network::Disconnected) {
594 // make sure we no longer receive data from the tcp buffer
595 disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
596 disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
597 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
598 net->disconnectFromIrc();
606 void CoreSession::destroyNetwork(NetworkId id)
608 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
609 Network *net = _networks.take(id);
610 if (net && Core::removeNetwork(user(), id)) {
611 // make sure that all unprocessed RawMessages from this network are removed
612 QList<RawMessage>::iterator messageIter = _messageQueue.begin();
613 while (messageIter != _messageQueue.end()) {
614 if (messageIter->networkId == id) {
615 messageIter = _messageQueue.erase(messageIter);
621 // remove buffers from syncer
622 foreach(BufferId bufferId, removedBuffers) {
623 _bufferSyncer->removeBuffer(bufferId);
625 emit networkRemoved(id);
631 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
633 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
634 if (bufferInfo.isValid()) {
635 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
640 void CoreSession::clientsConnected()
642 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
643 Identity *identity = 0;
644 CoreNetwork *net = 0;
646 while (netIter != _networks.end()) {
650 if (!net->isConnected())
652 identity = net->identityPtr();
659 if (identity->detachAwayEnabled() && me->isAway()) {
660 net->userInputHandler()->handleAway(BufferInfo(), QString());
666 void CoreSession::clientsDisconnected()
668 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
669 Identity *identity = 0;
670 CoreNetwork *net = 0;
673 while (netIter != _networks.end()) {
677 if (!net->isConnected())
680 identity = net->identityPtr();
687 if (identity->detachAwayEnabled() && !me->isAway()) {
688 if (!identity->detachAwayReason().isEmpty())
689 awayReason = identity->detachAwayReason();
690 net->setAutoAwayActive(true);
691 // Allow handleAway() to format the current date/time in the string.
692 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
698 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
700 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
701 CoreNetwork *net = 0;
702 while (netIter != _networks.end()) {
706 if (!net->isConnected())
709 net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
713 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
715 bool success = false;
716 UserId uid = Core::validateUser(userName, oldPassword);
717 if (uid.isValid() && uid == user())
718 success = Core::changeUserPassword(uid, newPassword);
720 emit passwordChanged(peer, success);
723 void CoreSession::kickClient(int peerId) {
724 auto peer = signalProxy()->peerById(peerId);
726 qWarning() << "Invalid peer Id: " << peerId;
728 peer->close("Terminated by user action");