-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
recorder.c
2184 lines (1864 loc) · 55.8 KB
/
recorder.c
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
/*
* OwnTracks Recorder
* Copyright (C) 2015-2024 Jan-Piet Mens <jpmens@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#if WITH_MQTT
# include <mosquitto.h>
#endif
#include <getopt.h>
#include <time.h>
#include <math.h>
#include "json.h"
#include <sys/utsname.h>
#include <regex.h>
#include "recorder.h"
#include "udata.h"
#include "utstring.h"
#include "geo.h"
#include "geohash.h"
#include "base64.h"
#include "misc.h"
#include "util.h"
#include "storage.h"
#include "fences.h"
#include "gcache.h"
#ifdef WITH_HTTP
# include "http.h"
#endif
#ifdef WITH_LUA
# include "hooks.h"
#endif
#if WITH_ENCRYPT
# include <sodium.h>
#endif
#include "version.h"
#include <dirent.h>
#define SSL_VERIFY_PEER (1)
#define SSL_VERIFY_NONE (0)
#define TOPIC_PARTS (4) /* owntracks/user/device/info */
#define DEFAULT_QOS (2)
#define CLEAN_SESSION false
#define GWNUMBERSMAX 50 /* number of batt,ext,status in array */
static int run = 1;
static const char *ltime(time_t t) {
static char buf[] = "HH:MM:SS";
strftime(buf, sizeof(buf), "%T", localtime(&t));
return(buf);
}
/*
* Process info/ message containing a CARD. If the payload is a card, return TRUE.
*/
int do_info(void *userdata, UT_string *username, UT_string *device, JsonNode *json)
{
struct udata *ud = (struct udata *)userdata;
JsonNode *j;
static UT_string *name = NULL, *face = NULL;
FILE *fp;
char *img;
int rc = FALSE;
size_t imglen;
utstring_renew(name);
utstring_renew(face);
/* I know the payload is valid JSON: write card */
if ((fp = pathn("wb", "cards", username, device, "json", time(0))) != NULL) {
char *js = json_stringify(json, NULL);
if (js) {
fprintf(fp, "%s\n", js);
free(js);
}
fclose(fp);
}
rc = TRUE;
if ((j = json_find_member(json, "name")) != NULL) {
if (j->tag == JSON_STRING) {
// printf("I got: [%s]\n", j->string_);
utstring_printf(name, "%s", j->string_);
}
}
if ((j = json_find_member(json, "face")) != NULL) {
if (j->tag == JSON_STRING) {
// printf("I got: [%s]\n", j->string_);
utstring_printf(face, "%s", j->string_);
}
}
if (ud->verbose) {
printf("* CARD: %s-%s %s\n", UB(username), UB(device), UB(name));
}
/* We have a base64-encoded "face". Decode it and store binary image */
if ((img = base64_decode(UB(face), &imglen)) != NULL) {
if ((fp = pathn("wb", "photos", username, device, "png", time(0))) != NULL) {
fwrite(img, sizeof(char), imglen, fp);
fclose(fp);
}
free(img);
}
return (rc);
}
/*
* Handle inline images: extract the base64-encoded image, decode and store in
* file. Remove the `image' element from the JSON (it's very large) and write
* the remaining elements into a .json file adjacent to the actual image file.
*/
int do_image(void *userdata, UT_string *username, UT_string *device, JsonNode *json)
{
struct udata *ud = (struct udata *)userdata;
JsonNode *j;
if ((j = json_find_member(json, "image")) != NULL) {
if (j->tag == JSON_STRING) {
char *b64 = j->string_;
size_t imglen = strlen(b64);
unsigned char *img;
FILE *fp;
time_t tics = time(0);
if ((img = base64_decode(b64, &imglen)) == NULL) {
olog(LOG_ERR, "Cannot decode image base64");
return false;
}
if ((fp = pathn("wb", "images", username, device, "jpg", tics)) != NULL) {
fwrite(img, sizeof(char), imglen, fp);
fclose(fp);
}
/* Delete image data element and write remaining as JSON */
if ((fp = pathn("wb", "images", username, device, "json", tics)) != NULL) {
if ((j = json_find_member(json, "image")) != NULL) {
json_delete(j);
char *js = json_stringify(json, " ");
if (js) {
fprintf(fp, "%s\n", js);
free(js);
}
fclose(fp);
}
}
}
}
if (ud->verbose) {
if ((j = json_find_member(json, "imageName")) != NULL) {
if (j->tag == JSON_STRING) {
printf("* IMAGE: %s-%s %s\n", UB(username), UB(device), j->string_);
}
}
}
return true;
}
#ifdef WITH_MQTT
void publish(struct udata *userdata, char *topic, char *payload)
{
struct udata *ud = (struct udata *)userdata;
int qos = 2;
mosquitto_publish(ud->mosq, NULL, topic, strlen(payload), payload, qos, false);
}
void republish(struct mosquitto *mosq, struct udata *userdata, char *username, char *topic, double lat, double lon, char *cc, char *addr, long tst, char *t)
{
struct udata *ud = (struct udata *)userdata;
JsonNode *json;
static UT_string *newtopic = NULL;
char *payload;
if (ud->pubprefix == NULL)
return;
if ((json = json_mkobject()) == NULL) {
return;
}
utstring_renew(newtopic);
utstring_printf(newtopic, "%s/%s", ud->pubprefix, topic);
json_append_member(json, "username", json_mkstring(username));
json_append_member(json, "topic", json_mkstring(topic));
json_append_member(json, "cc", json_mkstring(cc));
json_append_member(json, "addr", json_mkstring(addr));
json_append_member(json, "t", json_mkstring(t));
json_append_member(json, "tst", json_mknumber(tst));
json_append_member(json, "lat", json_mknumber(lat));
json_append_member(json, "lon", json_mknumber(lon));
if ((payload = json_stringify(json, NULL)) != NULL) {
mosquitto_publish(mosq, NULL, UB(newtopic),
strlen(payload), payload, 1, true);
fprintf(stderr, "%s %s\n", UB(newtopic), payload);
free(payload);
}
json_delete(json);
}
#endif /* WITH_MQTT */
/*
* Quickly check wheterh the payload looks like
* Greenwich CSV with a regex. We could use this
* to split out the fields, instead of reverting
* to sscanf
*/
// TID , TST , T , LAT , LON , COG , VEL , ALT , DIST , TRIP
#define CSV_RE "^([[:alnum:]]+),([[:xdigit:]]+),[[:alnum:]],-?[[:digit:]]+,-?[[:digit:]]+,[[:digit:]]+,[[:digit:]]+,[[:digit:]]+,[[:digit:]]+,[[:digit:]]+$"
static int csv_looks_sane(char *payload)
{
static int virgin = 1;
static regex_t regex;
int nomatch;
int cflags = REG_EXTENDED | REG_ICASE | REG_NOSUB;
if (virgin) {
virgin = !virgin;
if (regcomp(®ex, CSV_RE, cflags)) {
olog(LOG_ERR, "Cannot compile CSV RE");
return (FALSE);
}
}
nomatch = regexec(®ex, payload, 0, NULL, 0);
return (nomatch ? FALSE : TRUE);
}
/*
* Decode OwnTracks CSV (Greenwich) and return a new JSON object
* of _type = location.
* #define CSV "X0,542A46AA,k,30365854,7575769,26,4,7,5,872"
*/
#define MILL 1000000.0
JsonNode *csv_to_json(char *payload)
{
JsonNode *json;
char tid[64], t[10];
double dist = 0, lat, lon, vel, trip, alt, cog;
long tst;
char tmptst[40];
if (!csv_looks_sane(payload))
return (NULL);
if (sscanf(payload, "%[^,],%[^,],%[^,],%lf,%lf,%lf,%lf,%lf,%lf,%lf", tid, tmptst, t, &lat, &lon, &cog, &vel, &alt, &dist, &trip) != 10) {
// fprintf(stderr, "**** payload not CSV: %s\n", payload);
return (NULL);
}
lat /= MILL;
lon /= MILL;
cog *= 10;
alt *= 10;
trip *= 1000;
tst = strtoul(tmptst, NULL, 16);
json = json_mkobject();
json_append_member(json, "_type", json_mkstring("location"));
json_append_member(json, "t", json_mkstring(t));
json_append_member(json, "tid", json_mkstring(tid));
json_append_member(json, "tst", json_mknumber(tst));
json_append_member(json, "lat", json_mknumber(lat));
json_append_member(json, "lon", json_mknumber(lon));
json_append_member(json, "cog", json_mknumber(cog));
json_append_member(json, "vel", json_mknumber(vel));
json_append_member(json, "alt", json_mknumber(alt));
json_append_member(json, "dist", json_mknumber(dist));
json_append_member(json, "trip", json_mknumber(trip));
json_append_member(json, "csv", json_mkbool(1));
return (json);
}
#define RECFORMAT "%s\t%-18s\t%s\n"
/*
* Store payload in REC file. Use the epoch
* time to construct path name and "key"
*/
static void putrec(struct udata *ud, time_t epoch, UT_string *reltopic, UT_string *username, UT_string *device, char *string)
{
FILE *fp;
if (ud->norec)
return;
if ((fp = pathn("a", "rec", username, device, "rec", epoch)) == NULL) {
olog(LOG_ERR, "Cannot write REC for %s/%s: %m",
UB(username), UB(device));
return;
}
/*
* `string' might contain JSON, and it might be such that is
* contains newlines, etc. We have to sanitize if so else the
* .rec file will become unparseable.
*/
if (strchr(string, '\n') != 0 || strchr(string, '\t') != 0) {
JsonNode *j;
char *js = NULL;
if ((j = json_decode(string)) != NULL) {
js = json_stringify(j, NULL);
fprintf(stderr, "JPJPJP: [%s]\n", js);
fprintf(fp, RECFORMAT, isotime(epoch),
UB(reltopic), js);
free(js);
json_delete(j);
}
} else {
fprintf(fp, RECFORMAT, isotime(epoch),
UB(reltopic), string);
}
fclose(fp);
}
/*
* Payload contains JSON string with a configuration obtained
* via cmd `dump' to the device. Store it "pretty".
*/
static char *prettyfy(char *payloadstring)
{
JsonNode *json;
char *pretty_js;
if ((json = json_decode(payloadstring)) == NULL) {
olog(LOG_ERR, "Cannot decode JSON from %s", payloadstring);
return (NULL);
}
pretty_js = json_stringify(json, "\t");
json_delete(json);
return (pretty_js);
}
static void xx_dump(struct udata *ud, UT_string *username, UT_string *device, char *payloadstring, char *type, char *extension)
{
static UT_string *ts = NULL, *u = NULL, *d = NULL;
char *pretty_js = prettyfy(payloadstring);
utstring_renew(ts);
/* Ensure user / devicename are lowercased */
utstring_renew(u);
utstring_renew(d);
utstring_printf(u, "%s", UB(username));
utstring_printf(d, "%s", UB(device));
lowercase(UB(u));
lowercase(UB(d));
utstring_printf(ts, "%s/%s/%s/%s",
STORAGEDIR,
type,
UB(u),
UB(d));
if (mkpath(UB(ts)) < 0) {
olog(LOG_ERR, "Cannot mkdir %s: %m", UB(ts));
if (pretty_js) free(pretty_js);
return;
}
utstring_printf(ts, "/%s-%s.%s", UB(u), UB(d), extension);
if (ud->verbose) {
printf("Received %s dump, storing at %s\n", type, UB(ts));
}
safewrite(UB(ts), (pretty_js) ? pretty_js : payloadstring);
if (pretty_js) free(pretty_js);
}
/* Dump a config payload; get the 'configuration' element out of the dumped payloadstring */
void config_dump(struct udata *ud, UT_string *username, UT_string *device, char *payloadstring)
{
JsonNode *json = json_decode(payloadstring), *config;
if (json == NULL)
return;
if ((config = json_find_member(json, "configuration")) != NULL) {
char *js_string = json_stringify(config, NULL);
if (js_string) {
xx_dump(ud, username, device, js_string, "config", "otrc");
json_delete(json);
free(js_string);
}
}
}
/* Dump a waypoints (plural) payload */
void waypoints_dump(struct udata *ud, UT_string *username, UT_string *device, char *payloadstring)
{
JsonNode *json = json_decode(payloadstring), *j;
char *js = NULL;
if (json == NULL)
return;
if ((j = json_find_member(json, "r")) != NULL) {
json_delete(j);
js = json_stringify(json, NULL);
json_delete(json);
}
xx_dump(ud, username, device, (js) ? js : payloadstring, "waypoints", "otrw");
load_otrw_from_string(ud, UB(username), UB(device), (js) ? js : payloadstring);
if (js)
free(js);
}
#ifdef WITH_TOURS
static char *elem(JsonNode *json, char *e)
{
JsonNode *j;
char *val = "-";
if ((j = json_find_member(json, e)) != NULL) {
if (j->tag == JSON_STRING) {
val = j->string_;
}
}
return (val);
}
# endif /* WITH_TOURS */
#ifdef WITH_TOURS
void do_request(struct udata *ud, UT_string *username, UT_string *device, char *payloadstring, bool httpmode, JsonNode **jnode)
{
JsonNode *json = json_decode(payloadstring), *j, *r, *resp;
char *request_type = NULL, *js;
static UT_string *url, *fulltopic;
static int virgin = 1;
static regex_t regex;
int cflags = REG_EXTENDED | REG_ICASE | REG_NOSUB;
if (json == NULL)
return;
utstring_renew(url);
utstring_renew(fulltopic);
utstring_printf(fulltopic, "owntracks/%s/%s/cmd", UB(username), UB(device));
if ((js = json_stringify(json, NULL)) != NULL) {
olog(LOG_DEBUG, "do_request gets: %s", js);
free(js);
}
// 3d9d97d4-a27e-4cd1-842f-6bf51c18a5c2.json
#define UUID_RE "^([[:alnum:]]{8})-([[:alnum:]]{4})-([[:alnum:]]{4})-([[:alnum:]]{4})-([[:alnum:]]{12})\\.json"
if (virgin) {
virgin = !virgin;
if (regcomp(®ex, UUID_RE, cflags)) {
olog(LOG_ERR, "Cannot compile UUID RE");
return;
}
}
if ((j = json_find_member(json, "request")) != NULL) {
if (j->tag != JSON_STRING) {
json_delete(json);
return;
}
request_type = j->string_;
}
if (strcmp(request_type, "tour") == 0) {
FILE *fp;
char path[BUFSIZ];
if ((r = json_find_member(json, "tour")) == NULL) {
return;
}
char *uuid = uuid4();
utstring_printf(url, "%s/view/%s",
ud->http_prefix ? ud->http_prefix : "OTR_HTTPPREFIX",
uuid);
JsonNode *o = json_mkobject();
json_append_member(o, "page", json_mkstring("leafletmap.html"));
json_append_member(o, "user", json_mkstring(UB(username)));
json_append_member(o, "device", json_mkstring(UB(device)));
json_append_member(o, "label", json_mkstring(elem(r, "label")));
json_append_member(o, "zoom", json_mknumber(6));
json_append_member(o, "from", json_mkstring(elem(r, "from")));
json_append_member(o, "to", json_mkstring(elem(r, "to")));
json_append_member(o, "uuid", json_mkstring(uuid));
json_append_member(o, "url", json_mkstring(UB(url)));
snprintf(path, sizeof(path), "%s.json", uuid);
if ((fp = tourfile(ud, path, "w")) != NULL) {
char *js = json_stringify(o, " ");
fprintf(fp, "%s\n", js);
free(js);
fclose(fp);
} else {
olog(LOG_ERR, "Can't create tour at %s: %m", path);
json_delete(o);
return;
}
json_delete(o);
resp = json_mkobject();
json_append_member(resp, "_type", json_mkstring("cmd"));
json_append_member(resp, "action", json_mkstring("response"));
json_append_member(resp, "request", json_mkstring("tour"));
json_append_member(resp, "status", json_mknumber(200));
JsonNode *nt = json_mkobject();
json_copy_to_object(nt, r, false);
json_append_member(nt, "uuid", json_mkstring(uuid));
json_append_member(nt, "url", json_mkstring(UB(url)));
json_append_member(resp, "tour", nt);
if (httpmode) {
*jnode = resp; // caller will delete `resp'
return;
}
#ifdef WITH_MQTT
if ((js = json_stringify(resp, NULL)) != NULL) {
publish(ud, UB(fulltopic), js);
free(js);
}
#endif
json_delete(resp);
} else if (strcmp(request_type, "tours") == 0) {
JsonNode *arr, *o;
char path[BUFSIZ];
DIR *dirp;
struct dirent *dp;
int nomatch, ntour = 0;
resp = json_mkobject();
json_append_member(resp, "_type", json_mkstring("cmd"));
json_append_member(resp, "action", json_mkstring("response"));
json_append_member(resp, "request", json_mkstring("tours"));
arr = json_mkarray();
if ((dirp = opendir(toursdir())) != NULL) {
while ((dp = readdir(dirp)) != NULL) {
char *fn = dp->d_name;
if (dp->d_type != DT_REG)
continue;
nomatch = regexec(®ex, fn, 0, NULL, 0);
if (nomatch)
continue;
o = json_mkobject();
snprintf(path, sizeof(path), "%s/%s", toursdir(), fn);
if (json_copy_from_file(o, path) == false) {
olog(LOG_ERR, "Can't copy JSON from %s", path);
json_delete(o);
continue;
}
if (strcasecmp(elem(o, "user"), UB(username)) != 0 ||
strcasecmp(elem(o, "device"), UB(device)) != 0) {
olog(LOG_DEBUG, "Skipping %s: owner mismatch", path);
json_delete(o);
continue;
}
json_append_element(arr, o);
++ntour;
}
closedir(dirp);
} else {
perror(ud->viewsdir);
}
json_append_member(resp, "tours", arr);
json_append_member(resp, "ntours", json_mknumber(ntour));
olog(LOG_DEBUG, "Returning ntours=%d for %s/%s", ntour, UB(username), UB(device));
if (httpmode) {
*jnode = resp; // caller will delete `resp'
return;
}
#ifdef WITH_MQTT
if ((js = json_stringify(resp, NULL)) != NULL) {
publish(ud, UB(fulltopic), js);
free(js);
}
#endif
json_delete(resp);
} else if (strcmp(request_type, "untour") == 0) {
JsonNode *r, *o;
char path[BUFSIZ], *uuid;
if ((r = json_find_member(json, "uuid")) == NULL) {
fprintf(stderr, "No uuid in untour request\n");
return;
}
uuid = r->string_;
olog(LOG_DEBUG, "Untour %s for %s/%s", uuid, UB(username), UB(device));
snprintf(path, sizeof(path), "%s/%s.json", toursdir(), uuid);
if (access(path, R_OK) < 0) {
olog(LOG_ERR, "Can't find tour %s: %m", uuid);
json_delete(r);
return;
}
o = json_mkobject();
snprintf(path, sizeof(path), "%s/%s.json", toursdir(), uuid);
if (json_copy_from_file(o, path) == false) {
olog(LOG_ERR, "Can't copy JSON from %s", path);
json_delete(o);
json_delete(r);
return;
}
if (strcasecmp(elem(o, "user"), UB(username)) != 0 ||
strcasecmp(elem(o, "device"), UB(device)) != 0) {
olog(LOG_DEBUG, "Skipping %s: owner mismatch", uuid);
json_delete(o);
return;
}
if (remove(path) != 0) {
olog(LOG_ERR, "Can't delete tour %s: %m", r->string_);
}
json_delete(r);
}
}
#endif /* WITH_TOURS */
#if WITH_ENCRYPT
/*
* Decrypt the payload and return a pointer to allocated space containing
* the clear text.
* p64 contains the base64-encoded, encrypted payload from the device. `username'
* and `device' are needed to obtain the decryption key for this object.
*/
unsigned char *decrypt(struct udata *ud, char *topic, char *p64, char *username, char *device)
{
unsigned char key[crypto_secretbox_KEYBYTES];
unsigned char *ciphertext, *cleartext;
size_t ciphertext_len;
int n, klen;
static UT_string *userdev = NULL;
utstring_renew(userdev);
utstring_printf(userdev, "%s-%s", username, device);
lowercase(UB(userdev));
for (n = 0; n < strlen(UB(userdev)); n++) {
if (UB(userdev)[n] == ' ')
UB(userdev)[n] = '-';
}
memset(key, 0, sizeof(key));
klen = gcache_get(ud->keydb, (char *)UB(userdev), (char *)key, sizeof(key));
if (klen < 1) {
olog(LOG_ERR, "no decryption key for %s in %s", UB(userdev), topic);
return (NULL);
}
debug(ud, "Key for %s is [%s]", UB(userdev), key);
n = strlen(p64); /* This is more than enough */
if ((ciphertext = base64_decode(p64, &ciphertext_len)) == NULL) {
olog(LOG_ERR, "payload of %s cannot be base64-decoded", topic);
return (NULL);
}
debug(ud, "START DECRYPT. clen==%lu", ciphertext_len);
if ((cleartext = calloc(n, sizeof(unsigned char))) == NULL) {
free(ciphertext);
return (NULL);
}
if (crypto_secretbox_open_easy(cleartext, // message
ciphertext + crypto_secretbox_NONCEBYTES, // skip over nonce
ciphertext_len - crypto_secretbox_NONCEBYTES, // len (- nonce)
ciphertext, // nonce
key) != 0)
{
olog(LOG_ERR, "payload of %s cannot be decrypted; forged?", topic);
free(ciphertext);
free(cleartext);
return (NULL);
}
debug(ud, "DECRYPTED: %s", (char *)cleartext);
free(ciphertext);
return (cleartext);
}
#endif /* ENCRYPT */
static bool is_newer_than_last(JsonNode *json)
{
bool is_newer = true;
JsonNode *last_array;
JsonNode *fields = json_mkarray();
json_append_element(fields, json_mkstring("tst"));
JsonNode *usernode = json_find_member(json, "username");
JsonNode *devicenode = json_find_member(json, "device");
if (usernode != NULL && devicenode != NULL) {
if ((last_array = last_users(usernode->string_, devicenode->string_, fields)) != NULL) {
JsonNode *lastrec = json_first_child(last_array);
if (lastrec != NULL) {
JsonNode *tst = json_find_member(lastrec, "tst");
if (tst != NULL) {
double last = number(lastrec, "tst");
double current = number(json, "tst");
is_newer = last < current;
}
}
json_delete(last_array);
}
}
json_delete(fields);
return is_newer;
}
/*
* if `jnode' will be set to a JsonNode object with results added to the
* outgoing HTTP payload; the caller (in http.c) will delete the object
* when it returns the payload to the client.
*/
void handle_message(void *userdata, char *topic, char *payload, size_t payloadlen, int retain, int httpmode, int was_encrypted, JsonNode **jnode)
{
JsonNode *json, *j, *geo = NULL;
char *tid = NULL, *t = NULL, *p;
double lat, lon, acc;
long tst;
struct udata *ud = (struct udata *)userdata;
char *topics[42];
int count = 0;
bool cached, fresh;
static UT_string *basetopic = NULL, *username = NULL, *device = NULL, *addr = NULL, *cc = NULL, *ghash = NULL, *ts = NULL;
static UT_string *reltopic = NULL, *filename = NULL;
char *jsonstring, *_typestr = NULL, *dumpedpayload = NULL;
time_t now, epoch;
int pingping = FALSE, skipslash = 0, geoprec = geohash_prec();
int r_ok = TRUE; /* True if recording enabled for a publish */
payload_type _type;
/*
* mosquitto_message->
* int mid;
* char *topic;
* void *payload;
* int payloadlen;
* int qos;
* bool retain;
*/
time(&now);
monitorhook(ud, now, topic);
chomp(payload);
debug(ud, "%s (plen=%d, r=%d) [%s]", topic, payloadlen, retain, payload);
if (payloadlen == 0) {
return;
}
if (retain == TRUE && ud->ignoreretained) {
return;
}
// printf("%s %s\n", m->topic, bindump(m->payload, m->payloadlen)); fflush(stdout);
utstring_renew(ts);
utstring_renew(basetopic);
utstring_renew(username);
utstring_renew(device);
if ((count = splitter(topic, "/", topics)) == -1) {
return;
}
/*
* Do we have a leading / in topic?
* Also, if topic is too short, ignore and return. We *demand* 3 parts
* i.e. "owntracks/user/device"
*/
if (topics[0] == NULL) {
/* Topic has leading / */
skipslash = 1;
}
if (count - skipslash < 3) {
fprintf(stderr, "Ignoring short topic %s\n", topic);
splitterfree(topics);
return;
}
/*
* Determine "relative topic", relative to base, i.e. whatever comes
* behind owntracks/user/device/. If it's the base topic, use "*".
*/
utstring_renew(reltopic);
if (count != (3 + skipslash)) {
int j;
for (j = 3 + skipslash; j < count; j++) {
utstring_printf(reltopic, "%s%c", topics[j], (j < count - 1) ? '/' : 0);
}
} else {
utstring_printf(reltopic, "*");
}
if (utstring_len(reltopic) == 0)
utstring_printf(reltopic, "-");
/*
* Are we handing ../user/device/pico from OwnTracks Pico / Homie?
* Pretend we have a base-topic publish, so change "/pico" to "*"
*/
if ( (count == (4 + skipslash)) && (strcmp(UB(reltopic), "pico") == 0)) {
utstring_renew(reltopic);
utstring_printf(reltopic, "*");
}
utstring_printf(basetopic, "%s/%s/%s", topics[0 + skipslash], topics[1 + skipslash], topics[2 + skipslash]);
utstring_printf(username, "%s", topics[1 + skipslash]);
utstring_printf(device, "%s", topics[2 + skipslash]);
#ifdef WITH_PING
if (!strcmp(UB(username), "ping") && !strcmp(UB(device), "ping")) {
pingping = TRUE;
}
#endif
splitterfree(topics);
/*
* Now let's see if this contains some sort of valid JSON
* or an OwnTracks CSV. If it doesn't, just store this payload because
* there's nothing left for us to do with it.
*/
if ((json = json_decode(payload)) == NULL) {
if ((json = csv_to_json(payload)) == NULL) {
dumpedpayload = bindump(payload, payloadlen);
/* It's not JSON or it's not a location CSV; store it using
* now as time -- we have no other */
#ifdef WITH_LUA
r_ok = hooks_norec(ud, UB(username), UB(device), dumpedpayload) == 0;
#endif
if (r_ok) {
putrec(ud, now, reltopic, username, device, dumpedpayload);
}
return;
}
}
if (ud->skipdemo && (json_find_member(json, "_demo") != NULL)) {
json_delete(json);
return;
}
_type = T_UNKNOWN;
if ((j = json_find_member(json, "_type")) != NULL) {
if (j->tag == JSON_STRING) {
_typestr = strdup(j->string_);
if (!strcmp(j->string_, "location")) _type = T_LOCATION;
else if (!strcmp(j->string_, "beacon")) _type = T_BEACON;
else if (!strcmp(j->string_, "card")) _type = T_CARD;
else if (!strcmp(j->string_, "cmd")) _type = T_CMD;
else if (!strcmp(j->string_, "image")) _type = T_IMAGE;
else if (!strcmp(j->string_, "lwt")) _type = T_LWT;
else if (!strcmp(j->string_, "steps")) _type = T_STEPS;
else if (!strcmp(j->string_, "status")) _type = T_STATUS;
else if (!strcmp(j->string_, "transition")) _type = T_TRANSITION;
else if (!strcmp(j->string_, "waypoint")) _type = T_WAYPOINT;
else if (!strcmp(j->string_, "waypoints")) _type = T_WAYPOINTS;
else if (!strcmp(j->string_, "dump")) _type = T_CONFIG;
#ifdef WITH_TOURS
else if (!strcmp(j->string_, "request")) _type = T_REQUEST;
#endif /* WITH_TOURS */
#if WITH_ENCRYPT
else if (!strcmp(j->string_, "encrypted")) _type = T_ENCRYPTED;
#endif /* WITH_ENCRYPT */
}
}
switch (_type) {
case T_CARD:
do_info(ud, username, device, json);
goto cleanup;
case T_BEACON:
dumpedpayload = bindump(payload, payloadlen);
#ifdef WITH_LUA
r_ok = hooks_norec(ud, UB(username), UB(device), dumpedpayload) == 0;
#endif
if (!r_ok) {
goto cleanup;
}
#ifdef WITH_HTTP
if (ud->mgserver && !pingping) {
json_append_member(json, "topic", json_mkstring(topic));
json_append_member(json, "username", json_mkstring(UB(username)));
json_append_member(json, "device", json_mkstring(UB(device)));
http_ws_push_json(ud->mgserver, json);
}
#endif
putrec(ud, now, reltopic, username, device, dumpedpayload);
goto cleanup;
case T_LWT:
/*
* LWT gets a pseudo-reltopic called 'lwt'; reason: if we keep the
* empty original reltopic, it would become '*' in the .rec file
* which confuses the recorder when serving location data.
* Also, this appears to be sensible, and it probably should have
* been that way all along in the apps.
*/
utstring_clear(reltopic);
utstring_printf(reltopic, "lwt");
/* Fall through */
case T_CMD:
case T_STEPS:
#ifdef WITH_LUA
r_ok = hooks_norec(ud, UB(username), UB(device), payload) == 0;
#endif
if (r_ok) {
putrec(ud, now, reltopic, username, device, payload);
}