forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discovery.cpp
532 lines (462 loc) · 16 KB
/
discovery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
* Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QFile>
#include <QHostInfo>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QSysInfo>
#include "de_web_plugin_private.h"
#include "json.h"
#ifdef Q_OS_LINUX
#include <unistd.h>
#include <sys/time.h>
#endif
/*! Inits the internet discovery manager.
*/
void DeRestPluginPrivate::initInternetDicovery()
{
Q_ASSERT(inetDiscoveryManager == 0);
inetDiscoveryManager = new QNetworkAccessManager;
connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*)));
DBG_Assert(gwAnnounceInterval >= 0);
if (gwAnnounceInterval < 0)
{
gwAnnounceInterval = 15;
}
gwAnnounceVital = 0;
inetDiscoveryTimer = new QTimer(this);
inetDiscoveryTimer->setSingleShot(false);
{
QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl));
if (!proxies.isEmpty())
{
const QNetworkProxy &proxy = proxies.first();
if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy)
{
gwProxyPort = proxy.port();
gwProxyAddress = proxy.hostName();
inetDiscoveryManager->setProxy(proxy);
QHostInfo::lookupHost(proxy.hostName(),
this, SLOT(inetProxyHostLookupDone(QHostInfo)));
}
}
}
connect(inetDiscoveryTimer, SIGNAL(timeout()),
this, SLOT(internetDiscoveryTimerFired()));
setInternetDiscoveryInterval(gwAnnounceInterval);
// force first run
if (gwAnnounceInterval > 0)
{
QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
}
{
QFile f("/etc/os-release");
if (f.exists() && f.open(QFile::ReadOnly))
{
QTextStream stream(&f);
while (!stream.atEnd())
{
QString line = stream.readLine(200);
QStringList lineLs = line.split(QChar('='));
if (lineLs.size() != 2)
{
continue;
}
if (lineLs[0] == QLatin1String("PRETTY_NAME"))
{
osPrettyName = lineLs[1];
osPrettyName.remove(QChar('"'));
}
}
}
}
#ifdef ARCH_ARM
{ // get raspberry pi revision
QFile f("/proc/cpuinfo");
if (f.exists() && f.open(QFile::ReadOnly))
{
QByteArray arr = f.readAll();
QTextStream stream(arr);
while (!stream.atEnd())
{
QString line = stream.readLine(200);
QStringList lineLs = line.split(QChar(':'));
if (lineLs.size() != 2)
{
continue;
}
if (lineLs[0].startsWith(QLatin1String("Revision")))
{
piRevision = lineLs[1].trimmed();
break;
}
}
}
}
#endif // ARCH_ARM
if (osPrettyName.isEmpty())
{
#ifdef Q_OS_WIN
switch (QSysInfo::WindowsVersion)
{
case QSysInfo::WV_XP: osPrettyName = QLatin1String("WinXP"); break;
case QSysInfo::WV_WINDOWS7: osPrettyName = QLatin1String("Win7"); break;
case QSysInfo::WV_WINDOWS8: osPrettyName = QLatin1String("Win8"); break;
case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String("Win8.1"); break;
case QSysInfo::WV_WINDOWS10: osPrettyName = QLatin1String("Win10"); break;
default:
osPrettyName = QLatin1String("Win");
break;
}
#endif
#ifdef Q_OS_OSX
osPrettyName = "Mac";
#endif
#ifdef Q_OS_LINUX
osPrettyName = "Linux";
#endif
}
}
/*! Sets the announce interval for internet discovery.
\param minutes a value between 0..180 min
\return true on success
*/
bool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes)
{
if ((minutes < 0) || (minutes > 180))
{
DBG_Printf(DBG_INFO, "discovery ignored invalid announce interval (%d minutes)\n", minutes);
return false;
}
inetDiscoveryTimer->stop();
gwAnnounceInterval = minutes;
if (gwAnnounceInterval > 0)
{
int msec = 1000 * 60 * gwAnnounceInterval;
inetDiscoveryTimer->start(msec);
DBG_Printf(DBG_INFO, "discovery updated announce interval to %d minutes\n", minutes);
}
return true;
}
/*! Handle announce trigger timer.
*/
void DeRestPluginPrivate::internetDiscoveryTimerFired()
{
if (gwAnnounceInterval <= 0)
{
return;
}
int i = 0;
const deCONZ::Node *node;
deCONZ::ApsController *ctrl = deCONZ::ApsController::instance();
while (ctrl && ctrl->getNode(i, &node) == 0)
{
i++;
}
QVariantMap map;
map["name"] = gwName;
map["mac"] = gwBridgeId;
map["internal_ip"] = gwConfig["ipaddress"].toString();
map["internal_port"] = gwConfig["port"].toDouble();
map["interval"] = gwAnnounceInterval;
map["swversion"] = gwConfig["swversion"].toString();
map["fwversion"] = gwConfig["fwversion"].toString();
map["nodecount"] = (double)i;
map["uptime"] = (double)getUptime();
map["updatechannel"] = gwUpdateChannel;
map["os"] = osPrettyName;
map["runmode"] = gwRunMode;
if (!piRevision.isEmpty())
{
map["pirev"] = piRevision;
}
QByteArray data = Json::serialize(map);
inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data);
}
/*! Callback for finished HTTP requests.
\param reply the reply to a HTTP request
*/
void DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply)
{
DBG_Assert(reply != 0);
if (!reply)
{
return;
}
if (reply->error() == QNetworkReply::NoError)
{
if (gwAnnounceVital < 0)
{
gwAnnounceVital = 0;
}
gwAnnounceVital++;
DBG_Printf(DBG_INFO, "Announced to internet\n");
internetDiscoveryExtractGeo(reply);
#ifdef ARCH_ARM
// currently this is only supported for the RaspBee Gateway
internetDiscoveryExtractVersionInfo(reply);
#endif // ARCH_ARM
}
else
{
DBG_Printf(DBG_INFO, "discovery network reply error: %s\n", qPrintable(reply->errorString()));
if (gwAnnounceVital > 0)
{
gwAnnounceVital = 0;
}
gwAnnounceVital--;
if (gwProxyAddress != QLatin1String("none") && gwProxyPort > 0)
{
if (inetDiscoveryManager->proxy().type() != QNetworkProxy::HttpProxy)
{
//first fail, speed up retry
QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
}
QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort);
inetDiscoveryManager->setProxy(proxy);
}
}
reply->deleteLater();
}
/*! Extracts the update channels version info about the deCONZ/WebApp.
\param reply which holds the version info in JSON format
*/
void DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply)
{
bool ok;
QByteArray content = reply->readAll();
QVariant var = Json::parse(content, ok);
QVariantMap map = var.toMap();
if (!ok || map.isEmpty())
{
DBG_Printf(DBG_ERROR, "discovery couldn't extract version info from reply\n");
}
if (reply->hasRawHeader("date") || reply->hasRawHeader("Date"))
{
// if NTP is not working (UDP blocked, proxies, etc)
// try to extract time from discover server http header if local time is too off
QString date = reply->rawHeader("date");
if (date.isEmpty())
{
date = reply->rawHeader("Date");
}
DBG_Printf(DBG_INFO, "discovery server date: %s\n", qPrintable(date));
QStringList ls = date.split(' ');
if (ls.size() == 6) // RFC 1123: ddd, dd MMM yyyy HH:mm:ss GTM
{
int day = ls[1].toInt();
int month = 0;
int year = ls[3].toInt();
const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
for (int i = 0; i < 12; i++)
{
if (ls[2].startsWith(months[i]))
{
month = i + 1;
break;
}
}
QDateTime dt;
dt.setTimeSpec(Qt::UTC);
dt.setDate(QDate(year, month, day));
dt.setTime(QTime::fromString(ls[4]));
QDateTime now = QDateTime::currentDateTimeUtc();
int diff = qAbs(now.secsTo(dt));
if (diff < 60)
{
DBG_Printf(DBG_INFO, "\t local time seems to be ok\n");
}
else if (getUptime() > 600 &&
gwConfig["ntp"].toString() != QLatin1String("synced"))
{
DBG_Printf(DBG_INFO, "\t = %s, diff %d\n", qPrintable(dt.toString()), diff);
#ifdef ARCH_ARM
// lazy adjustment of process time
//time_t t = dt.toSecsSinceEpoch(); // Qt 5.8
time_t t = dt.toTime_t();
struct tm tbrokenDown;
if (localtime_r(&t, &tbrokenDown))
{
struct timeval tv;
tv.tv_sec = mktime(&tbrokenDown);
tv.tv_usec = 0;
if (settimeofday(&tv, NULL) < 0)
{
DBG_Printf(DBG_ERROR, "settimeofday(): errno %d\n", errno);
}
}
#endif // ARCH_ARM
}
}
}
if (map.contains("versions") && (map["versions"].type() == QVariant::Map))
{
QString version;
QVariantMap versions = map["versions"].toMap();
if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String))
{
version = versions[gwUpdateChannel].toString();
if (!version.isEmpty())
{
if (gwUpdateVersion != version)
{
DBG_Printf(DBG_INFO, "discovery found version %s for update channel %s\n", qPrintable(version), qPrintable(gwUpdateChannel));
gwUpdateVersion = version;
gwSwUpdateState = swUpdateState.readyToInstall;
updateEtag(gwConfigEtag);
}
}
else
{
DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info for update channel %s\n", qPrintable(gwUpdateChannel));
}
}
else
{
DBG_Printf(DBG_ERROR, "discovery reply doesn't contain version info for update channel %s\n", qPrintable(gwUpdateChannel));
}
}
else
{
DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info\n");
}
}
/*! Extracts the geo information.
\param reply from discovery server
*/
void DeRestPluginPrivate::internetDiscoveryExtractGeo(QNetworkReply *reply)
{
// for (const QByteArray &hdr : reply->rawHeaderList())
// {
// DBG_Printf(DBG_INFO, "hdr: %s: %s\n", qPrintable(hdr), qPrintable(reply->rawHeader(hdr)));
// }
if (reply->hasRawHeader("X-AppEngine-CityLatLong"))
{
QList<QByteArray> ll = reply->rawHeader("X-AppEngine-CityLatLong").split(',');
if (ll.size() != 2)
{
// no geo information available
return;
}
Sensor *sensor = getSensorNodeForId(daylightSensorId);
DBG_Assert(sensor != 0);
if (!sensor)
{
return;
}
ResourceItem *configured = sensor->item(RConfigConfigured);
ResourceItem *lat = sensor->item(RConfigLat);
ResourceItem *lon = sensor->item(RConfigLong);
DBG_Assert(configured && lat && lon);
if (!configured || !lat || !lon)
{
return;
}
if (!configured->toBool() || !configured->lastSet().isValid())
{
configured->setValue(true);
lat->setValue(QString(ll[0]));
lon->setValue(QString(ll[1]));
sensor->setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
}
}
}
/*! Finished Lookup of http proxy IP address.
\param host holds the proxy host info
*/
void DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host)
{
if (host.error() != QHostInfo::NoError)
{
DBG_Printf(DBG_ERROR, "Proxy host lookup failed: %s\n", qPrintable(host.errorString()));
return;
}
foreach (const QHostAddress &address, host.addresses())
{
QString addr = address.toString();
if (address.protocol() == QAbstractSocket::IPv4Protocol &&
!addr.isEmpty() && gwProxyAddress != address.toString())
{
DBG_Printf(DBG_INFO, "Found proxy IP address: %s\n", qPrintable(address.toString()));
gwProxyAddress = address.toString();
DBG_Assert(gwProxyPort != 0);
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
updateEtag(gwConfigEtag);
return;
}
}
}
/*! Check if a received via field contains a usable proxy.
\param via holds the proxy host info received by http request header
*/
void DeRestPluginPrivate::inetProxyCheckHttpVia(const QString &via)
{
if (via.isEmpty())
{
return;
}
if (gwProxyPort != 0 && !gwProxyAddress.isEmpty() && gwProxyAddress != QLatin1String("none"))
{
return; // already configured?
}
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45
// 1.1 proxy.some-domain.com:3128 (squid/2.7.STABLE9)
DBG_Printf(DBG_INFO, "Test proxy: \t%s\n", qPrintable(via));
for (QString &entry : via.split(',')) // there might be multiple proxied in the chain
{
QStringList ls = entry.split(' ');
if (ls.size() < 2)
{
continue;
}
if (!ls[0].contains(QLatin1String("1.1")))
{
continue;
}
QStringList recvBy = ls[1].split(':');
if (ls.size() < 1) // at least host must be specified
{
continue;
}
quint16 port = 8080;
if (recvBy.size() == 2) // optional
{
port = recvBy[1].toUInt();
}
DBG_Printf(DBG_INFO, "\t --> %s:%u\n", qPrintable(recvBy[0]), port);
if (gwProxyPort != 0)
{
continue;
}
if (gwAnnounceVital >= 0)
{
continue;
}
gwProxyAddress = recvBy[0];
gwProxyPort = port;
if (gwProxyAddress.contains('.'))
{
recvBy = gwProxyAddress.split('.');
gwProxyAddress = recvBy[0]; // strip domain // todo might be too restrictive
}
QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort);
inetDiscoveryManager->setProxy(proxy);
QHostInfo::lookupHost(proxy.hostName(),
this, SLOT(inetProxyHostLookupDone(QHostInfo)));
updateEtag(gwConfigEtag);
if (gwAnnounceInterval > 0)
{
QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
}
}
}