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 ***************************************************************************/
20 #include "networkconnection.h"
22 #include <QMetaObject>
23 #include <QMetaMethod>
28 #include "coresession.h"
30 #include "ircchannel.h"
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session) : QObject(network),
40 _connectionState(Network::Disconnected),
42 _coreSession(session),
43 _ircServerHandler(new IrcServerHandler(this)),
44 _userInputHandler(new UserInputHandler(this)),
45 _ctcpHandler(new CtcpHandler(this)),
46 _autoReconnectCount(0)
48 _autoReconnectTimer.setSingleShot(true);
50 _previousConnectionAttemptFailed = false;
51 _lastUsedServerlistIndex = 0;
53 // TODO make autowho configurable (possibly per-network)
54 _autoWhoEnabled = true;
55 _autoWhoInterval = 90;
56 _autoWhoNickLimit = 0; // unlimited
59 _autoWhoTimer.setInterval(_autoWhoDelay * 1000);
60 _autoWhoTimer.setSingleShot(false);
61 _autoWhoCycleTimer.setInterval(_autoWhoInterval * 1000);
62 _autoWhoCycleTimer.setSingleShot(false);
64 QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
65 foreach(QString chan, channels.keys()) {
66 _channelKeys[chan.toLower()] = channels[chan];
69 connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
70 connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho()));
71 connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle()));
73 connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
74 connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
75 connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
76 connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
79 connect(&socket, SIGNAL(encrypted()), this, SLOT(socketEncrypted()));
80 connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
82 connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
84 connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
85 connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
86 connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
87 connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
89 connect(_ircServerHandler, SIGNAL(nickChanged(const QString &, const QString &)),
90 this, SLOT(nickChanged(const QString &, const QString &)));
92 network->proxy()->attachSignal(this, SIGNAL(sslErrors(const QVariant &)));
95 NetworkConnection::~NetworkConnection() {
96 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
97 disconnectFromIrc(false); // clean up, but this does not count as requested disconnect!
98 delete _ircServerHandler;
99 delete _userInputHandler;
103 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
104 _connectionState = state;
105 network()->setConnectionState(state);
106 emit connectionStateChanged(state);
109 QString NetworkConnection::serverDecode(const QByteArray &string) const {
110 return network()->decodeServerString(string);
113 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
114 if(!bufferName.isEmpty()) {
115 IrcChannel *channel = network()->ircChannel(bufferName);
116 if(channel) return channel->decodeString(string);
118 return network()->decodeString(string);
121 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
122 IrcUser *user = network()->ircUser(userNick);
123 if(user) return user->decodeString(string);
124 return network()->decodeString(string);
127 QByteArray NetworkConnection::serverEncode(const QString &string) const {
128 return network()->encodeServerString(string);
131 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
132 if(!bufferName.isEmpty()) {
133 IrcChannel *channel = network()->ircChannel(bufferName);
134 if(channel) return channel->encodeString(string);
136 return network()->encodeString(string);
139 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
140 IrcUser *user = network()->ircUser(userNick);
141 if(user) return user->encodeString(string);
142 return network()->encodeString(string);
145 void NetworkConnection::autoReconnectSettingsChanged() {
146 if(!network()->useAutoReconnect()) {
147 _autoReconnectTimer.stop();
148 _autoReconnectCount = 0;
150 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
151 if(_autoReconnectCount != 0) {
152 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
153 else _autoReconnectCount = network()->autoReconnectRetries();
158 void NetworkConnection::connectToIrc(bool reconnecting) {
159 if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
160 _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
161 if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
162 else _autoReconnectCount = network()->autoReconnectRetries();
164 QVariantList serverList = network()->serverList();
165 Identity *identity = coreSession()->identity(network()->identity());
166 if(!serverList.count()) {
167 qWarning() << "Server list empty, ignoring connect request!";
171 qWarning() << "Invalid identity configures, ignoring connect request!";
174 // use a random server?
175 if(network()->useRandomServer()) {
176 _lastUsedServerlistIndex = qrand() % serverList.size();
177 } else if(_previousConnectionAttemptFailed) {
178 // cycle to next server if previous connection attempt failed
179 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server"));
180 if(++_lastUsedServerlistIndex == serverList.size()) {
181 _lastUsedServerlistIndex = 0;
184 _previousConnectionAttemptFailed = false;
186 QString host = serverList[_lastUsedServerlistIndex].toMap()["Host"].toString();
187 quint16 port = serverList[_lastUsedServerlistIndex].toMap()["Port"].toUInt();
188 displayStatusMsg(tr("Connecting to %1:%2...").arg(host).arg(port));
189 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(host).arg(port));
190 socket.connectToHost(host, port);
193 void NetworkConnection::networkInitialized(const QString ¤tServer) {
194 if(currentServer.isEmpty()) return;
196 if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
197 _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
202 // now we are initialized
203 setConnectionState(Network::Initialized);
204 network()->setConnected(true);
205 emit connected(networkId());
207 if(_autoWhoEnabled) {
208 _autoWhoCycleTimer.start();
209 _autoWhoTimer.start();
210 startAutoWhoCycle(); // FIXME wait for autojoin to be completed
214 void NetworkConnection::sendPerform() {
215 BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
217 if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
218 userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
221 foreach(QString line, network()->perform()) {
222 if(!line.isEmpty()) userInput(statusBuf, line);
225 // rejoin channels we've been in
226 QStringList channels, keys;
227 foreach(QString chan, persistentChannels()) {
228 QString key = channelKey(chan);
230 channels.prepend(chan); keys.prepend(key);
232 channels.append(chan);
235 QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed();
236 if(!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString);
239 void NetworkConnection::disconnectFromIrc(bool requested) {
240 _autoReconnectTimer.stop();
241 _autoReconnectCount = 0;
242 displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
243 if(socket.state() < QAbstractSocket::ConnectedState) {
244 setConnectionState(Network::Disconnected);
245 socketDisconnected();
246 } else socket.disconnectFromHost();
249 emit quitRequested(networkId());
253 void NetworkConnection::socketHasData() {
254 while(socket.canReadLine()) {
255 QByteArray s = socket.readLine().trimmed();
256 ircServerHandler()->handleServerMsg(s);
260 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
261 _previousConnectionAttemptFailed = true;
262 qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
263 emit connectionError(socket.errorString());
264 emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
265 network()->emitConnectionError(socket.errorString());
266 if(socket.state() < QAbstractSocket::ConnectedState) {
267 setConnectionState(Network::Disconnected);
268 socketDisconnected();
270 // mark last connection attempt as failed
272 //qDebug() << "exiting...";
276 #ifndef QT_NO_OPENSSL
278 void NetworkConnection::sslErrors(const QList<QSslError> &sslErrors) {
279 socket.ignoreSslErrors();
280 /* TODO errorhandling
282 QVariantList errnums;
283 foreach(QSslError err, errors) errnums << err.error();
284 errmsg["SslErrors"] = errnums;
285 errmsg["SslCert"] = socket.peerCertificate().toPem();
286 errmsg["PeerAddress"] = socket.peerAddress().toString();
287 errmsg["PeerPort"] = socket.peerPort();
288 errmsg["PeerName"] = socket.peerName();
289 emit sslErrors(errmsg);
294 void NetworkConnection::socketEncrypted() {
295 //qDebug() << "encrypted!";
299 #endif // QT_NO_OPENSSL
301 void NetworkConnection::socketConnected() {
306 if(!network()->serverList()[_lastUsedServerlistIndex].toMap()["UseSSL"].toBool()) {
310 //qDebug() << "starting handshake";
311 socket.startClientEncryption();
315 void NetworkConnection::socketInitialized() {
316 //emit connected(networkId()); initialize first!
317 Identity *identity = coreSession()->identity(network()->identity());
319 qWarning() << "Identity invalid!";
323 QString passwd = network()->serverList()[_lastUsedServerlistIndex].toMap()["Password"].toString();
324 if(!passwd.isEmpty()) {
325 putRawLine(serverEncode(QString("PASS %1").arg(passwd)));
327 putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0]))); // FIXME: try more nicks if error occurs
328 putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
331 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
332 Network::ConnectionState state;
333 switch(socketState) {
334 case QAbstractSocket::UnconnectedState:
335 state = Network::Disconnected;
337 case QAbstractSocket::HostLookupState:
338 case QAbstractSocket::ConnectingState:
339 state = Network::Connecting;
341 case QAbstractSocket::ConnectedState:
342 state = Network::Initializing;
344 case QAbstractSocket::ClosingState:
345 state = Network::Disconnecting;
348 state = Network::Disconnected;
350 setConnectionState(state);
353 void NetworkConnection::socketDisconnected() {
354 _autoWhoCycleTimer.stop();
355 _autoWhoTimer.stop();
356 _autoWhoQueue.clear();
357 _autoWhoInProgress.clear();
359 network()->setConnected(false);
360 emit disconnected(networkId());
361 if(_autoReconnectCount != 0) {
362 setConnectionState(Network::Reconnecting);
363 if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
364 else _autoReconnectTimer.start();
368 void NetworkConnection::doAutoReconnect() {
369 if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
370 qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
373 if(_autoReconnectCount > 0) _autoReconnectCount--;
377 // FIXME switch to BufferId
378 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
379 userInputHandler()->handleUserInput(buf, msg);
382 void NetworkConnection::putRawLine(QByteArray s) {
387 void NetworkConnection::putCmd(const QString &cmd, const QVariantList ¶ms, const QByteArray &prefix) {
389 if(!prefix.isEmpty())
390 msg += ":" + prefix + " ";
391 msg += cmd.toUpper().toAscii();
393 for(int i = 0; i < params.size() - 1; i++) {
394 msg += " " + params[i].toByteArray();
396 if(!params.isEmpty())
397 msg += " :" + params.last().toByteArray();
402 void NetworkConnection::sendAutoWho() {
403 while(!_autoWhoQueue.isEmpty()) {
404 QString chan = _autoWhoQueue.takeFirst();
405 IrcChannel *ircchan = network()->ircChannel(chan);
406 if(!ircchan) continue;
407 if(_autoWhoNickLimit > 0 && ircchan->ircUsers().count() > _autoWhoNickLimit) continue;
408 _autoWhoInProgress.insert(chan);
409 putRawLine("WHO " + serverEncode(chan));
410 if(_autoWhoQueue.isEmpty() && _autoWhoEnabled && !_autoWhoCycleTimer.isActive()) {
411 // Timer was stopped, means a new cycle is due immediately
412 _autoWhoCycleTimer.start();
419 void NetworkConnection::startAutoWhoCycle() {
420 if(!_autoWhoQueue.isEmpty()) {
421 _autoWhoCycleTimer.stop();
424 _autoWhoQueue = network()->channels();
427 bool NetworkConnection::setAutoWhoDone(const QString &channel) {
428 return _autoWhoInProgress.remove(channel);
431 void NetworkConnection::setChannelJoined(const QString &channel) {
432 emit channelJoined(networkId(), channel, _channelKeys[channel.toLower()]);
433 _autoWhoQueue.prepend(channel); // prepend so this new chan is the first to be checked
436 void NetworkConnection::setChannelParted(const QString &channel) {
437 removeChannelKey(channel);
438 _autoWhoQueue.removeAll(channel);
439 _autoWhoInProgress.remove(channel);
440 emit channelParted(networkId(), channel);
443 void NetworkConnection::addChannelKey(const QString &channel, const QString &key) {
445 removeChannelKey(channel);
447 _channelKeys[channel.toLower()] = key;
451 void NetworkConnection::removeChannelKey(const QString &channel) {
452 _channelKeys.remove(channel.toLower());
455 void NetworkConnection::nickChanged(const QString &newNick, const QString &oldNick) {
456 emit nickChanged(networkId(), newNick, oldNick);
459 /* Exception classes for message handling */
460 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
462 _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
465 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
467 _msg = QString("Unknown Command: ") + cmd + params.join(" ");