24238def567c6c720f76489256836b5ce0784eff
[quassel.git] / src / core / networkconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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"
21
22 #include <QMetaObject>
23 #include <QMetaMethod>
24 #include <QDateTime>
25
26 #include "util.h"
27 #include "core.h"
28 #include "coresession.h"
29
30 #include "ircchannel.h"
31 #include "ircuser.h"
32 #include "network.h"
33 #include "identity.h"
34
35 #include "ircserverhandler.h"
36 #include "userinputhandler.h"
37 #include "ctcphandler.h"
38
39 NetworkConnection::NetworkConnection(Network *network, CoreSession *session, const QVariant &state) : QObject(network),
40     _connectionState(Network::Disconnected),
41     _network(network),
42     _coreSession(session),
43     _ircServerHandler(new IrcServerHandler(this)),
44     _userInputHandler(new UserInputHandler(this)),
45     _ctcpHandler(new CtcpHandler(this)),
46     _previousState(state),
47     _autoReconnectCount(0)
48 {
49   _autoReconnectTimer.setSingleShot(true);
50   connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect()));
51
52   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
53   connect(network, SIGNAL(useAutoReconnectSet(bool)), this, SLOT(autoReconnectSettingsChanged()));
54   connect(network, SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(autoReconnectSettingsChanged()));
55   connect(network, SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(autoReconnectSettingsChanged()));
56
57   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
58   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
59   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
60   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
61   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
62
63 }
64
65 NetworkConnection::~NetworkConnection() {
66   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting)
67     disconnectFromIrc();
68   delete _ircServerHandler;
69   delete _userInputHandler;
70   delete _ctcpHandler;
71 }
72
73 bool NetworkConnection::isConnected() const {
74   // return socket.state() == QAbstractSocket::ConnectedState;
75   return connectionState() == Network::Initialized;
76 }
77
78 Network::ConnectionState NetworkConnection::connectionState() const {
79   return _connectionState;
80 }
81
82 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
83   _connectionState = state;
84   network()->setConnectionState(state);
85   emit connectionStateChanged(state);
86 }
87
88 NetworkId NetworkConnection::networkId() const {
89   return network()->networkId();
90 }
91
92 QString NetworkConnection::networkName() const {
93   return network()->networkName();
94 }
95
96 Identity *NetworkConnection::identity() const {
97   return coreSession()->identity(network()->identity());
98 }
99
100 Network *NetworkConnection::network() const {
101   return _network;
102 }
103
104 CoreSession *NetworkConnection::coreSession() const {
105   return _coreSession;
106 }
107
108 IrcServerHandler *NetworkConnection::ircServerHandler() const {
109   return _ircServerHandler;
110 }
111
112 UserInputHandler *NetworkConnection::userInputHandler() const {
113   return _userInputHandler;
114 }
115
116 CtcpHandler *NetworkConnection::ctcpHandler() const {
117   return _ctcpHandler;
118 }
119
120 QString NetworkConnection::serverDecode(const QByteArray &string) const {
121   return network()->decodeServerString(string);
122 }
123
124 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
125   if(!bufferName.isEmpty()) {
126     IrcChannel *channel = network()->ircChannel(bufferName);
127     if(channel) return channel->decodeString(string);
128   }
129   return network()->decodeString(string);
130 }
131
132 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
133   IrcUser *user = network()->ircUser(userNick);
134   if(user) return user->decodeString(string);
135   return network()->decodeString(string);
136 }
137
138 QByteArray NetworkConnection::serverEncode(const QString &string) const {
139   return network()->encodeServerString(string);
140 }
141
142 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
143   if(!bufferName.isEmpty()) {
144     IrcChannel *channel = network()->ircChannel(bufferName);
145     if(channel) return channel->encodeString(string);
146   }
147   return network()->encodeString(string);
148 }
149
150 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
151   IrcUser *user = network()->ircUser(userNick);
152   if(user) return user->encodeString(string);
153   return network()->encodeString(string);
154 }
155
156 void NetworkConnection::autoReconnectSettingsChanged() {
157   if(!network()->useAutoReconnect()) {
158     _autoReconnectTimer.stop();
159     _autoReconnectCount = 0;
160   } else {
161     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
162     if(_autoReconnectCount != 0) {
163       if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
164       else _autoReconnectCount = network()->autoReconnectRetries();
165     }
166   }
167 }
168
169 void NetworkConnection::connectToIrc(bool reconnecting) {
170   if(!reconnecting && network()->useAutoReconnect() && _autoReconnectCount == 0) {
171     _autoReconnectTimer.setInterval(network()->autoReconnectInterval() * 1000);
172     if(network()->unlimitedReconnectRetries()) _autoReconnectCount = -1;
173     else _autoReconnectCount = network()->autoReconnectRetries();
174   }
175   QVariantList serverList = network()->serverList();
176   Identity *identity = coreSession()->identity(network()->identity());
177   if(!serverList.count()) {
178     qWarning() << "Server list empty, ignoring connect request!";
179     return;
180   }
181   if(!identity) {
182     qWarning() << "Invalid identity configures, ignoring connect request!";
183     return;
184   }
185   // TODO implement cycling / random servers
186   QString host = serverList[0].toMap()["Host"].toString();
187   quint16 port = serverList[0].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);
191 }
192
193 void NetworkConnection::networkInitialized(const QString &currentServer) {
194   if(currentServer.isEmpty()) return;
195
196   if(network()->useAutoReconnect() && !network()->unlimitedReconnectRetries()) {
197     _autoReconnectCount = network()->autoReconnectRetries(); // reset counter
198   }
199
200   sendPerform();
201
202     // rejoin channels we've been in
203   QStringList chans = _previousState.toStringList();
204   if(chans.count() > 0) {
205     qDebug() << "autojoining" << chans;
206     QVariantList list;
207     list << serverEncode(chans.join(",")); // TODO add channel passwords
208     putCmd("JOIN", list);  // FIXME check for 512 byte limit!
209   }
210   // delete _previousState, we won't need it again
211   _previousState = QVariant();
212   // now we are initialized
213   setConnectionState(Network::Initialized);
214   network()->setConnected(true);
215   emit connected(networkId());
216 }
217
218 void NetworkConnection::sendPerform() {
219   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
220   // do auto identify
221   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
222     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
223   }
224   // send perform list
225   foreach(QString line, network()->perform()) {
226     if(!line.isEmpty()) userInput(statusBuf, line);
227   }
228 }
229
230 QVariant NetworkConnection::state() const {
231   IrcUser *me = network()->ircUser(network()->myNick());
232   if(!me) return QVariant();  // this shouldn't really happen, I guess
233   return me->channels();
234 }
235
236 void NetworkConnection::disconnectFromIrc() {
237   _autoReconnectTimer.stop();
238   _autoReconnectCount = 0;
239   displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting."));
240   if(socket.state() < QAbstractSocket::ConnectedState) {
241     setConnectionState(Network::Disconnected);
242     socketDisconnected();
243   } else socket.disconnectFromHost();
244 }
245
246 void NetworkConnection::socketHasData() {
247   while(socket.canReadLine()) {
248     QByteArray s = socket.readLine().trimmed();
249     ircServerHandler()->handleServerMsg(s);
250   }
251 }
252
253 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
254   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
255   emit connectionError(socket.errorString());
256   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
257   network()->emitConnectionError(socket.errorString());
258   if(socket.state() < QAbstractSocket::ConnectedState) {
259     setConnectionState(Network::Disconnected);
260     socketDisconnected();
261   }
262 }
263
264 void NetworkConnection::socketConnected() {
265   //emit connected(networkId());  initialize first!
266   Identity *identity = coreSession()->identity(network()->identity());
267   if(!identity) {
268     qWarning() << "Identity invalid!";
269     disconnectFromIrc();
270     return;
271   }
272   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
273   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
274 }
275
276 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
277   Network::ConnectionState state;
278   switch(socketState) {
279     case QAbstractSocket::UnconnectedState:
280       state = Network::Disconnected;
281       break;
282     case QAbstractSocket::HostLookupState:
283     case QAbstractSocket::ConnectingState:
284       state = Network::Connecting;
285       break;
286     case QAbstractSocket::ConnectedState:
287       state = Network::Initializing;
288       break;
289     case QAbstractSocket::ClosingState:
290       state = Network::Disconnecting;
291       break;
292     default:
293       state = Network::Disconnected;
294   }
295   setConnectionState(state);
296 }
297
298 void NetworkConnection::socketDisconnected() {
299   network()->setConnected(false);
300   emit disconnected(networkId());
301   if(_autoReconnectCount == 0) emit quitRequested(networkId());
302   else {
303     setConnectionState(Network::Reconnecting);
304     qDebug() << "trying to reconnect... " << _autoReconnectTimer.interval();
305     if(_autoReconnectCount == network()->autoReconnectRetries()) doAutoReconnect(); // first try is immediate
306     else _autoReconnectTimer.start();
307   }
308 }
309
310 void NetworkConnection::doAutoReconnect() {
311   if(connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
312     qWarning() << "NetworkConnection::doAutoReconnect(): Cannot reconnect while not being disconnected!";
313     return;
314   }
315   if(_autoReconnectCount > 0) _autoReconnectCount--;
316   connectToIrc(true);
317 }
318
319 // FIXME switch to BufferId
320 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
321   userInputHandler()->handleUserInput(buf, msg);
322 }
323
324 void NetworkConnection::putRawLine(QByteArray s) {
325   s += "\r\n";
326   socket.write(s);
327 }
328
329 void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
330   QByteArray msg;
331   if(!prefix.isEmpty())
332     msg += ":" + prefix + " ";
333   msg += cmd.toUpper().toAscii();
334
335   for(int i = 0; i < params.size() - 1; i++) {
336     msg += " " + params[i].toByteArray();
337   }
338   if(!params.isEmpty())
339     msg += " :" + params.last().toByteArray();
340
341   putRawLine(msg);
342 }
343
344 /* Exception classes for message handling */
345 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
346   Q_UNUSED(prefix);
347   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
348 }
349
350 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
351   Q_UNUSED(prefix);
352   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
353 }