source: ntrip/trunk/BNC/src/upload/bncuploadcaster.cpp@ 9850

Last change on this file since 9850 was 9850, checked in by stuerze, 2 years ago

minor changes

File size: 12.0 KB
Line 
1/* -------------------------------------------------------------------------
2 * BKG NTRIP Server
3 * -------------------------------------------------------------------------
4 *
5 * Class: bncUploadCaster
6 *
7 * Purpose: Connection to NTRIP Caster
8 *
9 * Author: L. Mervart
10 *
11 * Created: 29-Mar-2011
12 *
13 * Changes:
14 *
15 * -----------------------------------------------------------------------*/
16
17#include <math.h>
18#include "bncuploadcaster.h"
19#include "bncversion.h"
20#include "bnccore.h"
21#include "bnctableitem.h"
22#include "bncsettings.h"
23#include "bncsslconfig.h"
24
25using namespace std;
26
27// Constructor
28////////////////////////////////////////////////////////////////////////////
29bncUploadCaster::bncUploadCaster(const QString &mountpoint,
30 const QString &outHost, int outPort, const QString &ntripVersion,
31 const QString &userName, const QString &password, int iRow, int rate) {
32 bncSettings settings;
33
34 _mountpoint = mountpoint;
35 _casterOutHost = outHost;
36 _casterOutPort = outPort;
37 _ntripVersion = ntripVersion;
38 _userName = userName;
39 _password = password;
40 _outSocket = 0;
41 _sOpenTrial = 0;
42 _iRow = iRow;
43 _rate = rate;
44
45 if (_rate < 0) {
46 _rate = 0;
47 } else if (_rate > 60) {
48 _rate = 60;
49 }
50 _isToBeDeleted = false;
51
52 connect(this, SIGNAL(newMessage(QByteArray,bool)), BNC_CORE, SLOT(slotMessage(const QByteArray,bool)));
53
54 if (BNC_CORE->_uploadTableItems.find(_iRow) != BNC_CORE->_uploadTableItems.end()) {
55 connect(this, SIGNAL(newBytes(QByteArray,double)),
56 BNC_CORE->_uploadTableItems.value(iRow),
57 SLOT(slotNewBytes(const QByteArray,double)));
58 }
59 if (BNC_CORE->_uploadEphTableItems.find(_iRow) != BNC_CORE->_uploadEphTableItems.end()) {
60 connect(this, SIGNAL(newBytes(QByteArray,double)),
61 BNC_CORE->_uploadEphTableItems.value(iRow),
62 SLOT(slotNewBytes(const QByteArray,double)));
63 }
64
65 _sslIgnoreErrors = (Qt::CheckState(settings.value("sslIgnoreErrors").toInt()) == Qt::Checked);
66
67 _proxyOutHost = settings.value("proxyHost").toString();
68 _proxyOutPort = settings.value("proxyPort").toInt();
69 (_proxyOutHost.isEmpty()) ? _proxy = false : _proxy = true;
70
71 _secure = false;
72 if (_ntripVersion == "2s") {
73 if (!QSslSocket::supportsSsl()) {
74 emit(newMessage(
75 "For SSL support please install OpenSSL run-time libraries: Ntrip Version 2 is tried",
76 true));
77 _ntripVersion == "2";
78 } else {
79 _secure = true;
80 _casterOutPort = 443;
81 // Generate filenames to consider a potential client certificate and private key
82 _crtFileName = settings.value("sslClientCertPath").toString() + _casterOutHost + QString(".%1.crt").arg(_casterOutPort);
83 _keyFileName = settings.value("sslClientCertPath").toString() + _casterOutHost + QString(".%1.key").arg(_casterOutPort);
84 }
85 }
86
87 if (!_secure && _proxy) {
88 _postExtension = QString("http://%1:%2").arg(_casterOutHost).arg(_casterOutPort);
89 } else {
90 _postExtension = "";
91 }
92}
93
94// Safe Desctructor
95////////////////////////////////////////////////////////////////////////////
96void bncUploadCaster::deleteSafely() {
97 _isToBeDeleted = true;
98 if (!isRunning()) {
99 delete this;
100 }
101}
102
103// Destructor
104////////////////////////////////////////////////////////////////////////////
105bncUploadCaster::~bncUploadCaster() {
106 if (isRunning()) {
107 wait();
108 }
109 if (_outSocket) {
110 delete _outSocket;
111 }
112}
113
114//
115////////////////////////////////////////////////////////////////////////////
116void bncUploadCaster::slotProxyAuthenticationRequired(const QNetworkProxy&,
117 QAuthenticator*) {
118 emit newMessage("slotProxyAuthenticationRequired", true);
119}
120
121// TSL/SSL
122 ////////////////////////////////////////////////////////////////////////////
123void bncUploadCaster::slotSslErrors(QList<QSslError> errors) {
124 QString msg = "SSL Error: ";
125 if (_outSocket) {
126 QSslCertificate cert = _outSocket->sslConfiguration().peerCertificate();
127 if (!cert.isNull() &&
128 cert.issuerInfo(QSslCertificate::OrganizationalUnitName).count() &&
129 cert.issuerInfo(QSslCertificate::Organization).count()) {
130 msg += QString("Server Certificate Issued by:\n" "%1\n%2\nCannot be verified\n")
131#if QT_VERSION >= 0x050000
132 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName).at(0))
133 .arg(cert.issuerInfo(QSslCertificate::Organization).at(0));
134#else
135 .arg(cert.issuerInfo(QSslCertificate::OrganizationalUnitName))
136 .arg(cert.issuerInfo(QSslCertificate::Organization));
137#endif
138 }
139
140 QListIterator<QSslError> it(errors);
141 while (it.hasNext()) {
142 const QSslError& err = it.next();
143 msg += err.errorString();
144 }
145 emit(newMessage(msg.toLatin1(), true));
146 }
147}
148
149
150// Endless Loop
151////////////////////////////////////////////////////////////////////////////
152void bncUploadCaster::run() {
153 while (true) {
154 if (_isToBeDeleted) {
155 QThread::quit();
156 deleteLater();
157 return;
158 }
159 open();
160 if (_outSocket && _outSocket->state() == QAbstractSocket::ConnectedState) {
161 QMutexLocker locker(&_mutex);
162 if (_outBuffer.size() > 0) {
163 if (_ntripVersion == "1") {
164 _outSocket->write(_outBuffer);
165 } else {
166 QString chunkSize = QString("%1").arg(_outBuffer.size(), 0, 16, QLatin1Char('0'));
167 QByteArray chunkedData = chunkSize.toLatin1() + "\r\n" + _outBuffer + "\r\n";
168 _outSocket->write(chunkedData);
169 }
170 _outSocket->flush();
171 emit newBytes(_mountpoint.toLatin1(), _outBuffer.size());
172 }
173 }
174 if (_rate == 0) {
175 {
176 QMutexLocker locker(&_mutex);
177 _outBuffer.clear();
178 }
179 msleep(100); //sleep 0.1 sec
180 } else {
181 sleep(_rate);
182 }
183 }
184}
185
186// Start the Communication with NTRIP Caster
187////////////////////////////////////////////////////////////////////////////
188void bncUploadCaster::open() {
189 const int timeOut = 5000; // 5 seconds
190 QByteArray msg;
191
192 if (_mountpoint.isEmpty()) {
193 return;
194 }
195
196 if (_outSocket != 0 &&
197 _outSocket->state() == QAbstractSocket::ConnectedState) {
198 return;
199 }
200
201 delete _outSocket; _outSocket = 0;
202
203 double minDt = pow(2.0, _sOpenTrial);
204 if (++_sOpenTrial > 4) {
205 _sOpenTrial = 4;
206 }
207 if (_outSocketOpenTime.isValid()
208 && _outSocketOpenTime.secsTo(QDateTime::currentDateTime()) < minDt) {
209 return;
210 } else {
211 _outSocketOpenTime = QDateTime::currentDateTime();
212 }
213
214 _outSocket = new QSslSocket();
215 _outSocket->setProxy(QNetworkProxy::NoProxy);
216
217 if (_sslIgnoreErrors) {
218 _outSocket->ignoreSslErrors();
219 } else {
220 bncSslConfig sslConfig = BNC_SSL_CONFIG;
221 QFile clientCrtFile(_crtFileName);
222 QFile privateKeyFile(_keyFileName);
223 if ( clientCrtFile.exists() && privateKeyFile.exists()) {
224 // set local certificate
225 clientCrtFile.open(QIODevice::ReadOnly);
226 QSslCertificate clientCrt(&clientCrtFile);
227 sslConfig.setLocalCertificate(clientCrt);
228 // set private key if available
229 privateKeyFile.open(QIODevice::ReadOnly);
230 QSslKey privateKey(&privateKeyFile, QSsl::Rsa);
231 sslConfig.setPrivateKey(privateKey);
232 }
233 _outSocket->setSslConfiguration(sslConfig);
234 connect(_outSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>)));
235 }
236
237 if (!_proxy) {
238 if (!connectToHost(_casterOutHost, _casterOutPort, _secure)) {
239 return;
240 }
241 } else {
242 if (_ntripVersion == "1") {
243 emit(newMessage("No proxy support in Ntrip Version 1 upload!", true));
244 delete _outSocket; _outSocket = 0;
245 return;
246 }
247 connect(_outSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*)),
248 this,SLOT(slotProxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*)));
249
250 if (!connectToHost(_proxyOutHost, _proxyOutPort, false)) {
251 return;
252 }
253
254 if (_secure) {
255 msg = "CONNECT " + _casterOutHost.toLatin1() + ":"
256 + QString("%1").arg(_casterOutPort).toLatin1() + " HTTP/1.1\r\n"
257 + "Proxy-Connection: Keep-Alive\r\n"
258 + "Host: " + _casterOutHost.toLatin1() + "\r\n"
259 + "User-Agent: NTRIP BNC/" BNCVERSION " (" + BNC_OS + ")\r\n"
260 + "\r\n";
261 _outSocket->write(msg);
262 _outSocket->waitForBytesWritten();
263 _outSocket->waitForReadyRead();
264
265 QByteArray ans = _outSocket->readAll();
266 if (ans.indexOf("200") == -1) {
267 int l = ans.indexOf("\r\n", 0);
268 emit(newMessage("Proxy: Connection broken for " + _mountpoint.toLatin1() + ": " + ans.left(l), true));
269 delete _outSocket; _outSocket = 0;
270 return;
271 } else {
272 emit(newMessage("Proxy: Connection established for " + _mountpoint.toLatin1(), true));
273 _sOpenTrial = 0;
274 _outSocket->setPeerVerifyName(_casterOutHost);
275 _outSocket->startClientEncryption();
276 if (!_outSocket->waitForEncrypted(timeOut)) {
277 emit(newMessage("Proxy/Caster: Encrypt timeout for " + _mountpoint.toLatin1() + " ("
278 + _casterOutHost.toLatin1() + ":"
279 + QString("%1) ").arg(_casterOutPort).toLatin1()
280 + _outSocket->errorString().toLatin1(), true));
281 delete _outSocket; _outSocket = 0;
282 return;
283 } else {
284 emit(newMessage("Proxy: SSL handshake completed for " + _mountpoint.toLatin1(), true));
285 }
286 }
287 }
288 }
289
290 if (_ntripVersion == "1") {
291 msg = "SOURCE " + _password.toLatin1() + " /" + _mountpoint.toLatin1()
292 + "\r\n" + "Source-Agent: NTRIP BNC/" BNCVERSION "\r\n\r\n";
293 } else {
294 msg = "POST " + _postExtension.toLatin1() + "/" + _mountpoint.toLatin1()
295 + " HTTP/1.1\r\n" + "Host: " + _casterOutHost.toLatin1() + "\r\n"
296 + "Ntrip-Version: Ntrip/2.0\r\n" + "Authorization: Basic "
297 + (_userName + ":" + _password).toLatin1().toBase64() + "\r\n"
298 + "User-Agent: NTRIP BNC/" BNCVERSION " (" + BNC_OS + ")\r\n"
299 + "Connection: close\r\n" + "Transfer-Encoding: chunked\r\n\r\n";
300 }
301 _outSocket->write(msg);
302 _outSocket->waitForBytesWritten();
303 _outSocket->waitForReadyRead();
304
305 QByteArray ans = _outSocket->readAll();
306
307 if (ans.indexOf("200") == -1) {
308 delete _outSocket; _outSocket = 0;
309 int l = ans.indexOf("\r\n", 0);
310 emit(newMessage("Broadcaster " + _casterOutHost.toLatin1() + ":" + QString("%1").arg(_casterOutPort).toLatin1() +
311 ": Connection broken for " + _mountpoint.toLatin1() + ": " + ans.left(l), true));
312 } else {
313 emit(newMessage("Broadcaster" + _casterOutHost.toLatin1() + ":" + QString("%1").arg(_casterOutPort).toLatin1() +
314 ": Connection opened for " + _mountpoint.toLatin1(), true));
315 _sOpenTrial = 0;
316 }
317}
318
319// Try connection to NTRIP Caster or Proxy
320////////////////////////////////////////////////////////////////////////////
321bool bncUploadCaster::connectToHost(QString outHost, int outPort, bool encrypted) {
322 const int timeOut = 5000; // 5 seconds
323 if (encrypted) {
324 _outSocket->connectToHostEncrypted(outHost, outPort);
325 if (!_outSocket->waitForEncrypted(timeOut)) {
326 emit(newMessage(
327 "Broadcaster " + _casterOutHost.toLatin1() + ":" + QString("%1").arg(_casterOutPort).toLatin1() +
328 ": Connect timeout for " + _mountpoint.toLatin1() + " ("
329 + outHost.toLatin1() + ":"
330 + QString("%1) ").arg(outPort).toLatin1()
331 + _outSocket->errorString().toLatin1(), true));
332 delete _outSocket; _outSocket = 0;
333 return false;
334 } else {
335 emit(newMessage("Broadcaster " + _casterOutHost.toLatin1() + ":" + QString("%1").arg(_casterOutPort).toLatin1() +
336 ": SSL handshake completed for " + _mountpoint.toLatin1(), true));
337 }
338 } else {
339 _outSocket->connectToHost(outHost, outPort);
340 if (!_outSocket->waitForConnected(timeOut)) {
341 emit(newMessage("Broadcaster " + _casterOutHost.toLatin1() + ":" + QString("%1").arg(_casterOutPort).toLatin1() +
342 ": Connect timeout for " + _mountpoint.toLatin1() + " ("
343 + outHost.toLatin1() + ":"
344 + QString("%1) ").arg(outPort).toLatin1()
345 + _outSocket->errorString().toLatin1(), true));
346 delete _outSocket; _outSocket = 0;
347 return false;
348 }
349 }
350 return true;
351}
352
353
Note: See TracBrowser for help on using the repository browser.