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"
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(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(connected()), this, SLOT(sslSocketConnected()));
78 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized()));
79 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
81 connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized()));
85 CoreNetwork::~CoreNetwork() {
86 if(connectionState() != Disconnected && connectionState() != Network::Reconnecting)
87 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
88 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
89 delete _ircServerHandler;
90 delete _userInputHandler;
94 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
95 if(!bufferName.isEmpty()) {
96 IrcChannel *channel = ircChannel(bufferName);
98 return channel->decodeString(string);
100 return decodeString(string);
103 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
104 IrcUser *user = ircUser(userNick);
106 return user->decodeString(string);
107 return decodeString(string);
110 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
111 if(!bufferName.isEmpty()) {
112 IrcChannel *channel = ircChannel(bufferName);
114 return channel->encodeString(string);
116 return encodeString(string);
119 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
120 IrcUser *user = ircUser(userNick);
122 return user->encodeString(string);
123 return encodeString(string);
126 void CoreNetwork::connectToIrc(bool reconnecting) {
127 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
128 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
129 if(unlimitedReconnectRetries())
130 _autoReconnectCount = -1;
132 _autoReconnectCount = autoReconnectRetries();
134 if(serverList().isEmpty()) {
135 qWarning() << "Server list empty, ignoring connect request!";
138 Identity *identity = identityPtr();
140 qWarning() << "Invalid identity configures, ignoring connect request!";
143 // use a random server?
144 if(useRandomServer()) {
145 _lastUsedServerIndex = qrand() % serverList().size();
146 } else if(_previousConnectionAttemptFailed) {
147 // cycle to next server if previous connection attempt failed
148 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
149 if(++_lastUsedServerIndex == serverList().size()) {
150 _lastUsedServerIndex = 0;
153 _previousConnectionAttemptFailed = false;
155 Server server = usedServer();
156 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
157 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
158 socket.connectToHost(server.host, server.port);
161 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
162 _quitRequested = requested; // see socketDisconnected();
163 _autoReconnectTimer.stop();
164 _autoReconnectCount = 0; // prohibiting auto reconnect
165 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
166 if(socket.state() == QAbstractSocket::UnconnectedState) {
167 socketDisconnected();
168 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
169 // we might be in a state waiting for a timeout...
170 // or (!requested) this is a core shutdown...
171 // in both cases we don't really care... set a disconnected state
173 socketDisconnected();
175 // quit gracefully if it's user requested quit
176 userInputHandler()->issueQuit(reason);
177 // the irc server has 10 seconds to close the socket
178 _socketCloseTimer.start(10000);
182 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
183 userInputHandler()->handleUserInput(buf, msg);
186 void CoreNetwork::putRawLine(QByteArray s) {
193 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
196 if(!prefix.isEmpty())
197 msg += ":" + prefix + " ";
198 msg += cmd.toUpper().toAscii();
200 for(int i = 0; i < params.size() - 1; i++) {
201 msg += " " + params[i];
203 if(!params.isEmpty())
204 msg += " :" + params.last();
209 void CoreNetwork::setChannelJoined(const QString &channel) {
210 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
212 Core::setChannelPersistent(userId(), networkId(), channel, true);
213 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
216 void CoreNetwork::setChannelParted(const QString &channel) {
217 removeChannelKey(channel);
218 _autoWhoQueue.removeAll(channel.toLower());
219 _autoWhoInProgress.remove(channel.toLower());
221 Core::setChannelPersistent(userId(), networkId(), channel, false);
224 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
226 removeChannelKey(channel);
228 _channelKeys[channel.toLower()] = key;
232 void CoreNetwork::removeChannelKey(const QString &channel) {
233 _channelKeys.remove(channel.toLower());
236 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
237 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
239 _autoWhoInProgress[channel.toLower()]--;
243 void CoreNetwork::setMyNick(const QString &mynick) {
244 Network::setMyNick(mynick);
245 if(connectionState() == Network::Initializing)
246 networkInitialized();
249 void CoreNetwork::socketHasData() {
250 while(socket.canReadLine()) {
251 QByteArray s = socket.readLine().trimmed();
252 ircServerHandler()->handleServerMsg(s);
256 void CoreNetwork::socketError(QAbstractSocket::SocketError) {
257 _previousConnectionAttemptFailed = true;
258 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
259 emit connectionError(socket.errorString());
260 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
261 emitConnectionError(socket.errorString());
262 if(socket.state() < QAbstractSocket::ConnectedState) {
263 socketDisconnected();
268 void CoreNetwork::sslSocketConnected() {
269 if(!usedServer().useSsl)
272 socket.startClientEncryption();
276 void CoreNetwork::socketInitialized() {
277 Identity *identity = identityPtr();
279 qCritical() << "Identity invalid!";
284 // TokenBucket to avoid sending too much at once
285 _messagesPerSecond = 1;
287 _tokenBucket = 5; // init with a full bucket
288 _tokenBucketTimer.start(_messagesPerSecond * 1000);
290 QString passwd = usedServer().password;
291 if(!passwd.isEmpty()) {
292 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
294 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
295 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
298 void CoreNetwork::socketDisconnected() {
300 _autoWhoCycleTimer.stop();
301 _autoWhoTimer.stop();
302 _autoWhoQueue.clear();
303 _autoWhoInProgress.clear();
305 _socketCloseTimer.stop();
307 _tokenBucketTimer.stop();
311 foreach(QString channel, me_->channels())
312 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
316 emit disconnected(networkId());
318 setConnectionState(Network::Disconnected);
319 Core::setNetworkConnected(userId(), networkId(), false);
320 } else if(_autoReconnectCount != 0) {
321 setConnectionState(Network::Reconnecting);
322 if(_autoReconnectCount == autoReconnectRetries())
323 doAutoReconnect(); // first try is immediate
325 _autoReconnectTimer.start();
329 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
330 Network::ConnectionState state;
331 switch(socketState) {
332 case QAbstractSocket::UnconnectedState:
333 state = Network::Disconnected;
335 case QAbstractSocket::HostLookupState:
336 case QAbstractSocket::ConnectingState:
337 state = Network::Connecting;
339 case QAbstractSocket::ConnectedState:
340 state = Network::Initializing;
342 case QAbstractSocket::ClosingState:
343 state = Network::Disconnecting;
346 state = Network::Disconnected;
348 setConnectionState(state);
351 void CoreNetwork::networkInitialized() {
352 setConnectionState(Network::Initialized);
355 if(useAutoReconnect()) {
357 _autoReconnectCount = autoReconnectRetries();
364 if(_autoWhoEnabled) {
365 _autoWhoCycleTimer.start();
366 _autoWhoTimer.start();
367 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
370 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
371 Core::setNetworkConnected(userId(), networkId(), true);
374 void CoreNetwork::sendPerform() {
375 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
378 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
379 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
383 foreach(QString line, perform()) {
384 if(!line.isEmpty()) userInput(statusBuf, line);
387 // rejoin channels we've been in
388 QStringList channels, keys;
389 foreach(QString chan, persistentChannels()) {
390 QString key = channelKey(chan);
392 channels.prepend(chan);
395 channels.append(chan);
398 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
399 if(!joinString.isEmpty())
400 userInputHandler()->handleJoin(statusBuf, joinString);
403 void CoreNetwork::setUseAutoReconnect(bool use) {
404 Network::setUseAutoReconnect(use);
406 _autoReconnectTimer.stop();
409 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
410 Network::setAutoReconnectInterval(interval);
411 _autoReconnectTimer.setInterval(interval * 1000);
414 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
415 Network::setAutoReconnectRetries(retries);
416 if(_autoReconnectCount != 0) {
417 if(unlimitedReconnectRetries())
418 _autoReconnectCount = -1;
420 _autoReconnectCount = autoReconnectRetries();
424 void CoreNetwork::doAutoReconnect() {
425 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
426 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
429 if(_autoReconnectCount > 0)
430 _autoReconnectCount--;
434 void CoreNetwork::sendPing() {
435 userInputHandler()->handlePing(BufferInfo(), QString());
438 void CoreNetwork::sendAutoWho() {
439 while(!_autoWhoQueue.isEmpty()) {
440 QString chan = _autoWhoQueue.takeFirst();
441 IrcChannel *ircchan = ircChannel(chan);
442 if(!ircchan) continue;
443 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
444 _autoWhoInProgress[chan]++;
445 putRawLine("WHO " + serverEncode(chan));
446 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
447 // Timer was stopped, means a new cycle is due immediately
448 _autoWhoCycleTimer.start();
455 void CoreNetwork::startAutoWhoCycle() {
456 if(!_autoWhoQueue.isEmpty()) {
457 _autoWhoCycleTimer.stop();
460 _autoWhoQueue = channels();
464 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
466 socket.ignoreSslErrors();
467 /* TODO errorhandling
469 QVariantList errnums;
470 foreach(QSslError err, errors) errnums << err.error();
471 errmsg["SslErrors"] = errnums;
472 errmsg["SslCert"] = socket.peerCertificate().toPem();
473 errmsg["PeerAddress"] = socket.peerAddress().toString();
474 errmsg["PeerPort"] = socket.peerPort();
475 errmsg["PeerName"] = socket.peerName();
476 emit sslErrors(errmsg);
482 void CoreNetwork::fillBucketAndProcessQueue() {
483 if(_tokenBucket < _burstSize) {
487 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
488 writeToSocket(_msgQueue.takeFirst());
492 void CoreNetwork::writeToSocket(const QByteArray &data) {
494 socket.write("\r\n");
498 void CoreNetwork::requestConnect() const {
499 if(connectionState() != Disconnected) {
500 qWarning() << "Requesting connect while already being connected!";
503 Network::requestConnect();
506 void CoreNetwork::requestDisconnect() const {
507 if(connectionState() == Disconnected) {
508 qWarning() << "Requesting disconnect while not being connected!";
511 userInputHandler()->handleQuit(BufferInfo(), QString());
514 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
515 setNetworkInfo(info);
516 Core::updateNetwork(coreSession()->user(), info);