More improvements to encoding handling. There is now a server encoding that
[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 {
48   connect(network, SIGNAL(currentServerSet(const QString &)), this, SLOT(networkInitialized(const QString &)));
49
50   connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected()));
51   connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
52   connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
53   connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
54   connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData()));
55
56 }
57
58 NetworkConnection::~NetworkConnection() {
59   disconnectFromIrc();
60   delete _ircServerHandler;
61   delete _userInputHandler;
62   delete _ctcpHandler;
63 }
64
65 bool NetworkConnection::isConnected() const {
66   // return socket.state() == QAbstractSocket::ConnectedState;
67   return connectionState() == Network::Initialized;
68 }
69
70 Network::ConnectionState NetworkConnection::connectionState() const {
71   return _connectionState;
72 }
73
74 void NetworkConnection::setConnectionState(Network::ConnectionState state) {
75   _connectionState = state;
76   network()->setConnectionState(state);
77   emit connectionStateChanged(state);
78 }
79
80 NetworkId NetworkConnection::networkId() const {
81   return network()->networkId();
82 }
83
84 QString NetworkConnection::networkName() const {
85   return network()->networkName();
86 }
87
88 Identity *NetworkConnection::identity() const {
89   return coreSession()->identity(network()->identity());
90 }
91
92 Network *NetworkConnection::network() const {
93   return _network;
94 }
95
96 CoreSession *NetworkConnection::coreSession() const {
97   return _coreSession;
98 }
99
100 IrcServerHandler *NetworkConnection::ircServerHandler() const {
101   return _ircServerHandler;
102 }
103
104 UserInputHandler *NetworkConnection::userInputHandler() const {
105   return _userInputHandler;
106 }
107
108 CtcpHandler *NetworkConnection::ctcpHandler() const {
109   return _ctcpHandler;
110 }
111
112 QString NetworkConnection::serverDecode(const QByteArray &string) const {
113   return network()->decodeServerString(string);
114 }
115
116 QString NetworkConnection::channelDecode(const QString &bufferName, const QByteArray &string) const {
117   if(!bufferName.isEmpty()) {
118     IrcChannel *channel = network()->ircChannel(bufferName);
119     if(channel) return channel->decodeString(string);
120   }
121   return network()->decodeString(string);
122 }
123
124 QString NetworkConnection::userDecode(const QString &userNick, const QByteArray &string) const {
125   IrcUser *user = network()->ircUser(userNick);
126   if(user) return user->decodeString(string);
127   return network()->decodeString(string);
128 }
129
130 QByteArray NetworkConnection::serverEncode(const QString &string) const {
131   return network()->encodeServerString(string);
132 }
133
134 QByteArray NetworkConnection::channelEncode(const QString &bufferName, const QString &string) const {
135   if(!bufferName.isEmpty()) {
136     IrcChannel *channel = network()->ircChannel(bufferName);
137     if(channel) return channel->encodeString(string);
138   }
139   return network()->encodeString(string);
140 }
141
142 QByteArray NetworkConnection::userEncode(const QString &userNick, const QString &string) const {
143   IrcUser *user = network()->ircUser(userNick);
144   if(user) return user->encodeString(string);
145   return network()->encodeString(string);
146 }
147
148
149 void NetworkConnection::connectToIrc() {
150   QVariantList serverList = network()->serverList();
151   Identity *identity = coreSession()->identity(network()->identity());
152   if(!serverList.count()) {
153     qWarning() << "Server list empty, ignoring connect request!";
154     return;
155   }
156   if(!identity) {
157     qWarning() << "Invalid identity configures, ignoring connect request!";
158     return;
159   }
160   // TODO implement cycling / random servers
161   QString host = serverList[0].toMap()["Host"].toString();
162   quint16 port = serverList[0].toMap()["Port"].toUInt();
163   displayStatusMsg(QString("Connecting to %1:%2...").arg(host).arg(port));
164   socket.connectToHost(host, port);
165 }
166
167 void NetworkConnection::networkInitialized(const QString &currentServer) {
168   if(currentServer.isEmpty()) return;
169
170   sendPerform();
171
172     // rejoin channels we've been in
173   QStringList chans = _previousState.toStringList();
174   if(chans.count() > 0) {
175     qDebug() << "autojoining" << chans;
176     QVariantList list;
177     foreach(QString chan, chans) list << serverEncode(chan);
178     putCmd("JOIN", list);  // FIXME check for 512 byte limit!
179   }
180   // delete _previousState, we won't need it again
181   _previousState = QVariant();
182   // now we are initialized
183   setConnectionState(Network::Initialized);
184   network()->setConnected(true);
185   emit connected(networkId());
186 }
187
188 void NetworkConnection::sendPerform() {
189   BufferInfo statusBuf = Core::bufferInfo(coreSession()->user(), network()->networkId(), BufferInfo::StatusBuffer);
190   // do auto identify
191   if(network()->useAutoIdentify() && !network()->autoIdentifyService().isEmpty() && !network()->autoIdentifyPassword().isEmpty()) {
192     userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(network()->autoIdentifyService(), network()->autoIdentifyPassword()));
193   }
194   // send perform list
195   foreach(QString line, network()->perform()) {
196     if(!line.isEmpty()) userInput(statusBuf, line);
197   }
198 }
199
200 QVariant NetworkConnection::state() const {
201   IrcUser *me = network()->ircUser(network()->myNick());
202   if(!me) return QVariant();  // this shouldn't really happen, I guess
203   return me->channels();
204 }
205
206 void NetworkConnection::disconnectFromIrc() {
207   socket.disconnectFromHost();
208 }
209
210 void NetworkConnection::socketHasData() {
211   while(socket.canReadLine()) {
212     QByteArray s = socket.readLine().trimmed();
213     ircServerHandler()->handleServerMsg(s);
214   }
215 }
216
217 void NetworkConnection::socketError(QAbstractSocket::SocketError) {
218   qDebug() << qPrintable(tr("Could not connect to %1 (%2)").arg(network()->networkName(), socket.errorString()));
219   emit connectionError(socket.errorString());
220   emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString()));
221   network()->emitConnectionError(socket.errorString());
222 }
223
224 void NetworkConnection::socketConnected() {
225   //emit connected(networkId());  initialize first!
226   Identity *identity = coreSession()->identity(network()->identity());
227   if(!identity) {
228     qWarning() << "Identity invalid!";
229     disconnectFromIrc();
230     return;
231   }
232   putRawLine(serverEncode(QString("NICK :%1").arg(identity->nicks()[0])));  // FIXME: try more nicks if error occurs
233   putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName())));
234 }
235
236 void NetworkConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
237   Network::ConnectionState state;
238   switch(socketState) {
239     case QAbstractSocket::UnconnectedState:
240       state = Network::Disconnected;
241       break;
242     case QAbstractSocket::HostLookupState:
243     case QAbstractSocket::ConnectingState:
244       state = Network::Connecting;
245       break;
246     case QAbstractSocket::ConnectedState:
247       state = Network::Initializing;
248       break;
249     case QAbstractSocket::ClosingState:
250       state = Network::Disconnecting;
251       break;
252     default:
253       state = Network::Disconnected;
254   }
255   setConnectionState(state);
256 }
257
258 void NetworkConnection::socketDisconnected() {
259   network()->setConnected(false);
260   emit disconnected(networkId());
261 }
262
263 // FIXME switch to BufferId
264 void NetworkConnection::userInput(BufferInfo buf, QString msg) {
265   userInputHandler()->handleUserInput(buf, msg);
266 }
267
268 void NetworkConnection::putRawLine(QByteArray s) {
269   s += "\r\n";
270   socket.write(s);
271 }
272
273 void NetworkConnection::putCmd(const QString &cmd, const QVariantList &params, const QByteArray &prefix) {
274   QByteArray msg;
275   if(!prefix.isEmpty())
276     msg += ":" + prefix + " ";
277   msg += cmd.toUpper().toAscii();
278
279   for(int i = 0; i < params.size() - 1; i++) {
280     msg += " " + params[i].toByteArray();
281   }
282   if(!params.isEmpty())
283     msg += " :" + params.last().toByteArray();
284
285   putRawLine(msg);
286 }
287
288 /* Exception classes for message handling */
289 NetworkConnection::ParseError::ParseError(QString cmd, QString prefix, QStringList params) {
290   Q_UNUSED(prefix);
291   _msg = QString("Command Parse Error: ") + cmd + params.join(" ");
292 }
293
294 NetworkConnection::UnknownCmdError::UnknownCmdError(QString cmd, QString prefix, QStringList params) {
295   Q_UNUSED(prefix);
296   _msg = QString("Unknown Command: ") + cmd + params.join(" ");
297 }