+ : Network(networkid, session),
+ _coreSession(session),
+ _userInputHandler(new CoreUserInputHandler(this)),
+ _autoReconnectCount(0),
+ _quitRequested(false),
+
+ _previousConnectionAttemptFailed(false),
+ _lastUsedServerIndex(0),
+
+ _lastPingTime(0),
+ _pingCount(0),
+ _requestedUserModes('-')
+{
+ _autoReconnectTimer.setSingleShot(true);
+ _socketCloseTimer.setSingleShot(true);
+ connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
+
+ setPingInterval(networkConfig()->pingInterval());
+ connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
+
+ setAutoWhoDelay(networkConfig()->autoWhoDelay());
+ setAutoWhoInterval(networkConfig()->autoWhoInterval());
+
+ QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
+ foreach(QString chan, channels.keys()) {
+ _channelKeys[chan.toLower()] = channels[chan];
+ }
+
+ connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool)));
+ connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int)));
+ connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool)));
+ connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int)));
+ connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int)));
+
+ connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
+ connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
+ connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
+ connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
+
+ connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
+ connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
+ connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
+ connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
+ connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
+#ifdef HAVE_SSL
+ connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
+ connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
+#endif
+ connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *)));
+
+ if (Quassel::isOptionSet("oidentd")) {
+ connect(this, SIGNAL(socketInitialized(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection);
+ connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)));
+ }
+}
+
+
+CoreNetwork::~CoreNetwork()
+{
+ if (connectionState() != Disconnected && connectionState() != Network::Reconnecting)
+ disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
+ disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
+ delete _userInputHandler;
+}
+
+
+QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
+{
+ if (!bufferName.isEmpty()) {
+ IrcChannel *channel = ircChannel(bufferName);
+ if (channel)
+ return channel->decodeString(string);
+ }
+ return decodeString(string);
+}
+
+
+QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
+{
+ IrcUser *user = ircUser(userNick);
+ if (user)
+ return user->decodeString(string);
+ return decodeString(string);
+}
+
+
+QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
+{
+ if (!bufferName.isEmpty()) {
+ IrcChannel *channel = ircChannel(bufferName);
+ if (channel)
+ return channel->encodeString(string);
+ }
+ return encodeString(string);
+}
+
+
+QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
+{
+ IrcUser *user = ircUser(userNick);
+ if (user)
+ return user->encodeString(string);
+ return encodeString(string);
+}
+
+
+void CoreNetwork::connectToIrc(bool reconnecting)
+{
+ if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
+ _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
+ if (unlimitedReconnectRetries())
+ _autoReconnectCount = -1;
+ else
+ _autoReconnectCount = autoReconnectRetries();
+ }
+ if (serverList().isEmpty()) {
+ qWarning() << "Server list empty, ignoring connect request!";
+ return;
+ }
+ CoreIdentity *identity = identityPtr();
+ if (!identity) {
+ qWarning() << "Invalid identity configures, ignoring connect request!";
+ return;
+ }
+
+ // cleaning up old quit reason
+ _quitReason.clear();
+
+ // use a random server?
+ if (useRandomServer()) {
+ _lastUsedServerIndex = qrand() % serverList().size();
+ }
+ else if (_previousConnectionAttemptFailed) {
+ // cycle to next server if previous connection attempt failed
+ displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
+ if (++_lastUsedServerIndex >= serverList().size()) {
+ _lastUsedServerIndex = 0;
+ }
+ }
+ _previousConnectionAttemptFailed = false;
+
+ Server server = usedServer();
+ displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
+ displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
+
+ if (server.useProxy) {
+ QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
+ socket.setProxy(proxy);
+ }
+ else {
+ socket.setProxy(QNetworkProxy::NoProxy);
+ }
+
+#ifdef HAVE_SSL
+ socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
+ if (server.useSsl) {
+ CoreIdentity *identity = identityPtr();
+ if (identity) {
+ socket.setLocalCertificate(identity->sslCert());
+ socket.setPrivateKey(identity->sslKey());
+ }
+ socket.connectToHostEncrypted(server.host, server.port);
+ }
+ else {
+ socket.connectToHost(server.host, server.port);
+ }
+#else
+ socket.connectToHost(server.host, server.port);
+#endif
+}
+
+
+void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
+{
+ _quitRequested = requested; // see socketDisconnected();
+ if (!withReconnect) {
+ _autoReconnectTimer.stop();
+ _autoReconnectCount = 0; // prohibiting auto reconnect
+ }
+ disablePingTimeout();
+ _msgQueue.clear();
+
+ IrcUser *me_ = me();
+ if (me_) {
+ QString awayMsg;
+ if (me_->isAway())
+ awayMsg = me_->awayMessage();
+ Core::setAwayMessage(userId(), networkId(), awayMsg);
+ }
+
+ if (reason.isEmpty() && identityPtr())
+ _quitReason = identityPtr()->quitReason();
+ else
+ _quitReason = reason;
+
+ displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
+ switch (socket.state()) {
+ case QAbstractSocket::ConnectedState:
+ userInputHandler()->issueQuit(_quitReason);
+ if (requested || withReconnect) {
+ // the irc server has 10 seconds to close the socket
+ _socketCloseTimer.start(10000);
+ break;
+ }
+ default:
+ socket.close();
+ socketDisconnected();
+ }
+}
+
+
+void CoreNetwork::userInput(BufferInfo buf, QString msg)
+{
+ userInputHandler()->handleUserInput(buf, msg);
+}
+
+
+void CoreNetwork::putRawLine(QByteArray s)
+{
+ if (_tokenBucket > 0)
+ writeToSocket(s);
+ else
+ _msgQueue.append(s);
+}
+
+
+void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix)
+{
+ QByteArray msg;
+
+ if (!prefix.isEmpty())
+ msg += ":" + prefix + " ";
+ msg += cmd.toUpper().toAscii();
+
+ for (int i = 0; i < params.size() - 1; i++) {
+ msg += " " + params[i];
+ }
+ if (!params.isEmpty())
+ msg += " :" + params.last();
+
+ putRawLine(msg);
+}
+
+
+void CoreNetwork::setChannelJoined(const QString &channel)
+{
+ _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
+
+ Core::setChannelPersistent(userId(), networkId(), channel, true);
+ Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
+}
+
+
+void CoreNetwork::setChannelParted(const QString &channel)
+{
+ removeChannelKey(channel);
+ _autoWhoQueue.removeAll(channel.toLower());
+ _autoWhoPending.remove(channel.toLower());
+
+ Core::setChannelPersistent(userId(), networkId(), channel, false);
+}
+
+
+void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
+{
+ if (key.isEmpty()) {
+ removeChannelKey(channel);
+ }
+ else {
+ _channelKeys[channel.toLower()] = key;
+ }
+}
+
+
+void CoreNetwork::removeChannelKey(const QString &channel)
+{
+ _channelKeys.remove(channel.toLower());
+}
+
+
+#ifdef HAVE_QCA2
+Cipher *CoreNetwork::cipher(const QString &target) const
+{
+ if (target.isEmpty())
+ return 0;
+
+ if (!Cipher::neededFeaturesAvailable())
+ return 0;
+
+ QByteArray key = cipherKey(target);
+ if (key.isEmpty())
+ return 0;
+
+ CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
+ if (channel) {
+ if (channel->cipher()->setKey(key))
+ return channel->cipher();
+ }
+ else {
+ CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target));
+ if (user && user->cipher()->setKey(key))
+ return user->cipher();
+ }
+ return 0;
+}
+
+
+QByteArray CoreNetwork::cipherKey(const QString &recipient) const
+{
+ return _cipherKeys.value(recipient.toLower(), QByteArray());
+}
+
+
+void CoreNetwork::setCipherKey(const QString &recipient, const QByteArray &key)
+{
+ if (!key.isEmpty())
+ _cipherKeys[recipient.toLower()] = key;
+ else
+ _cipherKeys.remove(recipient.toLower());
+}
+
+
+#endif /* HAVE_QCA2 */
+
+bool CoreNetwork::setAutoWhoDone(const QString &channel)
+{
+ QString chan = channel.toLower();
+ if (_autoWhoPending.value(chan, 0) <= 0)
+ return false;
+ if (--_autoWhoPending[chan] <= 0)
+ _autoWhoPending.remove(chan);
+ return true;
+}
+
+
+void CoreNetwork::setMyNick(const QString &mynick)
+{
+ Network::setMyNick(mynick);
+ if (connectionState() == Network::Initializing)
+ networkInitialized();
+}
+
+
+void CoreNetwork::socketHasData()
+{
+ while (socket.canReadLine()) {
+ QByteArray s = socket.readLine().trimmed();
+ NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
+#if QT_VERSION >= 0x040700
+ event->setTimestamp(QDateTime::currentDateTimeUtc());
+#else
+ event->setTimestamp(QDateTime::currentDateTime().toUTC());
+#endif
+ emit newEvent(event);
+ }
+}
+
+
+void CoreNetwork::socketError(QAbstractSocket::SocketError error)
+{
+ if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
+ return;
+
+ _previousConnectionAttemptFailed = true;
+ qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
+ emit connectionError(socket.errorString());
+ displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
+ emitConnectionError(socket.errorString());
+ if (socket.state() < QAbstractSocket::ConnectedState) {
+ socketDisconnected();
+ }
+}
+
+
+void CoreNetwork::socketInitialized()
+{
+ Server server = usedServer();
+#ifdef HAVE_SSL
+ if (server.useSsl && !socket.isEncrypted())
+ return;
+#endif
+
+ CoreIdentity *identity = identityPtr();
+ if (!identity) {
+ qCritical() << "Identity invalid!";
+ disconnectFromIrc();
+ return;
+ }
+
+ emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort());
+
+ // TokenBucket to avoid sending too much at once
+ _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay)
+ _burstSize = 5;
+ _tokenBucket = _burstSize; // init with a full bucket
+ _tokenBucketTimer.start(_messageDelay);
+
+ if (networkInfo().useSasl) {
+ putRawLine(serverEncode(QString("CAP REQ :sasl")));
+ }
+ if (!server.password.isEmpty()) {
+ putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
+ }
+ QString nick;
+ if (identity->nicks().isEmpty()) {
+ nick = "quassel";
+ qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id();
+ }
+ else {
+ nick = identity->nicks()[0];
+ }
+ putRawLine(serverEncode(QString("NICK :%1").arg(nick)));
+ putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
+}
+
+
+void CoreNetwork::socketDisconnected()