1 /***************************************************************************
2 * Copyright (C) 2009 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 ***************************************************************************/
21 #include "coreconnection.h"
23 #ifndef QT_NO_NETWORKPROXY
24 # include <QNetworkProxy>
28 #include "coreaccountmodel.h"
31 #include "networkmodel.h"
33 #include "signalproxy.h"
36 CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent)
44 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
48 void CoreConnection::start() {
52 void CoreConnection::init() {
53 connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
56 void CoreConnection::setProgressText(const QString &text) {
57 if(_progressText != text) {
59 emit progressTextChanged(text);
63 void CoreConnection::setProgressValue(int value) {
64 if(_progressValue != value) {
65 _progressValue = value;
66 emit progressValueChanged(value);
70 void CoreConnection::setProgressMinimum(int minimum) {
71 if(_progressMinimum != minimum) {
72 _progressMinimum = minimum;
73 emit progressRangeChanged(minimum, _progressMaximum);
77 void CoreConnection::setProgressMaximum(int maximum) {
78 if(_progressMaximum != maximum) {
79 _progressMaximum = maximum;
80 emit progressRangeChanged(_progressMinimum, maximum);
84 void CoreConnection::updateProgress(int value, int max) {
85 if(max != _progressMaximum) {
86 _progressMaximum = max;
87 emit progressRangeChanged(_progressMinimum, _progressMaximum);
89 setProgressValue(value);
92 void CoreConnection::resetConnection() {
94 disconnect(_socket, 0, this, 0);
95 _socket->deleteLater();
100 _coreMsgBuffer.clear();
105 setProgressMaximum(-1); // disable
106 emit connectionMsg(tr("Disconnected from core."));
109 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
112 switch(socketState) {
113 case QAbstractSocket::UnconnectedState:
114 text = tr("Disconnected.");
116 case QAbstractSocket::HostLookupState:
117 text = tr("Looking up %1...").arg(currentAccount().hostName());
119 case QAbstractSocket::ConnectingState:
120 text = tr("Connecting to %1...").arg(currentAccount().hostName());
122 case QAbstractSocket::ConnectedState:
123 text = tr("Connected to %1.").arg(currentAccount().hostName());
125 case QAbstractSocket::ClosingState:
126 text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
133 emit progressTextChanged(text);
135 setState(socketState);
138 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
139 ConnectionState state;
141 switch(socketState) {
142 case QAbstractSocket::UnconnectedState:
143 state = Disconnected;
145 case QAbstractSocket::HostLookupState:
146 case QAbstractSocket::ConnectingState:
149 case QAbstractSocket::ConnectedState:
153 state = Disconnected;
159 void CoreConnection::setState(ConnectionState state) {
160 if(state != _state) {
162 emit stateChanged(state);
166 void CoreConnection::setWarningsHandler(const char *slot) {
167 resetWarningsHandler();
168 connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
171 void CoreConnection::resetWarningsHandler() {
172 disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
175 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
176 qDebug() << "coreSocketError" << _socket << _socket->errorString();
177 emit connectionError(_socket->errorString());
181 void CoreConnection::coreSocketDisconnected() {
182 setState(Disconnected);
185 // FIXME handle disconnects gracefully
188 void CoreConnection::coreHasData() {
190 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
191 QVariantMap msg = item.toMap();
192 if(!msg.contains("MsgType")) {
193 // This core is way too old and does not even speak our init protocol...
194 emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
195 disconnectFromCore();
198 if(msg["MsgType"] == "ClientInitAck") {
200 } else if(msg["MsgType"] == "ClientInitReject") {
201 emit connectionError(msg["Error"].toString());
202 disconnectFromCore();
204 } else if(msg["MsgType"] == "CoreSetupAck") {
205 //emit coreSetupSuccess();
206 } else if(msg["MsgType"] == "CoreSetupReject") {
207 //emit coreSetupFailed(msg["Error"].toString());
208 } else if(msg["MsgType"] == "ClientLoginReject") {
209 loginFailed(msg["Error"].toString());
210 } else if(msg["MsgType"] == "ClientLoginAck") {
212 } else if(msg["MsgType"] == "SessionInit") {
213 // that's it, let's hand over to the signal proxy
214 // if the socket is an orphan, the signalProxy adopts it.
215 // -> we don't need to care about it anymore
216 _socket->setParent(0);
217 Client::signalProxy()->addPeer(_socket);
219 sessionStateReceived(msg["SessionState"].toMap());
220 break; // this is definitively the last message we process here!
222 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
223 disconnectFromCore();
228 updateProgress(_socket->bytesAvailable(), _blockSize);
232 void CoreConnection::disconnectFromCore() {
234 Client::signalProxy()->removeAllPeers();
239 void CoreConnection::reconnectToCore() {
243 void CoreConnection::connectToCore(AccountId accId) {
245 _account = accountModel()->account(accId);
247 if(!_account.accountId().isValid()) {
248 emit connectionError(tr("Invalid core account, cannot connect!"));
254 QSslSocket *sock = new QSslSocket(Client::instance());
256 if(_account.useSsl()) {
257 emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
260 QTcpSocket *sock = new QTcpSocket(Client::instance());
263 #ifndef QT_NO_NETWORKPROXY
264 if(_account.useProxy()) {
265 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
266 sock->setProxy(proxy);
271 connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
272 connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
273 connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
274 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
275 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
277 emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
278 sock->connectToHost(_account.hostName(), _account.port());
281 void CoreConnection::coreSocketConnected() {
282 // Phase One: Send client info and wait for core info
284 emit connectionMsg(tr("Synchronizing to core..."));
286 QVariantMap clientInit;
287 clientInit["MsgType"] = "ClientInit";
288 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
289 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
290 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
291 clientInit["UseSsl"] = _account.useSsl();
292 #ifndef QT_NO_COMPRESS
293 clientInit["UseCompression"] = true;
295 clientInit["UseCompression"] = false;
298 SignalProxy::writeDataToDevice(_socket, clientInit);
301 void CoreConnection::clientInitAck(const QVariantMap &msg) {
302 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
303 uint ver = msg["ProtocolVersion"].toUInt();
304 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
305 emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
306 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
307 disconnectFromCore();
311 #ifndef QT_NO_COMPRESS
312 if(msg["SupportsCompression"].toBool()) {
313 _socket->setProperty("UseCompression", true);
317 _coreMsgBuffer = msg;
319 if(currentAccount().useSsl()) {
320 if(msg["SupportSsl"].toBool()) {
321 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
323 connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
324 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
326 sslSocket->startClientEncryption();
328 emit connectionError(tr("<b>The Quassel Core you are trying to connect to does not support SSL!</b><br />If you want to connect anyways, disable the usage of SSL in the account settings."));
329 disconnectFromCore();
334 // if we use SSL we wait for the next step until every SSL warning has been cleared
339 void CoreConnection::connectionReady() {
340 if(!_coreMsgBuffer["Configured"].toBool()) {
342 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
343 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
346 _coreMsgBuffer.clear();
347 resetWarningsHandler();
350 void CoreConnection::loginToCore() {
351 emit connectionMsg(tr("Logging in..."));
352 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
353 emit userAuthenticationRequired(&_account); // *must* be a synchronous call
354 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
355 disconnectFromCore();
360 QVariantMap clientLogin;
361 clientLogin["MsgType"] = "ClientLogin";
362 clientLogin["User"] = currentAccount().user();
363 clientLogin["Password"] = currentAccount().password();
364 SignalProxy::writeDataToDevice(_socket, clientLogin);
367 void CoreConnection::loginFailed(const QString &error) {
368 emit userAuthenticationRequired(&_account, error); // *must* be a synchronous call
369 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
370 disconnectFromCore();
376 void CoreConnection::loginSuccess() {
377 updateProgress(0, 0);
378 setProgressText(tr("Receiving session state"));
379 setState(Synchronizing);
380 emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
383 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
384 updateProgress(100, 100);
386 // rest of communication happens through SignalProxy...
387 disconnect(_socket, SIGNAL(readyRead()), this, 0);
388 disconnect(_socket, SIGNAL(connected()), this, 0);
390 //Client::instance()->setConnectedToCore(currentAccount().accountId(), _socket);
394 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
395 setProgressText(tr("Receiving network states"));
396 updateProgress(0, 100);
399 foreach(QVariant vid, sessionState["Identities"].toList()) {
400 Client::instance()->coreIdentityCreated(vid.value<Identity>());
404 // FIXME: get rid of this crap -- why?
405 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
406 NetworkModel *networkModel = Client::networkModel();
407 Q_ASSERT(networkModel);
408 foreach(QVariant vinfo, bufferinfos)
409 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
411 QVariantList networkids = sessionState["NetworkIds"].toList();
413 // prepare sync progress thingys...
414 // FIXME: Care about removal of networks
415 _numNetsToSync = networkids.count();
416 updateProgress(0, _numNetsToSync);
418 // create network objects
419 foreach(QVariant networkid, networkids) {
420 NetworkId netid = networkid.value<NetworkId>();
421 if(Client::network(netid))
423 Network *net = new Network(netid, Client::instance());
424 _netsToSync.insert(net);
425 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
426 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
427 Client::addNetwork(net);
432 void CoreConnection::networkInitDone() {
433 Network *net = qobject_cast<Network *>(sender());
435 disconnect(net, 0, this, 0);
436 _netsToSync.remove(net);
437 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
441 void CoreConnection::checkSyncState() {
442 if(_netsToSync.isEmpty()) {
443 setState(Synchronized);
444 setProgressText(QString());
445 setProgressMaximum(-1);