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!
85 disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up
86 delete _ircServerHandler;
87 delete _userInputHandler;
91 QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const {
92 if(!bufferName.isEmpty()) {
93 IrcChannel *channel = ircChannel(bufferName);
95 return channel->decodeString(string);
97 return decodeString(string);
100 QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const {
101 IrcUser *user = ircUser(userNick);
103 return user->decodeString(string);
104 return decodeString(string);
107 QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const {
108 if(!bufferName.isEmpty()) {
109 IrcChannel *channel = ircChannel(bufferName);
111 return channel->encodeString(string);
113 return encodeString(string);
116 QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const {
117 IrcUser *user = ircUser(userNick);
119 return user->encodeString(string);
120 return encodeString(string);
123 void CoreNetwork::connectToIrc(bool reconnecting) {
124 if(!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) {
125 _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000);
126 if(unlimitedReconnectRetries())
127 _autoReconnectCount = -1;
129 _autoReconnectCount = autoReconnectRetries();
131 if(serverList().isEmpty()) {
132 qWarning() << "Server list empty, ignoring connect request!";
135 CoreIdentity *identity = identityPtr();
137 qWarning() << "Invalid identity configures, ignoring connect request!";
140 // use a random server?
141 if(useRandomServer()) {
142 _lastUsedServerIndex = qrand() % serverList().size();
143 } else if(_previousConnectionAttemptFailed) {
144 // cycle to next server if previous connection attempt failed
145 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
146 if(++_lastUsedServerIndex >= serverList().size()) {
147 _lastUsedServerIndex = 0;
150 _previousConnectionAttemptFailed = false;
152 Server server = usedServer();
153 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
154 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
156 if(server.useProxy) {
157 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
158 socket.setProxy(proxy);
160 socket.setProxy(QNetworkProxy::NoProxy);
164 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
166 CoreIdentity *identity = identityPtr();
168 socket.setLocalCertificate(identity->sslCert());
169 socket.setPrivateKey(identity->sslKey());
171 socket.connectToHostEncrypted(server.host, server.port);
173 socket.connectToHost(server.host, server.port);
176 socket.connectToHost(server.host, server.port);
180 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
181 _quitRequested = requested; // see socketDisconnected();
182 _autoReconnectTimer.stop();
183 _autoReconnectCount = 0; // prohibiting auto reconnect
189 awayMsg = me_->awayMessage();
190 Core::setAwayMessage(userId(), networkId(), awayMsg);
191 Core::setUserModes(userId(), networkId(), me_->userModes());
194 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
195 if(socket.state() == QAbstractSocket::UnconnectedState) {
196 socketDisconnected();
197 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
198 // we might be in a state waiting for a timeout...
199 // or (!requested) this is a core shutdown...
200 // in both cases we don't really care... set a disconnected state
202 socketDisconnected();
204 // quit gracefully if it's user requested quit
205 userInputHandler()->issueQuit(reason);
206 // the irc server has 10 seconds to close the socket
207 _socketCloseTimer.start(10000);
211 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
212 userInputHandler()->handleUserInput(buf, msg);
215 void CoreNetwork::putRawLine(QByteArray s) {
222 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
225 if(!prefix.isEmpty())
226 msg += ":" + prefix + " ";
227 msg += cmd.toUpper().toAscii();
229 for(int i = 0; i < params.size() - 1; i++) {
230 msg += " " + params[i];
232 if(!params.isEmpty())
233 msg += " :" + params.last();
238 void CoreNetwork::setChannelJoined(const QString &channel) {
239 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
241 Core::setChannelPersistent(userId(), networkId(), channel, true);
242 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
245 void CoreNetwork::setChannelParted(const QString &channel) {
246 removeChannelKey(channel);
247 _autoWhoQueue.removeAll(channel.toLower());
248 _autoWhoInProgress.remove(channel.toLower());
250 Core::setChannelPersistent(userId(), networkId(), channel, false);
253 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
255 removeChannelKey(channel);
257 _channelKeys[channel.toLower()] = key;
261 void CoreNetwork::removeChannelKey(const QString &channel) {
262 _channelKeys.remove(channel.toLower());
265 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
266 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
268 _autoWhoInProgress[channel.toLower()]--;
272 void CoreNetwork::setMyNick(const QString &mynick) {
273 Network::setMyNick(mynick);
274 if(connectionState() == Network::Initializing)
275 networkInitialized();
278 void CoreNetwork::socketHasData() {
279 while(socket.canReadLine()) {
280 QByteArray s = socket.readLine().trimmed();
281 ircServerHandler()->handleServerMsg(s);
285 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
286 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
289 _previousConnectionAttemptFailed = true;
290 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
291 emit connectionError(socket.errorString());
292 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
293 emitConnectionError(socket.errorString());
294 if(socket.state() < QAbstractSocket::ConnectedState) {
295 socketDisconnected();
299 void CoreNetwork::socketInitialized() {
300 Server server = usedServer();
302 if(server.useSsl && !socket.isEncrypted())
306 CoreIdentity *identity = identityPtr();
308 qCritical() << "Identity invalid!";
313 // TokenBucket to avoid sending too much at once
314 _messagesPerSecond = 1;
316 _tokenBucket = 5; // init with a full bucket
317 _tokenBucketTimer.start(_messagesPerSecond * 1000);
319 if(!server.password.isEmpty()) {
320 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
322 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
323 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
326 void CoreNetwork::socketDisconnected() {
328 _autoWhoCycleTimer.stop();
329 _autoWhoTimer.stop();
330 _autoWhoQueue.clear();
331 _autoWhoInProgress.clear();
333 _socketCloseTimer.stop();
335 _tokenBucketTimer.stop();
339 foreach(QString channel, me_->channels())
340 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
344 emit disconnected(networkId());
346 setConnectionState(Network::Disconnected);
347 Core::setNetworkConnected(userId(), networkId(), false);
348 } else if(_autoReconnectCount != 0) {
349 setConnectionState(Network::Reconnecting);
350 if(_autoReconnectCount == autoReconnectRetries())
351 doAutoReconnect(); // first try is immediate
353 _autoReconnectTimer.start();
357 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
358 Network::ConnectionState state;
359 switch(socketState) {
360 case QAbstractSocket::UnconnectedState:
361 state = Network::Disconnected;
363 case QAbstractSocket::HostLookupState:
364 case QAbstractSocket::ConnectingState:
365 state = Network::Connecting;
367 case QAbstractSocket::ConnectedState:
368 state = Network::Initializing;
370 case QAbstractSocket::ClosingState:
371 state = Network::Disconnecting;
374 state = Network::Disconnected;
376 setConnectionState(state);
379 void CoreNetwork::networkInitialized() {
380 setConnectionState(Network::Initialized);
382 _quitRequested = false;
384 if(useAutoReconnect()) {
386 _autoReconnectCount = autoReconnectRetries();
393 if(_autoWhoEnabled) {
394 _autoWhoCycleTimer.start();
395 _autoWhoTimer.start();
396 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
399 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
400 Core::setNetworkConnected(userId(), networkId(), true);
403 void CoreNetwork::sendPerform() {
404 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
407 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
408 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
412 foreach(QString line, perform()) {
413 if(!line.isEmpty()) userInput(statusBuf, line);
416 // rejoin channels we've been in
417 if(rejoinChannels()) {
418 QStringList channels, keys;
419 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
420 QString key = channelKey(chan);
422 channels.prepend(chan);
425 channels.append(chan);
428 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
429 if(!joinString.isEmpty())
430 userInputHandler()->handleJoin(statusBuf, joinString);
434 void CoreNetwork::setUseAutoReconnect(bool use) {
435 Network::setUseAutoReconnect(use);
437 _autoReconnectTimer.stop();
440 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
441 Network::setAutoReconnectInterval(interval);
442 _autoReconnectTimer.setInterval(interval * 1000);
445 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
446 Network::setAutoReconnectRetries(retries);
447 if(_autoReconnectCount != 0) {
448 if(unlimitedReconnectRetries())
449 _autoReconnectCount = -1;
451 _autoReconnectCount = autoReconnectRetries();
455 void CoreNetwork::doAutoReconnect() {
456 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
457 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
460 if(_autoReconnectCount > 0)
461 _autoReconnectCount--;
465 void CoreNetwork::sendPing() {
466 userInputHandler()->handlePing(BufferInfo(), QString());
469 void CoreNetwork::sendAutoWho() {
470 while(!_autoWhoQueue.isEmpty()) {
471 QString chan = _autoWhoQueue.takeFirst();
472 IrcChannel *ircchan = ircChannel(chan);
473 if(!ircchan) continue;
474 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
475 _autoWhoInProgress[chan]++;
476 putRawLine("WHO " + serverEncode(chan));
477 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
478 // Timer was stopped, means a new cycle is due immediately
479 _autoWhoCycleTimer.start();
486 void CoreNetwork::startAutoWhoCycle() {
487 if(!_autoWhoQueue.isEmpty()) {
488 _autoWhoCycleTimer.stop();
491 _autoWhoQueue = channels();
495 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
497 socket.ignoreSslErrors();
498 // TODO errorhandling
502 void CoreNetwork::fillBucketAndProcessQueue() {
503 if(_tokenBucket < _burstSize) {
507 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
508 writeToSocket(_msgQueue.takeFirst());
512 void CoreNetwork::writeToSocket(const QByteArray &data) {
514 socket.write("\r\n");
518 Network::Server CoreNetwork::usedServer() const {
519 if(_lastUsedServerIndex < serverList().count())
520 return serverList()[_lastUsedServerIndex];
522 if(!serverList().isEmpty())
523 return serverList()[0];
525 return Network::Server();
528 void CoreNetwork::requestConnect() const {
529 if(connectionState() != Disconnected) {
530 qWarning() << "Requesting connect while already being connected!";
533 Network::requestConnect();
536 void CoreNetwork::requestDisconnect() const {
537 if(connectionState() == Disconnected) {
538 qWarning() << "Requesting disconnect while not being connected!";
541 userInputHandler()->handleQuit(BufferInfo(), QString());
544 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
545 Network::Server currentServer = usedServer();
546 setNetworkInfo(info);
547 Core::updateNetwork(coreSession()->user(), info);
549 // the order of the servers might have changed,
550 // so we try to find the previously used server
551 _lastUsedServerIndex = 0;
552 for(int i = 0; i < serverList().count(); i++) {
553 Network::Server server = serverList()[i];
554 if(server.host == currentServer.host && server.port == currentServer.port) {
555 _lastUsedServerIndex = i;