-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
storage.c
1752 lines (1449 loc) · 43.8 KB
/
storage.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 <[email protected]>
*
* 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.
*/
#define __USE_XOPEN 1
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <fnmatch.h>
#include <unistd.h>
#include <glob.h>
#include <ctype.h>
#include <assert.h>
#include <sys/stat.h>
#include "utstring.h"
#include "storage.h"
#include "geohash.h"
#include "fences.h"
#include "gcache.h"
#include "util.h"
#include "listsort.h"
char STORAGEDIR[BUFSIZ] = STORAGEDEFAULT;
#define LINESIZE 8192
#define LARGEBUF (BUFSIZ * 2)
static struct gcache *gc = NULL;
#ifdef WITH_TZ
# include "zonedetect.h"
static ZoneDetect *zdb = NULL;
#endif
void storage_init(int revgeo)
{
setenv("TZ", "UTC", 1);
if (revgeo) {
char path[LARGEBUF];
snprintf(path, LARGEBUF, "%s/ghash", STORAGEDIR);
gc = gcache_open(path, NULL, TRUE);
if (gc == NULL) {
olog(LOG_ERR, "storage_init(): gc is NULL");
}
}
#ifdef WITH_TZ
if (zdb == NULL) {
zdb = ZDOpenDatabase(TZDATADB);
}
#endif
}
void storage_gcache_dump(char *lmdbname)
{
char path[LARGEBUF];
snprintf(path, LARGEBUF, "%s/ghash", STORAGEDIR);
gcache_dump(path, lmdbname);
}
void storage_gcache_load(char *lmdbname)
{
char path[LARGEBUF];
snprintf(path, LARGEBUF, "%s/ghash", STORAGEDIR);
gcache_load(path, lmdbname);
}
/*
* Adjust seconds obtained via mktime() to offset from the last
* timezone we set. This fixes time to what GMT time is without
* actually knowing what the local $TZ is. We do this to avoid
* switching $TZ back and forth from UTC to whatever tzname
* a location has, a very expensive operation.
*/
time_t local2gmt(time_t tlocal) {
struct tm *tm;
time_t gm_tics;
tm = localtime(&tlocal);
gm_tics = tlocal + tm->tm_gmtoff;
return gm_tics;
}
static char * my_strptime(const char * restrict buf, const char * restrict format,
struct tm * restrict timeptr)
{
return strptime(buf, format, timeptr);
}
void get_geo(JsonNode *o, char *ghash)
{
JsonNode *geo;
if ((geo = gcache_json_get(gc, ghash)) != NULL) {
json_copy_to_object(o, geo, FALSE);
json_delete(geo);
}
}
/*
* Populate a JSON object (`obj') keyed by directory name; each element points
* to a JSON array with a list of subdirectories on the first level.
*
* { "jpm": [ "5s", "nex4" ], "jjolie": [ "iphone5" ] }
*
* Returns 1 on failure.
*/
static int user_device_list(char *name, int level, JsonNode *obj)
{
DIR *dirp;
struct dirent *dp;
char path[BUFSIZ];
JsonNode *devlist;
int rc = 0;
struct stat sb;
if ((dirp = opendir(name)) == NULL) {
// Hide error; the directory will be created automatically later
// perror(name);
return (1);
}
while ((dp = readdir(dirp)) != NULL) {
if (*dp->d_name != '.') {
sprintf(path, "%s/%s", name, dp->d_name);
if (stat(path, &sb) != 0) {
continue;
}
if (!S_ISDIR(sb.st_mode))
continue;
if (level == 0) {
devlist = json_mkarray();
json_append_member(obj, dp->d_name, devlist);
rc = user_device_list(path, level + 1, devlist);
} else if (level == 1) {
json_append_element(obj, json_mkstring(dp->d_name));
}
}
}
closedir(dirp);
return (rc);
}
void append_card_to_object(JsonNode *obj, char *user, char *device)
{
char path[LARGEBUF], path1[LARGEBUF], *cardfile = NULL;
JsonNode *card;
if (!user || !*user)
return;
snprintf(path, LARGEBUF, "%s/cards/%s/%s/%s-%s.json",
STORAGEDIR, user, device, user, device);
if (access(path, R_OK) == 0) {
cardfile = path;
} else {
snprintf(path1, LARGEBUF, "%s/cards/%s/%s.json",
STORAGEDIR, user, user);
if (access(path1, R_OK) == 0) {
cardfile = path1;
}
}
card = json_mkobject();
if (cardfile && json_copy_from_file(card, cardfile) == TRUE) {
json_copy_to_object(obj, card, FALSE);
}
json_delete(card);
}
#ifdef WITH_TZ
static void tz_info(JsonNode *json, double lat, double lon, time_t tst)
{
// olog(LOG_DEBUG, "tz_info for (%lf, %lf)", lat, lon);
if (zdb) {
char *tz_str = ZDHelperSimpleLookupString(zdb, lat, lon);
if (tz_str) {
json_append_member(json, "tzname", json_mkstring(tz_str));
json_append_member(json, "isolocal", json_mkstring(isolocal(tst, tz_str)));
ZDHelperSimpleLookupStringFree(tz_str);
}
}
}
#endif
void append_device_details(JsonNode *userlist, char *user, char *device)
{
char path[LARGEBUF];
JsonNode *node, *last;
snprintf(path, LARGEBUF, "%s/last/%s/%s/%s-%s.json",
STORAGEDIR, user, device, user, device);
last = json_mkobject();
if (json_copy_from_file(last, path) == TRUE) {
JsonNode *jtst;
if ((jtst = json_find_member(last, "tst")) != NULL) {
json_append_member(last, "isotst", json_mkstring(isotime(jtst->number_)));
json_append_member(last, "disptst", json_mkstring(disptime(jtst->number_)));
#ifdef WITH_TZ
JsonNode *jlat, *jlon;
if ((jlat = json_find_member(last, "lat")) &&
(jlon = json_find_member(last, "lon"))) {
tz_info(last, jlat->number_, jlon->number_, jtst->number_);
}
#endif
}
}
append_card_to_object(last, user, device);
if ((node = json_find_member(last, "ghash")) != NULL) {
if (node->tag == JSON_STRING) {
get_geo(last, node->string_);
}
}
/* Extra data */
snprintf(path, LARGEBUF, "%s/last/%s/%s/extra.json",
STORAGEDIR, user, device);
json_copy_from_file(last, path);
json_append_element(userlist, last);
}
/*
* Return an array of users gleaned from LAST with merged details.
* If user and device are specified, limit to those; either may be
* NULL. If `fields' is not NULL, it's a JSON array of fields to
* be returned.
*/
JsonNode *last_users(char *in_user, char *in_device, JsonNode *fields)
{
JsonNode *obj = json_mkobject();
JsonNode *un, *dn, *userlist = json_mkarray();
char path[LARGEBUF], user[BUFSIZ], device[BUFSIZ];
snprintf(path, LARGEBUF, "%s/last", STORAGEDIR);
// fprintf(stderr, "last_users(%s, %s)\n", (in_user) ? in_user : "<nil>",
// (in_device) ? in_device : "<nil>");
if (user_device_list(path, 0, obj) == 1) {
json_delete(userlist);
return (obj);
}
/* Loop through users, devices */
json_foreach(un, obj) {
if (un->tag != JSON_ARRAY)
continue;
strcpy(user, un->key);
json_foreach(dn, un) {
if (dn->tag == JSON_STRING) {
strcpy(device, dn->string_);
} else if (dn->tag == JSON_NUMBER) { /* all digits? */
sprintf(device, "%.lf", dn->number_);
}
if (!in_user && !in_device) {
append_device_details(userlist, user, device);
} else if (in_user && !in_device) {
if (strcmp(user, in_user) == 0) {
append_device_details(userlist, user, device);
}
} else if (in_user && in_device) {
if (strcmp(user, in_user) == 0 && strcmp(device, in_device) == 0) {
append_device_details(userlist, user, device);
}
}
}
}
json_delete(obj);
/*
* userlist now is an array of user objects. If fields were
* specified, re-create that array with object which have
* only the requested fields. It's a shame we have to re-do
* this here, but I can't think of an alternative way at
* the moment.
*/
if (fields) {
JsonNode *new_userlist = json_mkarray(), *user;
json_foreach(user, userlist) {
JsonNode *o = json_mkobject(), *f, *j;
json_foreach(f, fields) {
char *field_name = f->string_;
if ((j = json_find_member(user, field_name)) != NULL) {
json_copy_element_to_object(o, field_name, j);
}
}
json_append_element(new_userlist, o);
}
json_delete(userlist);
return (new_userlist);
}
return (userlist);
}
/*
* `s' has a time string in it. Try to convert into time_t
* using a variety of formats from higher to lower precision.
* Return 1 on success, 0 on failure.
*/
static int str_time_to_secs(char *s, time_t *secs)
{
static char **f, *formats[] = {
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M",
"%Y-%m-%dT%H",
"%Y-%m-%dt%H:%M:%S",
"%Y-%m-%dt%H:%M",
"%Y-%m-%dt%H",
"%Y-%m-%d",
"%Y-%m",
NULL
};
struct tm tm;
int success = 0;
memset(&tm, 0, sizeof(struct tm));
for (f = formats; f && *f; f++) {
if (my_strptime(s, *f, &tm) != NULL) {
success = 1;
// fprintf(stderr, "str_time_to_secs succeeds with %s\n", *f);
break;
}
}
if (!success)
return (0);
tm.tm_mday = (tm.tm_mday < 1) ? 1 : tm.tm_mday;
tm.tm_isdst = -1; /* A negative value for tm_isdst causes
* the mktime() function to attempt to
* divine whether summer time is in
* effect for the specified time. */
*secs = local2gmt(mktime(&tm));
// fprintf(stderr, "str_time_to_secs: %s becomes %04d-%02d-%02d %02d:%02d:%02d\n",
// s,
// tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
// tm.tm_hour, tm.tm_min, tm.tm_sec);
return (1);
}
/*
* For each of the strings, create an epoch time at the s_ pointers. If
* a string is NULL, use a default time (from: HOURS previous, to: now)
* Return 1 if the time conversion was successful and from <= to.
*/
int make_times(char *time_from, time_t *s_lo, char *time_to, time_t *s_hi, int hours)
{
time_t now;
time(&now);
if (!time_from || !*time_from) {
*s_lo = now - (60 * 60 * ((hours) ? hours : DEFAULT_HISTORY_HOURS));
} else {
if (str_time_to_secs(time_from, s_lo) == 0)
return (0);
}
if (!time_to || !*time_to) {
*s_hi = now;
} else {
if (str_time_to_secs(time_to, s_hi) == 0)
return (0);
}
return (*s_lo > *s_hi ? 0 : 1);
}
/*
* List the directories in the directory at `path' and put
* the names into a JSON array which is in obj.
*/
static void ls(char *path, JsonNode *obj)
{
DIR *dirp;
struct dirent *dp;
JsonNode *jarr = json_mkarray();
if (obj == NULL || obj->tag != JSON_OBJECT) {
json_delete(jarr);
return;
}
if ((dirp = opendir(path)) == NULL) {
json_append_member(obj, "error", json_mkstring("Cannot open requested directory"));
json_delete(jarr);
return;
}
while ((dp = readdir(dirp)) != NULL) {
bool is_dir = false;
/* XFS doesn't support d_type, and it's used on CentOS 7.
* Ensure we can determine whether something's a directory.
*/
if (dp->d_type == DT_DIR) {
is_dir = true;
} else {
struct stat st;
static UT_string *fullp = NULL;
utstring_renew(fullp);
utstring_printf(fullp, "%s/%s", path, dp->d_name);
assert(stat(UB(fullp), &st) != -1);
is_dir = S_ISDIR(st.st_mode);
}
if (is_dir && (*dp->d_name != '.')) {
json_append_element(jarr, json_mkstring(dp->d_name));
}
}
json_append_member(obj, "results", jarr);
closedir(dirp);
}
/*
* List the files in the directory at `pathpat' and
* put the names into a new JSON array in obj. Filenames (2015-08.rec)
* are checked whether they fall (time-wise) into the times between
* s_lo and s_hi.
*/
static time_t t_lo, t_hi; /* must be global so that filter() can access them */
static int filter_filename(const struct dirent *d)
{
struct tm tmfile, *tm;
int lo_months, hi_months, file_months;
/* if the filename doesn't look like YYYY-MM.rec we can safely ignore it.
* Needs modifying after the year 2999 ;-) */
if (fnmatch("2[0-9][0-9][0-9]-[0-3][0-9].rec", d->d_name, 0) != 0)
return (0);
/* Convert filename (YYYY-MM) to a tm; see if months falls between
* from months and to months. */
memset(&tmfile, 0, sizeof(struct tm));
if (my_strptime(d->d_name, "%Y-%m", &tmfile) == NULL) {
fprintf(stderr, "filter: convert err");
return (0);
}
file_months = (tmfile.tm_year + 1900) * 12 + tmfile.tm_mon;
tm = gmtime(&t_lo);
lo_months = (tm->tm_year + 1900) * 12 + tm->tm_mon;
tm = gmtime(&t_hi);
hi_months = (tm->tm_year + 1900) * 12 + tm->tm_mon;
/*
printf("filter: file %s has %04d-%02d-%02d %02d:%02d:%02d\n",
d->d_name,
tmfile.tm_year + 1900, tmfile.tm_mon + 1, tmfile.tm_mday,
tmfile.tm_hour, tmfile.tm_min, tmfile.tm_sec);
*/
if (file_months >= lo_months && file_months <= hi_months) {
// fprintf(stderr, "filter: returns: %s\n", d->d_name);
return (1);
}
return (0);
}
static int cmp( const struct dirent **a, const struct dirent **b)
{
return strcmp((*a)->d_name, (*b)->d_name);
}
static void lsscan(char *pathpat, time_t s_lo, time_t s_hi, JsonNode *obj, int reverse)
{
struct dirent **namelist;
int i, n;
JsonNode *jarr = NULL;
static UT_string *path = NULL;
if (obj == NULL || obj->tag != JSON_OBJECT)
return;
utstring_renew(path);
/* Set global t_ values */
t_lo = s_lo;
t_hi = s_hi;
if ((n = scandir(pathpat, &namelist, filter_filename, cmp)) < 0) {
json_append_member(obj, "error", json_mkstring("Cannot lsscan requested directory"));
return;
}
/* If our obj contains the "results" array, use that
* and remove from obj; we'll add it back later.
*/
if ((jarr = json_find_member(obj, "results")) == NULL) {
jarr = json_mkarray();
} else {
json_delete(jarr);
}
if (reverse) {
for (i = n - 1; i >= 0; i--) {
utstring_clear(path);
utstring_printf(path, "%s/%s", pathpat, namelist[i]->d_name);
json_append_element(jarr, json_mkstring(UB(path)));
free(namelist[i]);
}
} else {
for (i = 0; i < n; i++) {
utstring_clear(path);
utstring_printf(path, "%s/%s", pathpat, namelist[i]->d_name);
json_append_element(jarr, json_mkstring(UB(path)));
free(namelist[i]);
}
}
free(namelist);
json_append_member(obj, "results", jarr);
}
/*
* If `user' and `device' are both NULL, return list of users.
* If `user` is specified, and device is NULL, return user's devices
* If both user and device are specified, return list of .rec files;
* in that case, limit with `s_lo` and `s_hi`. `reverse' is TRUE if
* list should be sorted in descending order.
*/
JsonNode *lister(char *user, char *device, time_t s_lo, time_t s_hi, int reverse)
{
JsonNode *json = json_mkobject();
static UT_string *path = NULL;
char *bp;
utstring_renew(path);
for (bp = user; bp && *bp; bp++) {
if (isupper(*bp))
*bp = tolower(*bp);
}
for (bp = device; bp && *bp; bp++) {
if (isupper(*bp))
*bp = tolower(*bp);
}
if (!user && !device) {
utstring_printf(path, "%s/rec", STORAGEDIR);
ls(UB(path), json);
} else if (!device) {
utstring_printf(path, "%s/rec/%s", STORAGEDIR, user);
ls(UB(path), json);
} else {
utstring_printf(path, "%s/rec/%s/%s",
STORAGEDIR, user, device);
lsscan(UB(path), s_lo, s_hi, json, reverse);
}
return (json);
}
/*
* List multiple user/device combinations. udpairs is a JSON
* array of strings, each of which is a user/device pair
* separated by a slash.
*/
JsonNode *multilister(JsonNode *udpairs, time_t s_lo, time_t s_hi, int reverse)
{
JsonNode *json = json_mkobject(), *ud;
static UT_string *path = NULL;
char *pairs[3];
int np;
if (udpairs == NULL || udpairs->tag != JSON_ARRAY) {
return (json);
}
json_foreach(ud, udpairs) {
if ((np = splitter(ud->string_, "/", pairs)) != 2) {
continue;
}
utstring_renew(path);
utstring_printf(path, "%s/rec/%s/%s",
STORAGEDIR,
pairs[0], /* user */
pairs[1]); /* device */
lsscan(UB(path), s_lo, s_hi, json, reverse);
splitterfree(pairs);
}
return (json);
}
struct jparam {
JsonNode *obj;
JsonNode *locs;
time_t s_lo;
time_t s_hi;
output_type otype;
int limit; /* if non-zero, we're searching backwards */
JsonNode *fields; /* If non-NULL array of fields names to return */
char *username; /* If non-NULL, add username to location */
char *device; /* If non-NULL, add device name to location */
};
/*
* line is a single valid '*' line from a .rec file. Turn it into a JSON object.
* objectorize it. Is that a word? :)
*/
static JsonNode *line_to_location(char *line)
{
JsonNode *o, *j;
char *ghash;
#ifdef WITH_TZ
char *tzname = NULL;
#endif
char tstamp[64], *bp;
double lat, lon;
long tst;
int geoprec = geohash_prec();
snprintf(tstamp, 21, "%s", line);
if ((bp = strchr(line, '{')) == NULL)
return (NULL);
if ((o = json_decode(bp)) == NULL) {
return (NULL);
}
if ((j = json_find_member(o, "_type")) == NULL) {
json_delete(o);
return (NULL);
}
if (j->tag != JSON_STRING || strcmp(j->string_, "location") != 0) {
json_delete(o);
return (NULL);
}
lat = lon = 0.0;
if ((j = json_find_member(o, "lat")) != NULL) {
lat = j->number_;
}
if ((j = json_find_member(o, "lon")) != NULL) {
lon = j->number_;
}
if ((j = json_find_member(o, "_geoprec")) != NULL) {
geoprec = j->number_;
}
if ((ghash = geohash_encode(lat, lon, abs(geoprec))) != NULL) {
json_append_member(o, "ghash", json_mkstring(ghash));
get_geo(o, ghash);
free(ghash);
}
json_append_member(o, "isorcv", json_mkstring(tstamp));
tst = 0L;
if ((j = json_find_member(o, "tst")) != NULL) {
tst = j->number_;
}
json_append_member(o, "isotst", json_mkstring(isotime(tst)));
json_append_member(o, "disptst", json_mkstring(disptime(tst)));
/*
* If tzname is in the cached geo data, we've already added it
* to the outgoing JSON and we use it to construct isolocal.
* Otherwise determine the TZ name from the tzdatadb.
*/
#ifdef WITH_TZ
if ((j = json_find_member(o, "tzname")) != NULL) {
tzname = j->string_;
json_append_member(o, "isolocal", json_mkstring(isolocal(tst, tzname)));
} else {
/* if tzname is not in the object, i.e. it wasn't originally
* obtained during geo lookup and cached, then look it up
* in the binary zonedetect database now. Note that this will
* add quite a substantial amount of time to producing API
* results. We might need to make this run-time configurable.
*/
tz_info(o, lat, lon, tst);
}
#endif
return (o);
}
/*
* Invoked via tac() and cat(). Verify that line is indeed a location
* line from a .rec file. Then objectorize it and add to the locations
* JSON array and update the counter in our JSON object.
* Return 0 to tell caller to "ignore" the line, 1 to use it.
*/
static int candidate_line(char *line, void *param)
{
long counter = 0L;
JsonNode *j, *o;
struct jparam *jarg = (struct jparam*)param;
char *bp;
JsonNode *obj = jarg->obj;
JsonNode *locs = jarg->locs;
int limit = jarg->limit;
time_t s_lo = jarg->s_lo;
time_t s_hi = jarg->s_hi;
JsonNode *fields = jarg->fields;
output_type otype = jarg->otype;
char *username = jarg->username;
char *device = jarg->device;
if (obj == NULL || obj->tag != JSON_OBJECT)
return (-1);
if (locs == NULL || locs->tag != JSON_ARRAY)
return (-1);
if (limit == 0) {
/* Reading forwards; account for time */
char *p;
struct tm tmline;
time_t secs;
if ((p = my_strptime(line, "%Y-%m-%dT%H:%M:%SZ", &tmline)) == NULL) {
fprintf(stderr, "invalid strptime format on %s", line);
return (0);
}
tmline.tm_isdst = -1; /* A negative value for tm_isdst causes
* the mktime() function to attempt to
* divine whether summer time is in
* effect for the specified time. */
secs = local2gmt(mktime(&tmline));
if (secs <= s_lo || secs >= s_hi) {
return (0);
}
if (otype == RAW) {
printf("%s\n", line);
return (0);
} else if (otype == RAWPAYLOAD) {
char *bp;
if ((bp = strchr(line, '{')) != NULL) {
printf("%s\n", bp);
}
}
} else if (limit > 0 && otype == RAW) {
printf("%s\n", line);
return (1); /* make it 'count' or tac() will not decrement line counter and continue until EOF */
} else if (limit > 0) {
/* reading backwards; check time */
char *p;
struct tm tmline;
time_t secs;
if ((p = my_strptime(line, "%Y-%m-%dT%H:%M:%SZ", &tmline)) == NULL) {
fprintf(stderr, "invalid strptime format on %s", line);
return (0);
}
tmline.tm_isdst = -1;
secs = local2gmt(mktime(&tmline));
if (secs <= s_lo || secs >= s_hi) {
return (0);
}
}
/* Do we have location line? */
if ((bp = strstr(line, "Z\t* ")) == NULL) { /* Not a location line */
return (0);
}
if ((bp = strrchr(bp, '\t')) == NULL) {
return (0);
}
/* Initialize our counter to what the JSON obj currently has */
if ((j = json_find_member(obj, "count")) != NULL) {
counter = j->number_;
json_delete(j);
}
// fprintf(stderr, "-->[%s]\n", line);
if ((o = line_to_location(line)) != NULL) {
/*
* Username/device are added typically for multilister() only.
*/
if (username)
json_append_member(o, "username", json_mkstring(username));
if (device)
json_append_member(o, "device", json_mkstring(device));
if (fields) {
/* Create a new object, copying members we're interested in into it */
JsonNode *f, *node;
JsonNode *newo = json_mkobject();
json_foreach(f, fields) {
char *key = f->string_;
if ((node = json_find_member(o, key)) != NULL) {
json_copy_element_to_object(newo, key, node);
}
}
json_delete(o);
o = newo;
}
json_append_element(locs, o);
++counter;
}
/* Add the (possibly) incremented counter back into `obj' */
json_append_member(obj, "count", json_mknumber(counter));
return (1);
}
/*
* Read the file at `filename' (- is stdin) and store location
* objects at the JSON array `arr`. `obj' is a JSON object which
* contains `arr'.
* If limit is zero, we're going forward, else backwards.
* Fields, if not NULL, is a JSON array of desired element names.
*
* If username & device are not NULL, populate the JSON locations
* with them for multilister().
*/
void locations(char *filename, JsonNode *obj, JsonNode *arr, time_t s_lo, time_t s_hi, output_type otype, int limit, JsonNode *fields, char *username, char *device)
{
struct jparam jarg;
if (obj == NULL || obj->tag != JSON_OBJECT)
return;
jarg.obj = obj;
jarg.locs = arr;
jarg.s_lo = s_lo;
jarg.s_hi = s_hi;
jarg.otype = otype;
jarg.limit = limit;
jarg.fields = fields;
jarg.username = username;
jarg.device = device;
if (limit == 0) {
cat(filename, candidate_line, &jarg);
} else {
tac(filename, limit, candidate_line, &jarg);
}
}
/*
* We're being passed an array of location objects created in
* locations(). Produce a Geo JSON tree.
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-80.83775386582222,35.24980190252168]
},
"properties": {
"name": "DOUBLE OAKS CENTER",
"address": "1326 WOODWARD AV"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-80.83827000459532,35.25674709224663]
},
"properties": {
"name": "DOUBLE OAKS NEIGHBORHOOD PARK",
"address": "2605 DOUBLE OAKS RD"
}
}
]
}
*
*/
static void append_to_feature_array(JsonNode *features, double lat, double lon, char *tid, char *addr, long tst, long vel, long acc, long alt, char *poi, char *isotst)
{
JsonNode *geom, *props, *f = json_mkobject();
json_append_member(f, "type", json_mkstring("Feature"));
geom = json_mkobject();
json_append_member(geom, "type", json_mkstring("Point"));
JsonNode *coords = json_mkarray();
json_append_element(coords, json_mknumber(lon)); /* first LON! */
json_append_element(coords, json_mknumber(lat));
json_append_member(geom, "coordinates", coords);
props = json_mkobject();
if (poi && *poi) {
json_append_member(props, "name", json_mkstring(poi));
} else {
json_append_member(props, "name", json_mkstring(tid));
json_append_member(props, "vel", json_mknumber(vel));
json_append_member(props, "tst", json_mknumber(tst));
json_append_member(props, "acc", json_mknumber(acc));
json_append_member(props, "alt", json_mknumber(alt));
}
json_append_member(props, "address", json_mkstring(addr));
json_append_member(props, "isotst", json_mkstring(isotst));
json_append_member(f, "geometry", geom);
json_append_member(f, "properties", props);
json_append_element(features, f);
}
JsonNode *geo_json(JsonNode *location_array, bool poi_only)
{
JsonNode *one, *j;
JsonNode *feature_array, *fcollection;
if ((fcollection = json_mkobject()) == NULL)
return (NULL);
json_append_member(fcollection, "type", json_mkstring("FeatureCollection"));
feature_array = json_mkarray();
json_foreach(one, location_array) {
double lat = 0.0, lon = 0.0;
char *addr = "", *tid = "", *poi = "", *isotst = "";
long tst = 0, vel = 0, acc = 0, alt = 0;
if (poi_only) {