source: ntrip/trunk/BNC/src/bncnetqueryv2.cpp@ 10984

Last change on this file since 10984 was 10984, checked in by stuerze, 10 days ago

First read after startRequest/reconnect now gets 5 × _timeOut (100 s) instead of the strict 20 s, giving Windows' slow WPAD/proxy‑autodetect + TLS handshake room to finish.

File size: 9.2 KB
Line 
1/* -------------------------------------------------------------------------
2 * BKG NTRIP Client
3 * -------------------------------------------------------------------------
4 *
5 * Class: bncNetQueryV2
6 *
7 * Purpose: Blocking Network Requests (NTRIP Version 2)
8 *
9 * Author: L. Mervart
10 *
11 * Created: 27-Dec-2008
12 *
13 * Changes:
14 *
15 * -----------------------------------------------------------------------*/
16
17#include <iostream>
18
19#include <QTimer>
20
21#include "bncnetqueryv2.h"
22#include "bncsettings.h"
23#include "bncversion.h"
24#include "bncsslconfig.h"
25#include "bncsettings.h"
26
27// Constructor
28////////////////////////////////////////////////////////////////////////////
29bncNetQueryV2::bncNetQueryV2(bool secure) {
30 _secure = secure;
31 _manager = new QNetworkAccessManager(this);
32 connect(_manager, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*)),
33 this, SLOT(slotProxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*)));
34 _reply = 0;
35 _eventLoop = new QEventLoop(this);
36 _firstData = true;
37 _status = init;
38 _timeOut = 20000;
39
40 bncSettings settings;
41 _sslIgnoreErrors = (Qt::CheckState(settings.value("sslIgnoreErrors").toInt()) == Qt::Checked);
42
43 if (_secure ) {
44 if (!QSslSocket::supportsSsl()) {
45 BNC_CORE->slotMessage("No SSL support, install OpenSSL run-time libraries", true);
46 stop();
47 }
48 }
49
50}
51
52// Destructor
53////////////////////////////////////////////////////////////////////////////
54bncNetQueryV2::~bncNetQueryV2() {
55 delete _eventLoop;
56 if (_reply) {
57 _reply->abort();
58 delete _reply;
59 }
60 delete _manager;
61}
62
63// Stop (quit event loop)
64////////////////////////////////////////////////////////////////////////////
65void bncNetQueryV2::stop() {
66 if (_reply) {
67 _reply->abort();
68 delete _reply;
69 _reply = 0;
70 }
71 _eventLoop->quit();
72 _status = finished;
73}
74
75// End of Request
76////////////////////////////////////////////////////////////////////////////
77void bncNetQueryV2::slotFinished() {
78 _eventLoop->quit();
79 if (_reply && _reply->error() != QNetworkReply::NoError) {
80 _status = error;
81 if (!_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray().isEmpty()) {
82 emit newMessage(_url.path().toLatin1().replace(0,1,"") +
83 ": NetQueryV2: server replied: " +
84 _reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(),
85 true);
86 } else {
87 emit newMessage(_url.path().toLatin1().replace(0,1,"") +
88 ": NetQueryV2: server replied: " +
89 _reply->errorString().toLatin1(),
90 true);
91 }
92 }
93 else {
94 _status = finished;
95 }
96}
97
98//
99////////////////////////////////////////////////////////////////////////////
100void bncNetQueryV2::slotProxyAuthenticationRequired(const QNetworkProxy&,
101 QAuthenticator*) {
102 emit newMessage("slotProxyAuthenticationRequired", true);
103}
104
105// Start request, block till the next read
106////////////////////////////////////////////////////////////////////////////
107void bncNetQueryV2::startRequest(const QUrl& url, const QByteArray& gga) {
108 startRequestPrivate(url, gga, false);
109}
110
111// Start request, block till the next read
112////////////////////////////////////////////////////////////////////////////
113void bncNetQueryV2::keepAliveRequest(const QUrl& url, const QByteArray& gga) {
114 startRequestPrivate(url, gga, false);
115}
116
117// Start Request (Private Method)
118////////////////////////////////////////////////////////////////////////////
119void bncNetQueryV2::startRequestPrivate(const QUrl& url, const QByteArray& gga,
120 bool full) {
121
122 _status = running;
123
124 // Default scheme and path
125 // -----------------------
126 _url = url;
127 if (_url.scheme().isEmpty()) {
128 if (_secure) {
129 _url.setScheme("https");
130 }
131 else {
132 _url.setScheme("http");
133 }
134 }
135 if (_url.path().isEmpty()) {
136 _url.setPath("/");
137 }
138
139 // Network Request
140 // ---------------
141 bncSslConfig sslConfig = BNC_SSL_CONFIG;
142
143 if (_secure) {
144 bncSettings settings;
145 // Generate filenames to consider a potential client certificate
146 _crtFileName = settings.value("sslClientCertPath").toString() + _url.host() + QString(".%1.crt").arg(_url.port());
147 _keyFileName = settings.value("sslClientCertPath").toString() + _url.host() + QString(".%1.key").arg(_url.port());
148 QFile clientCrtFile(_crtFileName);
149 QFile privateKeyFile(_keyFileName);
150 if ( clientCrtFile.exists() && privateKeyFile.exists()) {
151 // set local certificate if available
152 clientCrtFile.open(QIODevice::ReadOnly);
153 QSslCertificate clientCrt(&clientCrtFile);
154 sslConfig.setLocalCertificate(clientCrt);
155 // set private key if available
156 privateKeyFile.open(QIODevice::ReadOnly);
157 QSslKey privateKey(&privateKeyFile, QSsl::Rsa);
158 sslConfig.setPrivateKey(privateKey);
159 }
160 }
161
162 QNetworkRequest request;
163 request.setSslConfiguration(sslConfig);
164 request.setUrl(_url);
165 request.setRawHeader("Host" , _url.host().toLatin1());
166 request.setRawHeader("Ntrip-Version", "Ntrip/2.0");
167 request.setRawHeader("User-Agent" , "NTRIP BNC/" BNCVERSION " (" BNC_OS ")");
168 if (!_url.userName().isEmpty()) {
169 QString uName = QUrl::fromPercentEncoding(_url.userName().toLatin1());
170 QString passW = QUrl::fromPercentEncoding(_url.password().toLatin1());
171 request.setRawHeader("Authorization", "Basic " +
172 (uName + ":" + passW).toLatin1().toBase64());
173 }
174 if (!gga.isEmpty()) {
175 request.setRawHeader("Ntrip-GGA", gga);
176 }
177 request.setRawHeader("Connection" , "close");
178
179 if (_reply) {
180 delete _reply;
181 _reply = 0;
182 }
183 _reply = _manager->get(request);
184
185 // Connect Signals
186 // ---------------
187 connect(_reply, SIGNAL(finished()), this, SLOT(slotFinished()));
188 connect(_reply, SIGNAL(finished()), _eventLoop, SLOT(quit()));
189 connect(_reply, SIGNAL(sslErrors(QList<QSslError>)),this, SLOT(slotSslErrors(QList<QSslError>)));
190 if (!full) {
191 connect(_reply, SIGNAL(readyRead()), _eventLoop, SLOT(quit()));
192 }
193}
194
195// Start Request, wait for its completion
196////////////////////////////////////////////////////////////////////////////
197void bncNetQueryV2::waitForRequestResult(const QUrl& url, QByteArray& outData) {
198
199 // Send Request
200 // ------------
201 startRequestPrivate(url, "", true);
202
203 // Wait Loop
204 // ---------
205 _eventLoop->exec();
206
207 // Copy Data and Return
208 // --------------------
209 if (_reply) {
210 outData = _reply->readAll();
211 }
212}
213
214// Wait for next data
215////////////////////////////////////////////////////////////////////////////
216void bncNetQueryV2::waitForReadyRead(QByteArray& outData) {
217
218 // Wait Loop
219 // ---------
220 bool timedOut = false;
221 if (!_reply->bytesAvailable()) {
222 QTimer timer;
223 timer.setSingleShot(true);
224 connect(&timer, SIGNAL(timeout()), _eventLoop, SLOT(quit()));
225 // The very first read of a request can take much longer than a
226 // steady-state read: it includes connection setup, TLS handshake and
227 // (on Windows) potentially slow system/WPAD proxy auto-detection. Only
228 // apply the strict outage-detection timeout once the stream is live.
229 timer.start(_firstData ? 5 * _timeOut : _timeOut);
230 _eventLoop->exec();
231 timedOut = !timer.isActive();
232 }
233 if (!_reply) {
234 return;
235 }
236
237 // Timeout: neither new data arrived nor did the request finish
238 // (e.g. connection silently dropped by a NAT/firewall)
239 // --------------------------------------------------------------
240 if (timedOut) {
241 _status = error;
242 emit newMessage(_url.path().toLatin1().replace(0,1,"")
243 + ": Read timeout", true);
244 disconnect(_reply, SIGNAL(finished()), this, SLOT(slotFinished()));
245 _reply->abort();
246 return;
247 }
248
249 // Check NTRIPv2 error code
250 // ------------------------
251 if (_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
252 _reply->abort();
253 }
254
255 // Append Data
256 // -----------
257 else {
258 outData.append(_reply->readAll());
259 _firstData = false;
260 }
261}
262
263// TSL/SSL
264////////////////////////////////////////////////////////////////////////////
265void bncNetQueryV2::slotSslErrors(QList<QSslError> errors) {
266
267 QString msg = "SSL Error: ";
268 QSslCertificate cert = _reply->sslConfiguration().peerCertificate();
269 if (!cert.isNull() &&
270 cert.issuerInfo(QSslCertificate::OrganizationalUnitName).count() &&
271 cert.issuerInfo(QSslCertificate::Organization).count()) {
272
273 msg += QString("Server Certificate Issued by:\n"
274 "%1\n%2\nCannot be verified\n")
275#if QT_VERSION >= 0x050000
276 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName).at(0))
277 .arg(cert.issuerInfo(QSslCertificate::Organization).at(0));
278#else
279 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName))
280 .arg(cert.issuerInfo(QSslCertificate::Organization));
281#endif
282 }
283
284 QListIterator<QSslError> it(errors);
285 while (it.hasNext()) {
286 const QSslError& err = it.next();
287 msg += err.errorString();
288 }
289
290 if (_sslIgnoreErrors) {
291 _reply->ignoreSslErrors();
292 BNC_CORE->slotMessage("BNC ignores SSL errors as configured", true);
293 }
294 else {
295 BNC_CORE->slotMessage(msg.toLatin1(), true);
296 stop();
297 }
298 return;
299}
Note: See TracBrowser for help on using the repository browser.