1 /***************************************************************************
2 * Copyright (C) 2005-08 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"
25 #include "coresession.h"
26 #include "coreidentity.h"
28 #include "ircserverhandler.h"
29 #include "userinputhandler.h"
30 #include "ctcphandler.h"
32 CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
33 : Network(networkid, session),
34 _coreSession(session),
35 _ircServerHandler(new IrcServerHandler(this)),
36 _userInputHandler(new UserInputHandler(this)),
37 _ctcpHandler(new CtcpHandler(this)),
38 _autoReconnectCount(0),
39 _quitRequested(false),
41 _previousConnectionAttemptFailed(false),
42 _lastUsedServerIndex(0),
44 // TODO make autowho configurable (possibly per-network)
45 _autoWhoEnabled(true),
47 _autoWhoNickLimit(0), // unlimited
50 _autoReconnectTimer.setSingleShot(true);
51 _socketCloseTimer.setSingleShot(true);
52 connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout()));
54 _pingTimer.setInterval(60000);
55 connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
57 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
58 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
60 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
61 foreach(QString chan, channels.keys()) {
62 _channelKeys[chan.toLower()] = channels[chan];
65 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
66 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
67 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
68 connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue()));
69 connect(this, SIGNAL(connectRequested()), this, SLOT(connectToIrc()));
72 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
73 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
74 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
75 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
76 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
78 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
79 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
83 CoreNetwork::~CoreNetwork() {
84 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
85 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
86 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
87 delete _ircServerHandler;
88 delete _userInputHandler;
92 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
93 if(!bufferName.isEmpty()) {
94 IrcChannel *channel = ircChannel(bufferName);
96 return channel->decodeString(string);
98 return decodeString(string);
101 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
102 IrcUser *user = ircUser(userNick);
104 return user->decodeString(string);
105 return decodeString(string);
108 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
109 if(!bufferName.isEmpty()) {
110 IrcChannel *channel = ircChannel(bufferName);
112 return channel->encodeString(string);
114 return encodeString(string);
117 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
118 IrcUser *user = ircUser(userNick);
120 return user->encodeString(string);
121 return encodeString(string);
124 void CoreNetwork::connectToIrc(bool reconnecting) {
125 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
126 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
127 if(unlimitedReconnectRetries())
128 _autoReconnectCount = -1;
130 _autoReconnectCount = autoReconnectRetries();
132 if(serverList().isEmpty()) {
133 qWarning() << "Server list empty, ignoring connect request!";
136 CoreIdentity *identity = identityPtr();
138 qWarning() << "Invalid identity configures, ignoring connect request!";
141 // use a random server?
142 if(useRandomServer()) {
143 _lastUsedServerIndex = qrand() % serverList().size();
144 } else if(_previousConnectionAttemptFailed) {
145 // cycle to next server if previous connection attempt failed
146 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
147 if(++_lastUsedServerIndex == serverList().size()) {
148 _lastUsedServerIndex = 0;
151 _previousConnectionAttemptFailed = false;
153 Server server = usedServer();
154 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
155 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
157 if(server.useProxy) {
158 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
159 socket.setProxy(proxy);
161 socket.setProxy(QNetworkProxy::NoProxy);
165 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
167 socket.connectToHostEncrypted(server.host, server.port);
169 socket.connectToHost(server.host, server.port);
171 socket.connectToHost(server.host, server.port);
175 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
176 _quitRequested = requested; // see socketDisconnected();
177 _autoReconnectTimer.stop();
178 _autoReconnectCount = 0; // prohibiting auto reconnect
179 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
180 if(socket.state() == QAbstractSocket::UnconnectedState) {
181 socketDisconnected();
182 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
183 // we might be in a state waiting for a timeout...
184 // or (!requested) this is a core shutdown...
185 // in both cases we don't really care... set a disconnected state
187 socketDisconnected();
189 // quit gracefully if it's user requested quit
190 userInputHandler()->issueQuit(reason);
191 // the irc server has 10 seconds to close the socket
192 _socketCloseTimer.start(10000);
196 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
197 userInputHandler()->handleUserInput(buf, msg);
200 void CoreNetwork::putRawLine(QByteArray s) {
207 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
210 if(!prefix.isEmpty())
211 msg += ":" + prefix + " ";
212 msg += cmd.toUpper().toAscii();
214 for(int i = 0; i < params.size() - 1; i++) {
215 msg += " " + params[i];
217 if(!params.isEmpty())
218 msg += " :" + params.last();
223 void CoreNetwork::setChannelJoined(const QString &channel) {
224 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
226 Core::setChannelPersistent(userId(), networkId(), channel, true);
227 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
230 void CoreNetwork::setChannelParted(const QString &channel) {
231 removeChannelKey(channel);
232 _autoWhoQueue.removeAll(channel.toLower());
233 _autoWhoInProgress.remove(channel.toLower());
235 Core::setChannelPersistent(userId(), networkId(), channel, false);
238 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
240 removeChannelKey(channel);
242 _channelKeys[channel.toLower()] = key;
246 void CoreNetwork::removeChannelKey(const QString &channel) {
247 _channelKeys.remove(channel.toLower());
250 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
251 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
253 _autoWhoInProgress[channel.toLower()]--;
257 void CoreNetwork::setMyNick(const QString &mynick) {
258 Network::setMyNick(mynick);
259 if(connectionState() == Network::Initializing)
260 networkInitialized();
263 void CoreNetwork::socketHasData() {
264 while(socket.canReadLine()) {
265 QByteArray s = socket.readLine().trimmed();
266 ircServerHandler()->handleServerMsg(s);
270 void CoreNetwork::socketError(QAbstractSocket::SocketError) {
271 _previousConnectionAttemptFailed = true;
272 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
273 emit connectionError(socket.errorString());
274 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
275 emitConnectionError(socket.errorString());
276 if(socket.state() < QAbstractSocket::ConnectedState) {
277 socketDisconnected();
281 void CoreNetwork::socketInitialized() {
282 Server server = usedServer();
284 if(server.useSsl && !socket.isEncrypted())
288 CoreIdentity *identity = identityPtr();
290 qCritical() << "Identity invalid!";
295 // TokenBucket to avoid sending too much at once
296 _messagesPerSecond = 1;
298 _tokenBucket = 5; // init with a full bucket
299 _tokenBucketTimer.start(_messagesPerSecond * 1000);
301 if(!server.password.isEmpty()) {
302 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
304 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
305 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
308 void CoreNetwork::socketDisconnected() {
310 _autoWhoCycleTimer.stop();
311 _autoWhoTimer.stop();
312 _autoWhoQueue.clear();
313 _autoWhoInProgress.clear();
315 _socketCloseTimer.stop();
317 _tokenBucketTimer.stop();
321 foreach(QString channel, me_->channels())
322 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
326 emit disconnected(networkId());
328 setConnectionState(Network::Disconnected);
329 Core::setNetworkConnected(userId(), networkId(), false);
330 } else if(_autoReconnectCount != 0) {
331 setConnectionState(Network::Reconnecting);
332 if(_autoReconnectCount == autoReconnectRetries())
333 doAutoReconnect(); // first try is immediate
335 _autoReconnectTimer.start();
339 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
340 Network::ConnectionState state;
341 switch(socketState) {
342 case QAbstractSocket::UnconnectedState:
343 state = Network::Disconnected;
345 case QAbstractSocket::HostLookupState:
346 case QAbstractSocket::ConnectingState:
347 state = Network::Connecting;
349 case QAbstractSocket::ConnectedState:
350 state = Network::Initializing;
352 case QAbstractSocket::ClosingState:
353 state = Network::Disconnecting;
356 state = Network::Disconnected;
358 setConnectionState(state);
361 void CoreNetwork::networkInitialized() {
362 setConnectionState(Network::Initialized);
365 if(useAutoReconnect()) {
367 _autoReconnectCount = autoReconnectRetries();
374 if(_autoWhoEnabled) {
375 _autoWhoCycleTimer.start();
376 _autoWhoTimer.start();
377 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
380 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
381 Core::setNetworkConnected(userId(), networkId(), true);
384 void CoreNetwork::sendPerform() {
385 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
388 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
389 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
393 foreach(QString line, perform()) {
394 if(!line.isEmpty()) userInput(statusBuf, line);
397 // rejoin channels we've been in
398 QStringList channels, keys;
399 foreach(QString chan, persistentChannels()) {
400 QString key = channelKey(chan);
402 channels.prepend(chan);
405 channels.append(chan);
408 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
409 if(!joinString.isEmpty())
410 userInputHandler()->handleJoin(statusBuf, joinString);
413 void CoreNetwork::setUseAutoReconnect(bool use) {
414 Network::setUseAutoReconnect(use);
416 _autoReconnectTimer.stop();
419 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
420 Network::setAutoReconnectInterval(interval);
421 _autoReconnectTimer.setInterval(interval * 1000);
424 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
425 Network::setAutoReconnectRetries(retries);
426 if(_autoReconnectCount != 0) {
427 if(unlimitedReconnectRetries())
428 _autoReconnectCount = -1;
430 _autoReconnectCount = autoReconnectRetries();
434 void CoreNetwork::doAutoReconnect() {
435 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
436 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
439 if(_autoReconnectCount > 0)
440 _autoReconnectCount--;
444 void CoreNetwork::sendPing() {
445 userInputHandler()->handlePing(BufferInfo(), QString());
448 void CoreNetwork::sendAutoWho() {
449 while(!_autoWhoQueue.isEmpty()) {
450 QString chan = _autoWhoQueue.takeFirst();
451 IrcChannel *ircchan = ircChannel(chan);
452 if(!ircchan) continue;
453 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
454 _autoWhoInProgress[chan]++;
455 putRawLine("WHO " + serverEncode(chan));
456 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
457 // Timer was stopped, means a new cycle is due immediately
458 _autoWhoCycleTimer.start();
465 void CoreNetwork::startAutoWhoCycle() {
466 if(!_autoWhoQueue.isEmpty()) {
467 _autoWhoCycleTimer.stop();
470 _autoWhoQueue = channels();
474 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
476 socket.ignoreSslErrors();
477 // TODO errorhandling
481 void CoreNetwork::fillBucketAndProcessQueue() {
482 if(_tokenBucket < _burstSize) {
486 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
487 writeToSocket(_msgQueue.takeFirst());
491 void CoreNetwork::writeToSocket(const QByteArray &data) {
493 socket.write("\r\n");
497 Network::Server CoreNetwork::usedServer() const {
498 if(_lastUsedServerIndex < serverList().count())
499 return serverList()[_lastUsedServerIndex];
501 return Network::Server();
504 void CoreNetwork::requestConnect() const {
505 if(connectionState() != Disconnected) {
506 qWarning() << "Requesting connect while already being connected!";
509 Network::requestConnect();
512 void CoreNetwork::requestDisconnect() const {
513 if(connectionState() == Disconnected) {
514 qWarning() << "Requesting disconnect while not being connected!";
517 userInputHandler()->handleQuit(BufferInfo(), QString());
520 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
521 Network::Server currentServer = usedServer();
522 setNetworkInfo(info);
523 Core::updateNetwork(coreSession()->user(), info);
525 // update _lastUsedServerIndex;
526 for(int i = 0; i < serverList().count(); i++) {
527 Network::Server server = serverList()[i];
528 if(server.host == currentServer.host && server.port == currentServer.port) {
529 _lastUsedServerIndex = i;