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
184 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
185 if(socket.state() == QAbstractSocket::UnconnectedState) {
186 socketDisconnected();
187 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
188 // we might be in a state waiting for a timeout...
189 // or (!requested) this is a core shutdown...
190 // in both cases we don't really care... set a disconnected state
192 socketDisconnected();
194 // quit gracefully if it's user requested quit
195 userInputHandler()->issueQuit(reason);
196 // the irc server has 10 seconds to close the socket
197 _socketCloseTimer.start(10000);
201 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
202 userInputHandler()->handleUserInput(buf, msg);
205 void CoreNetwork::putRawLine(QByteArray s) {
212 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
215 if(!prefix.isEmpty())
216 msg += ":" + prefix + " ";
217 msg += cmd.toUpper().toAscii();
219 for(int i = 0; i < params.size() - 1; i++) {
220 msg += " " + params[i];
222 if(!params.isEmpty())
223 msg += " :" + params.last();
228 void CoreNetwork::setChannelJoined(const QString &channel) {
229 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
231 Core::setChannelPersistent(userId(), networkId(), channel, true);
232 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
235 void CoreNetwork::setChannelParted(const QString &channel) {
236 removeChannelKey(channel);
237 _autoWhoQueue.removeAll(channel.toLower());
238 _autoWhoInProgress.remove(channel.toLower());
240 Core::setChannelPersistent(userId(), networkId(), channel, false);
243 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
245 removeChannelKey(channel);
247 _channelKeys[channel.toLower()] = key;
251 void CoreNetwork::removeChannelKey(const QString &channel) {
252 _channelKeys.remove(channel.toLower());
255 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
256 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
258 _autoWhoInProgress[channel.toLower()]--;
262 void CoreNetwork::setMyNick(const QString &mynick) {
263 Network::setMyNick(mynick);
264 if(connectionState() == Network::Initializing)
265 networkInitialized();
268 void CoreNetwork::socketHasData() {
269 while(socket.canReadLine()) {
270 QByteArray s = socket.readLine().trimmed();
271 ircServerHandler()->handleServerMsg(s);
275 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
276 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
279 _previousConnectionAttemptFailed = true;
280 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
281 emit connectionError(socket.errorString());
282 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
283 emitConnectionError(socket.errorString());
284 if(socket.state() < QAbstractSocket::ConnectedState) {
285 socketDisconnected();
289 void CoreNetwork::socketInitialized() {
290 Server server = usedServer();
292 if(server.useSsl && !socket.isEncrypted())
296 CoreIdentity *identity = identityPtr();
298 qCritical() << "Identity invalid!";
303 // TokenBucket to avoid sending too much at once
304 _messagesPerSecond = 1;
306 _tokenBucket = 5; // init with a full bucket
307 _tokenBucketTimer.start(_messagesPerSecond * 1000);
309 if(!server.password.isEmpty()) {
310 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
312 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
313 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
316 void CoreNetwork::socketDisconnected() {
318 _autoWhoCycleTimer.stop();
319 _autoWhoTimer.stop();
320 _autoWhoQueue.clear();
321 _autoWhoInProgress.clear();
323 _socketCloseTimer.stop();
325 _tokenBucketTimer.stop();
329 foreach(QString channel, me_->channels())
330 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, "", me_->hostmask());
334 emit disconnected(networkId());
336 setConnectionState(Network::Disconnected);
337 Core::setNetworkConnected(userId(), networkId(), false);
338 } else if(_autoReconnectCount != 0) {
339 setConnectionState(Network::Reconnecting);
340 if(_autoReconnectCount == autoReconnectRetries())
341 doAutoReconnect(); // first try is immediate
343 _autoReconnectTimer.start();
347 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
348 Network::ConnectionState state;
349 switch(socketState) {
350 case QAbstractSocket::UnconnectedState:
351 state = Network::Disconnected;
353 case QAbstractSocket::HostLookupState:
354 case QAbstractSocket::ConnectingState:
355 state = Network::Connecting;
357 case QAbstractSocket::ConnectedState:
358 state = Network::Initializing;
360 case QAbstractSocket::ClosingState:
361 state = Network::Disconnecting;
364 state = Network::Disconnected;
366 setConnectionState(state);
369 void CoreNetwork::networkInitialized() {
370 setConnectionState(Network::Initialized);
372 _quitRequested = false;
374 if(useAutoReconnect()) {
376 _autoReconnectCount = autoReconnectRetries();
383 if(_autoWhoEnabled) {
384 _autoWhoCycleTimer.start();
385 _autoWhoTimer.start();
386 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
389 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
390 Core::setNetworkConnected(userId(), networkId(), true);
393 void CoreNetwork::sendPerform() {
394 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
397 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
398 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
402 foreach(QString line, perform()) {
403 if(!line.isEmpty()) userInput(statusBuf, line);
406 // rejoin channels we've been in
407 if(rejoinChannels()) {
408 QStringList channels, keys;
409 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
410 QString key = channelKey(chan);
412 channels.prepend(chan);
415 channels.append(chan);
418 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
419 if(!joinString.isEmpty())
420 userInputHandler()->handleJoin(statusBuf, joinString);
424 void CoreNetwork::setUseAutoReconnect(bool use) {
425 Network::setUseAutoReconnect(use);
427 _autoReconnectTimer.stop();
430 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
431 Network::setAutoReconnectInterval(interval);
432 _autoReconnectTimer.setInterval(interval * 1000);
435 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
436 Network::setAutoReconnectRetries(retries);
437 if(_autoReconnectCount != 0) {
438 if(unlimitedReconnectRetries())
439 _autoReconnectCount = -1;
441 _autoReconnectCount = autoReconnectRetries();
445 void CoreNetwork::doAutoReconnect() {
446 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
447 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
450 if(_autoReconnectCount > 0)
451 _autoReconnectCount--;
455 void CoreNetwork::sendPing() {
456 userInputHandler()->handlePing(BufferInfo(), QString());
459 void CoreNetwork::sendAutoWho() {
460 while(!_autoWhoQueue.isEmpty()) {
461 QString chan = _autoWhoQueue.takeFirst();
462 IrcChannel *ircchan = ircChannel(chan);
463 if(!ircchan) continue;
464 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
465 _autoWhoInProgress[chan]++;
466 putRawLine("WHO " + serverEncode(chan));
467 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
468 // Timer was stopped, means a new cycle is due immediately
469 _autoWhoCycleTimer.start();
476 void CoreNetwork::startAutoWhoCycle() {
477 if(!_autoWhoQueue.isEmpty()) {
478 _autoWhoCycleTimer.stop();
481 _autoWhoQueue = channels();
485 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
487 socket.ignoreSslErrors();
488 // TODO errorhandling
492 void CoreNetwork::fillBucketAndProcessQueue() {
493 if(_tokenBucket < _burstSize) {
497 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
498 writeToSocket(_msgQueue.takeFirst());
502 void CoreNetwork::writeToSocket(const QByteArray &data) {
504 socket.write("\r\n");
508 Network::Server CoreNetwork::usedServer() const {
509 if(_lastUsedServerIndex < serverList().count())
510 return serverList()[_lastUsedServerIndex];
512 if(!serverList().isEmpty())
513 return serverList()[0];
515 return Network::Server();
518 void CoreNetwork::requestConnect() const {
519 if(connectionState() != Disconnected) {
520 qWarning() << "Requesting connect while already being connected!";
523 Network::requestConnect();
526 void CoreNetwork::requestDisconnect() const {
527 if(connectionState() == Disconnected) {
528 qWarning() << "Requesting disconnect while not being connected!";
531 userInputHandler()->handleQuit(BufferInfo(), QString());
534 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
535 Network::Server currentServer = usedServer();
536 setNetworkInfo(info);
537 Core::updateNetwork(coreSession()->user(), info);
539 // the order of the servers might have changed,
540 // so we try to find the previously used server
541 _lastUsedServerIndex = 0;
542 for(int i = 0; i < serverList().count(); i++) {
543 Network::Server server = serverList()[i];
544 if(server.host == currentServer.host && server.port == currentServer.port) {
545 _lastUsedServerIndex = i;