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 CoreIdentity *identity = identityPtr();
169 socket.setLocalCertificate(identity->sslCert());
170 socket.setPrivateKey(identity->sslKey());
172 socket.connectToHostEncrypted(server.host, server.port);
174 socket.connectToHost(server.host, server.port);
177 socket.connectToHost(server.host, server.port);
181 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
182 _quitRequested = requested; // see socketDisconnected();
183 _autoReconnectTimer.stop();
184 _autoReconnectCount = 0; // prohibiting auto reconnect
185 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
186 if(socket.state() == QAbstractSocket::UnconnectedState) {
187 socketDisconnected();
188 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
189 // we might be in a state waiting for a timeout...
190 // or (!requested) this is a core shutdown...
191 // in both cases we don't really care... set a disconnected state
193 socketDisconnected();
195 // quit gracefully if it's user requested quit
196 userInputHandler()->issueQuit(reason);
197 // the irc server has 10 seconds to close the socket
198 _socketCloseTimer.start(10000);
202 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
203 userInputHandler()->handleUserInput(buf, msg);
206 void CoreNetwork::putRawLine(QByteArray s) {
213 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
216 if(!prefix.isEmpty())
217 msg += ":" + prefix + " ";
218 msg += cmd.toUpper().toAscii();
220 for(int i = 0; i < params.size() - 1; i++) {
221 msg += " " + params[i];
223 if(!params.isEmpty())
224 msg += " :" + params.last();
229 void CoreNetwork::setChannelJoined(const QString &channel) {
230 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
232 Core::setChannelPersistent(userId(), networkId(), channel, true);
233 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
236 void CoreNetwork::setChannelParted(const QString &channel) {
237 removeChannelKey(channel);
238 _autoWhoQueue.removeAll(channel.toLower());
239 _autoWhoInProgress.remove(channel.toLower());
241 Core::setChannelPersistent(userId(), networkId(), channel, false);
244 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
246 removeChannelKey(channel);
248 _channelKeys[channel.toLower()] = key;
252 void CoreNetwork::removeChannelKey(const QString &channel) {
253 _channelKeys.remove(channel.toLower());
256 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
257 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
259 _autoWhoInProgress[channel.toLower()]--;
263 void CoreNetwork::setMyNick(const QString &mynick) {
264 Network::setMyNick(mynick);
265 if(connectionState() == Network::Initializing)
266 networkInitialized();
269 void CoreNetwork::socketHasData() {
270 while(socket.canReadLine()) {
271 QByteArray s = socket.readLine().trimmed();
272 ircServerHandler()->handleServerMsg(s);
276 void CoreNetwork::socketError(QAbstractSocket::SocketError) {
277 _previousConnectionAttemptFailed = true;
278 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
279 emit connectionError(socket.errorString());
280 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
281 emitConnectionError(socket.errorString());
282 if(socket.state() < QAbstractSocket::ConnectedState) {
283 socketDisconnected();
287 void CoreNetwork::socketInitialized() {
288 Server server = usedServer();
290 if(server.useSsl && !socket.isEncrypted())
294 CoreIdentity *identity = identityPtr();
296 qCritical() << "Identity invalid!";
301 // TokenBucket to avoid sending too much at once
302 _messagesPerSecond = 1;
304 _tokenBucket = 5; // init with a full bucket
305 _tokenBucketTimer.start(_messagesPerSecond * 1000);
307 if(!server.password.isEmpty()) {
308 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
310 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
311 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
314 void CoreNetwork::socketDisconnected() {
316 _autoWhoCycleTimer.stop();
317 _autoWhoTimer.stop();
318 _autoWhoQueue.clear();
319 _autoWhoInProgress.clear();
321 _socketCloseTimer.stop();
323 _tokenBucketTimer.stop();
327 foreach(QString channel, me_->channels())
328 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
332 emit disconnected(networkId());
334 setConnectionState(Network::Disconnected);
335 Core::setNetworkConnected(userId(), networkId(), false);
336 } else if(_autoReconnectCount != 0) {
337 setConnectionState(Network::Reconnecting);
338 if(_autoReconnectCount == autoReconnectRetries())
339 doAutoReconnect(); // first try is immediate
341 _autoReconnectTimer.start();
345 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
346 Network::ConnectionState state;
347 switch(socketState) {
348 case QAbstractSocket::UnconnectedState:
349 state = Network::Disconnected;
351 case QAbstractSocket::HostLookupState:
352 case QAbstractSocket::ConnectingState:
353 state = Network::Connecting;
355 case QAbstractSocket::ConnectedState:
356 state = Network::Initializing;
358 case QAbstractSocket::ClosingState:
359 state = Network::Disconnecting;
362 state = Network::Disconnected;
364 setConnectionState(state);
367 void CoreNetwork::networkInitialized() {
368 setConnectionState(Network::Initialized);
371 if(useAutoReconnect()) {
373 _autoReconnectCount = autoReconnectRetries();
380 if(_autoWhoEnabled) {
381 _autoWhoCycleTimer.start();
382 _autoWhoTimer.start();
383 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
386 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
387 Core::setNetworkConnected(userId(), networkId(), true);
390 void CoreNetwork::sendPerform() {
391 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
394 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
395 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
399 foreach(QString line, perform()) {
400 if(!line.isEmpty()) userInput(statusBuf, line);
403 // rejoin channels we've been in
404 QStringList channels, keys;
405 foreach(QString chan, persistentChannels()) {
406 QString key = channelKey(chan);
408 channels.prepend(chan);
411 channels.append(chan);
414 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
415 if(!joinString.isEmpty())
416 userInputHandler()->handleJoin(statusBuf, joinString);
419 void CoreNetwork::setUseAutoReconnect(bool use) {
420 Network::setUseAutoReconnect(use);
422 _autoReconnectTimer.stop();
425 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
426 Network::setAutoReconnectInterval(interval);
427 _autoReconnectTimer.setInterval(interval * 1000);
430 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
431 Network::setAutoReconnectRetries(retries);
432 if(_autoReconnectCount != 0) {
433 if(unlimitedReconnectRetries())
434 _autoReconnectCount = -1;
436 _autoReconnectCount = autoReconnectRetries();
440 void CoreNetwork::doAutoReconnect() {
441 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
442 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
445 if(_autoReconnectCount > 0)
446 _autoReconnectCount--;
450 void CoreNetwork::sendPing() {
451 userInputHandler()->handlePing(BufferInfo(), QString());
454 void CoreNetwork::sendAutoWho() {
455 while(!_autoWhoQueue.isEmpty()) {
456 QString chan = _autoWhoQueue.takeFirst();
457 IrcChannel *ircchan = ircChannel(chan);
458 if(!ircchan) continue;
459 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
460 _autoWhoInProgress[chan]++;
461 putRawLine("WHO " + serverEncode(chan));
462 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
463 // Timer was stopped, means a new cycle is due immediately
464 _autoWhoCycleTimer.start();
471 void CoreNetwork::startAutoWhoCycle() {
472 if(!_autoWhoQueue.isEmpty()) {
473 _autoWhoCycleTimer.stop();
476 _autoWhoQueue = channels();
480 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
482 socket.ignoreSslErrors();
483 // TODO errorhandling
487 void CoreNetwork::fillBucketAndProcessQueue() {
488 if(_tokenBucket < _burstSize) {
492 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
493 writeToSocket(_msgQueue.takeFirst());
497 void CoreNetwork::writeToSocket(const QByteArray &data) {
499 socket.write("\r\n");
503 Network::Server CoreNetwork::usedServer() const {
504 if(_lastUsedServerIndex < serverList().count())
505 return serverList()[_lastUsedServerIndex];
507 return Network::Server();
510 void CoreNetwork::requestConnect() const {
511 if(connectionState() != Disconnected) {
512 qWarning() << "Requesting connect while already being connected!";
515 Network::requestConnect();
518 void CoreNetwork::requestDisconnect() const {
519 if(connectionState() == Disconnected) {
520 qWarning() << "Requesting disconnect while not being connected!";
523 userInputHandler()->handleQuit(BufferInfo(), QString());
526 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
527 Network::Server currentServer = usedServer();
528 setNetworkInfo(info);
529 Core::updateNetwork(coreSession()->user(), info);
531 // update _lastUsedServerIndex;
532 for(int i = 0; i < serverList().count(); i++) {
533 Network::Server server = serverList()[i];
534 if(server.host == currentServer.host && server.port == currentServer.port) {
535 _lastUsedServerIndex = i;