1 /***************************************************************************
2 * Copyright (C) 2005-09 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include "corenetwork.h"
24 #include "coresession.h"
25 #include "coreidentity.h"
27 #include "ircserverhandler.h"
28 #include "userinputhandler.h"
29 #include "ctcphandler.h"
31 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
32 : Network(networkid, session),
33 _coreSession(session),
34 _ircServerHandler(new IrcServerHandler(this)),
35 _userInputHandler(new UserInputHandler(this)),
36 _ctcpHandler(new CtcpHandler(this)),
37 _autoReconnectCount(0),
38 _quitRequested(false),
40 _previousConnectionAttemptFailed(false),
41 _lastUsedServerIndex(0),
43 // TODO make autowho configurable (possibly per-network)
44 _autoWhoEnabled(true),
46 _autoWhoNickLimit(0), // unlimited
49 _autoReconnectTimer.setSingleShot(true);
50 _socketCloseTimer.setSingleShot(true);
51 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
53 _pingTimer.setInterval(60000);
54 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
56 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
57 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
59 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
60 foreach(QString chan, channels.keys()) {
61 _channelKeys[chan.toLower()] = channels[chan];
64 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
65 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
66 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
67 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
68 connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
71 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
72 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
73 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
74 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
75 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
77 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
78 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
82 CoreNetwork::~CoreNetwork() {
83 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
84 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
87 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
88 delete _ircServerHandler;
89 delete _userInputHandler;
93 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
94 if(!bufferName.isEmpty()) {
95 IrcChannel *channel = ircChannel(bufferName);
97 return channel->decodeString(string);
99 return decodeString(string);
102 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
103 IrcUser *user = ircUser(userNick);
105 return user->decodeString(string);
106 return decodeString(string);
109 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
110 if(!bufferName.isEmpty()) {
111 IrcChannel *channel = ircChannel(bufferName);
113 return channel->encodeString(string);
115 return encodeString(string);
118 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
119 IrcUser *user = ircUser(userNick);
121 return user->encodeString(string);
122 return encodeString(string);
125 void CoreNetwork::connectToIrc(bool reconnecting) {
126 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
127 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
128 if(unlimitedReconnectRetries())
129 _autoReconnectCount = -1;
131 _autoReconnectCount = autoReconnectRetries();
133 if(serverList().isEmpty()) {
134 qWarning() << "Server list empty, ignoring connect request!";
137 CoreIdentity *identity = identityPtr();
139 qWarning() << "Invalid identity configures, ignoring connect request!";
142 // use a random server?
143 if(useRandomServer()) {
144 _lastUsedServerIndex = qrand() % serverList().size();
145 } else if(_previousConnectionAttemptFailed) {
146 // cycle to next server if previous connection attempt failed
147 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
148 if(++_lastUsedServerIndex >= serverList().size()) {
149 _lastUsedServerIndex = 0;
152 _previousConnectionAttemptFailed = false;
154 Server server = usedServer();
155 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
156 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
158 if(server.useProxy) {
159 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
160 socket.setProxy(proxy);
162 socket.setProxy(QNetworkProxy::NoProxy);
166 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
168 CoreIdentity *identity = identityPtr();
170 socket.setLocalCertificate(identity->sslCert());
171 socket.setPrivateKey(identity->sslKey());
173 socket.connectToHostEncrypted(server.host, server.port);
175 socket.connectToHost(server.host, server.port);
178 socket.connectToHost(server.host, server.port);
182 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
183 _quitRequested = requested; // see socketDisconnected();
184 _autoReconnectTimer.stop();
185 _autoReconnectCount = 0; // prohibiting auto reconnect
186 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
187 if(socket.state() == QAbstractSocket::UnconnectedState) {
188 socketDisconnected();
189 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
190 // we might be in a state waiting for a timeout...
191 // or (!requested) this is a core shutdown...
192 // in both cases we don't really care... set a disconnected state
194 socketDisconnected();
196 // quit gracefully if it's user requested quit
197 userInputHandler()->issueQuit(reason);
198 // the irc server has 10 seconds to close the socket
199 _socketCloseTimer.start(10000);
203 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
204 userInputHandler()->handleUserInput(buf, msg);
207 void CoreNetwork::putRawLine(QByteArray s) {
214 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
217 if(!prefix.isEmpty())
218 msg += ":" + prefix + " ";
219 msg += cmd.toUpper().toAscii();
221 for(int i = 0; i < params.size() - 1; i++) {
222 msg += " " + params[i];
224 if(!params.isEmpty())
225 msg += " :" + params.last();
230 void CoreNetwork::setChannelJoined(const QString &channel) {
231 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
233 Core::setChannelPersistent(userId(), networkId(), channel, true);
234 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
237 void CoreNetwork::setChannelParted(const QString &channel) {
238 removeChannelKey(channel);
239 _autoWhoQueue.removeAll(channel.toLower());
240 _autoWhoInProgress.remove(channel.toLower());
242 Core::setChannelPersistent(userId(), networkId(), channel, false);
245 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
247 removeChannelKey(channel);
249 _channelKeys[channel.toLower()] = key;
253 void CoreNetwork::removeChannelKey(const QString &channel) {
254 _channelKeys.remove(channel.toLower());
257 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
258 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
260 _autoWhoInProgress[channel.toLower()]--;
264 void CoreNetwork::setMyNick(const QString &mynick) {
265 Network::setMyNick(mynick);
266 if(connectionState() == Network::Initializing)
267 networkInitialized();
270 void CoreNetwork::socketHasData() {
271 while(socket.canReadLine()) {
272 QByteArray s = socket.readLine().trimmed();
273 ircServerHandler()->handleServerMsg(s);
277 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
278 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
281 _previousConnectionAttemptFailed = true;
282 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
283 emit connectionError(socket.errorString());
284 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
285 emitConnectionError(socket.errorString());
286 if(socket.state() < QAbstractSocket::ConnectedState) {
287 socketDisconnected();
291 void CoreNetwork::socketInitialized() {
292 Server server = usedServer();
294 if(server.useSsl && !socket.isEncrypted())
298 CoreIdentity *identity = identityPtr();
300 qCritical() << "Identity invalid!";
305 // TokenBucket to avoid sending too much at once
306 _messagesPerSecond = 1;
308 _tokenBucket = 5; // init with a full bucket
309 _tokenBucketTimer.start(_messagesPerSecond * 1000);
311 if(!server.password.isEmpty()) {
312 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
314 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
315 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
318 void CoreNetwork::socketDisconnected() {
320 _autoWhoCycleTimer.stop();
321 _autoWhoTimer.stop();
322 _autoWhoQueue.clear();
323 _autoWhoInProgress.clear();
325 _socketCloseTimer.stop();
327 _tokenBucketTimer.stop();
331 foreach(QString channel, me_->channels())
332 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
336 emit disconnected(networkId());
338 setConnectionState(Network::Disconnected);
339 Core::setNetworkConnected(userId(), networkId(), false);
340 } else if(_autoReconnectCount != 0) {
341 setConnectionState(Network::Reconnecting);
342 if(_autoReconnectCount == autoReconnectRetries())
343 doAutoReconnect(); // first try is immediate
345 _autoReconnectTimer.start();
349 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
350 Network::ConnectionState state;
351 switch(socketState) {
352 case QAbstractSocket::UnconnectedState:
353 state = Network::Disconnected;
355 case QAbstractSocket::HostLookupState:
356 case QAbstractSocket::ConnectingState:
357 state = Network::Connecting;
359 case QAbstractSocket::ConnectedState:
360 state = Network::Initializing;
362 case QAbstractSocket::ClosingState:
363 state = Network::Disconnecting;
366 state = Network::Disconnected;
368 setConnectionState(state);
371 void CoreNetwork::networkInitialized() {
372 setConnectionState(Network::Initialized);
374 _quitRequested = false;
376 if(useAutoReconnect()) {
378 _autoReconnectCount = autoReconnectRetries();
385 if(_autoWhoEnabled) {
386 _autoWhoCycleTimer.start();
387 _autoWhoTimer.start();
388 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
391 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
392 Core::setNetworkConnected(userId(), networkId(), true);
395 void CoreNetwork::sendPerform() {
396 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
399 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
400 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
404 foreach(QString line, perform()) {
405 if(!line.isEmpty()) userInput(statusBuf, line);
408 // rejoin channels we've been in
409 if(rejoinChannels()) {
410 QStringList channels, keys;
411 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
412 QString key = channelKey(chan);
414 channels.prepend(chan);
417 channels.append(chan);
420 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
421 if(!joinString.isEmpty())
422 userInputHandler()->handleJoin(statusBuf, joinString);
426 void CoreNetwork::setUseAutoReconnect(bool use) {
427 Network::setUseAutoReconnect(use);
429 _autoReconnectTimer.stop();
432 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
433 Network::setAutoReconnectInterval(interval);
434 _autoReconnectTimer.setInterval(interval * 1000);
437 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
438 Network::setAutoReconnectRetries(retries);
439 if(_autoReconnectCount != 0) {
440 if(unlimitedReconnectRetries())
441 _autoReconnectCount = -1;
443 _autoReconnectCount = autoReconnectRetries();
447 void CoreNetwork::doAutoReconnect() {
448 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
449 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
452 if(_autoReconnectCount > 0)
453 _autoReconnectCount--;
457 void CoreNetwork::sendPing() {
458 userInputHandler()->handlePing(BufferInfo(), QString());
461 void CoreNetwork::sendAutoWho() {
462 while(!_autoWhoQueue.isEmpty()) {
463 QString chan = _autoWhoQueue.takeFirst();
464 IrcChannel *ircchan = ircChannel(chan);
465 if(!ircchan) continue;
466 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
467 _autoWhoInProgress[chan]++;
468 putRawLine("WHO " + serverEncode(chan));
469 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
470 // Timer was stopped, means a new cycle is due immediately
471 _autoWhoCycleTimer.start();
478 void CoreNetwork::startAutoWhoCycle() {
479 if(!_autoWhoQueue.isEmpty()) {
480 _autoWhoCycleTimer.stop();
483 _autoWhoQueue = channels();
487 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
489 socket.ignoreSslErrors();
490 // TODO errorhandling
494 void CoreNetwork::fillBucketAndProcessQueue() {
495 if(_tokenBucket < _burstSize) {
499 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
500 writeToSocket(_msgQueue.takeFirst());
504 void CoreNetwork::writeToSocket(const QByteArray &data) {
506 socket.write("\r\n");
510 Network::Server CoreNetwork::usedServer() const {
511 if(_lastUsedServerIndex < serverList().count())
512 return serverList()[_lastUsedServerIndex];
514 if(!serverList().isEmpty())
515 return serverList()[0];
517 return Network::Server();
520 void CoreNetwork::requestConnect() const {
521 if(connectionState() != Disconnected) {
522 qWarning() << "Requesting connect while already being connected!";
525 Network::requestConnect();
528 void CoreNetwork::requestDisconnect() const {
529 if(connectionState() == Disconnected) {
530 qWarning() << "Requesting disconnect while not being connected!";
533 userInputHandler()->handleQuit(BufferInfo(), QString());
536 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
537 Network::Server currentServer = usedServer();
538 setNetworkInfo(info);
539 Core::updateNetwork(coreSession()->user(), info);
541 // the order of the servers might have changed,
542 // so we try to find the previously used server
543 _lastUsedServerIndex = 0;
544 for(int i = 0; i < serverList().count(); i++) {
545 Network::Server server = serverList()[i];
546 if(server.host == currentServer.host && server.port == currentServer.port) {
547 _lastUsedServerIndex = i;