1 /***************************************************************************
2 * Copyright (C) 2005-2015 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 "coreeventmanager.h"
31 #include "coreidentity.h"
32 #include "coreignorelistmanager.h"
33 #include "coreirclisthelper.h"
34 #include "corenetwork.h"
35 #include "corenetworkconfig.h"
36 #include "coresessioneventprocessor.h"
37 #include "coretransfermanager.h"
38 #include "coreusersettings.h"
39 #include "ctcpparser.h"
40 #include "eventstringifier.h"
41 #include "internalpeer.h"
42 #include "ircchannel.h"
43 #include "ircparser.h"
46 #include "messageevent.h"
47 #include "remotepeer.h"
52 class ProcessMessagesEvent : public QEvent
55 ProcessMessagesEvent() : QEvent(QEvent::User) {}
59 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
62 _signalProxy(new SignalProxy(SignalProxy::Server, this)),
64 _bufferSyncer(new CoreBufferSyncer(this)),
65 _backlogManager(new CoreBacklogManager(this)),
66 _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
67 _ircListHelper(new CoreIrcListHelper(this)),
68 _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
70 _transferManager(new CoreTransferManager(this)),
71 _eventManager(new CoreEventManager(this)),
72 _eventStringifier(new EventStringifier(this)),
73 _sessionEventProcessor(new CoreSessionEventProcessor(this)),
74 _ctcpParser(new CtcpParser(this)),
75 _ircParser(new IrcParser(this)),
76 scriptEngine(new QScriptEngine(this)),
77 _processMessages(false),
78 _ignoreListManager(this)
80 SignalProxy *p = signalProxy();
81 p->setHeartBeatInterval(30);
82 p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
84 connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
86 connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
87 connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
89 p->attachSlot(SIGNAL(sendInput(BufferInfo, QString)), this, SLOT(msgFromClient(BufferInfo, QString)));
90 p->attachSignal(this, SIGNAL(displayMsg(Message)));
91 p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
93 p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
94 p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
95 p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
96 p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
98 p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
99 p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
100 p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
101 p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
103 p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
104 p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
109 eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
110 eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
111 eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
112 eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
113 eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
114 // some events need to be handled after msg generation
115 eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
116 eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
118 // periodically save our session state
119 connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
121 p->synchronize(_bufferSyncer);
122 p->synchronize(&aliasManager());
123 p->synchronize(_backlogManager);
124 p->synchronize(ircListHelper());
125 p->synchronize(networkConfig());
126 p->synchronize(&_coreInfo);
127 p->synchronize(&_ignoreListManager);
128 p->synchronize(transferManager());
129 // Restore session state
131 restoreSessionState();
137 CoreSession::~CoreSession()
141 /* Why partially duplicate CoreNetwork destructor? When each CoreNetwork quits in the
142 * destructor, disconnections are processed in sequence for each object. For many IRC servers
143 * on a slow network, this could significantly delay core shutdown [msecs wait * network count].
145 * Here, CoreSession first calls disconnect on all networks, letting them all start
146 * disconnecting before beginning to sequentially wait for each network. Ideally, after the
147 * first network is disconnected, the other networks will have already closed. Worst-case may
148 * still wait [msecs wait time * num. of networks], but the risk should be much lower.
150 * CoreNetwork should still do cleanup in its own destructor in case a network is deleted
151 * outside of deleting the whole CoreSession.
153 * If this proves to be problematic in the future, there's an alternative Qt signal-based system
154 * implemented in another pull request that guarentees a maximum amount of time to disconnect,
155 * but at the cost of more complex code.
157 * See https://github.com/quassel/quassel/pull/203
160 foreach(CoreNetwork *net, _networks.values()) {
161 // Request each network properly disconnect, but don't count as user-requested disconnect
162 if (net->socketConnected()) {
163 // Only try if the socket's fully connected (not initializing or disconnecting).
164 // Force an immediate disconnect, jumping the command queue. Ensures the proper QUIT is
165 // shown even if other messages are queued.
166 net->disconnectFromIrc(false, QString(), false, true);
170 // Process the putCmd events that trigger the quit. Without this, shutting down the core
171 // results in abrubtly closing the socket rather than sending the QUIT as expected.
172 QCoreApplication::processEvents();
174 foreach(CoreNetwork *net, _networks.values()) {
175 // Wait briefly for each network to disconnect. Sometimes it takes a little while to send.
176 if (!net->forceDisconnect()) {
177 qWarning() << "Timed out quitting network" << net->networkName() <<
178 "(user ID " << net->userId() << ")";
180 // Delete the network now that it's closed
186 CoreNetwork *CoreSession::network(NetworkId id) const
188 if (_networks.contains(id)) return _networks[id];
193 CoreIdentity *CoreSession::identity(IdentityId id) const
195 if (_identities.contains(id)) return _identities[id];
200 void CoreSession::loadSettings()
202 CoreUserSettings s(user());
205 QList<IdentityId> ids = s.identityIds();
206 QList<NetworkInfo> networkInfos = Core::networks(user());
207 foreach(IdentityId id, ids) {
208 CoreIdentity identity(s.identity(id));
209 IdentityId newId = Core::createIdentity(user(), identity);
210 QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
211 while (networkIter != networkInfos.end()) {
212 if (networkIter->identity == id) {
213 networkIter->identity = newId;
214 Core::updateNetwork(user(), *networkIter);
215 networkIter = networkInfos.erase(networkIter);
221 s.removeIdentity(id);
225 foreach(CoreIdentity identity, Core::identities(user())) {
226 createIdentity(identity);
229 foreach(NetworkInfo info, Core::networks(user())) {
235 void CoreSession::saveSessionState() const
237 _bufferSyncer->storeDirtyIds();
238 _bufferViewManager->saveBufferViews();
239 _networkConfig->save();
243 void CoreSession::restoreSessionState()
245 QList<NetworkId> nets = Core::connectedNetworks(user());
246 CoreNetwork *net = 0;
247 foreach(NetworkId id, nets) {
255 void CoreSession::addClient(RemotePeer *peer)
257 peer->dispatch(sessionState());
258 signalProxy()->addPeer(peer);
262 void CoreSession::addClient(InternalPeer *peer)
264 signalProxy()->addPeer(peer);
265 emit sessionState(sessionState());
269 void CoreSession::removeClient(Peer *peer)
271 RemotePeer *p = qobject_cast<RemotePeer *>(peer);
273 quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
277 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
279 return Core::persistentChannels(user(), id);
283 // FIXME switch to BufferId
284 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
286 CoreNetwork *net = network(bufinfo.networkId());
288 net->userInput(bufinfo, msg);
291 qWarning() << "Trying to send to unconnected network:" << msg;
296 // ALL messages coming pass through these functions before going to the GUI.
297 // So this is the perfect place for storing the backlog and log stuff.
298 void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
299 const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
301 // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
302 // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
303 // KDE's notifications), hence we remove those just to be safe.
304 QString text = text_;
305 text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
306 RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
308 // check for HardStrictness ignore
309 CoreNetwork *currentNetwork = network(networkId);
310 QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
311 if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
314 _messageQueue << rawMsg;
315 if (!_processMessages) {
316 _processMessages = true;
317 QCoreApplication::postEvent(this, new ProcessMessagesEvent());
322 void CoreSession::recvStatusMsgFromServer(QString msg)
324 CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
326 emit displayStatusMsg(net->networkName(), msg);
330 void CoreSession::processMessageEvent(MessageEvent *event)
332 recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
333 event->target().isNull() ? "" : event->target(),
334 event->text().isNull() ? "" : event->text(),
335 event->sender().isNull() ? "" : event->sender(),
340 QList<BufferInfo> CoreSession::buffers() const
342 return Core::requestBuffers(user());
346 void CoreSession::customEvent(QEvent *event)
348 if (event->type() != QEvent::User)
356 void CoreSession::processMessages()
358 if (_messageQueue.count() == 1) {
359 const RawMessage &rawMsg = _messageQueue.first();
360 bool createBuffer = !(rawMsg.flags & Message::Redirected);
361 BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
362 if (!bufferInfo.isValid()) {
363 Q_ASSERT(!createBuffer);
364 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
366 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
367 if(Core::storeMessage(msg))
368 emit displayMsg(msg);
371 QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
372 MessageList messages;
373 QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
374 BufferInfo bufferInfo;
375 for (int i = 0; i < _messageQueue.count(); i++) {
376 const RawMessage &rawMsg = _messageQueue.at(i);
377 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
378 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
381 bool createBuffer = !(rawMsg.flags & Message::Redirected);
382 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
383 if (!bufferInfo.isValid()) {
384 Q_ASSERT(!createBuffer);
385 redirectedMessages << rawMsg;
388 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
390 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
394 // recheck if there exists a buffer to store a redirected message in
395 for (int i = 0; i < redirectedMessages.count(); i++) {
396 const RawMessage &rawMsg = redirectedMessages.at(i);
397 if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
398 bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
401 // no luck -> we store them in the StatusBuffer
402 bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
403 // add the StatusBuffer to the Cache in case there are more Messages for the original target
404 bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
406 Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
410 if(Core::storeMessages(messages)) {
411 // FIXME: extend protocol to a displayMessages(MessageList)
412 for (int i = 0; i < messages.count(); i++) {
413 emit displayMsg(messages[i]);
417 _processMessages = false;
418 _messageQueue.clear();
422 Protocol::SessionState CoreSession::sessionState() const
424 QVariantList bufferInfos;
425 QVariantList networkIds;
426 QVariantList identities;
428 foreach(const BufferInfo &id, buffers())
429 bufferInfos << QVariant::fromValue(id);
430 foreach(const NetworkId &id, _networks.keys())
431 networkIds << QVariant::fromValue(id);
432 foreach(const Identity *i, _identities.values())
433 identities << QVariant::fromValue(*i);
435 return Protocol::SessionState(identities, bufferInfos, networkIds);
439 void CoreSession::initScriptEngine()
441 signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
442 signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
445 //QScriptValue storage_ = scriptEngine->newQObject(storage);
446 //scriptEngine->globalObject().setProperty("storage", storage_);
450 void CoreSession::scriptRequest(QString script)
452 emit scriptResult(scriptEngine->evaluate(script).toString());
456 /*** Identity Handling ***/
457 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
463 CoreIdentity coreIdentity(identity);
465 if (additional.contains("KeyPem"))
466 coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
467 if (additional.contains("CertPem"))
468 coreIdentity.setSslCert(additional["CertPem"].toByteArray());
470 qDebug() << Q_FUNC_INFO;
471 IdentityId id = Core::createIdentity(user(), coreIdentity);
475 createIdentity(coreIdentity);
479 void CoreSession::createIdentity(const CoreIdentity &identity)
481 CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
482 _identities[identity.id()] = coreIdentity;
483 // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
484 coreIdentity->synchronize(signalProxy());
485 connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
486 emit identityCreated(*coreIdentity);
490 void CoreSession::updateIdentityBySender()
492 CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
495 Core::updateIdentity(user(), *identity);
499 void CoreSession::removeIdentity(IdentityId id)
501 CoreIdentity *identity = _identities.take(id);
503 emit identityRemoved(id);
504 Core::removeIdentity(user(), id);
505 identity->deleteLater();
510 /*** Network Handling ***/
512 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
514 NetworkInfo info = info_;
517 if (!info.networkId.isValid())
518 Core::createNetwork(user(), info);
520 if (!info.networkId.isValid()) {
521 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
525 id = info.networkId.toInt();
526 if (!_networks.contains(id)) {
527 // create persistent chans
528 QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
529 foreach(QString channel, persistentChans) {
530 if (!rx.exactMatch(channel)) {
531 qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
534 Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
535 Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
536 if (!rx.cap(2).isEmpty())
537 Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
540 CoreNetwork *net = new CoreNetwork(id, this);
541 connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
542 SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
543 connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
544 connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
546 net->setNetworkInfo(info);
547 net->setProxy(signalProxy());
549 signalProxy()->synchronize(net);
550 emit networkCreated(id);
553 qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
554 _networks[info.networkId]->requestSetNetworkInfo(info);
559 void CoreSession::removeNetwork(NetworkId id)
561 // Make sure the network is disconnected!
562 CoreNetwork *net = network(id);
566 if (net->connectionState() != Network::Disconnected) {
567 // make sure we no longer receive data from the tcp buffer
568 disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
569 disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
570 connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
571 net->disconnectFromIrc();
579 void CoreSession::destroyNetwork(NetworkId id)
581 QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
582 Network *net = _networks.take(id);
583 if (net && Core::removeNetwork(user(), id)) {
584 // make sure that all unprocessed RawMessages from this network are removed
585 QList<RawMessage>::iterator messageIter = _messageQueue.begin();
586 while (messageIter != _messageQueue.end()) {
587 if (messageIter->networkId == id) {
588 messageIter = _messageQueue.erase(messageIter);
594 // remove buffers from syncer
595 foreach(BufferId bufferId, removedBuffers) {
596 _bufferSyncer->removeBuffer(bufferId);
598 emit networkRemoved(id);
604 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
606 BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
607 if (bufferInfo.isValid()) {
608 _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
613 void CoreSession::clientsConnected()
615 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
616 Identity *identity = 0;
617 CoreNetwork *net = 0;
619 while (netIter != _networks.end()) {
623 if (!net->isConnected())
625 identity = net->identityPtr();
632 if (identity->detachAwayEnabled() && me->isAway()) {
633 net->userInputHandler()->handleAway(BufferInfo(), QString());
639 void CoreSession::clientsDisconnected()
641 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
642 Identity *identity = 0;
643 CoreNetwork *net = 0;
646 while (netIter != _networks.end()) {
650 if (!net->isConnected())
653 identity = net->identityPtr();
660 if (identity->detachAwayEnabled() && !me->isAway()) {
661 if (!identity->detachAwayReason().isEmpty())
662 awayReason = identity->detachAwayReason();
663 net->setAutoAwayActive(true);
664 net->userInputHandler()->handleAway(BufferInfo(), awayReason);
670 void CoreSession::globalAway(const QString &msg)
672 QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
673 CoreNetwork *net = 0;
674 while (netIter != _networks.end()) {
678 if (!net->isConnected())
681 net->userInputHandler()->issueAway(msg, false /* no force away */);
685 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
687 bool success = false;
688 UserId uid = Core::validateUser(userName, oldPassword);
689 if (uid.isValid() && uid == user())
690 success = Core::changeUserPassword(uid, newPassword);
692 emit passwordChanged(peer, success);