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)));
111 eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
112 eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
113 eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
114 eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
115 eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
116 // some events need to be handled after msg generation
117 eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
118 eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
120 // periodically save our session state
121 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
123 p->synchronize(_bufferSyncer);
124 p->synchronize(&aliasManager());
125 p->synchronize(_backlogManager);
126 p->synchronize(dccConfig());
127 p->synchronize(ircListHelper());
128 p->synchronize(networkConfig());
129 p->synchronize(&_coreInfo);
130 p->synchronize(&_ignoreListManager);
131 p->synchronize(transferManager());
132 // Restore session state
134 restoreSessionState();
140 CoreSession::~CoreSession()
144 /* Why partially duplicate CoreNetwork destructor? When each CoreNetwork quits in the
145 * destructor, disconnections are processed in sequence for each object. For many IRC servers
146 * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
148 * Here, CoreSession first calls disconnect on all networks, letting them all start
149 * disconnecting before beginning to sequentially wait for each network. Ideally, after the
150 * first network is disconnected, the other networks will have already closed. Worst-case may
151 * still wait [msecs wait time * num. of networks], but the risk should be much lower.
153 * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
154 * outside of deleting the whole CoreSession.
156 * If this proves to be problematic in the future, there's an alternative Qt signal-based system
157 * implemented in another pull request that guarentees a maximum amount of time to disconnect,
158 * but at the cost of more complex code.
160 * See https://github.com/quassel/quassel/pull/203
163 foreach(CoreNetwork *net, _networks.values()) {
164 // Request each network properly disconnect, but don't count as user-requested disconnect
165 if (net->socketConnected()) {
166 // Only try if the socket's fully connected (not initializing or disconnecting).
167 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
168 // shown even if other messages are queued.
169 net->disconnectFromIrc(false, QString(), false, true);
173 // Process the putCmd events that trigger the quit. Without this, shutting down the core
174 // results in abrubtly closing the socket rather than sending the QUIT as expected.
175 QCoreApplication::processEvents();
177 foreach(CoreNetwork *net, _networks.values()) {
178 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
179 if (!net->forceDisconnect()) {
180 qWarning() << "Timed out quitting network" << net->networkName() <<
181 "(user ID " << net->userId() << ")";
183 // Delete the network now that it's closed
189 CoreNetwork *CoreSession::network(NetworkId id) const
191 if (_networks.contains(id)) return _networks[id];
196 CoreIdentity *CoreSession::identity(IdentityId id) const
198 if (_identities.contains(id)) return _identities[id];
203 void CoreSession::loadSettings()
205 CoreUserSettings s(user());
208 QList<IdentityId> ids = s.identityIds();
209 QList<NetworkInfo> networkInfos = Core::networks(user());
210 foreach(IdentityId id, ids) {
211 CoreIdentity identity(s.identity(id));
212 IdentityId newId = Core::createIdentity(user(), identity);
213 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
214 while (networkIter != networkInfos.end()) {
215 if (networkIter->identity == id) {
216 networkIter->identity = newId;
217 Core::updateNetwork(user(), *networkIter);
218 networkIter = networkInfos.erase(networkIter);
224 s.removeIdentity(id);
228 foreach(CoreIdentity identity, Core::identities(user())) {
229 createIdentity(identity);
232 foreach(NetworkInfo info, Core::networks(user())) {
238 void CoreSession::saveSessionState() const
240 _bufferSyncer->storeDirtyIds();
241 _bufferViewManager->saveBufferViews();
242 _networkConfig->save();
246 void CoreSession::restoreSessionState()
248 QList<NetworkId> nets = Core::connectedNetworks(user());
249 CoreNetwork *net = 0;
250 foreach(NetworkId id, nets) {
258 void CoreSession::addClient(RemotePeer *peer)
260 peer->dispatch(sessionState());
261 signalProxy()->addPeer(peer);
265 void CoreSession::addClient(InternalPeer *peer)
267 signalProxy()->addPeer(peer);
268 emit sessionState(sessionState());
272 void CoreSession::removeClient(Peer *peer)
274 RemotePeer *p = qobject_cast<RemotePeer *>(peer);
276 quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
280 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
282 return Core::persistentChannels(user(), id);
286 // FIXME switch to BufferId
287 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
289 CoreNetwork *net = network(bufinfo.networkId());
291 net->userInput(bufinfo, msg);
294 qWarning() << "Trying to send to unconnected network:" << msg;
299 // ALL messages coming pass through these functions before going to the GUI.
300 // So this is the perfect place for storing the backlog and log stuff.
301 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
302 const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
304 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
305 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
306 // KDE's notifications), hence we remove those just to be safe.
307 QString text = text_;
308 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
309 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
311 // check for HardStrictness ignore
312 CoreNetwork *currentNetwork = network(networkId);
313 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
314 if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
317 _messageQueue << rawMsg;
318 if (!_processMessages) {
319 _processMessages = true;
320 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
325 void CoreSession::recvStatusMsgFromServer(QString msg)
327 CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
329 emit displayStatusMsg(net->networkName(), msg);
333 void CoreSession::processMessageEvent(MessageEvent *event)
335 recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
336 event->target().isNull() ? "" : event->target(),
337 event->text().isNull() ? "" : event->text(),
338 event->sender().isNull() ? "" : event->sender(),
343 QList<BufferInfo> CoreSession::buffers() const
345 return Core::requestBuffers(user());
349 void CoreSession::customEvent(QEvent *event)
351 if (event->type() != QEvent::User)
359 void CoreSession::processMessages()
361 if (_messageQueue.count() == 1) {
362 const RawMessage &rawMsg = _messageQueue.first();
363 bool createBuffer = !(rawMsg.flags & Message::Redirected);
364 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
365 if (!bufferInfo.isValid()) {
366 Q_ASSERT(!createBuffer);
367 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
369 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
370 if(Core::storeMessage(msg))
371 emit displayMsg(msg);
374 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
375 MessageList messages;
376 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
377 BufferInfo bufferInfo;
378 for (int i = 0; i < _messageQueue.count(); i++) {
379 const RawMessage &rawMsg = _messageQueue.at(i);
380 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
381 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
384 bool createBuffer = !(rawMsg.flags & Message::Redirected);
385 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
386 if (!bufferInfo.isValid()) {
387 Q_ASSERT(!createBuffer);
388 redirectedMessages << rawMsg;
391 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
393 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
397 // recheck if there exists a buffer to store a redirected message in
398 for (int i = 0; i < redirectedMessages.count(); i++) {
399 const RawMessage &rawMsg = redirectedMessages.at(i);
400 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
401 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
404 // no luck -> we store them in the StatusBuffer
405 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
406 // add the StatusBuffer to the Cache in case there are more Messages for the original target
407 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
409 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
413 if(Core::storeMessages(messages)) {
414 // FIXME: extend protocol to a displayMessages(MessageList)
415 for (int i = 0; i < messages.count(); i++) {
416 emit displayMsg(messages[i]);
420 _processMessages = false;
421 _messageQueue.clear();
425 Protocol::SessionState CoreSession::sessionState() const
427 QVariantList bufferInfos;
428 QVariantList networkIds;
429 QVariantList identities;
431 foreach(const BufferInfo &id, buffers())
432 bufferInfos << QVariant::fromValue(id);
433 foreach(const NetworkId &id, _networks.keys())
434 networkIds << QVariant::fromValue(id);
435 foreach(const Identity *i, _identities.values())
436 identities << QVariant::fromValue(*i);
438 return Protocol::SessionState(identities, bufferInfos, networkIds);
442 void CoreSession::initScriptEngine()
444 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
445 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
448 //QScriptValue storage_ = scriptEngine->newQObject(storage);
449 //scriptEngine->globalObject().setProperty("storage", storage_);
453 void CoreSession::scriptRequest(QString script)
455 emit scriptResult(scriptEngine->evaluate(script).toString());
459 /*** Identity Handling ***/
460 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
466 CoreIdentity coreIdentity(identity);
468 if (additional.contains("KeyPem"))
469 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
470 if (additional.contains("CertPem"))
471 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
473 qDebug() << Q_FUNC_INFO;
474 IdentityId id = Core::createIdentity(user(), coreIdentity);
478 createIdentity(coreIdentity);
482 void CoreSession::createIdentity(const CoreIdentity &identity)
484 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
485 _identities[identity.id()] = coreIdentity;
486 // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
487 coreIdentity->synchronize(signalProxy());
488 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
489 emit identityCreated(*coreIdentity);
493 void CoreSession::updateIdentityBySender()
495 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
498 Core::updateIdentity(user(), *identity);
502 void CoreSession::removeIdentity(IdentityId id)
504 CoreIdentity *identity = _identities.take(id);
506 emit identityRemoved(id);
507 Core::removeIdentity(user(), id);
508 identity->deleteLater();
513 /*** Network Handling ***/
515 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
517 NetworkInfo info = info_;
520 if (!info.networkId.isValid())
521 Core::createNetwork(user(), info);
523 if (!info.networkId.isValid()) {
524 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
528 id = info.networkId.toInt();
529 if (!_networks.contains(id)) {
530 // create persistent chans
531 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
532 foreach(QString channel, persistentChans) {
533 if (!rx.exactMatch(channel)) {
534 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
537 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
538 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
539 if (!rx.cap(2).isEmpty())
540 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
543 CoreNetwork *net = new CoreNetwork(id, this);
544 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
545 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
546 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
547 connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
549 net->setNetworkInfo(info);
550 net->setProxy(signalProxy());
552 signalProxy()->synchronize(net);
553 emit networkCreated(id);
556 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
557 _networks[info.networkId]->requestSetNetworkInfo(info);
562 void CoreSession::removeNetwork(NetworkId id)
564 // Make sure the network is disconnected!
565 CoreNetwork *net = network(id);
569 if (net->connectionState() != Network::Disconnected) {
570 // make sure we no longer receive data from the tcp buffer
571 disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
572 disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
573 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
574 net->disconnectFromIrc();
582 void CoreSession::destroyNetwork(NetworkId id)
584 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
585 Network *net = _networks.take(id);
586 if (net && Core::removeNetwork(user(), id)) {
587 // make sure that all unprocessed RawMessages from this network are removed
588 QList<RawMessage>::iterator messageIter = _messageQueue.begin();
589 while (messageIter != _messageQueue.end()) {
590 if (messageIter->networkId == id) {
591 messageIter = _messageQueue.erase(messageIter);
597 // remove buffers from syncer
598 foreach(BufferId bufferId, removedBuffers) {
599 _bufferSyncer->removeBuffer(bufferId);
601 emit networkRemoved(id);
607 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
609 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
610 if (bufferInfo.isValid()) {
611 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
616 void CoreSession::clientsConnected()
618 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
619 Identity *identity = 0;
620 CoreNetwork *net = 0;
622 while (netIter != _networks.end()) {
626 if (!net->isConnected())
628 identity = net->identityPtr();
635 if (identity->detachAwayEnabled() && me->isAway()) {
636 net->userInputHandler()->handleAway(BufferInfo(), QString());
642 void CoreSession::clientsDisconnected()
644 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
645 Identity *identity = 0;
646 CoreNetwork *net = 0;
649 while (netIter != _networks.end()) {
653 if (!net->isConnected())
656 identity = net->identityPtr();
663 if (identity->detachAwayEnabled() && !me->isAway()) {
664 if (!identity->detachAwayReason().isEmpty())
665 awayReason = formatCurrentDateTimeInString(identity->detachAwayReason());
666 net->setAutoAwayActive(true);
667 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
673 void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
675 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
676 CoreNetwork *net = 0;
677 while (netIter != _networks.end()) {
681 if (!net->isConnected())
684 net->userInputHandler()->issueAway(msg, false /* no force away */, skipFormatting);
688 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
690 bool success = false;
691 UserId uid = Core::validateUser(userName, oldPassword);
692 if (uid.isValid() && uid == user())
693 success = Core::changeUserPassword(uid, newPassword);
695 emit passwordChanged(peer, success);