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!";
141 // cleaning up old quit reason
144 // use a random server?
145 if(useRandomServer()) {
146 _lastUsedServerIndex = qrand() % serverList().size();
147 } else if(_previousConnectionAttemptFailed) {
148 // cycle to next server if previous connection attempt failed
149 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
150 if(++_lastUsedServerIndex >= serverList().size()) {
151 _lastUsedServerIndex = 0;
154 _previousConnectionAttemptFailed = false;
156 Server server = usedServer();
157 displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
158 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port));
160 if(server.useProxy) {
161 QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass);
162 socket.setProxy(proxy);
164 socket.setProxy(QNetworkProxy::NoProxy);
168 socket.setProtocol((QSsl::SslProtocol)server.sslVersion);
170 CoreIdentity *identity = identityPtr();
172 socket.setLocalCertificate(identity->sslCert());
173 socket.setPrivateKey(identity->sslKey());
175 socket.connectToHostEncrypted(server.host, server.port);
177 socket.connectToHost(server.host, server.port);
180 socket.connectToHost(server.host, server.port);
184 void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason) {
185 _quitRequested = requested; // see socketDisconnected();
186 _autoReconnectTimer.stop();
187 _autoReconnectCount = 0; // prohibiting auto reconnect
193 awayMsg = me_->awayMessage();
194 Core::setAwayMessage(userId(), networkId(), awayMsg);
195 Core::setUserModes(userId(), networkId(), me_->userModes());
198 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
199 if(socket.state() == QAbstractSocket::UnconnectedState) {
200 socketDisconnected();
201 } else if(socket.state() < QAbstractSocket::ConnectedState || !requested) {
202 // we might be in a state waiting for a timeout...
203 // or (!requested) this is a core shutdown...
204 // in both cases we don't really care... set a disconnected state
206 socketDisconnected();
208 // quit gracefully if it's user requested quit
209 if(reason.isEmpty() && identityPtr())
210 _quitReason = identityPtr()->quitReason();
212 _quitReason = reason;
213 userInputHandler()->issueQuit(_quitReason);
214 // the irc server has 10 seconds to close the socket
215 _socketCloseTimer.start(10000);
219 void CoreNetwork::userInput(BufferInfo buf, QString msg) {
220 userInputHandler()->handleUserInput(buf, msg);
223 void CoreNetwork::putRawLine(QByteArray s) {
230 void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix) {
233 if(!prefix.isEmpty())
234 msg += ":" + prefix + " ";
235 msg += cmd.toUpper().toAscii();
237 for(int i = 0; i < params.size() - 1; i++) {
238 msg += " " + params[i];
240 if(!params.isEmpty())
241 msg += " :" + params.last();
246 void CoreNetwork::setChannelJoined(const QString &channel) {
247 _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked
249 Core::setChannelPersistent(userId(), networkId(), channel, true);
250 Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
253 void CoreNetwork::setChannelParted(const QString &channel) {
254 removeChannelKey(channel);
255 _autoWhoQueue.removeAll(channel.toLower());
256 _autoWhoInProgress.remove(channel.toLower());
258 Core::setChannelPersistent(userId(), networkId(), channel, false);
261 void CoreNetwork::addChannelKey(const QString &channel, const QString &key) {
263 removeChannelKey(channel);
265 _channelKeys[channel.toLower()] = key;
269 void CoreNetwork::removeChannelKey(const QString &channel) {
270 _channelKeys.remove(channel.toLower());
273 bool CoreNetwork::setAutoWhoDone(const QString &channel) {
274 if(_autoWhoInProgress.value(channel.toLower(), 0) <= 0)
276 _autoWhoInProgress[channel.toLower()]--;
280 void CoreNetwork::setMyNick(const QString &mynick) {
281 Network::setMyNick(mynick);
282 if(connectionState() == Network::Initializing)
283 networkInitialized();
286 void CoreNetwork::socketHasData() {
287 while(socket.canReadLine()) {
288 QByteArray s = socket.readLine().trimmed();
289 ircServerHandler()->handleServerMsg(s);
293 void CoreNetwork::socketError(QAbstractSocket::SocketError error) {
294 if(_quitRequested && error == QAbstractSocket::RemoteHostClosedError)
297 _previousConnectionAttemptFailed = true;
298 qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString()));
299 emit connectionError(socket.errorString());
300 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
301 emitConnectionError(socket.errorString());
302 if(socket.state() < QAbstractSocket::ConnectedState) {
303 socketDisconnected();
307 void CoreNetwork::socketInitialized() {
308 Server server = usedServer();
310 if(server.useSsl && !socket.isEncrypted())
314 CoreIdentity *identity = identityPtr();
316 qCritical() << "Identity invalid!";
321 // TokenBucket to avoid sending too much at once
322 _messagesPerSecond = 1;
324 _tokenBucket = 5; // init with a full bucket
325 _tokenBucketTimer.start(_messagesPerSecond * 1000);
327 if(!server.password.isEmpty()) {
328 putRawLine(serverEncode(QString("PASS %1").arg(server.password)));
330 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));
331 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
334 void CoreNetwork::socketDisconnected() {
336 _autoWhoCycleTimer.stop();
337 _autoWhoTimer.stop();
338 _autoWhoQueue.clear();
339 _autoWhoInProgress.clear();
341 _socketCloseTimer.stop();
343 _tokenBucketTimer.stop();
347 foreach(QString channel, me_->channels())
348 emit displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
352 emit disconnected(networkId());
354 setConnectionState(Network::Disconnected);
355 Core::setNetworkConnected(userId(), networkId(), false);
356 } else if(_autoReconnectCount != 0) {
357 setConnectionState(Network::Reconnecting);
358 if(_autoReconnectCount == autoReconnectRetries())
359 doAutoReconnect(); // first try is immediate
361 _autoReconnectTimer.start();
365 void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) {
366 Network::ConnectionState state;
367 switch(socketState) {
368 case QAbstractSocket::UnconnectedState:
369 state = Network::Disconnected;
371 case QAbstractSocket::HostLookupState:
372 case QAbstractSocket::ConnectingState:
373 state = Network::Connecting;
375 case QAbstractSocket::ConnectedState:
376 state = Network::Initializing;
378 case QAbstractSocket::ClosingState:
379 state = Network::Disconnecting;
382 state = Network::Disconnected;
384 setConnectionState(state);
387 void CoreNetwork::networkInitialized() {
388 setConnectionState(Network::Initialized);
390 _quitRequested = false;
392 if(useAutoReconnect()) {
394 _autoReconnectCount = autoReconnectRetries();
397 // restore away state
398 userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId()));
400 // restore old user modes if server default mode is set.
403 if(!me_->userModes().isEmpty()) {
406 connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
407 connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
415 if(_autoWhoEnabled) {
416 _autoWhoCycleTimer.start();
417 _autoWhoTimer.start();
418 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
421 Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
422 Core::setNetworkConnected(userId(), networkId(), true);
425 void CoreNetwork::sendPerform() {
426 BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
429 if(useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) {
430 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword()));
434 foreach(QString line, perform()) {
435 if(!line.isEmpty()) userInput(statusBuf, line);
438 // rejoin channels we've been in
439 if(rejoinChannels()) {
440 QStringList channels, keys;
441 foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
442 QString key = channelKey(chan);
444 channels.prepend(chan);
447 channels.append(chan);
450 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
451 if(!joinString.isEmpty())
452 userInputHandler()->handleJoin(statusBuf, joinString);
456 void CoreNetwork::restoreUserModes() {
460 disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes()));
461 disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes()));
464 QString addModes = Core::userModes(userId(), networkId());
465 QString currentModes = me_->userModes();
467 removeModes = currentModes;
468 removeModes.remove(QRegExp(QString("[%1]").arg(addModes)));
469 addModes.remove(QRegExp(QString("[%1]").arg(currentModes)));
471 removeModes = QString("%1 -%2").arg(me_->nick(), removeModes);
472 addModes = QString("%1 +%2").arg(me_->nick(), addModes);
473 userInputHandler()->handleMode(BufferInfo(), removeModes);
474 userInputHandler()->handleMode(BufferInfo(), addModes);
477 void CoreNetwork::setUseAutoReconnect(bool use) {
478 Network::setUseAutoReconnect(use);
480 _autoReconnectTimer.stop();
483 void CoreNetwork::setAutoReconnectInterval(quint32 interval) {
484 Network::setAutoReconnectInterval(interval);
485 _autoReconnectTimer.setInterval(interval * 1000);
488 void CoreNetwork::setAutoReconnectRetries(quint16 retries) {
489 Network::setAutoReconnectRetries(retries);
490 if(_autoReconnectCount != 0) {
491 if(unlimitedReconnectRetries())
492 _autoReconnectCount = -1;
494 _autoReconnectCount = autoReconnectRetries();
498 void CoreNetwork::doAutoReconnect() {
499 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
500 qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!";
503 if(_autoReconnectCount > 0)
504 _autoReconnectCount--;
508 void CoreNetwork::sendPing() {
509 userInputHandler()->handlePing(BufferInfo(), QString());
512 void CoreNetwork::sendAutoWho() {
513 while(!_autoWhoQueue.isEmpty()) {
514 QString chan = _autoWhoQueue.takeFirst();
515 IrcChannel *ircchan = ircChannel(chan);
516 if(!ircchan) continue;
517 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
518 _autoWhoInProgress[chan]++;
519 putRawLine("WHO " + serverEncode(chan));
520 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
521 // Timer was stopped, means a new cycle is due immediately
522 _autoWhoCycleTimer.start();
529 void CoreNetwork::startAutoWhoCycle() {
530 if(!_autoWhoQueue.isEmpty()) {
531 _autoWhoCycleTimer.stop();
534 _autoWhoQueue = channels();
538 void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) {
540 socket.ignoreSslErrors();
541 // TODO errorhandling
545 void CoreNetwork::fillBucketAndProcessQueue() {
546 if(_tokenBucket < _burstSize) {
550 while(_msgQueue.size() > 0 && _tokenBucket > 0) {
551 writeToSocket(_msgQueue.takeFirst());
555 void CoreNetwork::writeToSocket(const QByteArray &data) {
557 socket.write("\r\n");
561 Network::Server CoreNetwork::usedServer() const {
562 if(_lastUsedServerIndex < serverList().count())
563 return serverList()[_lastUsedServerIndex];
565 if(!serverList().isEmpty())
566 return serverList()[0];
568 return Network::Server();
571 void CoreNetwork::requestConnect() const {
572 if(connectionState() != Disconnected) {
573 qWarning() << "Requesting connect while already being connected!";
576 Network::requestConnect();
579 void CoreNetwork::requestDisconnect() const {
580 if(connectionState() == Disconnected) {
581 qWarning() << "Requesting disconnect while not being connected!";
584 userInputHandler()->handleQuit(BufferInfo(), QString());
587 void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) {
588 Network::Server currentServer = usedServer();
589 setNetworkInfo(info);
590 Core::updateNetwork(coreSession()->user(), info);
592 // the order of the servers might have changed,
593 // so we try to find the previously used server
594 _lastUsedServerIndex = 0;
595 for(int i = 0; i < serverList().count(); i++) {
596 Network::Server server = serverList()[i];
597 if(server.host == currentServer.host && server.port == currentServer.port) {
598 _lastUsedServerIndex = i;