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