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

Last change on this file since 10960 was 10960, checked in by stuerze, 2 weeks ago

A timeout is added to allow a reonnect after an outage of Ntrip Version 2/2s streams

File size: 8.8 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 timer.start(_timeOut);
226 _eventLoop->exec();
227 timedOut = !timer.isActive();
228 }
229 if (!_reply) {
230 return;
231 }
232
233 // Timeout: neither new data arrived nor did the request finish
234 // (e.g. connection silently dropped by a NAT/firewall)
235 // --------------------------------------------------------------
236 if (timedOut) {
237 _status = error;
238 emit newMessage(_url.path().toLatin1().replace(0,1,"")
239 + ": Read timeout", true);
240 disconnect(_reply, SIGNAL(finished()), this, SLOT(slotFinished()));
241 _reply->abort();
242 return;
243 }
244
245 // Check NTRIPv2 error code
246 // ------------------------
247 if (_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() != 200) {
248 _reply->abort();
249 }
250
251 // Append Data
252 // -----------
253 else {
254 outData.append(_reply->readAll());
255 }
256}
257
258// TSL/SSL
259////////////////////////////////////////////////////////////////////////////
260void bncNetQueryV2::slotSslErrors(QList<QSslError> errors) {
261
262 QString msg = "SSL Error: ";
263 QSslCertificate cert = _reply->sslConfiguration().peerCertificate();
264 if (!cert.isNull() &&
265 cert.issuerInfo(QSslCertificate::OrganizationalUnitName).count() &&
266 cert.issuerInfo(QSslCertificate::Organization).count()) {
267
268 msg += QString("Server Certificate Issued by:\n"
269 "%1\n%2\nCannot be verified\n")
270#if QT_VERSION >= 0x050000
271 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName).at(0))
272 .arg(cert.issuerInfo(QSslCertificate::Organization).at(0));
273#else
274 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName))
275 .arg(cert.issuerInfo(QSslCertificate::Organization));
276#endif
277 }
278
279 QListIterator<QSslError> it(errors);
280 while (it.hasNext()) {
281 const QSslError& err = it.next();
282 msg += err.errorString();
283 }
284
285 if (_sslIgnoreErrors) {
286 _reply->ignoreSslErrors();
287 BNC_CORE->slotMessage("BNC ignores SSL errors as configured", true);
288 }
289 else {
290 BNC_CORE->slotMessage(msg.toLatin1(), true);
291 stop();
292 }
293 return;
294}
Note: See TracBrowser for help on using the repository browser.