-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttn-letterbox.cgi
executable file
·1639 lines (1418 loc) · 53.8 KB
/
ttn-letterbox.cgi
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
#!/usr/bin/perl -w -T
#
# TheThingsNetwork HTTP integration for letterbox-sensor (v1+v2)
# - receives payload via POST from TTN
# - serves a small web page with status of letterbox sensor(s)
# - directly called CGI
# - included with SSI
#
# See also
# https:/hierle/letterbox-sensor
# https:/hierle/letterbox-sensor-v2
#
# Initial:
# (P) & (C) 2019-2019 Alexander Hierle <[email protected]>
#
# Major extensions:
# (P) & (C) 2019-2024 Dr. Peter Bieringer <[email protected]>
#
# License: GPLv3
#
# Authors: Alexander Hierle (hie)
# Dr. Peter Bieringer (bie)
#
#
# Compatibility of letterbox-sensor
# - supports version 1+2 sending "full" / "empty"
# - supports planned future version sending also "emptied" / "filled"
#
# Preparation
# - installation of following usually not by default installed Perl modules (EL8/Fedora35)
# perl-Data-UUID
# perl-URI-Encode
# perl-Apache-Htpasswd (for user authentication)
# perl-Authen-Passphrase or perl-Crypt-SaltedHash (for user authentication)
# perl-LWP-Protocol-https (for user CAPTCHA verification)
#
# Installation
# - store CGI into cgi-bin directory
# - optionally: include CGI in SSI enabled webpage using
# <!--#include virtual="cgi-bin/ttn-letterbox.cgi" -->
#
# Configuration (optional overwritten by config file <DOCUMENT_ROOT>/../conf/ttn-letterbox.conf)
# - datadir=<by CGI user writable directory>:
# - default: <DOCUMENT_ROOT>/ttn
# - autoregister=<value>
# - default: 0 (do not autoregister devices)
# - 1 (autoregister devices)
# - debug=<value>
# - default: 0 (no debug) 1 (normal debug) 2 (some tracing)
# - threshold.<dev_id>=<value>
# - default: received in JSON from sensor
# - delta.warn=<minutes>
# - default: 45
# - delta.crit=<minutes>
# - default: 90
# - alias.<dev_id>="Alias Name"
#
# Access control
# - CGI honors for POST requests X-TTN-AUTH header which can be configured manually on TTN controller side
# - on device autoregistration, password will be also stored in device list, allowed chars: [:alnum:]\.\-\+%
# - in case device is already registered without password, watch for hint in log
# - GET requests are currently NOT protected
#
# Supported Query String parameters (main, for modules see there)
# QUERY_STRING from CGI env + HTTP_X_TTN_LETTERBOX_QUERY_STRING from mod_include
# - dev_id=<dev_id>
# - details=(on|off|l1)
# - autoreload=(on|off)
#
# Supported "Accept"
# text/plain: response in plain text
# application/json: response in json text
#
# Logging
# - warnings/errors will be logged to web server error log using "print STDERR"
#
#
# Persistent data storage for log & status
# - it is strongly recommended to store the persistent data outside pub directory (see configuration above)
#
# File: ttn.devices.list
# Contents: <dev_id>:<hardware_serial>:<salted encrpyted password>
# Purpose: (auto)store seen devices, add seen password on registration
#
# File: ttn.<dev_id>.%Y%m%d.raw.log
# Contents: <TIMESTAMP> <raw data received from TTN>
# Purpose: log all received data
#
# File: ttn.<dev_id>.%Y%m%d.raw.status
# Contents: <TIMESTAMP> <raw data received from TTN>
# Purpose: last received data
#
# File: ttn.<dev_id>.%Y%m%d.filled.status
# Contents: <TIMESTAMP>
# Purpose: time of last detected (received/autodetected) filled status
#
# File: ttn.<dev_id>.%Y%m%d.emptied.status
# Contents: <TIMESTAMP>
# Purpose: time of last detected (received/autodetected) emptied status
#
# File: ttn.notify.list
# Contents: <dev_id>:<comma_separated_notification_token>
# Purpose: list of notification recipients defined with method
# Supported:
# signal=<phone_number>[;<lang>] (by ttn-letterbox-notifyDbusSignal.pm)
# email=<recipient>[;<lang>] (by ttn-letterbox-notifyEmail.pm)
#
# Changelog:
# 20191007/hie: initial
# 20191029/bie: major extension, improve output, add support for additional sensors, add some error catching
# 20191030/bie: add full/empty status support
# 20191031/bie: add filled/empty support (directly [future usage] and indirectly)
# 20191101/bie: add optional password protection capability for POST request, add support for config file
# 20191104/bie: add deltaLastChanged and threshold per dev_id in config, change color in case lastReceived is above limits
# 20191107/bie: fix+improve delta time calc+display
# 20191110/bie: implement hooks for additional modules (statistics), minor reorg
# 20191111/bie: add adjusted status filled/emptied also to content hash to be used by data update hooks, add query string handling, add additional buttons for switching graphics on/off
# 20191112/bie: rework button implementation
# 20191113/bie: implement auto-reload button
# 20191114/bie: add support for HTTP_TTN_LETTERBOX_QUERY_STRING (SSI/mod_include), change color of Reload button
# 20191115/bie: cosmetic name change
# 20191116/bie: rename HTTP_TTN_LETTERBOX_QUERY_STRING to HTTP_X_TTN_LETTERBOX_QUERY_STRING
# 20191117/bie: implement hooks for authentication, cosmetics, reorg
# 20191123/bie: cosmetics, minor bugfixes
# 20191126/bie: add support for plain and json output
# 20191214/bie: add translation support for "de"
# 20200107/bie: use only major language token for translation support
# 20200213/bie: improve layout for Mobile browers
# 20200828/bie: fix issues on EL8 and add various META HTTP-EQUIV to avoid local brower caching
# 20201109/bie: fix german translation
# 20210627/bie: add module and extended support for ttn-letterbox-notifyDbusSignal.pm
# 20210628/bie: add module and extended support for ttn-letterbox-notifyEmail.pm
# 20211001/bie: adjust German translation
# 20211030/bie: add support for v3 API, extend debugging, add payload validator
# 20211109/bie: fix payload validator for "tempC" (supporting also negative values)
# 20220217/bie: fix "counter" related to v3 API
# 20220217/bie: add support for Salted Hash provided by Authen::Passphrase::SaltedDigest in case of Crypt::SaltedHash (only available on EPEL7) is not installed/available
# 20220218/bie: add missing 'init_device' hook for POST
# 20220219/bie: display '*undef* in case a raw data value is missing (e.g. sometimes 'snr' for unknown reason)
# 20220219/bie: include device hash into module hook 'get_graphics' calls
# 20220331/bie: define button height global, align button sizes
# 20220402/bie: adjust raw content in case of threshold is provided by config (fixes improper WebUI box status display)
# 20220415/bie: add additional "details" level "l1" with limited display of details
# 20220417/bie: extend query string=value pattern check
# 20220422/bie: add support for options (used for local testing/debugging)
# 20220424/bie: clean query string from URI in response if refresh_delay is given (e.g. logout)
# 20230923/bie: set counter to 0 in case neither 'counter' nor 'f_cnt' is set
# 20240117/bie: add support for letterbox-sensor-v2
# 20240118/bie: cosmetic extension of the "details" button
# 20240119/bie: add support for device alias, cosmetic extensions
# 20240123/bie: add support for letterbox-sensor-v2/extended-payload "datarate","txpower","changed","period"
#
# TODO:
# - lock around file writes
# - safety check on config file value parsing
use English;
use strict;
use warnings;
use CGI;
use POSIX qw(strftime);
use JSON;
use Date::Parse;
use I18N::LangTags::Detect;
use Getopt::Std;
use utf8;
# autodetection of supported modules for Salted Hash
my $HAVE_Crypt_SaltedHash = 0;
eval "use Crypt::SaltedHash";
if ($@) {
$HAVE_Crypt_SaltedHash = 0;
eval "use Authen::Passphrase::SaltedDigest";
if ($@) {
die "Missing one of the module supporting salted hashes: Crypt::SaltedHash Authen::Passphrase::SaltedDigest";
};
} else {
$HAVE_Crypt_SaltedHash = 1;
};
push @INC, ".";
# global hooks
our %hooks;
# features
our %features;
# notify
our @notify_list;
# optional modules
my @module_list;
push @module_list, "ttn-letterbox-userauth.pm";
push @module_list, "ttn-letterbox-statistics.pm";
push @module_list, "ttn-letterbox-rrd.pm";
push @module_list, "ttn-letterbox-notifyDbusSignal.pm";
push @module_list, "ttn-letterbox-notifyEmail.pm";
for my $module (@module_list) {
if (-e $module && -r $module) {
require $module;
};
};
# name of program
my $program = "ttn-letterbox.cgi";
# prototyping
sub response($$;$$$$$);
sub letter($);
sub logging($);
sub deltatime_string($);
sub req_post();
sub req_get();
sub translate($);
# global config (can be overwritten/extended by config file)
our %config = (
'autoregister' => 0, # autoregister devices
'autorefresh' => 900, # (seconds) of HTML autorefreshing
'delta.warn' => 45, # (minutes) when color of deltaLastReceived turns orange
'delta.crit' => 75, # (minutes) when color of deltaLastReceived turns red
'button.height' => 50, # button height in px
'button.width' => 100, # button width in px
'debugmask' => 0, # debug mask (0x1: log raw JSON/POST)
'debug' => 0 # debug
);
# translations
our %translations;
my @languagesSupported = ( 'en', 'de' );
our $language = "en"; # default
# global data
our %querystring;
our $datadir;
our $conffile;
our $mobile = 0;
# set time strings
my $nowstr = strftime "%Y-%m-%dT%H:%M:%SZ", gmtime(time);
my $today = strftime "%Y%m%d", gmtime(time);
# defines from environment
my $reqm = $ENV{'REQUEST_METHOD'};
# payload validator
my %payload_validator = (
'box' => { 'pattern' => '(full|empty|filled|emptied)', 'required' => 1 }, # mandatory (v1+v2)
'sensor1' => { 'pattern' => '[0-9]+' , 'required' => 0 }, # new in v2
'sensor2' => { 'pattern' => '[0-9]+' , 'required' => 0 }, # new in v2
'sensor' => { 'pattern' => '[0-9]+' , 'required' => 1 }, # only in v1, will be filled with max(sensor1,sensor2) in v2
'temp' => { 'pattern' => '[0-9]+' , 'required' => 1 }, # n/a in v2 but will be filled with dummy value
'tempC' => { 'pattern' => '[0-9-]+', 'required' => 1 }, # n/a in v2 but will be filled with dummy value
'threshold' => { 'pattern' => '[0-9]+' , 'required' => 1 }, # mandatory (v1+v2)
'voltage' => { 'pattern' => '[0-9.]+', 'required' => 1 }, # mandatory (v1+v2)
'txpower' => { 'pattern' => '[0-7]' , 'required' => 0 }, # optional (v2 "extrainfo")
'datarate' => { 'pattern' => '[0-7]' , 'required' => 0 }, # optional (v2 "extrainfo")
'changed' => { 'pattern' => '[0-1]' , 'required' => 0 }, # optional (v2 "extrainfo")
'period' => { 'pattern' => '[0-9]+' , 'required' => 0 }, # optional (v2 "extrainfo")
);
# details depending on detail level
my @details_on = ("rssi", "snr", "tempC", "counter", "txpower", "datarate", "period", "changed", "hardwareSerial"); # only displayed in case of "details" == "on"
my @details_l1 = ("voltage", "threshold"); # only displayed in case of "details" == "l1" || "on"
####################
## option handling (for testing)
####################
sub help() {
print qq{
Usage:
-c <FILE> config file
-h|-? this online help
};
};
my %opts;
if (! getopts('h\?c:', \%opts)) {
print "Error in command line arguments (see -h|?)\n";
exit 1;
};
if (defined $opts{'h'} || defined $opts{'?'}) {
help();
exit 0;
};
# config file
if (defined $opts{'c'}) {
if (! -e $opts{'c'}) {
logging("provided config file by option -c <FILE> is not existing: ". $opts{'c'});
exit 1;
};
$conffile = $opts{'c'};
};
####################
## basic error check
####################
# default
if (!defined $ENV{'SERVER_NAME'}) {
$ENV{'SERVER_NAME'} = "UNDEFINED";
response(500, "major problem found", "", "'SERVER_NAME' not defined in environment");
exit;
};
if (!defined $ENV{'DOCUMENT_ROOT'}) {
response(500, "major problem found", "", "'DOCUMENT_ROOT' not defined in environment");
exit;
};
my $confdir = $ENV{'DOCUMENT_ROOT'} . "/../conf"; # default
$datadir = $ENV{'DOCUMENT_ROOT'} . "/ttn"; # default
# read optional config
$conffile = $confdir . "/ttn-letterbox.conf" if (! defined $conffile);
if (-e $conffile) {
if (! -r $conffile) {
response(500, "major problem found", "", "config file exists but not readable: $conffile");
exit;
};
# read key value
open CONFF, '<', $conffile or die;
while (my $line = <CONFF>) {
chomp($line);
if ($line =~ /^([A-Za-z0-9-\.]+)=([^"]*)$/o) {
$config{$1} = $2;
# strip quotes
} elsif ($line =~ /^([A-Za-z0-9-\.]+)="([^"]*)"$/o) {
$config{$1} = $2;
};
};
close CONFF;
if (defined $config{'debug'} && $config{'debug'} > 0) {
for my $key (sort keys %config) {
logging("config: " . $key . "=" . $config{$key});
};
};
};
# print environment to error log
if (defined $config{'debug'} && $config{'debug'} ne "0") {
for my $env (sort keys %ENV) {
logging("CGI environment: " . $env . "=" . $ENV{$env});
};
};
# owerwrite datadir
if (defined $config{'datadir'}) {
$datadir = $config{'datadir'};
} else {
# store in config hash
$config{'datadir'} = $datadir;
};
if (! -e $datadir) {
response(500, "major problem found", "", "datadir not existing: $datadir");
exit;
};
if (! -r $datadir) {
response(500, "major problem found", "", "datadir not readable: $datadir");
exit;
};
if (! -w $datadir) {
response(500, "major problem found", "", "datadir not writable: $datadir");
exit;
};
if (! defined $reqm) {
response(500, "major problem found", "", "REQUEST_METHOD not defined");
exit;
};
## background colors
my %bg_colors = (
'full' => 'lightgreen',
'empty' => 'lightgrey',
'filled' => 'yellow',
'emptied' => 'pink',
);
# notification file
my $notifyfile = "$datadir/ttn.notify.list";
# list of seen devices
my $devfile = "$datadir/ttn.devices.list";
# filetemplates per DEV_ID
my $rawfile_template = "$datadir/ttn.DEV_ID.$today.raw.log";
my $lastfile_template = "$datadir/ttn.DEV_ID.last.raw.status";
my $filledfile_template = "$datadir/ttn.DEV_ID.filled.time.status";
my $emptiedfile_template = "$datadir/ttn.DEV_ID.emptied.time.status";
# list and order of info rows in output
my @info_array = ('timeNow', 'deltaLastChanged', 'deltaLastReceived', 'timeLastReceived', 'timeLastFilled', 'timeLastEmptied', 'sensor', 'threshold', 'tempC', 'voltage', 'rssi', 'snr', 'counter', 'txpower', 'datarate', 'changed', 'period', 'hardwareSerial');
# definitions
my %dev_hash;
# translations
$translations{'timeNow'}->{'de'} = "Aktuelle Uhrzeit";
$translations{'deltaLastChanged'}->{'de'} = "Zeit seit letzter Änderung";
$translations{'deltaLastReceived'}->{'de'} = "Zeit seit letzter Übermittlung";
$translations{'timeLastReceived'}->{'de'} = "Uhrzeit der letzten Übermittlung";
$translations{'timeLastFilled'}->{'de'} = "Uhrzeit der letzten Füllung";
$translations{'timeLastEmptied'}->{'de'} = "Uhrzeit der letzten Leerung";
$translations{'letterbox'}->{'de'} = "Briefkasten";
$translations{'boxstatus'}->{'de'} = "Briefkasten-Status";
$translations{'status'}->{'de'} = "Status";
$translations{'EMPTY'}->{'de'} = "LEER";
$translations{'EMPTIED'}->{'de'} = "GELEERT";
$translations{'FILLED'}->{'de'} = "GEFÜLLT";
$translations{'FULL'}->{'de'} = "VOLL";
$translations{'hosted on'}->{'de'} = "bereitgestellt durch";
$translations{'redirect in'}->{'de'} = "weitergeleitet in";
$translations{'Letterbox Sensor Status'}->{'de'} = "Briefkasten Sensor Status";
$translations{'Reload'}->{'de'} = "Neu laden";
$translations{'Autoreload'}->{'de'} = "Autom neu laden";
$translations{'automatic refresh active every'}->{'de'} = "automatisches Auffrischen aktiv alle";
$translations{'seconds'}->{'de'} = "Sekunden";
$translations{'Graphics'}->{'de'} = "Grafik";
$translations{'hrs'}->{'de'} = "Std";
$translations{'mins'}->{'de'} = "Min";
$translations{'days'}->{'de'} = "Tage";
$translations{'More'}->{'de'} = "Mehr";
####################
## init hook
####################
for my $module (sort keys %hooks) {
if (defined $hooks{$module}->{'init'}) {
$hooks{$module}->{'init'}->();
};
};
###########
## START ##
###########
my @languageUserWants = I18N::LangTags::Detect::detect();
logging("accepted languages: " . join(" ", @languageUserWants)) if ($config{'debug'} > 0);
my %languages = map { $_ => 1 } @languagesSupported;
for my $l (@languageUserWants) {
$l =~ s/-.*//og; # cut everything behind "-"
logging("check language: " . $l) if ($config{'debug'} > 0);
if (defined($languages{$l})) {
$language = $l;
logging("selected language: " . $language) if ($config{'debug'} > 0);
last;
};
};
## detect mobile browers
if (defined $ENV{'HTTP_USER_AGENT'} && $ENV{'HTTP_USER_AGENT'} =~ /Mobile/) {
$mobile = 1;
};
## handle web request
if (defined $reqm && $reqm eq "POST") { # POST data
req_post();
exit;
} elsif (defined $reqm && $reqm eq "GET") { # GET request
# hook for authentication
for my $module (sort keys %hooks) {
if (defined $hooks{$module}->{'auth_check'}) {
$hooks{$module}->{'auth_check'}->();
};
};
req_get();
exit;
} elsif (defined $reqm && $reqm eq "HEAD") { # HEAD request
response(200, "OK");
exit;
} elsif (defined $reqm) { # not supported method
response(400, "unsupported request method", "", "request method: $reqm");
exit;
};
##############
##############
# Main functions
##############
##############
##############
# Hash functions
##############
## Generate (hardcoded SHA-512)
## returns salted SHA-512 hashed password
sub generate_salted_password($) {
my $plain = $_[0];
my $crypt;
if ($HAVE_Crypt_SaltedHash) {
my $csh = Crypt::SaltedHash->new(algorithm => 'SHA-512');
$csh->add($plain);
$crypt = $csh->generate;
} else {
# Fallback
my $ppr = Authen::Passphrase::SaltedDigest->new(algorithm => 'SHA-512', salt_random => 4, passphrase => $plain);
$crypt = "{SSHA512}" . MIME::Base64::encode_base64($ppr->hash . $ppr->salt, '')
};
return($crypt);
};
## Validate
# returns: 1->validated 0->nomatch
sub validate_salted_password($$) {
my $crypt = $_[0];
my $plain = $_[1];
if ($HAVE_Crypt_SaltedHash) {
if (Crypt::SaltedHash->validate($crypt, $plain)) {
return 1;
} else {
return 0;
};
} else {
# Fallback
if ($crypt !~ /^{SSHA512}(.*)$/o) {
die "validate_salted_password: crypt string contains unsupported hash method: $crypt";
};
$crypt = $1; # payload (Base64 encoded)
$crypt = MIME::Base64::decode_base64($crypt); # convert into binary
$crypt = unpack "H*", $crypt; # convert into hex string
# create object, hex encoded SHA512 has 128 chars
my $ppr = Authen::Passphrase::SaltedDigest->new(algorithm => 'SHA-512', salt_hex => substr($crypt, 128), hash_hex => substr($crypt, 0, 128));
# final validation
if ($ppr->match($plain)) {
return 1;
} else {
return 0;
};
};
};
##############
## query string parser
## default: QUERY_STRING,REDIRECT_QUERY_STRING,HTTP_X_TTN_LETTERBOX_QUERY_STRING
## optional: given querystring
## optional2: given hash to store
##############
sub parse_querystring(;$$) {
## simple query string parser
my $qs;
if (! defined $_[0]) {
$qs = $ENV{'QUERY_STRING'};
if (!defined $qs) {
# try from redirect
$qs = $ENV{'REDIRECT_QUERY_STRING'};
};
# append optional TTN_LETTERBOX_QUERY_STRING (e.g. provided by SSI/mod_include)
if (defined $ENV{'HTTP_X_TTN_LETTERBOX_QUERY_STRING'}) {
if (defined $qs && length($qs) > 0) {
$qs .= "&" . $ENV{'HTTP_X_TTN_LETTERBOX_QUERY_STRING'};
} else {
$qs = $ENV{'HTTP_X_TTN_LETTERBOX_QUERY_STRING'};
};
};
} else {
$qs = $_[0];
};
if (defined $qs) {
foreach my $query_stringlet (split /[\?\&]/, $qs) {
if ($query_stringlet !~ /^([[:alnum:]_\-]+)=([[:alnum:].\-:=\/\$%+_]+)$/o) {
# ignore improper stringlet
next;
};
if (defined $_[1]) {
$_[1]->{$1} = $2;
} else {
# store in global querystring hash
$querystring{$1} = $2;
};
};
};
};
##############
## handling POST request
##############
sub req_post() {
# receive POST data
my @lines;
while (<STDIN>) {
push @lines, $_;
};
if ($config{'debugmask'} & 0x1) {
logging("raw POST data: @lines");
};
# check contents
if (scalar(@lines) > 1) {
response(500, "too many lines received via POST request");
exit;
};
# hook for authentication
for my $module (sort keys %hooks) {
if (defined $hooks{$module}->{'auth_verify'}) {
# can stay in module or return if not responsible or only tweaking content
$hooks{$module}->{'auth_verify'}->($lines[0]);
};
};
# decode JSON
my $content = eval{ decode_json($lines[0])};
if ($@) {
response(500, "unsupported POST data", "", "POST request does not contain valid JSON content");
exit;
};
# extract & check dev_id
my $dev_id;
$dev_id = $content->{'end_device_ids'}->{'device_id'}; # v3 (default)
$dev_id = $content->{'dev_id'} if (! defined $dev_id); # v2 (fallback)
if (! defined $dev_id) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'dev_id' not found");
exit;
};
if ($dev_id !~ /^([a-zA-Z0-9-]+)$/o) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'dev_id' contains illegal chars");
exit;
};
$dev_id = $1; # to avoid complain in tainted mode
logging("POST/dev_id check passed: $dev_id") if ($config{'debug'} > 1);
# extract & check hardware_serial
my $hardware_serial;
$hardware_serial = $content->{'end_device_ids'}->{'dev_eui'}; # v3 (default)
$hardware_serial = $content->{'hardware_serial'} if (! defined $hardware_serial); # v2 (fallback)
if (! defined $hardware_serial) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'hardware_serial' not found");
exit;
};
if ($hardware_serial !~ /^([A-F0-9-]{16})$/o) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'hardware_serial' contains illegal chars/improper length");
exit;
};
logging("POST/hardware_serial check passed: $hardware_serial") if ($config{'debug'} > 1);
## check payload anchor in JSON
my $metadata;
$metadata = $content->{'uplink_message'}->{'rx_metadata'}[0]; # v3 (default)
$metadata = $content->{'metadata'}->{'gateways'}[0] if (! defined $metadata); # v2 (fallback)
if (! defined $metadata) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'metadata' (v2) or 'rx_metadata' (v3) not detected");
exit;
};
## check payload anchor in JSON
my $payload;
$payload = $content->{'uplink_message'}->{'decoded_payload'}; # v3 (default)
$payload = $content->{'payload_fields'} if (! defined $payload); # v2 (fallback)
if (! defined $payload) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but 'payload_fields' (v2) or 'decoded_payload' (v3) not detected");
exit;
};
## letterbox-sensor-v2 handling
# v2 has 2 sensors, highest value has precedence
if (defined $payload->{'sensor1'} && defined $payload->{'sensor2'}) {
$payload->{'sensor'} = $payload->{'sensor1'};
$payload->{'sensor'} = $payload->{'sensor2'} if $payload->{'sensor2'} > $payload->{'sensor1'};
logging("POST/payload 'sensor' aggregated from 'sensor1' & 'sensor2' (new capability of letterbox-sensor-v2)") if ($config{'debug'} > 1);
};
# v2 has no temperature sensor so far, preset with 0
if (!defined $payload->{'temp'}) {
logging("POST/payload 'temp' preset to 0 (missing support in letterbox-sensor-v2)") if ($config{'debug'} > 1);
$payload->{'temp'} = 0;
};
if (!defined $payload->{'tempC'}) {
logging("POST/payload 'temp' preset to 0 (missing support in letterbox-sensor-v2)") if ($config{'debug'} > 1);
$payload->{'tempC'} = 0;
};
for my $key (keys %payload_validator) {
if (!defined $payload->{$key}) {
if ($payload_validator{$key}->{'required'} == 1) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but required payload is missing '$key'");
exit;
} else {
next;
};
};
if ($payload->{$key} !~ /^$payload_validator{$key}->{'pattern'}$/) {
response(500, "unsupported POST data", "", "POST request does contain valid JSON but payload key '$key' contains invalid content '$payload->{$key}'");
exit;
};
};
logging("POST/payload check passed") if ($config{'debug'} > 1);
# get optional auth header
my $auth;
if (defined $ENV{'HTTP_X_TTN_AUTH'}) {
# check for illegal chars
if ($ENV{'HTTP_X_TTN_AUTH'} !~ /^([[:alnum:]\.\-\+%]+)$/o) {
response(500, "unsupported HTTP_X_TTN_AUTH header content", "", "HTTP_X_TTN_AUTH header contains illegal chars");
exit;
} else {
$auth = $1;
};
};
logging("POST/auth check passed") if ($config{'debug'} > 1);
# check for dev_id/hardware_serial in file
my $found = 0;
if (-e $devfile) {
open DEVF, '<', $devfile or die;
while (my $line = <DEVF>) {
chomp($line);
if ($line !~ /^([^:]+):([^:]+)(:.*)?$/o) {
next;
};
if (defined $1 && $1 eq $dev_id) {
# dev_id found
if (defined $2 && $2 eq $hardware_serial) {
if (defined $auth && defined $3) {
# password defined and given, crypt string is starting with : from regex above
if (validate_salted_password(substr($3, 1), $auth)) {
# password defined and given and match
$found = 1;
last;
} else {
response(403, "access denied", "", "POST request does contain valid JSON, dev_id=$dev_id/hardware_serial=$hardware_serial matching but required password is not matching");
exit;
};
} elsif (defined $3) {
# password defined but not given
response(403, "access denied", "", "POST request does contain valid JSON, dev_id=$dev_id/hardware_serial=$hardware_serial matching but no required password given");
exit;
} elsif (defined $auth) {
# password given but not defined
my $crypt = generate_salted_password($auth);
logging("request received with password, strongly recommend to replace entry in $devfile with $dev_id:$hardware_serial:" . $crypt);
$found = 1;
last;
} else {
# password neither given nor defined
$found = 1;
last;
};
} else {
response(403, "access denied", "", "POST request does contain valid JSON but dev_id=$dev_id/hardware_serial=$hardware_serial is not matching known one");
exit;
};
};
};
close DEVF;
} else {
if (defined $config{'autoregister'} && $config{'autoregister'} ne "1") {
response(403, "access denied", "", "POST request does contain valid JSON with dev_id=$dev_id/hardware_serial=$hardware_serial, autoregister is disabled and file missing: $devfile");
};
};
if ($found == 0) {
logging("POST/autoregister") if ($config{'debug'} > 1);
if (defined $config{'autoregister'} && $config{'autoregister'} eq "1") {
my $line = $dev_id . ":" . $hardware_serial;
if (defined $auth) {
$line .= ":" . generate_salted_password($auth);
};
# add to file
open DEVF, '>>', $devfile or die;
print DEVF $line . "\n";
close DEVF;
logging("new device registered: $dev_id:$hardware_serial");
} else {
response(403, "access denied", "", "POST request does contain valid JSON with dev_id=$dev_id/hardware_serial=$hardware_serial, but autoregister is disabled");
exit;
};
};
# fill with template
my $lastfile = $lastfile_template;
my $rawfile = $rawfile_template;
my $filledfile = $filledfile_template;
my $emptiedfile = $emptiedfile_template;
# replace placeholders
$lastfile =~ s/DEV_ID/$dev_id/g;
$rawfile =~ s/DEV_ID/$dev_id/g;
$filledfile =~ s/DEV_ID/$dev_id/g;
$emptiedfile =~ s/DEV_ID/$dev_id/g;
# empty/full toggle
my $emptiedtime_write = 0;
my $filledtime_write = 0;
if (defined $config{"threshold." . $dev_id}) {
# overwrite threshold if given
my $threshold = $config{"threshold." . $dev_id};
$payload->{'threshold'} = $threshold;
my $sensor = $payload->{'sensor'};
my $box = $payload->{'box'};
# overwrite box status with given threshold
if (($sensor < $threshold) && ($box =~ /^(full|filled)$/o)) {
$lines[0] =~ s/("box":)"(full|filled)"/$1"empty"/o; # adjust raw content
$payload->{'box'} = "empty";
} elsif (($sensor >= $threshold) && ($box =~ /^(empty|emptied)$/o)) {
$lines[0] =~ s/("box":)"(empty|emptied)"/$1"full"/o; # adjust raw content
$payload->{'box'} = "full";
};
};
# init in case of lastfilled/lastemptied is missing
if ($payload->{'box'} =~ /^(full|filled)$/o) {
if (! -e $filledfile) {
$filledtime_write = 1;
};
};
if ($payload->{'box'} =~ /^(empty|emptied)$/o) {
if (! -e $emptiedfile) {
$emptiedtime_write = 1;
};
};
## state adjustments empty->filled->full->emptied->empty
if (-e $filledfile && -e $emptiedfile) {
# files are existing, retrieve contents
open FILLEDF, "<", $filledfile or die;
my $filledtime_ut = str2time(<FILLEDF>);
close FILLEDF;
open EMPTIEDF, "<", $emptiedfile or die;
my $emptiedtime_ut = str2time(<EMPTIEDF>);
close EMPTIEDF;
if ($payload->{'box'} eq "filled") {
# support for future
$filledtime_write = 1;
} elsif ($payload->{'box'} eq "emptied") {
# support for future
$emptiedtime_write = 1;
} elsif ($payload->{'box'} eq "full") {
# box is full
if ($filledtime_ut < $emptiedtime_ut) {
# box was empty last time
$filledtime_write = 1;
# adjust status
$lines[0] =~ s/("box":)"full"/$1"filled"/o; # adjust raw content
$payload->{'box'} = "filled";
};
} elsif ($payload->{'box'} eq "empty") {
# box is empty
if ($emptiedtime_ut < $filledtime_ut) {
# box was full last time
$emptiedtime_write = 1;
# adjust status
$lines[0] =~ s/("box":)"empty"/$1"emptied"/o; # adjust raw content
$payload->{'box'} = "emptied";
};
};
};
if ($filledtime_write == 1) {
open FILLEDF, ">", $filledfile or die;
print FILLEDF $nowstr;
close FILLEDF;
};
if ($emptiedtime_write == 1) {
open EMPTIEDF, ">", $emptiedfile or die;
print EMPTIEDF $nowstr;
close EMPTIEDF;
};
## write contents to files
# last status
open LASTF, ">", $lastfile or die;
print LASTF $nowstr . " ";
print LASTF $lines[0] . "\n";
close LASTF;
# log
open LOGF, ">>", $rawfile or die;
print LOGF $nowstr . " ";
print LOGF $lines[0] . "\n";
close LOGF;
# preparation for features
if (defined $features{'notify'}) {
# read notification list
if (! -e $notifyfile) {
logging("notification feature supported, but UNSUABLE, config file is not existing: " . $notifyfile);
# file is not existing, not that critical
} else {
if (open NOTIFYF, '<', $notifyfile) {
while (my $line = <NOTIFYF>) {
chomp($line);
if ($line !~ /^([^:]+):([^:]+)$/o) {
next;
};
if (defined $1 && $1 eq $dev_id) {
# dev_id found
if (defined $2) {
#logging("notification feature supported and ENABLED for $dev_id: $2");
@notify_list = split(/,/, $2);
};
};
};
close NOTIFYF;
} else {
logging("notification feature supported but UNUSABLE, config file is existing, but can't be read: " . $notifyfile);
};
};
};
logging("POST/main finished, call now modules") if ($config{'debug'} > 1);
####################
for my $module (sort keys %hooks) {
if (defined $hooks{$module}->{'init_device'}) {
logging("POST/call now module/init_device: $module") if ($config{'debug'} > 1);
$hooks{$module}->{'init_device'}->($dev_id);
};
};
####################
for my $module (sort keys %hooks) {
if (defined $hooks{$module}->{'store_data'}) {
logging("POST/call now module/store_data: $module") if ($config{'debug'} > 1);
$hooks{$module}->{'store_data'}->($dev_id, $nowstr, $content);
};
};
response(200, "OK");
};
##############
## handling GET request
##############
sub req_get() {
parse_querystring();
my @devices;
if (-e $devfile) {
# read devices
open DEVF, '<', $devfile or die;
while (my $line = <DEVF>) {
push @devices, $line;
};
close DEVF;
} else {
response(500, "no devices seen so far", "", "file not existing: $devfile");
exit;
};
if (scalar(@devices) == 0) {
response(500, "no devices seen so far", "", "file empty: $devfile");
exit;
};
for my $line (@devices) {
chomp($line);