Added Socks5 and HTTP-Proxy support to the client.
[quassel.git] / src / client / clientsyncer.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
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
21 #include "clientsyncer.h"
22
23 #include <QNetworkProxy>
24
25 #include "client.h"
26 #include "global.h"
27 #include "identity.h"
28 #include "ircuser.h"
29 #include "ircchannel.h"
30 #include "network.h"
31 #include "signalproxy.h"
32
33
34 ClientSyncer::ClientSyncer(QObject *parent) : QObject(parent) {
35   socket = 0;
36   blockSize = 0;
37
38   connect(Client::signalProxy(), SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
39
40 }
41
42 ClientSyncer::~ClientSyncer() {
43
44
45 }
46
47 void ClientSyncer::coreHasData() {
48   QVariant item;
49   while(SignalProxy::readDataFromDevice(socket, blockSize, item)) {
50     emit recvPartialItem(1,1);
51     QVariantMap msg = item.toMap();
52     if(!msg.contains("MsgType")) {
53       // This core is way too old and does not even speak our init protocol...
54       emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
55       disconnectFromCore();
56       return;
57     }
58     if(msg["MsgType"] == "ClientInitAck") {
59       clientInitAck(msg);
60     } else if(msg["MsgType"] == "ClientInitReject") {
61       emit connectionError(msg["Error"].toString());
62       disconnectFromCore();
63       return;
64     } else if(msg["MsgType"] == "CoreSetupAck") {
65       emit coreSetupSuccess();
66     } else if(msg["MsgType"] == "CoreSetupReject") {
67       emit coreSetupFailed(msg["Error"].toString());
68     } else if(msg["MsgType"] == "ClientLoginReject") {
69       emit loginFailed(msg["Error"].toString());
70     } else if(msg["MsgType"] == "ClientLoginAck") {
71       // prevent multiple signal connections
72       disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
73       connect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
74       emit loginSuccess();
75     } else if(msg["MsgType"] == "SessionInit") {
76       sessionStateReceived(msg["SessionState"].toMap());
77       break; // this is definitively the last message we process here!
78     } else {
79       emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
80       disconnectFromCore();
81       return;
82     }
83   }
84   if(blockSize > 0) {
85     emit recvPartialItem(socket->bytesAvailable(), blockSize);
86   }
87 }
88
89 void ClientSyncer::coreSocketError(QAbstractSocket::SocketError) {
90   emit connectionError(socket->errorString());
91   socket->deleteLater();
92 }
93
94 void ClientSyncer::disconnectFromCore() {
95   if(socket) socket->close();
96 }
97
98 void ClientSyncer::connectToCore(const QVariantMap &conn) {
99   // TODO implement SSL
100   coreConnectionInfo = conn;
101   //if(isConnected()) {
102   //  emit coreConnectionError(tr("Already connected to Core!"));
103   //  return;
104   // }
105   if(socket != 0) {
106     socket->deleteLater();
107     socket = 0;
108   }
109   if(conn["Host"].toString().isEmpty()) {
110     emit connectionError(tr("Internal connections not yet supported."));
111     return; // FIXME implement internal connections
112     //clientMode = LocalCore;
113     socket = new QBuffer(this);
114     connect(socket, SIGNAL(readyRead()), this, SLOT(coreHasData()));
115     socket->open(QIODevice::ReadWrite);
116     //QVariant state = connectToLocalCore(coreConnectionInfo["User"].toString(), coreConnectionInfo["Password"].toString());
117     //syncToCore(state);
118     coreSocketConnected();
119   } else {
120     //clientMode = RemoteCore;
121     //emit coreConnectionMsg(tr("Connecting..."));
122     Q_ASSERT(!socket);
123     QTcpSocket *sock = new QTcpSocket(Client::instance());
124     if(conn.contains("useProxy") && conn["useProxy"].toBool()) {
125       QNetworkProxy proxy((QNetworkProxy::ProxyType)conn["proxyType"].toInt(), conn["proxyHost"].toString(), conn["proxyPort"].toUInt(), conn["proxyUser"].toString(), conn["proxyPassword"].toString());
126       sock->setProxy(proxy);
127     }
128     socket = sock;
129     connect(sock, SIGNAL(readyRead()), this, SLOT(coreHasData()));
130     connect(sock, SIGNAL(connected()), this, SLOT(coreSocketConnected()));
131     connect(sock, SIGNAL(disconnected()), this, SLOT(coreSocketDisconnected()));
132     connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(coreSocketError(QAbstractSocket::SocketError)));
133     connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SIGNAL(socketStateChanged(QAbstractSocket::SocketState)));
134     sock->connectToHost(conn["Host"].toString(), conn["Port"].toUInt());
135   }
136 }
137
138 void ClientSyncer::coreSocketConnected() {
139   //connect(this, SIGNAL(recvPartialItem(uint, uint)), this, SIGNAL(coreConnectionProgress(uint, uint)));
140   // Phase One: Send client info and wait for core info
141
142   //emit coreConnectionMsg(tr("Synchronizing to core..."));
143   QVariantMap clientInit;
144   clientInit["MsgType"] = "ClientInit";
145   clientInit["ClientVersion"] = Global::quasselVersion;
146   clientInit["ClientDate"] = Global::quasselDate;
147   clientInit["ClientBuild"] = Global::quasselBuild; // this is a minimum, since we probably won't update for every commit
148   clientInit["UseSsl"] = false;  // FIXME implement SSL
149   SignalProxy::writeDataToDevice(socket, clientInit);
150 }
151
152 void ClientSyncer::coreSocketDisconnected() {
153   emit socketDisconnected();
154   Client::instance()->disconnectFromCore();
155
156   // FIXME handle disconnects gracefully in here as well!
157
158   coreConnectionInfo.clear();
159   netsToSync.clear();
160   channelsToSync.clear();
161   usersToSync.clear();
162   blockSize = 0;
163   //restartPhaseNull();
164 }
165
166 void ClientSyncer::clientInitAck(const QVariantMap &msg) {
167   // Core has accepted our version info and sent its own. Let's see if we accept it as well...
168   if(msg["CoreBuild"].toUInt() < Global::coreBuildNeeded) {
169     emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
170         "Need at least a Core Version %1 (Build >= %2) to connect.").arg(Global::quasselVersion).arg(Global::coreBuildNeeded));
171     disconnectFromCore();
172     return;
173   }
174   emit connectionMsg(msg["CoreInfo"].toString());
175   if(!msg["Configured"].toBool()) {
176     // start wizard
177     emit startCoreSetup(msg["StorageBackends"].toList());
178   } else if(msg["LoginEnabled"].toBool()) {
179     emit startLogin();
180   }
181 }
182
183 void ClientSyncer::doCoreSetup(const QVariant &setupData) {
184   QVariantMap setup;
185   setup["MsgType"] = "CoreSetupData";
186   setup["SetupData"] = setupData;
187   SignalProxy::writeDataToDevice(socket, setup);
188 }
189
190 void ClientSyncer::loginToCore(const QString &user, const QString &passwd) {
191   emit connectionMsg(tr("Logging in..."));
192   QVariantMap clientLogin;
193   clientLogin["MsgType"] = "ClientLogin";
194   clientLogin["User"] = user;
195   clientLogin["Password"] = passwd;
196   SignalProxy::writeDataToDevice(socket, clientLogin);
197 }
198
199 void ClientSyncer::sessionStateReceived(const QVariantMap &state) {
200   emit sessionProgress(1, 1);
201   disconnect(this, SIGNAL(recvPartialItem(quint32, quint32)), this, SIGNAL(sessionProgress(quint32, quint32)));
202   disconnect(socket, 0, this, 0);  // rest of communication happens through SignalProxy
203   //Client::signalProxy()->addPeer(socket);
204   Client::instance()->setConnectedToCore(socket, coreConnectionInfo["AccountId"].value<AccountId>());
205   syncToCore(state);
206 }
207
208 void ClientSyncer::syncToCore(const QVariantMap &sessionState) {
209
210   // create identities
211   foreach(QVariant vid, sessionState["Identities"].toList()) {
212     Client::instance()->coreIdentityCreated(vid.value<Identity>());
213   }
214
215   // create buffers
216   // FIXME: get rid of this crap
217   QVariantList bufferinfos = sessionState["BufferInfos"].toList();
218   foreach(QVariant vinfo, bufferinfos) Client::buffer(vinfo.value<BufferInfo>());  // create Buffers and BufferItems
219
220   QVariantList networkids = sessionState["NetworkIds"].toList();
221
222   // prepare sync progress thingys... FIXME: Care about removal of networks
223   numNetsToSync = networkids.count();
224   numChannelsToSync = 0; //sessionState["IrcChannelCount"].toUInt();
225   numUsersToSync = 0; // sessionState["IrcUserCount"].toUInt(); qDebug() << numUsersToSync;
226   emit networksProgress(0, numNetsToSync);
227   emit channelsProgress(0, numChannelsToSync);
228   emit ircUsersProgress(0, numUsersToSync);
229
230   // create network objects
231   foreach(QVariant networkid, networkids) {
232     NetworkId netid = networkid.value<NetworkId>();
233     Network *net = new Network(netid, Client::instance());
234     netsToSync.insert(net);
235     connect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
236     connect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
237     connect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
238     connect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
239     connect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
240     connect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
241     connect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
242     Client::addNetwork(net);
243   }
244   checkSyncState();
245 }
246
247 void ClientSyncer::networkInitDone() {
248   netsToSync.remove(sender());
249   emit networksProgress(numNetsToSync - netsToSync.count(), numNetsToSync);
250   checkSyncState();
251 }
252
253 void ClientSyncer::ircChannelInitDone(IrcChannel *chan) {
254   channelsToSync.remove(chan);
255   emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
256   checkSyncState();
257 }
258
259 void ClientSyncer::ircChannelAdded(IrcChannel *chan) {
260   if(!chan->isInitialized()) {
261     channelsToSync.insert(chan);
262     numChannelsToSync++;
263     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
264     checkSyncState();
265   }
266 }
267
268 void ClientSyncer::ircChannelRemoved(QObject *chan) {
269   if(channelsToSync.contains(chan)) {
270     numChannelsToSync--;
271     channelsToSync.remove(chan);
272     emit channelsProgress(numChannelsToSync - channelsToSync.count(), numChannelsToSync);
273     checkSyncState();
274   }
275 }
276
277 void ClientSyncer::ircUserInitDone(IrcUser *user) {
278   usersToSync.remove(user);
279   emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
280   checkSyncState();
281 }
282
283 void ClientSyncer::ircUserAdded(IrcUser *user) {
284   if(!user->isInitialized()) {
285     usersToSync.insert(user);
286     numUsersToSync++;
287     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
288     checkSyncState();
289   }
290 }
291
292 void ClientSyncer::ircUserRemoved(QObject *user) {
293   if(usersToSync.contains(user)) {
294     numUsersToSync--;
295     usersToSync.remove(user);
296     emit ircUsersProgress(numUsersToSync - usersToSync.count(), numUsersToSync);
297     checkSyncState();
298   }
299 }
300
301 void ClientSyncer::checkSyncState() {
302   if(usersToSync.count() + channelsToSync.count() + netsToSync.count() == 0) {
303     // done syncing!
304     /*
305     qDebug() << "done";
306     foreach(Network *net, _networks.values()) {
307       //disconnect(net, 0, this, SLOT(networkInitDone()));
308       //disconnect(net, 0, this, SLOT(ircUserInitDone(IrcUser *)));
309       //disconnect(net, 0, this, SLOT(ircUserAdded(IrcUser *)));
310       //disconnect(net, 0, this, SLOT(ircUserRemoved(QObject *)));
311       //disconnect(net, 0, this, SLOT(ircChannelInitDone(IrcChannel *)));
312       //disconnect(net, 0, this, SLOT(ircChannelAdded(IrcChannel *)));
313       //disconnect(net, 0, this, SLOT(ircChannelRemoved(QObject *)));
314       qDebug() << "disconnecting";
315       disconnect(net, SIGNAL(initDone()), this, SLOT(networkInitDone()));
316       disconnect(net, SIGNAL(ircUserInitDone(IrcUser *)), this, SLOT(ircUserInitDone(IrcUser *)));
317       disconnect(net, SIGNAL(ircUserAdded(IrcUser *)), this, SLOT(ircUserAdded(IrcUser *)));
318       disconnect(net, SIGNAL(ircUserRemoved(QObject *)), this, SLOT(ircUserRemoved(QObject *)));
319       disconnect(net, SIGNAL(ircChannelInitDone(IrcChannel *)), this, SLOT(ircChannelInitDone(IrcChannel *)));
320       disconnect(net, SIGNAL(ircChannelAdded(IrcChannel *)), this, SLOT(ircChannelAdded(IrcChannel *)));
321       disconnect(net, SIGNAL(ircChannelRemoved(QObject *)), this, SLOT(ircChannelRemoved(QObject *)));
322     }
323     */
324
325     Client::instance()->setSyncedToCore();
326     emit syncFinished();
327     //emit connected();
328     //emit connectionStateChanged(true);
329
330   }
331 }
332