Merge pull request #146 from benapetr/master
[quassel.git] / src / client / coreconnection.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "coreconnection.h"
22
23 #include "client.h"
24 #include "clientauthhandler.h"
25 #include "clientsettings.h"
26 #include "coreaccountmodel.h"
27 #include "identity.h"
28 #include "internalpeer.h"
29 #include "network.h"
30 #include "networkmodel.h"
31 #include "quassel.h"
32 #include "signalproxy.h"
33 #include "util.h"
34
35 #include "protocols/legacy/legacypeer.h"
36
37 CoreConnection::CoreConnection(QObject *parent)
38     : QObject(parent),
39     _authHandler(0),
40     _state(Disconnected),
41     _wantReconnect(false),
42     _wasReconnect(false),
43     _progressMinimum(0),
44     _progressMaximum(-1),
45     _progressValue(-1),
46     _resetting(false)
47 {
48     qRegisterMetaType<ConnectionState>("CoreConnection::ConnectionState");
49 }
50
51
52 void CoreConnection::init()
53 {
54     Client::signalProxy()->setHeartBeatInterval(30);
55     connect(Client::signalProxy(), SIGNAL(lagUpdated(int)), SIGNAL(lagUpdated(int)));
56
57     _reconnectTimer.setSingleShot(true);
58     connect(&_reconnectTimer, SIGNAL(timeout()), SLOT(reconnectTimeout()));
59
60     _qNetworkConfigurationManager = new QNetworkConfigurationManager(this);
61     connect(_qNetworkConfigurationManager, SIGNAL(onlineStateChanged(bool)), SLOT(onlineStateChanged(bool)));
62
63     CoreConnectionSettings s;
64     s.initAndNotify("PingTimeoutInterval", this, SLOT(pingTimeoutIntervalChanged(QVariant)), 60);
65     s.initAndNotify("ReconnectInterval", this, SLOT(reconnectIntervalChanged(QVariant)), 60);
66     s.notify("NetworkDetectionMode", this, SLOT(networkDetectionModeChanged(QVariant)));
67     networkDetectionModeChanged(s.networkDetectionMode());
68 }
69
70
71 CoreAccountModel *CoreConnection::accountModel() const
72 {
73     return Client::coreAccountModel();
74 }
75
76
77 void CoreConnection::setProgressText(const QString &text)
78 {
79     if (_progressText != text) {
80         _progressText = text;
81         emit progressTextChanged(text);
82     }
83 }
84
85
86 void CoreConnection::setProgressValue(int value)
87 {
88     if (_progressValue != value) {
89         _progressValue = value;
90         emit progressValueChanged(value);
91     }
92 }
93
94
95 void CoreConnection::setProgressMinimum(int minimum)
96 {
97     if (_progressMinimum != minimum) {
98         _progressMinimum = minimum;
99         emit progressRangeChanged(minimum, _progressMaximum);
100     }
101 }
102
103
104 void CoreConnection::setProgressMaximum(int maximum)
105 {
106     if (_progressMaximum != maximum) {
107         _progressMaximum = maximum;
108         emit progressRangeChanged(_progressMinimum, maximum);
109     }
110 }
111
112
113 void CoreConnection::updateProgress(int value, int max)
114 {
115     if (max != _progressMaximum) {
116         _progressMaximum = max;
117         emit progressRangeChanged(_progressMinimum, _progressMaximum);
118     }
119     setProgressValue(value);
120 }
121
122
123 void CoreConnection::reconnectTimeout()
124 {
125     if (!_peer) {
126         CoreConnectionSettings s;
127         if (_wantReconnect && s.autoReconnect()) {
128             // If using QNetworkConfigurationManager, we don't want to reconnect if we're offline
129             if (s.networkDetectionMode() == CoreConnectionSettings::UseQNetworkConfigurationManager) {
130                if (!_qNetworkConfigurationManager->isOnline()) {
131                     return;
132                }
133             }
134             reconnectToCore();
135         }
136     }
137 }
138
139
140 void CoreConnection::networkDetectionModeChanged(const QVariant &vmode)
141 {
142     CoreConnectionSettings s;
143     CoreConnectionSettings::NetworkDetectionMode mode = (CoreConnectionSettings::NetworkDetectionMode)vmode.toInt();
144     if (mode == CoreConnectionSettings::UsePingTimeout)
145         Client::signalProxy()->setMaxHeartBeatCount(s.pingTimeoutInterval() / 30);
146     else {
147         Client::signalProxy()->setMaxHeartBeatCount(-1);
148     }
149 }
150
151
152 void CoreConnection::pingTimeoutIntervalChanged(const QVariant &interval)
153 {
154     CoreConnectionSettings s;
155     if (s.networkDetectionMode() == CoreConnectionSettings::UsePingTimeout)
156         Client::signalProxy()->setMaxHeartBeatCount(interval.toInt() / 30);  // interval is 30 seconds
157 }
158
159
160 void CoreConnection::reconnectIntervalChanged(const QVariant &interval)
161 {
162     _reconnectTimer.setInterval(interval.toInt() * 1000);
163 }
164
165
166 void CoreConnection::onlineStateChanged(bool isOnline)
167 {
168     CoreConnectionSettings s;
169     if (s.networkDetectionMode() != CoreConnectionSettings::UseQNetworkConfigurationManager)
170         return;
171
172     if(isOnline) {
173         // qDebug() << "QNetworkConfigurationManager reports Online";
174         if (state() == Disconnected) {
175             if (_wantReconnect && s.autoReconnect()) {
176                 reconnectToCore();
177             }
178         }
179     } else {
180         // qDebug() << "QNetworkConfigurationManager reports Offline";
181         if (state() != Disconnected && !isLocalConnection())
182             disconnectFromCore(tr("Network is down"), true);
183     }
184 }
185
186
187 bool CoreConnection::isEncrypted() const
188 {
189     return _peer && _peer->isSecure();
190 }
191
192
193 bool CoreConnection::isLocalConnection() const
194 {
195     if (!isConnected())
196         return false;
197     if (currentAccount().isInternal())
198         return true;
199     if (_authHandler)
200         return _authHandler->isLocal();
201     if (_peer)
202         return _peer->isLocal();
203
204     return false;
205 }
206
207
208 void CoreConnection::onConnectionReady()
209 {
210     setState(Connected);
211 }
212
213
214 void CoreConnection::setState(ConnectionState state)
215 {
216     if (state != _state) {
217         _state = state;
218         emit stateChanged(state);
219         if (state == Connected)
220             _wantReconnect = true;
221         if (state == Disconnected)
222             emit disconnected();
223     }
224 }
225
226
227 void CoreConnection::coreSocketError(QAbstractSocket::SocketError error, const QString &errorString)
228 {
229     Q_UNUSED(error)
230
231     disconnectFromCore(errorString, true);
232 }
233
234
235 void CoreConnection::coreSocketDisconnected()
236 {
237     setState(Disconnected);
238     _wasReconnect = false;
239     resetConnection(_wantReconnect);
240 }
241
242
243 void CoreConnection::disconnectFromCore()
244 {
245     disconnectFromCore(QString(), false); // requested disconnect, so don't try to reconnect
246 }
247
248
249 void CoreConnection::disconnectFromCore(const QString &errorString, bool wantReconnect)
250 {
251     if (wantReconnect)
252         _reconnectTimer.start();
253     else
254         _reconnectTimer.stop();
255
256     _wantReconnect = wantReconnect; // store if disconnect was requested
257     _wasReconnect = false;
258
259     if (_authHandler)
260         _authHandler->close();
261     else if(_peer)
262         _peer->close();
263
264     if (errorString.isEmpty())
265         emit connectionError(tr("Disconnected"));
266     else
267         emit connectionError(errorString);
268 }
269
270
271 void CoreConnection::resetConnection(bool wantReconnect)
272 {
273     if (_resetting)
274         return;
275     _resetting = true;
276
277     _wantReconnect = wantReconnect;
278
279     if (_authHandler) {
280         disconnect(_authHandler, 0, this, 0);
281         _authHandler->close();
282         _authHandler->deleteLater();
283         _authHandler = 0;
284     }
285
286     if (_peer) {
287         disconnect(_peer, 0, this, 0);
288         // peer belongs to the sigproxy and thus gets deleted by it
289         _peer->close();
290         _peer = 0;
291     }
292
293     _netsToSync.clear();
294     _numNetsToSync = 0;
295
296     setProgressMaximum(-1); // disable
297     setState(Disconnected);
298     emit lagUpdated(-1);
299
300     emit connectionMsg(tr("Disconnected from core."));
301     emit encrypted(false);
302     setState(Disconnected);
303
304     // initiate if a reconnect if appropriate
305     CoreConnectionSettings s;
306     if (wantReconnect && s.autoReconnect()) {
307         _reconnectTimer.start();
308     }
309
310     _resetting = false;
311 }
312
313
314 void CoreConnection::reconnectToCore()
315 {
316     if (currentAccount().isValid()) {
317         _wasReconnect = true;
318         connectToCore(currentAccount().accountId());
319     }
320 }
321
322
323 bool CoreConnection::connectToCore(AccountId accId)
324 {
325     if (isConnected())
326         return false;
327
328     CoreAccountSettings s;
329
330     // FIXME: Don't force connection to internal core in mono client
331     if (Quassel::runMode() == Quassel::Monolithic) {
332         _account = accountModel()->account(accountModel()->internalAccount());
333         Q_ASSERT(_account.isValid());
334     }
335     else {
336         if (!accId.isValid()) {
337             // check our settings and figure out what to do
338             if (!s.autoConnectOnStartup())
339                 return false;
340             if (s.autoConnectToFixedAccount())
341                 accId = s.autoConnectAccount();
342             else
343                 accId = s.lastAccount();
344             if (!accId.isValid())
345                 return false;
346         }
347         _account = accountModel()->account(accId);
348         if (!_account.accountId().isValid()) {
349             return false;
350         }
351         if (Quassel::runMode() != Quassel::Monolithic) {
352             if (_account.isInternal())
353                 return false;
354         }
355     }
356
357     s.setLastAccount(accId);
358     connectToCurrentAccount();
359     return true;
360 }
361
362
363 void CoreConnection::connectToCurrentAccount()
364 {
365     if (_authHandler) {
366         qWarning() << Q_FUNC_INFO << "Already connected!";
367         return;
368     }
369
370     if (currentAccount().isInternal()) {
371         if (Quassel::runMode() != Quassel::Monolithic) {
372             qWarning() << "Cannot connect to internal core in client-only mode!";
373             return;
374         }
375         emit startInternalCore();
376
377         InternalPeer *peer = new InternalPeer();
378         _peer = peer;
379         Client::instance()->signalProxy()->addPeer(peer); // sigproxy will take ownership
380         emit connectToInternalCore(peer);
381         setState(Connected);
382
383         return;
384     }
385
386     _authHandler = new ClientAuthHandler(currentAccount(), this);
387
388     connect(_authHandler, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
389     connect(_authHandler, SIGNAL(connectionReady()), SLOT(onConnectionReady()));
390     connect(_authHandler, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
391     connect(_authHandler, SIGNAL(transferProgress(int,int)), SLOT(updateProgress(int,int)));
392     connect(_authHandler, SIGNAL(requestDisconnect(QString,bool)), SLOT(disconnectFromCore(QString,bool)));
393
394     connect(_authHandler, SIGNAL(errorMessage(QString)), SIGNAL(connectionError(QString)));
395     connect(_authHandler, SIGNAL(errorPopup(QString)), SIGNAL(connectionErrorPopup(QString)), Qt::QueuedConnection);
396     connect(_authHandler, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
397     connect(_authHandler, SIGNAL(encrypted(bool)), SIGNAL(encrypted(bool)));
398     connect(_authHandler, SIGNAL(startCoreSetup(QVariantList)), SIGNAL(startCoreSetup(QVariantList)));
399     connect(_authHandler, SIGNAL(coreSetupFailed(QString)), SIGNAL(coreSetupFailed(QString)));
400     connect(_authHandler, SIGNAL(coreSetupSuccessful()), SIGNAL(coreSetupSuccess()));
401     connect(_authHandler, SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)), SIGNAL(userAuthenticationRequired(CoreAccount*,bool*,QString)));
402     connect(_authHandler, SIGNAL(handleNoSslInClient(bool*)), SIGNAL(handleNoSslInClient(bool*)));
403     connect(_authHandler, SIGNAL(handleNoSslInCore(bool*)), SIGNAL(handleNoSslInCore(bool*)));
404 #ifdef HAVE_SSL
405     connect(_authHandler, SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)), SIGNAL(handleSslErrors(const QSslSocket*,bool*,bool*)));
406 #endif
407
408     connect(_authHandler, SIGNAL(loginSuccessful(CoreAccount)), SLOT(onLoginSuccessful(CoreAccount)));
409     connect(_authHandler, SIGNAL(handshakeComplete(RemotePeer*,Protocol::SessionState)), SLOT(onHandshakeComplete(RemotePeer*,Protocol::SessionState)));
410
411     setState(Connecting);
412     _authHandler->connectToCore();
413 }
414
415
416 void CoreConnection::setupCore(const Protocol::SetupData &setupData)
417 {
418     _authHandler->setupCore(setupData);
419 }
420
421
422 void CoreConnection::loginToCore(const QString &user, const QString &password, bool remember)
423 {
424     _authHandler->login(user, password, remember);
425 }
426
427
428 void CoreConnection::onLoginSuccessful(const CoreAccount &account)
429 {
430     updateProgress(0, 0);
431
432     // save current account data
433     accountModel()->createOrUpdateAccount(account);
434     accountModel()->save();
435
436     _reconnectTimer.stop();
437
438     setProgressText(tr("Receiving session state"));
439     setState(Synchronizing);
440     emit connectionMsg(tr("Synchronizing to %1...").arg(account.accountName()));
441 }
442
443
444 void CoreConnection::onHandshakeComplete(RemotePeer *peer, const Protocol::SessionState &sessionState)
445 {
446     updateProgress(100, 100);
447
448     disconnect(_authHandler, 0, this, 0);
449     _authHandler->deleteLater();
450     _authHandler = 0;
451
452     _peer = peer;
453     connect(peer, SIGNAL(disconnected()), SLOT(coreSocketDisconnected()));
454     connect(peer, SIGNAL(statusMessage(QString)), SIGNAL(connectionMsg(QString)));
455     connect(peer, SIGNAL(socketError(QAbstractSocket::SocketError,QString)), SLOT(coreSocketError(QAbstractSocket::SocketError,QString)));
456
457     Client::signalProxy()->addPeer(_peer);  // sigproxy takes ownership of the peer!
458
459     syncToCore(sessionState);
460 }
461
462
463 void CoreConnection::internalSessionStateReceived(const Protocol::SessionState &sessionState)
464 {
465     updateProgress(100, 100);
466
467     Client::setCoreFeatures(Quassel::features()); // mono connection...
468
469     setState(Synchronizing);
470     syncToCore(sessionState);
471 }
472
473
474 void CoreConnection::syncToCore(const Protocol::SessionState &sessionState)
475 {
476     setProgressText(tr("Receiving network states"));
477     updateProgress(0, 100);
478
479     // create identities
480     foreach(const QVariant &vid, sessionState.identities) {
481         Client::instance()->coreIdentityCreated(vid.value<Identity>());
482     }
483
484     // create buffers
485     // FIXME: get rid of this crap -- why?
486     NetworkModel *networkModel = Client::networkModel();
487     Q_ASSERT(networkModel);
488     foreach(const QVariant &vinfo, sessionState.bufferInfos)
489         networkModel->bufferUpdated(vinfo.value<BufferInfo>());  // create BufferItems
490
491     // prepare sync progress thingys...
492     // FIXME: Care about removal of networks
493     _numNetsToSync = sessionState.networkIds.count();
494     updateProgress(0, _numNetsToSync);
495
496     // create network objects
497     foreach(const QVariant &networkid, sessionState.networkIds) {
498         NetworkId netid = networkid.value<NetworkId>();
499         if (Client::network(netid))
500             continue;
501         Network *net = new Network(netid, Client::instance());
502         _netsToSync.insert(net);
503         connect(net, SIGNAL(initDone()), SLOT(networkInitDone()));
504         connect(net, SIGNAL(destroyed()), SLOT(networkInitDone()));
505         Client::addNetwork(net);
506     }
507     checkSyncState();
508 }
509
510
511 // this is also called for destroyed networks!
512 void CoreConnection::networkInitDone()
513 {
514     QObject *net = sender();
515     Q_ASSERT(net);
516     disconnect(net, 0, this, 0);
517     _netsToSync.remove(net);
518     updateProgress(_numNetsToSync - _netsToSync.count(), _numNetsToSync);
519     checkSyncState();
520 }
521
522
523 void CoreConnection::checkSyncState()
524 {
525     if (_netsToSync.isEmpty() && state() >= Synchronizing) {
526         setState(Synchronized);
527         setProgressText(tr("Synchronized to %1").arg(currentAccount().accountName()));
528         setProgressMaximum(-1);
529         emit synchronized();
530     }
531 }