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 "clientsettings.h"
29 #include "coreaccountmodel.h"
32 #include "networkmodel.h"
34 #include "signalproxy.h"
37 CoreConnection::CoreConnection(CoreAccountModel *model, QObject *parent)
46 qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
50 void CoreConnection::init() {
51 connect(Client::signalProxy(), SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
54 void CoreConnection::setProgressText(const QString &text) {
55 if(_progressText != text) {
57 emit progressTextChanged(text);
61 void CoreConnection::setProgressValue(int value) {
62 if(_progressValue != value) {
63 _progressValue = value;
64 emit progressValueChanged(value);
68 void CoreConnection::setProgressMinimum(int minimum) {
69 if(_progressMinimum != minimum) {
70 _progressMinimum = minimum;
71 emit progressRangeChanged(minimum, _progressMaximum);
75 void CoreConnection::setProgressMaximum(int maximum) {
76 if(_progressMaximum != maximum) {
77 _progressMaximum = maximum;
78 emit progressRangeChanged(_progressMinimum, maximum);
82 void CoreConnection::updateProgress(int value, int max) {
83 if(max != _progressMaximum) {
84 _progressMaximum = max;
85 emit progressRangeChanged(_progressMinimum, _progressMaximum);
87 setProgressValue(value);
90 void CoreConnection::resetConnection() {
92 disconnect(_socket, 0, this, 0);
93 _socket->deleteLater();
98 _coreMsgBuffer.clear();
102 _state = Disconnected;
104 setProgressMaximum(-1); // disable
105 emit connectionMsg(tr("Disconnected from core."));
108 void CoreConnection::socketStateChanged(QAbstractSocket::SocketState socketState) {
111 switch(socketState) {
112 case QAbstractSocket::UnconnectedState:
113 text = tr("Disconnected.");
115 case QAbstractSocket::HostLookupState:
116 text = tr("Looking up %1...").arg(currentAccount().hostName());
118 case QAbstractSocket::ConnectingState:
119 text = tr("Connecting to %1...").arg(currentAccount().hostName());
121 case QAbstractSocket::ConnectedState:
122 text = tr("Connected to %1.").arg(currentAccount().hostName());
124 case QAbstractSocket::ClosingState:
125 text = tr("Disconnecting from %1...").arg(currentAccount().hostName());
132 emit progressTextChanged(text);
134 setState(socketState);
137 void CoreConnection::setState(QAbstractSocket::SocketState socketState) {
138 ConnectionState state;
140 switch(socketState) {
141 case QAbstractSocket::UnconnectedState:
142 state = Disconnected;
144 case QAbstractSocket::HostLookupState:
145 case QAbstractSocket::ConnectingState:
148 case QAbstractSocket::ConnectedState:
152 state = Disconnected;
158 void CoreConnection::setState(ConnectionState state) {
159 if(state != _state) {
161 emit stateChanged(state);
165 void CoreConnection::setWarningsHandler(const char *slot) {
166 resetWarningsHandler();
167 connect(this, SIGNAL(handleIgnoreWarnings(bool)), this, slot);
170 void CoreConnection::resetWarningsHandler() {
171 disconnect(this, SIGNAL(handleIgnoreWarnings(bool)), this, 0);
174 void CoreConnection::coreSocketError(QAbstractSocket::SocketError) {
175 qDebug() << "coreSocketError" << _socket << _socket->errorString();
176 emit connectionError(_socket->errorString());
180 void CoreConnection::coreSocketDisconnected() {
181 setState(Disconnected);
184 // FIXME handle disconnects gracefully
187 void CoreConnection::coreHasData() {
189 while(SignalProxy::readDataFromDevice(_socket, _blockSize, item)) {
190 QVariantMap msg = item.toMap();
191 if(!msg.contains("MsgType")) {
192 // This core is way too old and does not even speak our init protocol...
193 emit connectionError(tr("The Quassel Core you try to connect to is too old! Please consider upgrading."));
194 disconnectFromCore();
197 if(msg["MsgType"] == "ClientInitAck") {
199 } else if(msg["MsgType"] == "ClientInitReject") {
200 emit connectionError(msg["Error"].toString());
201 disconnectFromCore();
203 } else if(msg["MsgType"] == "CoreSetupAck") {
204 //emit coreSetupSuccess();
205 } else if(msg["MsgType"] == "CoreSetupReject") {
206 //emit coreSetupFailed(msg["Error"].toString());
207 } else if(msg["MsgType"] == "ClientLoginReject") {
208 loginFailed(msg["Error"].toString());
209 } else if(msg["MsgType"] == "ClientLoginAck") {
211 } else if(msg["MsgType"] == "SessionInit") {
212 // that's it, let's hand over to the signal proxy
213 // if the socket is an orphan, the signalProxy adopts it.
214 // -> we don't need to care about it anymore
215 _socket->setParent(0);
216 Client::signalProxy()->addPeer(_socket);
218 sessionStateReceived(msg["SessionState"].toMap());
219 break; // this is definitively the last message we process here!
221 emit connectionError(tr("<b>Invalid data received from core!</b><br>Disconnecting."));
222 disconnectFromCore();
227 updateProgress(_socket->bytesAvailable(), _blockSize);
231 void CoreConnection::disconnectFromCore() {
232 Client::signalProxy()->removeAllPeers();
236 void CoreConnection::reconnectToCore() {
237 if(currentAccount().isValid())
238 connectToCore(currentAccount().accountId());
241 bool CoreConnection::connectToCore(AccountId accId) {
245 CoreAccountSettings s;
247 if(!accId.isValid()) {
248 // check our settings and figure out what to do
249 if(!s.autoConnectOnStartup())
251 if(s.autoConnectToFixedAccount())
252 accId = s.autoConnectAccount();
254 accId = s.lastAccount();
258 _account = accountModel()->account(accId);
259 if(!_account.accountId().isValid()) {
263 s.setLastAccount(accId);
264 connectToCurrentAccount();
268 void CoreConnection::connectToCurrentAccount() {
273 QSslSocket *sock = new QSslSocket(Client::instance());
275 if(_account.useSsl()) {
276 emit connectionError(tr("<b>This client is built without SSL Support!</b><br />Disable the usage of SSL in the account settings."));
279 QTcpSocket *sock = new QTcpSocket(Client::instance());
282 #ifndef QT_NO_NETWORKPROXY
283 if(_account.useProxy()) {
284 QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
285 sock->setProxy(proxy);
290 connect(sock, SIGNAL(readyRead()), SLOT(coreHasData()));
291 connect(sock, SIGNAL(connected()), SLOT(coreSocketConnected()));
292 connect(sock, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
293 connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(coreSocketError(QAbstractSocket::SocketError)));
294 connect(sock, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(socketStateChanged(QAbstractSocket::SocketState)));
296 emit connectionMsg(tr("Connecting to %1...").arg(currentAccount().accountName()));
297 sock->connectToHost(_account.hostName(), _account.port());
300 void CoreConnection::coreSocketConnected() {
301 // Phase One: Send client info and wait for core info
303 emit connectionMsg(tr("Synchronizing to core..."));
305 QVariantMap clientInit;
306 clientInit["MsgType"] = "ClientInit";
307 clientInit["ClientVersion"] = Quassel::buildInfo().fancyVersionString;
308 clientInit["ClientDate"] = Quassel::buildInfo().buildDate;
309 clientInit["ProtocolVersion"] = Quassel::buildInfo().protocolVersion;
310 clientInit["UseSsl"] = _account.useSsl();
311 #ifndef QT_NO_COMPRESS
312 clientInit["UseCompression"] = true;
314 clientInit["UseCompression"] = false;
317 SignalProxy::writeDataToDevice(_socket, clientInit);
320 void CoreConnection::clientInitAck(const QVariantMap &msg) {
321 // Core has accepted our version info and sent its own. Let's see if we accept it as well...
322 uint ver = msg["ProtocolVersion"].toUInt();
323 if(ver < Quassel::buildInfo().clientNeedsProtocol) {
324 emit connectionError(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
325 "Need at least core/client protocol v%1 to connect.").arg(Quassel::buildInfo().clientNeedsProtocol));
326 disconnectFromCore();
330 #ifndef QT_NO_COMPRESS
331 if(msg["SupportsCompression"].toBool()) {
332 _socket->setProperty("UseCompression", true);
336 _coreMsgBuffer = msg;
338 if(currentAccount().useSsl()) {
339 if(msg["SupportSsl"].toBool()) {
340 QSslSocket *sslSocket = qobject_cast<QSslSocket *>(_socket);
342 connect(sslSocket, SIGNAL(encrypted()), this, SLOT(sslSocketEncrypted()));
343 connect(sslSocket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &)));
345 sslSocket->startClientEncryption();
347 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."));
348 disconnectFromCore();
353 // if we use SSL we wait for the next step until every SSL warning has been cleared
358 void CoreConnection::connectionReady() {
359 if(!_coreMsgBuffer["Configured"].toBool()) {
361 emit startCoreSetup(_coreMsgBuffer["StorageBackends"].toList());
362 } else if(_coreMsgBuffer["LoginEnabled"].toBool()) {
365 _coreMsgBuffer.clear();
366 resetWarningsHandler();
369 void CoreConnection::loginToCore(const QString &prevError) {
370 emit connectionMsg(tr("Logging in..."));
371 if(currentAccount().user().isEmpty() || currentAccount().password().isEmpty() || !prevError.isEmpty()) {
373 emit userAuthenticationRequired(&_account, &valid, prevError); // *must* be a synchronous call
374 if(!valid || currentAccount().user().isEmpty() || currentAccount().password().isEmpty()) {
375 disconnectFromCore();
376 emit connectionError(tr("Login canceled"));
381 QVariantMap clientLogin;
382 clientLogin["MsgType"] = "ClientLogin";
383 clientLogin["User"] = currentAccount().user();
384 clientLogin["Password"] = currentAccount().password();
385 SignalProxy::writeDataToDevice(_socket, clientLogin);
388 void CoreConnection::loginFailed(const QString &error) {
392 void CoreConnection::loginSuccess() {
393 updateProgress(0, 0);
395 // save current account data
396 _model->createOrUpdateAccount(currentAccount());
399 setProgressText(tr("Receiving session state"));
400 setState(Synchronizing);
401 emit connectionMsg(tr("Synchronizing to %1...").arg(currentAccount().accountName()));
404 void CoreConnection::sessionStateReceived(const QVariantMap &state) {
405 updateProgress(100, 100);
407 // rest of communication happens through SignalProxy...
408 disconnect(_socket, SIGNAL(readyRead()), this, 0);
409 disconnect(_socket, SIGNAL(connected()), this, 0);
411 //Client::instance()->setConnectedToCore(currentAccount().accountId(), _socket);
415 void CoreConnection::syncToCore(const QVariantMap &sessionState) {
416 setProgressText(tr("Receiving network states"));
417 updateProgress(0, 100);
420 foreach(QVariant vid, sessionState["Identities"].toList()) {
421 Client::instance()->coreIdentityCreated(vid.value<Identity>());
425 // FIXME: get rid of this crap -- why?
426 QVariantList bufferinfos = sessionState["BufferInfos"].toList();
427 NetworkModel *networkModel = Client::networkModel();
428 Q_ASSERT(networkModel);
429 foreach(QVariant vinfo, bufferinfos)
430 networkModel->bufferUpdated(vinfo.value<BufferInfo>()); // create BufferItems
432 QVariantList networkids = sessionState["NetworkIds"].toList();
434 // prepare sync progress thingys...
435 // FIXME: Care about removal of networks
436 _numNetsToSync = networkids.count();
437 updateProgress(0, _numNetsToSync);
439 // create network objects
440 foreach(QVariant networkid, networkids) {
441 NetworkId netid = networkid.value<NetworkId>();
442 if(Client::network(netid))
444 Network *net = new Network(netid, Client::instance());
445 _netsToSync.insert(net);
446 connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
447 connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
448 Client::addNetwork(net);
453 void CoreConnection::networkInitDone() {
454 Network *net = qobject_cast<Network *>(sender());
456 disconnect(net, 0, this, 0);
457 _netsToSync.remove(net);
458 updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
462 void CoreConnection::checkSyncState() {
463 if(_netsToSync.isEmpty()) {
464 setState(Synchronized);
465 setProgressText(QString());
466 setProgressMaximum(-1);