Quassel IRC  Pre-Release
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
coresession.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005-2015 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 "coreeventmanager.h"
31 #include "coreidentity.h"
32 #include "coreignorelistmanager.h"
33 #include "coreirclisthelper.h"
34 #include "corenetwork.h"
35 #include "corenetworkconfig.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"
44 #include "ircuser.h"
45 #include "logger.h"
46 #include "messageevent.h"
47 #include "remotepeer.h"
48 #include "storage.h"
49 #include "util.h"
50 
51 
52 class ProcessMessagesEvent : public QEvent
53 {
54 public:
55  ProcessMessagesEvent() : QEvent(QEvent::User) {}
56 };
57 
58 
59 CoreSession::CoreSession(UserId uid, bool restoreState, QObject *parent)
60  : QObject(parent),
61  _user(uid),
62  _signalProxy(new SignalProxy(SignalProxy::Server, this)),
63  _aliasManager(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)),
69  _coreInfo(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)
79 {
80  SignalProxy *p = signalProxy();
81  p->setHeartBeatInterval(30);
82  p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
83 
84  connect(p, SIGNAL(peerRemoved(Peer*)), SLOT(removeClient(Peer*)));
85 
86  connect(p, SIGNAL(connected()), SLOT(clientsConnected()));
87  connect(p, SIGNAL(disconnected()), SLOT(clientsDisconnected()));
88 
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)));
92 
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 &)));
97 
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)));
102 
103  p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
104  p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
105 
106  loadSettings();
108 
110  eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
113  eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
114  // some events need to be handled after msg generation
117 
118  // periodically save our session state
119  connect(&(Core::instance()->syncTimer()), SIGNAL(timeout()), this, SLOT(saveSessionState()));
120 
122  p->synchronize(&aliasManager());
126  p->synchronize(&_coreInfo);
129  // Restore session state
130  if (restoreState)
132 
133  emit initialized();
134 }
135 
136 
138 {
140  foreach(CoreNetwork *net, _networks.values()) {
141  delete net;
142  }
143 }
144 
145 
147 {
148  if (_networks.contains(id)) return _networks[id];
149  return 0;
150 }
151 
152 
154 {
155  if (_identities.contains(id)) return _identities[id];
156  return 0;
157 }
158 
159 
161 {
162  CoreUserSettings s(user());
163 
164  // migrate to db
165  QList<IdentityId> ids = s.identityIds();
166  QList<NetworkInfo> networkInfos = Core::networks(user());
167  foreach(IdentityId id, ids) {
170  QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
171  while (networkIter != networkInfos.end()) {
172  if (networkIter->identity == id) {
173  networkIter->identity = newId;
174  Core::updateNetwork(user(), *networkIter);
175  networkIter = networkInfos.erase(networkIter);
176  }
177  else {
178  networkIter++;
179  }
180  }
181  s.removeIdentity(id);
182  }
183  // end of migration
184 
186  createIdentity(identity);
187  }
188 
189  foreach(NetworkInfo info, Core::networks(user())) {
190  createNetwork(info);
191  }
192 }
193 
194 
196 {
199  _networkConfig->save();
200 }
201 
202 
204 {
205  QList<NetworkId> nets = Core::connectedNetworks(user());
206  CoreNetwork *net = 0;
207  foreach(NetworkId id, nets) {
208  net = network(id);
209  Q_ASSERT(net);
210  net->connectToIrc();
211  }
212 }
213 
214 
216 {
217  peer->dispatch(sessionState());
218  signalProxy()->addPeer(peer);
219 }
220 
221 
223 {
224  signalProxy()->addPeer(peer);
225  emit sessionState(sessionState());
226 }
227 
228 
230 {
231  RemotePeer *p = qobject_cast<RemotePeer *>(peer);
232  if (p)
233  quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
234 }
235 
236 
237 QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
238 {
239  return Core::persistentChannels(user(), id);
240 }
241 
242 
243 // FIXME switch to BufferId
244 void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
245 {
246  CoreNetwork *net = network(bufinfo.networkId());
247  if (net) {
248  net->userInput(bufinfo, msg);
249  }
250  else {
251  qWarning() << "Trying to send to unconnected network:" << msg;
252  }
253 }
254 
255 
256 // ALL messages coming pass through these functions before going to the GUI.
257 // So this is the perfect place for storing the backlog and log stuff.
259  const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
260 {
261  // U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
262  // text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
263  // KDE's notifications), hence we remove those just to be safe.
264  QString text = text_;
265  text.remove(QChar(0xfdd0)).remove(QChar(0xfdd1));
266  RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
267 
268  // check for HardStrictness ignore
269  CoreNetwork *currentNetwork = network(networkId);
270  QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
271  if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
272  return;
273 
274  _messageQueue << rawMsg;
275  if (!_processMessages) {
276  _processMessages = true;
277  QCoreApplication::postEvent(this, new ProcessMessagesEvent());
278  }
279 }
280 
281 
283 {
284  CoreNetwork *net = qobject_cast<CoreNetwork *>(sender());
285  Q_ASSERT(net);
286  emit displayStatusMsg(net->networkName(), msg);
287 }
288 
289 
291 {
292  recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
293  event->target().isNull() ? "" : event->target(),
294  event->text().isNull() ? "" : event->text(),
295  event->sender().isNull() ? "" : event->sender(),
296  event->msgFlags());
297 }
298 
299 
300 QList<BufferInfo> CoreSession::buffers() const
301 {
302  return Core::requestBuffers(user());
303 }
304 
305 
306 void CoreSession::customEvent(QEvent *event)
307 {
308  if (event->type() != QEvent::User)
309  return;
310 
311  processMessages();
312  event->accept();
313 }
314 
315 
317 {
318  if (_messageQueue.count() == 1) {
319  const RawMessage &rawMsg = _messageQueue.first();
320  bool createBuffer = !(rawMsg.flags & Message::Redirected);
321  BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
322  if (!bufferInfo.isValid()) {
323  Q_ASSERT(!createBuffer);
324  bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
325  }
326  Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
327  if(Core::storeMessage(msg))
328  emit displayMsg(msg);
329  }
330  else {
331  QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
332  MessageList messages;
333  QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
334  BufferInfo bufferInfo;
335  for (int i = 0; i < _messageQueue.count(); i++) {
336  const RawMessage &rawMsg = _messageQueue.at(i);
337  if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
338  bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
339  }
340  else {
341  bool createBuffer = !(rawMsg.flags & Message::Redirected);
342  bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
343  if (!bufferInfo.isValid()) {
344  Q_ASSERT(!createBuffer);
345  redirectedMessages << rawMsg;
346  continue;
347  }
348  bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
349  }
350  Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
351  messages << msg;
352  }
353 
354  // recheck if there exists a buffer to store a redirected message in
355  for (int i = 0; i < redirectedMessages.count(); i++) {
356  const RawMessage &rawMsg = redirectedMessages.at(i);
357  if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
358  bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
359  }
360  else {
361  // no luck -> we store them in the StatusBuffer
362  bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
363  // add the StatusBuffer to the Cache in case there are more Messages for the original target
364  bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
365  }
366  Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, rawMsg.flags);
367  messages << msg;
368  }
369 
370  if(Core::storeMessages(messages)) {
371  // FIXME: extend protocol to a displayMessages(MessageList)
372  for (int i = 0; i < messages.count(); i++) {
373  emit displayMsg(messages[i]);
374  }
375  }
376  }
377  _processMessages = false;
378  _messageQueue.clear();
379 }
380 
381 
383 {
384  QVariantList bufferInfos;
385  QVariantList networkIds;
386  QVariantList identities;
387 
388  foreach(const BufferInfo &id, buffers())
389  bufferInfos << QVariant::fromValue(id);
390  foreach(const NetworkId &id, _networks.keys())
391  networkIds << QVariant::fromValue(id);
392  foreach(const Identity *i, _identities.values())
393  identities << QVariant::fromValue(*i);
394 
395  return Protocol::SessionState(identities, bufferInfos, networkIds);
396 }
397 
398 
400 {
401  signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
402  signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
403 
404  // FIXME
405  //QScriptValue storage_ = scriptEngine->newQObject(storage);
406  //scriptEngine->globalObject().setProperty("storage", storage_);
407 }
408 
409 
410 void CoreSession::scriptRequest(QString script)
411 {
412  emit scriptResult(scriptEngine->evaluate(script).toString());
413 }
414 
415 
416 /*** Identity Handling ***/
417 void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
418 {
419 #ifndef HAVE_SSL
420  Q_UNUSED(additional)
421 #endif
422 
423  CoreIdentity coreIdentity(identity);
424 #ifdef HAVE_SSL
425  if (additional.contains("KeyPem"))
426  coreIdentity.setSslKey(additional["KeyPem"].toByteArray());
427  if (additional.contains("CertPem"))
428  coreIdentity.setSslCert(additional["CertPem"].toByteArray());
429 #endif
430  qDebug() << Q_FUNC_INFO;
431  IdentityId id = Core::createIdentity(user(), coreIdentity);
432  if (!id.isValid())
433  return;
434  else
435  createIdentity(coreIdentity);
436 }
437 
438 
440 {
441  CoreIdentity *coreIdentity = new CoreIdentity(identity, this);
442  _identities[identity.id()] = coreIdentity;
443  // CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
444  coreIdentity->synchronize(signalProxy());
445  connect(coreIdentity, SIGNAL(updated()), this, SLOT(updateIdentityBySender()));
446  emit identityCreated(*coreIdentity);
447 }
448 
449 
451 {
452  CoreIdentity *identity = qobject_cast<CoreIdentity *>(sender());
453  if (!identity)
454  return;
455  Core::updateIdentity(user(), *identity);
456 }
457 
458 
460 {
461  CoreIdentity *identity = _identities.take(id);
462  if (identity) {
463  emit identityRemoved(id);
464  Core::removeIdentity(user(), id);
465  identity->deleteLater();
466  }
467 }
468 
469 
470 /*** Network Handling ***/
471 
472 void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
473 {
474  NetworkInfo info = info_;
475  int id;
476 
477  if (!info.networkId.isValid())
478  Core::createNetwork(user(), info);
479 
480  if (!info.networkId.isValid()) {
481  qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
482  return;
483  }
484 
485  id = info.networkId.toInt();
486  if (!_networks.contains(id)) {
487  // create persistent chans
488  QRegExp rx("\\s*(\\S+)(?:\\s*(\\S+))?\\s*");
489  foreach(QString channel, persistentChans) {
490  if (!rx.exactMatch(channel)) {
491  qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
492  continue;
493  }
494  Core::bufferInfo(user(), info.networkId, BufferInfo::ChannelBuffer, rx.cap(1), true);
495  Core::setChannelPersistent(user(), info.networkId, rx.cap(1), true);
496  if (!rx.cap(2).isEmpty())
497  Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
498  }
499 
500  CoreNetwork *net = new CoreNetwork(id, this);
501  connect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)),
502  SLOT(recvMessageFromServer(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)));
503  connect(net, SIGNAL(displayStatusMsg(QString)), SLOT(recvStatusMsgFromServer(QString)));
504  connect(net, SIGNAL(disconnected(NetworkId)), SIGNAL(networkDisconnected(NetworkId)));
505 
506  net->setNetworkInfo(info);
507  net->setProxy(signalProxy());
508  _networks[id] = net;
509  signalProxy()->synchronize(net);
510  emit networkCreated(id);
511  }
512  else {
513  qWarning() << qPrintable(tr("CoreSession::createNetwork(): Trying to create a network that already exists, updating instead!"));
514  _networks[info.networkId]->requestSetNetworkInfo(info);
515  }
516 }
517 
518 
520 {
521  // Make sure the network is disconnected!
522  CoreNetwork *net = network(id);
523  if (!net)
524  return;
525 
526  if (net->connectionState() != Network::Disconnected) {
527  // make sure we no longer receive data from the tcp buffer
528  disconnect(net, SIGNAL(displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), this, 0);
529  disconnect(net, SIGNAL(displayStatusMsg(QString)), this, 0);
530  connect(net, SIGNAL(disconnected(NetworkId)), this, SLOT(destroyNetwork(NetworkId)));
531  net->disconnectFromIrc();
532  }
533  else {
534  destroyNetwork(id);
535  }
536 }
537 
538 
540 {
541  QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
542  Network *net = _networks.take(id);
543  if (net && Core::removeNetwork(user(), id)) {
544  // make sure that all unprocessed RawMessages from this network are removed
545  QList<RawMessage>::iterator messageIter = _messageQueue.begin();
546  while (messageIter != _messageQueue.end()) {
547  if (messageIter->networkId == id) {
548  messageIter = _messageQueue.erase(messageIter);
549  }
550  else {
551  messageIter++;
552  }
553  }
554  // remove buffers from syncer
555  foreach(BufferId bufferId, removedBuffers) {
556  _bufferSyncer->removeBuffer(bufferId);
557  }
558  emit networkRemoved(id);
559  net->deleteLater();
560  }
561 }
562 
563 
564 void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
565 {
566  BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
567  if (bufferInfo.isValid()) {
568  _bufferSyncer->renameBuffer(bufferInfo.bufferId(), newName);
569  }
570 }
571 
572 
574 {
575  QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
576  Identity *identity = 0;
577  CoreNetwork *net = 0;
578  IrcUser *me = 0;
579  while (netIter != _networks.end()) {
580  net = *netIter;
581  netIter++;
582 
583  if (!net->isConnected())
584  continue;
585  identity = net->identityPtr();
586  if (!identity)
587  continue;
588  me = net->me();
589  if (!me)
590  continue;
591 
592  if (identity->detachAwayEnabled() && me->isAway()) {
593  net->userInputHandler()->handleAway(BufferInfo(), QString());
594  }
595  }
596 }
597 
598 
600 {
601  QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
602  Identity *identity = 0;
603  CoreNetwork *net = 0;
604  IrcUser *me = 0;
605  QString awayReason;
606  while (netIter != _networks.end()) {
607  net = *netIter;
608  netIter++;
609 
610  if (!net->isConnected())
611  continue;
612 
613  identity = net->identityPtr();
614  if (!identity)
615  continue;
616  me = net->me();
617  if (!me)
618  continue;
619 
620  if (identity->detachAwayEnabled() && !me->isAway()) {
621  if (!identity->detachAwayReason().isEmpty())
622  awayReason = identity->detachAwayReason();
623  net->setAutoAwayActive(true);
624  net->userInputHandler()->handleAway(BufferInfo(), awayReason);
625  }
626  }
627 }
628 
629 
630 void CoreSession::globalAway(const QString &msg)
631 {
632  QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
633  CoreNetwork *net = 0;
634  while (netIter != _networks.end()) {
635  net = *netIter;
636  netIter++;
637 
638  if (!net->isConnected())
639  continue;
640 
641  net->userInputHandler()->issueAway(msg, false /* no force away */);
642  }
643 }
644 
645 void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword)
646 {
647  bool success = false;
648  UserId uid = Core::validateUser(userName, oldPassword);
649  if (uid.isValid() && uid == user())
650  success = Core::changeUserPassword(uid, newPassword);
651 
652  emit passwordChanged(peer, success);
653 }