forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest_configuration.cpp
3712 lines (3239 loc) · 114 KB
/
rest_configuration.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013-2019 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 <QApplication>
#include <QCryptographicHash>
#include <QMessageAuthenticationCode>
#include <QDesktopServices>
#include <QFile>
#include <QString>
#include <QTcpSocket>
#include <QVariantMap>
#include <QNetworkInterface>
#include <QProcessEnvironment>
#include "daylight.h"
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "json.h"
#include <stdlib.h>
#include <time.h>
#include <QProcess>
#include "gateway.h"
#ifdef Q_OS_LINUX
#include <unistd.h>
#ifdef ARCH_ARM
#include <sys/reboot.h>
#include <sys/time.h>
#include <signal.h>
#endif
#endif // Q_OS_LINUX
/*! Constructor. */
ApiConfig::ApiConfig() :
Resource(RConfig)
{
}
/*! Init the configuration. */
void DeRestPluginPrivate::initConfig()
{
QString dataPath = deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation);
pollDatabaseWifiTimer = 0;
// default configuration
gwWifiLastUpdated = 0;
gwRunFromShellScript = false;
gwDeleteUnknownRules = (deCONZ::appArgumentNumeric("--delete-unknown-rules", 1) == 1) ? true : false;
gwRfConnected = false; // will be detected later
gwRfConnectedExpected = (deCONZ::appArgumentNumeric("--auto-connect", 1) == 1) ? true : false;
gwPermitJoinDuration = 0;
gwPermitJoinResend = 0;
gwNetworkOpenDuration = 60;
gwWifiState = WifiStateInitMgmt;
gwWifiMgmt = 0;
gwWifi = QLatin1String("not-configured");
gwWifiStateString = QLatin1String("not-configured");
gwWifiType = QLatin1String("accesspoint");
gwWifiName = QString();
gwWifiEth0 = QString();
gwWifiWlan0 = QString();
gwWifiClientName = QString();
gwWifiChannel = "1";
gwWifiIp = QLatin1String("192.168.8.1");
gwWifiPw = "";
gwWifiClientPw = "";
//gwWifiApPw = "";
gwWifiPageActive = false;
gwHomebridge = QLatin1String("not-managed");
gwHomebridgeVersion = QString();
gwHomebridgeUpdateVersion = QString();
gwHomebridgeUpdate = false;
gwHomebridgePin = QString();
gwRgbwDisplay = "1";
gwTimeFormat = "12h";
gwZigbeeChannel = 0;
gwGroup0 = 0;
gwName = GW_DEFAULT_NAME;
gwUpdateVersion = GW_SW_VERSION; // will be replaced by discovery handler
{
const QDateTime d = QDateTime::fromMSecsSinceEpoch(GW_SW_DATE * 1000LLU);
gwUpdateDate = d.toString("yyyy-MM-ddTHH:mm:ss"); // ISO 8601;
}
gwSwUpdateState = swUpdateState.noUpdate;
gwUpdateChannel = "stable";
gwReportingEnabled = (deCONZ::appArgumentNumeric("--reporting", 1) == 1) ? true : false;
gwFirmwareNeedUpdate = false;
gwFirmwareVersion = "0x00000000"; // query later
gwFirmwareVersionUpdate = "";
gwMAC = "38:60:77:7c:53:18";
gwIPAddress = "127.0.0.1";
gwPort = (apsCtrl ? apsCtrl->getParameter(deCONZ::ParamHttpPort) : deCONZ::appArgumentNumeric("--http-port", 80));
gwNetMask = "255.0.0.0";
gwLANBridgeId = (deCONZ::appArgumentNumeric("--lan-bridgeid", 0) == 1);
gwBridgeId = "0000000000000000";
gwAllowLocal = (deCONZ::appArgumentNumeric("--allow-local", 1) == 1);
gwConfig["websocketport"] = 443;
fwUpdateState = FW_Idle;
wifiPageActiveTimer = new QTimer(this);
wifiPageActiveTimer->setSingleShot(true);
connect(wifiPageActiveTimer, SIGNAL(timeout()),
this, SLOT(wifiPageActiveTimerFired()));
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
if (env.contains(QLatin1String("INVOCATION_ID")))
{
// deCONZ is startet from a systemd unit
// -- deconz.service or deconz-gui.service
if (env.contains(QLatin1String("DISPLAY")))
{
gwRunMode = QLatin1String("systemd/gui");
}
else
{
gwRunMode = QLatin1String("systemd/headless");
}
}
else
{
gwRunMode = QLatin1String("normal");
#ifdef Q_OS_LINUX
// check if we run from shell script
QFile pproc(QString("/proc/%1/cmdline").arg(getppid()));
if (pproc.exists() && pproc.open(QIODevice::ReadOnly))
{
QByteArray name = pproc.readAll();
if (name.endsWith(".sh"))
{
DBG_Printf(DBG_INFO, "runs in shell script %s\n", qPrintable(name));
gwRunFromShellScript = true;
gwRunMode = QLatin1String("shellscript");
}
else
{
gwRunFromShellScript = false;
DBG_Printf(DBG_INFO, "parent process %s\n", qPrintable(name));
}
}
QFile cgroups("/proc/1/cgroup");
if (cgroups.exists() && cgroups.open(QIODevice::ReadOnly))
{
QByteArray content = cgroups.readAll();
if (content.contains("/docker/"))
{
// https://github.com/marthoc/docker-deconz/blob/master/amd64-hassio-addon/run.sh
if (QFile::exists("/data/options.json"))
{
gwRunMode = QLatin1String("docker/hassio");
}
else
{
gwRunMode = QLatin1String("docker");
}
}
}
#else
gwRunFromShellScript = false;
#endif
}
DBG_Printf(DBG_INFO, "gw run mode: %s\n", qPrintable(gwRunMode));
// offical dresden elektronik sd-card image?
{
QFile f(dataPath + QLatin1String("/gw-version"));
if (f.exists() && f.open(QFile::ReadOnly))
{
gwSdImageVersion = f.readAll().trimmed();
}
else
{
DBG_Printf(DBG_INFO, "GW sd-card image version file does not exist: %s\n", qPrintable(f.fileName()));
}
}
if (!gwSdImageVersion.isEmpty())
{
DBG_Printf(DBG_INFO, "GW sd-card image version: %s\n", qPrintable(gwSdImageVersion));
}
#ifdef Q_OS_LINUX
#ifdef ARCH_ARM
{
QFile f("/sys/block/mmcblk0/device/cid");
if (f.exists() && f.open(QFile::ReadOnly))
{
QByteArray cid = f.readAll().left(32);
// wipe serial number
for (int i = 18; i < (18 + 8); i++)
{ cid[i] = 'f'; }
DBG_Printf(DBG_INFO, "sd-card cid: %s\n", qPrintable(cid));
}
}
#endif
#endif
config.addItem(DataTypeTime, RConfigLocalTime);
{
QHttpRequestHeader hdr;
QStringList path;
QString content;
ApiRequest dummyReq(hdr, path, 0, content);
dummyReq.version = ApiVersion_1_DDEL;
configToMap(dummyReq, gwConfig);
}
gwProxyPort = 0;
gwProxyAddress = "none";
timeManagerState = TM_Init;
ntpqProcess = 0;
QTimer::singleShot(2000, this, SLOT(timeManagerTimerFired()));
pollSwUpdateStateTimer = new QTimer(this);
pollSwUpdateStateTimer->setSingleShot(false);
connect(pollSwUpdateStateTimer, SIGNAL(timeout()),
this, SLOT(pollSwUpdateStateTimerFired()));
connect(deCONZ::ApsController::instance(), &deCONZ::ApsController::configurationChanged,
this, &DeRestPluginPrivate::configurationChanged);
}
/*! Init timezone. */
void DeRestPluginPrivate::initTimezone()
{
#ifdef Q_OS_LINUX
#ifdef ARCH_ARM
if (gwTimezone.isEmpty())
{
// set timezone in system and save it in db
gwTimezone = QLatin1String("Etc/GMT");
if (getenv("TZ") == NULL)
{
setenv("TZ", qPrintable(gwTimezone), 1);
}
else
{
gwTimezone = getenv("TZ");
}
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
}
else
{
// set system timezone from db
if (getenv("TZ") != gwTimezone)
{
setenv("TZ", qPrintable(gwTimezone), 1);
}
}
tzset();
#endif
#endif
if (daylightSensorId.isEmpty())
{
Sensor dl;
ResourceItem *item;
openDb();
daylightSensorId = QString::number(getFreeSensorId());
closeDb();
dl.setId(daylightSensorId);
dl.setType(QLatin1String("Daylight"));
dl.setName(QLatin1String("Daylight"));
item = dl.addItem(DataTypeBool, RConfigConfigured);
item->setValue(false);
item = dl.addItem(DataTypeInt8, RConfigSunriseOffset);
item->setValue(30);
item = dl.addItem(DataTypeInt8, RConfigSunsetOffset);
item->setValue(-30);
item = dl.addItem(DataTypeBool, RStateDaylight);
item->setValue(QVariant());
item = dl.addItem(DataTypeBool, RStateDark);
item->setValue(QVariant());
item = dl.addItem(DataTypeInt32, RStateStatus);
item->setValue(QVariant());
dl.removeItem(RConfigReachable);
dl.setModelId(QLatin1String("PHDL00"));
dl.setManufacturer(QLatin1String("Philips"));
dl.setSwVersion(QLatin1String("1.0"));
dl.item(RConfigOn)->setValue(true);
dl.setNeedSaveDatabase(true);
queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
sensors.push_back(dl);
}
QTimer *daylighTimer = new QTimer(this);
connect(daylighTimer, SIGNAL(timeout()), this, SLOT(daylightTimerFired()));
daylighTimer->setSingleShot(false);
daylighTimer->start(10000);
daylightTimerFired();
}
/*! Init the network info. */
void DeRestPluginPrivate::initNetworkInfo()
{
bool ok = false;
bool retry = false;
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
QList<QNetworkInterface>::Iterator i = ifaces.begin();
QList<QNetworkInterface>::Iterator end = ifaces.end();
// optimistic approach chose the first available ethernet interface
for (; !ok && i != end; ++i)
{
if (i->name() == QLatin1String("tun0"))
{
continue;
}
retry = true;
if ((i->flags() & QNetworkInterface::IsUp) &&
(i->flags() & QNetworkInterface::IsRunning) &&
!(i->flags() & QNetworkInterface::IsLoopBack))
{
//DBG_Printf(DBG_INFO, "%s (%s)\n", qPrintable(i->name()), qPrintable(i->humanReadableName()));
QList<QNetworkAddressEntry> addresses = i->addressEntries();
if (ok || addresses.isEmpty())
{
continue;
}
QList<QNetworkAddressEntry>::Iterator a = addresses.begin();
QList<QNetworkAddressEntry>::Iterator aend = addresses.end();
for (; a != aend; ++a)
{
if (a->ip().protocol() != QAbstractSocket::IPv4Protocol)
{
continue;
}
quint32 ipv4 = a->ip().toIPv4Address();
if ((ipv4 & 0xff000000UL) == 0x7f000000UL)
{
// 127.x.x.x
continue;
}
if ((ipv4 & 0x80000000UL) != 0x00000000UL && // class A 0xxx xxxx
(ipv4 & 0xc0000000UL) != 0x80000000UL && // class B 10xx xxxx
(ipv4 & 0xe0000000UL) != 0xc0000000UL) // class C 110x xxxx
{
// unsupported network
continue;
}
QString mac = i->hardwareAddress().toLower();
gwMAC = mac;
if (gwLANBridgeId) {
gwBridgeId = mac.mid(0,2) + mac.mid(3,2) + mac.mid(6,2) + "fffe" + mac.mid(9,2) + mac.mid(12,2) + mac.mid(15,2);
if (!gwConfig.contains("bridgeid") || gwConfig["bridgeid"] != gwBridgeId)
{
DBG_Printf(DBG_INFO, "Set bridgeid to %s\n", qPrintable(gwBridgeId));
gwConfig["bridgeid"] = gwBridgeId;
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
}
}
gwIPAddress = a->ip().toString();
gwConfig["ipaddress"] = gwIPAddress;
gwNetMask = a->netmask().toString();
initDescriptionXml();
ok = true;
retry = false;
break;
}
}
}
if (!ok)
{
DBG_Printf(DBG_ERROR, "No valid ethernet interface found\n");
}
if (retry)
{
QTimer::singleShot(10000, this, SLOT(initNetworkInfo()));
}
}
/*! Init WiFi parameters if necessary. */
void DeRestPluginPrivate::initWiFi()
{
bool retry = false;
#if !defined(ARCH_ARMV6) && !defined (ARCH_ARMV7)
gwWifi = QLatin1String("not-available");
return;
#endif
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
QList<QNetworkInterface>::Iterator i = ifaces.begin();
QList<QNetworkInterface>::Iterator end = ifaces.end();
bool wifiAvailable = false;
// only show wifi if wlan0 interface is found
for (; i != end; ++i)
{
if (i->name() == QLatin1String("wlan0"))
{
wifiAvailable = true;
}
}
// or rpi3 is used
// 3A+ = 9020e0; 3B+ = a020d3; 3B(Embest) = a22082; 3B(Sony UK) = a02082; 3B(Sony Jp) = a32082; 3B(Stadium) = a52082;
if (piRevision == "9020e0" || piRevision == "a020d3" || piRevision == "a22082" ||
piRevision == "a02082" || piRevision == "a32082" || piRevision == "a52082")
{
wifiAvailable = true;
}
if (!wifiAvailable)
{
gwWifi = QLatin1String("not-available");
return;
}
// only configure for official image
if (gwSdImageVersion.isEmpty())
{
return;
}
if (gwWifiLastUpdated == 0)
{
QDateTime currentDateTime = QDateTime::currentDateTimeUtc();
gwWifiLastUpdated = currentDateTime.toTime_t();
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
}
if (gwWifiState == WifiStateInitMgmt)
{
retry = true;
}
if (gwBridgeId.isEmpty() || gwBridgeId.endsWith(QLatin1String("0000")))
{
retry = true;
}
quint32 fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);
if (fwVersion < 0x261e0500) // first version to support security material set
{
retry = true;
}
if (gwWifi != QLatin1String("not-configured"))
{
retry = true;
}
QByteArray sec0 = apsCtrl->getParameter(deCONZ::ParamSecurityMaterial0);
if (sec0.isEmpty())
{
retry = true;
}
if (retry)
{
QTimer::singleShot(10000, this, SLOT(initWiFi()));
return;
}
if (!pollDatabaseWifiTimer)
{
pollDatabaseWifiTimer = new QTimer(this);
pollDatabaseWifiTimer->setSingleShot(false);
connect(pollDatabaseWifiTimer, SIGNAL(timeout()),
this, SLOT(pollDatabaseWifiTimerFired()));
pollDatabaseWifiTimer->start(10000);
}
if (gwWifiMgmt & WIFI_MGMT_ACTIVE)
{
return;
}
if (gwWifiName == QLatin1String("Phoscon-Gateway-0000"))
{
// proceed to correct these
gwWifiName.clear();
}
gwWifi = QLatin1String("configured");
gwWifiType = QLatin1String("accesspoint");
gwWifiStateString = QLatin1String("configured-ap");
if (gwWifiName.isEmpty() || gwWifiName == QLatin1String("Not set"))
{
gwWifiName = QString("Phoscon-Gateway-%1").arg(gwBridgeId.right(4));
gwWifiBackupName = gwWifiName;
}
if (gwWifiPw.isEmpty() || gwWifiPw.length() < 8)
{
gwWifiPw = sec0.mid(16, 16).toUpper();
gwWifiBackupPw = gwWifiPw;
}
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
}
/*! Handle deCONZ::ApsController::configurationChanged() event.
This will be called when the configuration was changed via deCONZ network settings.
*/
void DeRestPluginPrivate::configurationChanged()
{
if (!apsCtrl)
{
return;
}
DBG_Printf(DBG_INFO, "deCONZ configuration changed");
bool update = false;
const quint64 macAddress = apsCtrl->getParameter(deCONZ::ParamMacAddress);
//const quint16 nwkAddress = apsCtrl->getParameter(deCONZ::ParamNwkAddress);
if (macAddress != 0 && gwDeviceAddress.ext() != macAddress)
{
gwDeviceAddress = {}; // reset let idle timer update bridgeid
update = true;
}
const quint8 channel = apsCtrl->getParameter(deCONZ::ParamCurrentChannel);
if (channel >= 11 && channel <= 26 && gwZigbeeChannel != channel)
{
gwZigbeeChannel = channel;
update = true;
}
if (update)
{
updateZigBeeConfigDb();
queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
}
}
/*! Configuration REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleConfigBasicApi(const ApiRequest &req, ApiResponse &rsp)
{
// POST /api
if ((req.path.size() == 1) && (req.hdr.method() == QLatin1String("POST")))
{
return createUser(req, rsp);
}
// GET /api/challenge
else if ((req.path.size() == 2) && (req.hdr.method() == QLatin1String("GET")) && (req.path[1] == QLatin1String("challenge")))
{
return getChallenge(req, rsp);
}
// GET /api/config
else if ((req.path.size() == 2) && (req.hdr.method() == QLatin1String("GET")) && (req.path[1] == QLatin1String("config")))
{
return getBasicConfig(req, rsp);
}
// DELETE /api/config/password
else if ((req.path.size() == 3) && (req.hdr.method() == QLatin1String("DELETE")) && (req.path[1] == QLatin1String("config")) && (req.path[2] == QLatin1String("password")))
{
return deletePassword(req, rsp);
}
// GET /api/<nouser>/config
else if ((req.path.size() == 3) && (req.hdr.method() == QLatin1String("GET")) && (req.path[2] == QLatin1String("config")))
{
return getBasicConfig(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! Configuration REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleConfigLocalApi(const ApiRequest &req, ApiResponse &rsp)
{
// GET api/<localuser>/config/wifi
if ((req.path.size() == 4) && (req.hdr.method() == QLatin1String("GET")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("wifi")))
{
return getWifiState(req, rsp);
}
// PUT /api/<localuser>/config/wifi/updated
else if ((req.path.size() == 5) && (req.hdr.method() == QLatin1String("PUT")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("wifi")) && (req.path[4] == QLatin1String("updated")))
{
return putWifiUpdated(req, rsp);
}
// PUT /api/<localuser>/config/homebridge/updated
else if ((req.path.size() == 5) && (req.hdr.method() == QLatin1String("PUT")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("homebridge")) && (req.path[4] == QLatin1String("updated")))
{
return putHomebridgeUpdated(req, rsp);
}
// PUT /api/<localuser>/config/wifi/scanresult
else if ((req.path.size() == 5) && (req.hdr.method() == QLatin1String("PUT")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("wifi")) && (req.path[4] == QLatin1String("scanresult")))
{
return putWifiScanResult(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! Configuration REST API broker.
\param req - request data
\param rsp - response data
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::handleConfigFullApi(const ApiRequest &req, ApiResponse &rsp)
{
// GET /api/<apikey>/config
if ((req.path.size() == 3) && (req.hdr.method() == "GET") && (req.path[2] == "config"))
{
return getConfig(req, rsp);
}
// GET api/<apikey>/config/wifi
else if ((req.path.size() == 4) && (req.hdr.method() == "GET") && (req.path[2] == "config") && (req.path[3] == "wifi"))
{
return getWifiState(req, rsp);
}
// PUT /api/<apikey>/config/wifi
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT") && (req.path[2] == "config") && (req.path[3] == "wifi"))
{
return configureWifi(req, rsp);
}
// PUT /api/<apikey>/config/wifi/restore
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT") && (req.path[2] == "config") && (req.path[3] == "wifi") && (req.path[4] == "restore"))
{
return restoreWifiConfig(req, rsp);
}
// GET /api/config/zigbee
else if ((req.path.size() == 4) && (req.hdr.method() == QLatin1String("GET")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("zigbee")))
{
return getZigbeeConfig(req, rsp);
}
// PUT /api/config/zigbee/<id>
else if ((req.path.size() == 5) && (req.hdr.method() == QLatin1String("PUT")) && (req.path[2] == QLatin1String("config")) && (req.path[3] == QLatin1String("zigbee")))
{
return putZigbeeConfig(req, rsp);
}
// PUT /api/<apikey>/config/homebridge/reset
else if ((req.path.size() == 5) && (req.hdr.method() == "PUT") && (req.path[2] == "config") && (req.path[3] == "homebridge") && (req.path[4] == "reset"))
{
return resetHomebridge(req, rsp);
}
// PUT, PATCH /api/<apikey>/config
else if ((req.path.size() == 3) && (req.hdr.method() == "PUT" || req.hdr.method() == "PATCH") && (req.path[2] == "config"))
{
return modifyConfig(req, rsp);
}
// DELETE /api/<apikey>/config/whitelist/<username2>
else if ((req.path.size() == 5) && (req.hdr.method() == "DELETE") && (req.path[2] == "config") && (req.path[3] == "whitelist"))
{
return deleteUser(req, rsp);
}
// POST /api/<apikey>/config/update
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "update"))
{
return updateSoftware(req, rsp);
}
// POST /api/<apikey>/config/restart
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "restart"))
{
return restartGateway(req, rsp);
}
// POST /api/<apikey>/config/restartapp
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "restartapp"))
{
return restartApp(req, rsp);
}
// POST /api/<apikey>/config/shutdown
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "shutdown"))
{
return shutDownGateway(req, rsp);
}
// POST /api/<apikey>/config/updatefirmware
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "updatefirmware"))
{
return updateFirmware(req, rsp);
}
// POST /api/<apikey>/config/export
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "export"))
{
return exportConfig(req, rsp);
}
// POST /api/<apikey>/config/import
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "import"))
{
return importConfig(req, rsp);
}
// POST /api/<apikey>/config/reset
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "reset"))
{
return resetConfig(req, rsp);
}
// POST /api/<apikey>/config/wifiscan
else if ((req.path.size() == 4) && (req.hdr.method() == "POST") && (req.path[2] == "config") && (req.path[3] == "wifiscan"))
{
return scanWifiNetworks(req, rsp);
}
// PUT /api/<apikey>/config/password
else if ((req.path.size() == 4) && (req.hdr.method() == "PUT") && (req.path[2] == "config") && (req.path[3] == "password"))
{
return changePassword(req, rsp);
}
return REQ_NOT_HANDLED;
}
/*! POST /api
\return REQ_READY_SEND
REQ_NOT_HANDLED
*/
int DeRestPluginPrivate::createUser(const ApiRequest &req, ApiResponse &rsp)
{
bool ok;
bool found = false; // already exist?
QVariant var = Json::parse(req.content, ok);
QVariantMap map = var.toMap();
ApiAuth auth;
QHostAddress localHost(QHostAddress::LocalHost);
if (!gwLinkButton)
{
if (gwAllowLocal && req.sock->peerAddress() == localHost)
{
// proceed
}
else if (!allowedToCreateApikey(req, rsp, map))
{
return REQ_READY_SEND;
}
}
if (!ok || map.isEmpty())
{
rsp.httpStatus = HttpStatusBadRequest;
rsp.list.append(errorToMap(ERR_INVALID_JSON, QLatin1String("/"), QLatin1String("body contains invalid JSON")));
return REQ_READY_SEND;
}
if (!map.contains("devicetype")) // required
{
rsp.list.append(errorToMap(ERR_MISSING_PARAMETER, QLatin1String("/"), QLatin1String("missing parameters in body")));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
auth.setDeviceType(map["devicetype"].toString());
if (map.contains("username")) // optional (note username = apikey)
{
if ((map["username"].type() != QVariant::String) ||
(map["username"].toString().length() < 10))
{
rsp.list.append(errorToMap(ERR_INVALID_VALUE, QLatin1String("/"), QString("invalid value, %1, for parameter, username").arg(map["username"].toString())));
rsp.httpStatus = HttpStatusBadRequest;
return REQ_READY_SEND;
}
auth.apikey = map["username"].toString();
// check if this apikey is already known
std::vector<ApiAuth>::const_iterator i = apiAuths.begin();
std::vector<ApiAuth>::const_iterator end = apiAuths.end();
for (; i != end; ++i)
{
if (auth.apikey == i->apikey && i->state == ApiAuth::StateNormal)
{
found = true;
break;
}
}
}
else
{
// check for glitches from some devices registering too fast (Amazon Echo)
std::vector<ApiAuth>::const_iterator i = apiAuths.begin();
std::vector<ApiAuth>::const_iterator end = apiAuths.end();
for (; i != end && !found ; ++i)
{
if (auth.devicetype == i->devicetype && i->state == ApiAuth::StateNormal)
{
if (i->createDate.secsTo(QDateTime::currentDateTimeUtc()) < 30)
{
auth = *i;
found = true;
DBG_Printf(DBG_INFO, "reuse recently created auth username: %s, devicetype: %s\n", qPrintable(auth.apikey), qPrintable(auth.devicetype));
}
}
}
if (!found)
{
// create a random key (used only if not provided)
for (int i = 0; i < 5; i++)
{
uint8_t rnd = (uint8_t)qrand();
QString frac;
frac.sprintf("%02X", rnd);
auth.apikey.append(frac);
}
}
}
QVariantMap map1;
QVariantMap map2;
map1["username"] = auth.apikey;
map2["success"] = map1;
rsp.list.append(map2);
rsp.httpStatus = HttpStatusOk;
if (!found)
{
auth.createDate = QDateTime::currentDateTimeUtc();
auth.lastUseDate = QDateTime::currentDateTimeUtc();
auth.needSaveDatabase = true;
apiAuths.push_back(auth);
queSaveDb(DB_AUTH, DB_SHORT_SAVE_DELAY);
updateEtag(gwConfigEtag);
DBG_Printf(DBG_INFO, "created username: %s, devicetype: %s\n", qPrintable(auth.apikey), qPrintable(auth.devicetype));
}
else
{
DBG_Printf(DBG_INFO, "apikey username: %s, devicetype: %s already exists\n", qPrintable(auth.apikey), qPrintable(auth.devicetype));
}
rsp.etag = gwConfigEtag;
return REQ_READY_SEND;
}
/*! Puts all parameters in a map for later JSON serialization.
*/
void DeRestPluginPrivate::configToMap(const ApiRequest &req, QVariantMap &map)
{
QVariantMap whitelist;
QVariantMap swupdate;
QVariantMap swupdate2;
QVariantMap autoinstall;
QVariantMap bridge;
QVariantMap devicetypes;
QVariantMap portalstate;
QVariantMap internetservices;
QVariantMap backup;
QDateTime datetime = QDateTime::currentDateTimeUtc();
QDateTime localtime = QDateTime::currentDateTime();
basicConfigToMap(map);
map["ipaddress"] = gwIPAddress;
map["netmask"] = gwNetMask;
if (gwDeviceName.isEmpty())
{
gwDeviceName = apsCtrl->getParameter(deCONZ::ParamDeviceName);
}
if (!gwDeviceName.isEmpty())
{
map["devicename"] = gwDeviceName;
}
std::vector<ApiAuth>::const_iterator i = apiAuths.begin();
std::vector<ApiAuth>::const_iterator end = apiAuths.end();
for (; i != end; ++i)
{
if (i->state == ApiAuth::StateNormal)
{
QVariantMap au;
au["last use date"] = i->lastUseDate.toString("yyyy-MM-ddTHH:mm:ss"); // ISO 8601
au["create date"] = i->createDate.toString("yyyy-MM-ddTHH:mm:ss"); // ISO 8601
au["name"] = i->devicetype;
whitelist[i->apikey] = au;
}
}
if (req.apiVersion() == ApiVersion_1_DDEL)
{
map["permitjoin"] = (double)gwPermitJoinDuration;
map["permitjoinfull"] = (double)gwPermitJoinResend;
map["otauactive"] = isOtauActive();
map["otaustate"] = (isOtauBusy() ? "busy" : (isOtauActive() ? "idle" : "off"));
map["groupdelay"] = (double)gwGroupSendDelay;
map["discovery"] = (gwAnnounceInterval > 0);
map["updatechannel"] = gwUpdateChannel;
map["fwneedupdate"] = gwFirmwareNeedUpdate;
map["runmode"] = gwRunMode;
if (gwFirmwareNeedUpdate)
{
map["fwversionupdate"] = gwFirmwareVersionUpdate;
}
switch (fwUpdateState)
{
case FW_DisconnectDevice:
case FW_Update:
case FW_UpdateWaitFinished:
{ map[QLatin1String("fwupdatestate")] = QLatin1String("running"); }
break;
default:
{ map[QLatin1String("fwupdatestate")] = QLatin1String("idle"); }
break;
}
map["announceurl"] = gwAnnounceUrl;
map["announceinterval"] = (double)gwAnnounceInterval;
map["swversion"] = QLatin1String(GW_SW_VERSION);
map["swcommit"] = QLatin1String(GIT_COMMMIT);
swupdate["version"] = gwUpdateVersion;
swupdate["updatestate"] = (double)0;
swupdate["url"] = "";
swupdate["text"] = "";
swupdate["notify"] = false;
map["swupdate"] = swupdate;
map["port"] = gwPort;
// since api version 1.2.1
map["apiversion"] = QLatin1String(GW_SW_VERSION);
map["system"] = "other";
#if defined(ARCH_ARMV6) || defined (ARCH_ARMV7)
#ifdef Q_OS_LINUX
map["system"] = "linux-gw";
#endif
map["wifi"] = gwWifi;
map["homebridge"] = gwHomebridge;
map["homebridgepin"] = gwHomebridgePin;
map["homebridgeversion"] = gwHomebridgeVersion;
map["homebridgeupdateversion"] = gwHomebridgeUpdateVersion;
map["homebridgeupdate"] = gwHomebridgeUpdate;
#else
map["wifi"] = QLatin1String("not-available");
map["homebridge"] = QLatin1String("not-available");
#endif
map["wifiavailable"] = gwWifiAvailable;
map["wifitype"] = gwWifiType;
map["wifiname"] = gwWifiName;
map["wificlientname"] = gwWifiClientName;
map["wifichannel"] = gwWifiChannel;
map["wifimgmt"] = (double)gwWifiMgmt;
map["wifiip"] = gwWifiIp;
// map["wifiappw"] = gwWifiPw;
// map["wifiappw"] = QString(); // TODO add secured transfer via PKI
// map["wificlientpw"] = QString(); // TODO add secured transfer via PKI
}
else
{
if (req.mode != ApiModeNormal)
{
map["swversion"] = QLatin1String("1810251352");
map["apiversion"] = QLatin1String("1.28.0");
map["modelid"] = QLatin1String("BSB002");
}
devicetypes["bridge"] = false;
devicetypes["lights"] = QVariantList();
devicetypes["sensors"] = QVariantList();
swupdate["devicetypes"] = devicetypes;
swupdate["updatestate"] = (double)0;
swupdate["checkforupdate"] = false;
swupdate["url"] = "";
swupdate["text"] = "";
swupdate["notify"] = false;
map["portalconnection"] = QLatin1String("disconnected");
portalstate["signedon"] = false;
portalstate["incoming"] = false;
portalstate["outgoing"] = false;
portalstate["communication"] = QLatin1String("disconnected");
map["portalstate"] = portalstate;
internetservices["remoteaccess"] = QLatin1String("disconnected");
map["internetservices"] = internetservices;
backup["status"] = QLatin1String("idle");
backup["errorcode"] = 0;
map["backup"] = backup;
map["swupdate"] = swupdate;
}
bridge["state"] = gwSwUpdateState;