Have the PeerFactory provide the list of supported protocols
[quassel.git] / src / client / clientauthhandler.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 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 "clientauthhandler.h"
22
23 // TODO: support system application proxy (new in Qt 4.6)
24
25 #include <QtEndian>
26
27 #ifdef HAVE_SSL
28     #include <QSslSocket>
29 #else
30     #include <QTcpSocket>
31 #endif
32
33 #include "client.h"
34 #include "clientsettings.h"
35 #include "peerfactory.h"
36
37 #include "protocols/legacy/legacypeer.h"
38
39 using namespace Protocol;
40
41 ClientAuthHandler::ClientAuthHandler(CoreAccount account, QObject *parent)
42     : AuthHandler(parent),
43     _peer(0),
44     _account(account),
45     _probing(false),
46     _legacy(false),
47     _connectionFeatures(0)
48 {
49
50 }
51
52
53 void ClientAuthHandler::connectToCore()
54 {
55     CoreAccountSettings s;
56
57 #ifdef HAVE_SSL
58     QSslSocket *socket = new QSslSocket(this);
59     // make sure the warning is shown if we happen to connect without SSL support later
60     s.setAccountValue("ShowNoClientSslWarning", true);
61 #else
62     if (_account.useSsl()) {
63         if (s.accountValue("ShowNoClientSslWarning", true).toBool()) {
64             bool accepted = false;
65             emit handleNoSslInClient(&accepted);
66             if (!accepted) {
67                 emit errorMessage(tr("Unencrypted connection canceled"));
68                 return;
69             }
70             s.setAccountValue("ShowNoClientSslWarning", false);
71         }
72     }
73     QTcpSocket *socket = new QTcpSocket(this);
74 #endif
75
76 // TODO: Handle system proxy
77 #ifndef QT_NO_NETWORKPROXY
78     if (_account.useProxy()) {
79         QNetworkProxy proxy(_account.proxyType(), _account.proxyHostName(), _account.proxyPort(), _account.proxyUser(), _account.proxyPassword());
80         socket->setProxy(proxy);
81     }
82 #endif
83
84     setSocket(socket);
85     connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), SLOT(onSocketStateChanged(QAbstractSocket::SocketState)));
86     connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
87     connect(socket, SIGNAL(connected()), SLOT(onSocketConnected()));
88
89     emit statusMessage(tr("Connecting to %1...").arg(_account.accountName()));
90     socket->connectToHost(_account.hostName(), _account.port());
91 }
92
93
94 void ClientAuthHandler::onSocketStateChanged(QAbstractSocket::SocketState socketState)
95 {
96     QString text;
97
98     switch(socketState) {
99         case QAbstractSocket::HostLookupState:
100             if (!_legacy)
101                 text = tr("Looking up %1...").arg(_account.hostName());
102             break;
103         case QAbstractSocket::ConnectingState:
104             if (!_legacy)
105                 text = tr("Connecting to %1...").arg(_account.hostName());
106             break;
107         case QAbstractSocket::ConnectedState:
108             text = tr("Connected to %1").arg(_account.hostName());
109             break;
110         case QAbstractSocket::ClosingState:
111             if (!_probing)
112                 text = tr("Disconnecting from %1...").arg(_account.hostName());
113             break;
114         case QAbstractSocket::UnconnectedState:
115             if (!_probing) {
116                 text = tr("Disconnected");
117                 // Ensure the disconnected() signal is sent even if we haven't reached the Connected state yet.
118                 // The baseclass implementation will make sure to only send the signal once.
119                 onSocketDisconnected();
120             }
121             break;
122         default:
123             break;
124     }
125
126     if (!text.isEmpty()) {
127         emit statusMessage(text);
128     }
129 }
130
131 void ClientAuthHandler::onSocketError(QAbstractSocket::SocketError error)
132 {
133     if (_probing && error == QAbstractSocket::RemoteHostClosedError) {
134         _legacy = true;
135         return;
136     }
137
138     _probing = false; // all other errors are unrelated to probing and should be handled
139     AuthHandler::onSocketError(error);
140 }
141
142
143 void ClientAuthHandler::onSocketDisconnected()
144 {
145     if (_probing && _legacy) {
146         // Remote host has closed the connection while probing
147         _probing = false;
148         disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
149         emit statusMessage(tr("Reconnecting in compatibility mode..."));
150         socket()->connectToHost(_account.hostName(), _account.port());
151         return;
152     }
153
154     AuthHandler::onSocketDisconnected();
155 }
156
157
158 void ClientAuthHandler::onSocketConnected()
159 {
160     if (_peer) {
161         qWarning() << Q_FUNC_INFO << "Peer already exists!";
162         return;
163     }
164
165     socket()->setSocketOption(QAbstractSocket::KeepAliveOption, true);
166
167     if (!_legacy) {
168         // First connection attempt, try probing for a capable core
169         _probing = true;
170
171         QDataStream stream(socket()); // stream handles the endianness for us
172
173         quint32 magic = Protocol::magic;
174 #ifdef HAVE_SSL
175         if (_account.useSsl())
176             magic |= Protocol::Encryption;
177 #endif
178         //magic |= Protocol::Compression; // not implemented yet
179
180         stream << magic;
181
182         // here goes the list of protocols we support, in order of preference
183         PeerFactory::ProtoList protos = PeerFactory::supportedProtocols();
184         for (int i = 0; i < protos.count(); ++i) {
185             quint32 reply = protos[i].first;
186             reply |= protos[i].second<<8;
187             if (i == protos.count() - 1)
188                 reply |= 0x80000000; // end list
189             stream << reply;
190         }
191
192         socket()->flush(); // make sure the probing data is sent immediately
193         return;
194     }
195
196     // If we arrive here, it's the second connection attempt, meaning probing was not successful -> enable legacy support
197
198     qDebug() << "Legacy core detected, switching to compatibility mode";
199
200     RemotePeer *peer = new LegacyPeer(this, socket(), this);
201     // Only needed for the legacy peer, as all others check the protocol version before instantiation
202     connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
203
204     setPeer(peer);
205 }
206
207
208 void ClientAuthHandler::onReadyRead()
209 {
210     if (socket()->bytesAvailable() < 4)
211         return;
212
213     if (!_probing)
214         return; // make sure to not read more data than needed
215
216     _probing = false;
217     disconnect(socket(), SIGNAL(readyRead()), this, SLOT(onReadyRead()));
218
219     quint32 reply;
220     socket()->read((char *)&reply, 4);
221     reply = qFromBigEndian<quint32>(reply);
222
223     Protocol::Type type = static_cast<Protocol::Type>(reply & 0xff);
224     quint16 protoFeatures = static_cast<quint16>(reply>>8 & 0xffff);
225     _connectionFeatures = static_cast<quint8>(reply>>24);
226
227     RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(type, protoFeatures), this, socket(), this);
228     if (!peer) {
229         qWarning() << "No valid protocol supported for this core!";
230         emit errorPopup(tr("<b>Incompatible Quassel Core!</b><br>"
231                            "None of the protocols this client speaks are supported by the core you are trying to connect to."));
232
233         requestDisconnect(tr("Core speaks none of the protocols we support"));
234         return;
235     }
236
237     if (peer->protocol() == Protocol::LegacyProtocol) {
238         connect(peer, SIGNAL(protocolVersionMismatch(int,int)), SLOT(onProtocolVersionMismatch(int,int)));
239         _legacy = true;
240     }
241
242     setPeer(peer);
243 }
244
245
246 void ClientAuthHandler::onProtocolVersionMismatch(int actual, int expected)
247 {
248     emit errorPopup(tr("<b>The Quassel Core you are trying to connect to is too old!</b><br>"
249            "We need at least protocol v%1, but the core speaks v%2 only.").arg(expected, actual));
250     requestDisconnect(tr("Incompatible protocol version, connection to core refused"));
251 }
252
253
254 void ClientAuthHandler::setPeer(RemotePeer *peer)
255 {
256     _peer = peer;
257     connect(_peer, SIGNAL(transferProgress(int,int)), SIGNAL(transferProgress(int,int)));
258
259     // The legacy protocol enables SSL later, after registration
260     if (!_account.useSsl() || _legacy)
261         startRegistration();
262     // otherwise, do it now
263     else
264         checkAndEnableSsl(_connectionFeatures & Protocol::Encryption);
265 }
266
267
268 void ClientAuthHandler::startRegistration()
269 {
270     emit statusMessage(tr("Synchronizing to core..."));
271
272     // useSsl will be ignored by non-legacy peers
273     bool useSsl = false;
274 #ifdef HAVE_SSL
275     useSsl = _account.useSsl();
276 #endif
277
278     _peer->dispatch(RegisterClient(Quassel::buildInfo().fancyVersionString, useSsl));
279 }
280
281
282 void ClientAuthHandler::handle(const ClientDenied &msg)
283 {
284     emit errorPopup(msg.errorString);
285     requestDisconnect(tr("The core refused connection from this client"));
286 }
287
288
289 void ClientAuthHandler::handle(const ClientRegistered &msg)
290 {
291     _coreConfigured = msg.coreConfigured;
292     _backendInfo = msg.backendInfo;
293
294     Client::setCoreFeatures(static_cast<Quassel::Features>(msg.coreFeatures));
295
296     // The legacy protocol enables SSL at this point
297     if(_legacy && _account.useSsl())
298         checkAndEnableSsl(msg.sslSupported);
299     else
300         onConnectionReady();
301 }
302
303
304 void ClientAuthHandler::onConnectionReady()
305 {
306     emit connectionReady();
307     emit statusMessage(tr("Connected to %1").arg(_account.accountName()));
308
309     if (!_coreConfigured) {
310         // start wizard
311         emit startCoreSetup(_backendInfo);
312     }
313     else // TODO: check if we need LoginEnabled
314         login();
315 }
316
317
318 void ClientAuthHandler::setupCore(const SetupData &setupData)
319 {
320     _peer->dispatch(setupData);
321 }
322
323
324 void ClientAuthHandler::handle(const SetupFailed &msg)
325 {
326     emit coreSetupFailed(msg.errorString);
327 }
328
329
330 void ClientAuthHandler::handle(const SetupDone &msg)
331 {
332     Q_UNUSED(msg)
333
334     emit coreSetupSuccessful();
335 }
336
337
338 void ClientAuthHandler::login(const QString &user, const QString &password, bool remember)
339 {
340     _account.setUser(user);
341     _account.setPassword(password);
342     _account.setStorePassword(remember);
343     login();
344 }
345
346
347 void ClientAuthHandler::login(const QString &previousError)
348 {
349     emit statusMessage(tr("Logging in..."));
350     if (_account.user().isEmpty() || _account.password().isEmpty() || !previousError.isEmpty()) {
351         bool valid = false;
352         emit userAuthenticationRequired(&_account, &valid, previousError); // *must* be a synchronous call
353         if (!valid || _account.user().isEmpty() || _account.password().isEmpty()) {
354             requestDisconnect(tr("Login canceled"));
355             return;
356         }
357     }
358
359     _peer->dispatch(Login(_account.user(), _account.password()));
360 }
361
362
363 void ClientAuthHandler::handle(const LoginFailed &msg)
364 {
365     login(msg.errorString);
366 }
367
368
369 void ClientAuthHandler::handle(const LoginSuccess &msg)
370 {
371     Q_UNUSED(msg)
372
373     emit loginSuccessful(_account);
374 }
375
376
377 void ClientAuthHandler::handle(const SessionState &msg)
378 {
379     disconnect(socket(), 0, this, 0); // this is the last message we shall ever get
380
381     // give up ownership of the peer; CoreSession takes responsibility now
382     _peer->setParent(0);
383     emit handshakeComplete(_peer, msg);
384 }
385
386
387 /*** SSL Stuff ***/
388
389 void ClientAuthHandler::checkAndEnableSsl(bool coreSupportsSsl)
390 {
391 #ifndef HAVE_SSL
392     Q_UNUSED(coreSupportsSsl);
393 #else
394     CoreAccountSettings s;
395     if (coreSupportsSsl && _account.useSsl()) {
396         // Make sure the warning is shown next time we don't have SSL in the core
397         s.setAccountValue("ShowNoCoreSslWarning", true);
398
399         QSslSocket *sslSocket = qobject_cast<QSslSocket *>(socket());
400         Q_ASSERT(sslSocket);
401         connect(sslSocket, SIGNAL(encrypted()), SLOT(onSslSocketEncrypted()));
402         connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(onSslErrors()));
403         qDebug() << "Starting encryption...";
404         sslSocket->flush();
405         sslSocket->startClientEncryption();
406     }
407     else {
408         if (s.accountValue("ShowNoCoreSslWarning", true).toBool()) {
409             bool accepted = false;
410             emit handleNoSslInCore(&accepted);
411             if (!accepted) {
412                 requestDisconnect(tr("Unencrypted connection cancelled"));
413                 return;
414             }
415             s.setAccountValue("ShowNoCoreSslWarning", false);
416             s.setAccountValue("SslCert", QString());
417         }
418         if (_legacy)
419             onConnectionReady();
420         else
421             startRegistration();
422     }
423 #endif
424 }
425
426 #ifdef HAVE_SSL
427
428 void ClientAuthHandler::onSslSocketEncrypted()
429 {
430     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
431     Q_ASSERT(socket);
432
433     if (!socket->sslErrors().count()) {
434         // Cert is valid, so we don't want to store it as known
435         // That way, a warning will appear in case it becomes invalid at some point
436         CoreAccountSettings s;
437         s.setAccountValue("SSLCert", QString());
438     }
439
440     emit encrypted(true);
441
442     if (_legacy)
443         onConnectionReady();
444     else
445         startRegistration();
446 }
447
448
449 void ClientAuthHandler::onSslErrors()
450 {
451     QSslSocket *socket = qobject_cast<QSslSocket *>(sender());
452     Q_ASSERT(socket);
453
454     CoreAccountSettings s;
455     QByteArray knownDigest = s.accountValue("SslCert").toByteArray();
456
457     if (knownDigest != socket->peerCertificate().digest()) {
458         bool accepted = false;
459         bool permanently = false;
460         emit handleSslErrors(socket, &accepted, &permanently);
461
462         if (!accepted) {
463             requestDisconnect(tr("Unencrypted connection canceled"));
464             return;
465         }
466
467         if (permanently)
468             s.setAccountValue("SslCert", socket->peerCertificate().digest());
469         else
470             s.setAccountValue("SslCert", QString());
471     }
472
473     socket->ignoreSslErrors();
474 }
475
476 #endif /* HAVE_SSL */