forked from dnsdb/dnsdbq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dnsdbq.c
1782 lines (1627 loc) · 42.8 KB
/
dnsdbq.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
/*
* Copyright (c) 2014-2018 by Farsight Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* External. */
/* asprintf() does not appear on linux without this */
#define _GNU_SOURCE
/* gettimeofday() does not appear on linux without this. */
#define _BSD_SOURCE
/* modern glibc will complain about the above if it doesn't see this. */
#define _DEFAULT_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <assert.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <wordexp.h>
#include <curl/curl.h>
#include <jansson.h>
#include "ns_ttl.h"
extern char **environ;
/* Types. */
struct dnsdb_json {
json_t *main,
*time_first, *time_last, *zone_first, *zone_last,
*bailiwick, *rrname, *rrtype, *rdata,
*count;
};
struct dnsdb_tuple {
struct dnsdb_json obj;
u_long time_first, time_last, zone_first, zone_last;
const char *bailiwick, *rrname, *rrtype, *rdata;
json_int_t count;
};
typedef struct dnsdb_tuple *dnsdb_tuple_t;
typedef void (*present_t)(const dnsdb_tuple_t, const char *, size_t, FILE *);
struct reader {
struct reader *next;
struct writer *writer;
CURL *easy;
struct curl_slist *hdrs;
char *url;
char *buf;
size_t len;
};
typedef struct reader *reader_t;
struct writer {
struct writer *next;
struct reader *readers;
u_long after;
u_long before;
FILE *sort_stdin;
FILE *sort_stdout;
pid_t sort_pid;
};
typedef struct writer *writer_t;
typedef enum { no_mode = 0, rdata_mode, name_mode, ip_mode } mode_e;
/* Constants. */
static const char * const conf_files[] = {
"~/.isc-dnsdb-query.conf",
"~/.dnsdb-query.conf",
"/etc/isc-dnsdb-query.conf",
"/etc/dnsdb-query.conf",
NULL
};
static const char path_sort[] = "/usr/bin/sort";
static const char json_header[] = "Accept: application/json";
static const char default_server[] = "https://api.dnsdb.info";
static const char env_api_key[] = "DNSDB_API_KEY";
static const char env_dnsdb_server[] = "DNSDB_SERVER";
#define MAX_KEYS 3
#define MAX_JOBS 8
#define DESTROY(p) if (p != NULL) { free(p); p = NULL; } else {}
/* Forward. */
static __attribute__((noreturn)) void usage(const char *);
static __attribute__((noreturn)) void my_exit(int, ...);
static void server_setup(void);
static void read_configs(void);
static void read_environ(void);
static void do_batch(FILE *, u_long, u_long);
static char *restful(mode_e, const char *, const char *,
const char *, const char *);
static void make_curl(void);
static void unmake_curl(void);
static void dnsdb_query(const char *, u_long, u_long);
static void query_launcher(const char *, writer_t, u_long, u_long);
static void launch(const char *, writer_t, u_long, u_long, u_long, u_long);
static void rendezvous(reader_t);
static void ruminate_json(int, u_long, u_long);
static writer_t writer_init(u_long, u_long);
static size_t writer_func(char *ptr, size_t size, size_t nmemb, void *blob);
static void writer_fini(writer_t);
static int reader_error(reader_t);
static void io_engine(int);
static void present_dns(const dnsdb_tuple_t, const char *, size_t, FILE *);
static void present_json(const dnsdb_tuple_t, const char *, size_t, FILE *);
static void present_csv(const dnsdb_tuple_t, const char *, size_t, FILE *);
static void present_csv_line(const dnsdb_tuple_t, const char *, FILE *);
static const char *tuple_make(dnsdb_tuple_t, char *, size_t);
static void tuple_unmake(dnsdb_tuple_t);
static int timecmp(u_long, u_long);
static void time_print(u_long x, FILE *);
static int time_get(const char *src, u_long *dst);
static void escape(char **);
/* Private. */
static const char *program_name = NULL;
static char *api_key = NULL;
static char *key_header = NULL;
static char *dnsdb_server = NULL;
static bool batch = false;
static bool merge = false;
static bool complete = false;
static int debuglev = 0;
static enum { no_sort = 0, normal_sort, reverse_sort } sorted = no_sort;
static int curl_cleanup_needed = 0;
static present_t pres = present_dns;
static int limit = 0;
static CURLM *multi = NULL;
static struct timeval now;
static struct timezone here;
static int nkeys, keys[MAX_KEYS];
static writer_t writers = NULL;
/* Public. */
int
main(int argc, char *argv[]) {
mode_e mode = no_mode;
char *name = NULL, *type = NULL, *bailiwick = NULL, *length = NULL;
u_long after = 0;
u_long before = 0;
int json_fd = -1;
int ch;
/* global dynamic initialization. */
gettimeofday(&now, &here);
program_name = strrchr(argv[0], '/');
if (program_name != NULL)
program_name++;
else
program_name = argv[0];
/* process the command line options. */
while ((ch = getopt(argc, argv,
"A:B:r:n:i:l:p:t:b:k:J:djfmsShc")) != -1)
{
switch (ch) {
case 'A':
if (!time_get(optarg, &after)) {
fprintf(stderr, "bad -A timestamp: '%s'\n",
optarg);
my_exit(1, NULL);
}
break;
case 'B':
if (!time_get(optarg, &before)) {
fprintf(stderr, "bad -B timestamp: '%s'\n",
optarg);
my_exit(1, NULL);
}
break;
case 'r': {
const char *p;
if (mode != no_mode)
usage("-r, -n, or -i can only appear once");
assert(name == NULL);
mode = rdata_mode;
if (type == NULL && bailiwick == NULL)
p = strchr(optarg, '/');
else
p = NULL;
if (p != NULL) {
const char *q;
q = strchr(p + 1, '/');
if (q != NULL) {
bailiwick = strdup(q + 1);
type = strndup(p + 1,
(size_t)(q - p - 1));
} else {
type = strdup(p + 1);
}
name = strndup(optarg, (size_t)(p - optarg));
} else {
name = strdup(optarg);
}
break;
}
case 'n': {
const char *p;
if (mode != no_mode)
usage("-r, -n, or -i can only appear once");
assert(name == NULL);
mode = name_mode;
if (type == NULL)
p = strchr(optarg, '/');
else
p = NULL;
if (p != NULL) {
name = strndup(optarg, (size_t)(p - optarg));
type = strdup(p + 1);
} else {
name = strdup(optarg);
}
break;
}
case 'i': {
const char *p;
if (mode != no_mode)
usage("-r, -n, or -i can only appear once");
assert(name == NULL);
mode = ip_mode;
p = strchr(optarg, '/');
if (p != NULL) {
name = strndup(optarg, (size_t)(p - optarg));
length = strdup(p + 1);
} else {
name = strdup(optarg);
}
break;
}
case 'l':
limit = atoi(optarg);
break;
case 'p':
if (strcmp(optarg, "json") == 0)
pres = present_json;
else if (strcmp(optarg, "dns") == 0)
pres = present_dns;
else if (strcmp(optarg, "csv") == 0)
pres = present_csv;
else
usage("-p must specify json, dns, or csv");
break;
case 't':
if (type != NULL)
free(type);
type = strdup(optarg);
break;
case 'b':
if (bailiwick != NULL)
free(bailiwick);
bailiwick = strdup(optarg);
break;
case 'k': {
const char *tok;
nkeys = 0;
for (tok = strtok(optarg, ",");
tok != NULL;
tok = strtok(NULL, ","))
{
int key = 0;
if (nkeys == MAX_KEYS)
usage("too many -k options given.");
if (strcasecmp(tok, "first") == 0)
key = 1;
else if (strcasecmp(tok, "last") == 0)
key = 2;
else if (strcasecmp(tok, "count") == 0)
key = 3;
else
usage("-k !< {first,last,count}");
keys[nkeys++] = key;
}
break;
}
case 'J':
if (strcmp(optarg, "-") == 0)
json_fd = STDIN_FILENO;
else
json_fd = open(optarg, O_RDONLY);
if (json_fd < 0) {
perror(optarg);
my_exit(1, NULL);
}
break;
case 'd':
debuglev++;
break;
case 'j':
pres = present_json;
break;
case 'f':
batch = true;
break;
case 'm':
merge = true;
break;
case 's':
sorted = normal_sort;
break;
case 'S':
sorted = reverse_sort;
break;
case 'c':
complete = true;
break;
case 'h':
usage(NULL);
break;
default:
usage("unrecognized option");
}
}
argc -= optind;
argv += optind;
if (argc != 0)
usage("there are no non-option arguments to this program");
/* recondition various options for HTML use. */
if (name != NULL)
escape(&name);
if (type != NULL)
escape(&type);
if (bailiwick != NULL)
escape(&bailiwick);
if (length != NULL)
escape(&length);
/* optionally dump program options as interpreted. */
if (debuglev > 0) {
if (name != NULL)
fprintf(stderr, "name = '%s'\n", name);
if (type != NULL)
fprintf(stderr, "type = '%s'\n", type);
if (bailiwick != NULL)
fprintf(stderr, "bailiwick = '%s'\n", bailiwick);
if (length != NULL)
fprintf(stderr, "length = '%s'\n", length);
if (after != 0) {
fprintf(stderr, "after = %ld : ", (long)after);
time_print(after, stderr);
putc('\n', stderr);
}
if (before != 0) {
fprintf(stderr, "before = %ld : ", (long)before);
time_print(before, stderr);
putc('\n', stderr);
}
if (limit != 0)
fprintf(stderr, "limit = %d\n", limit);
fprintf(stderr, "batch=%d, merge=%d\n", batch, merge);
}
/* validate some interrelated options. */
if (after != 0 && before != 0) {
if (after > 0 && before > 0 && after > before) {
fprintf(stderr,
"-A -B requires after <= before (for now)\n");
my_exit(1, NULL);
}
if (sorted == no_sort && json_fd == -1 && !complete) {
fprintf(stderr,
"-A and -B w/o -c requires sorting for dedup, "
"so turning on -S here.\n");
sorted = reverse_sort;
}
}
if (nkeys > 0 && sorted == no_sort) {
fprintf(stderr, "using -k without -s or -S makes no sense.\n");
my_exit(1, NULL);
}
if (merge && !batch) {
fprintf(stderr, "using -m without -f makes no sense.\n");
my_exit(1, NULL);
}
/* get some input from somewhere, and use it to drive our output. */
if (json_fd != -1) {
if (mode != no_mode)
usage("can't mix -n, -r, or -i with -J");
if (batch)
usage("can't mix -b with -J");
ruminate_json(json_fd, after, before);
close(json_fd);
} else if (batch) {
if (mode != no_mode)
usage("can't mix -n, -r, or -i with -f");
if (bailiwick != NULL)
usage("can't mix -b with -f");
if (type != NULL)
usage("can't mix -t with -f");
server_setup();
make_curl();
do_batch(stdin, after, before);
unmake_curl();
} else {
char *command;
if (mode == no_mode)
usage("must specify -r, -n, or -i"
" unless -f or -J is used");
command = restful(mode, name, type, bailiwick, length);
server_setup();
make_curl();
dnsdb_query(command, after, before);
DESTROY(command);
unmake_curl();
}
/* clean up and go. */
DESTROY(name);
DESTROY(type);
DESTROY(bailiwick);
DESTROY(length);
my_exit(0, NULL);
}
/* Private. */
/* usage -- display a usage error message, brief usage help text; then exit.
*/
static __attribute__((noreturn)) void
usage(const char *error) {
if (error != NULL)
fprintf(stderr, "error: %s\n", error);
fprintf(stderr,
"usage: %s [-vdjsShc] [-p dns|json|csv] [-k (first|last|count)[,...]]\n"
"\t[-l LIMIT] [-A after] [-B before] {\n"
"\t\t-f |\n"
"\t\t-J inputfile |\n"
"\t\t[-t type] [-b bailiwick] {\n"
"\t\t\t-r OWNER[/TYPE[/BAILIWICK]] |\n"
"\t\t\t-n NAME[/TYPE] |\n"
"\t\t\t-i IP[/PFXLEN]\n"
"\t\t}\n"
"\t}\n"
"for -f, stdin must contain lines of the following forms:\n"
"\trrset/name/NAME[/TYPE[/BAILIWICK]]\n"
"\trdata/name/NAME[/TYPE]\n"
"\trdata/ip/ADDR[/PFXLEN]\n"
"for -f, output format will be determined by -p, using --\\n framing\n"
"for -J, input format is newline-separated JSON, as for -j output\n"
"for -A and -B, use abs. YYYY-MM-DD[ HH:MM:SS] "
"or rel. %%dw%%dd%%dh%%dm%%ds format\n"
"use -j as a synonym for -p json.\n"
"use -s to sort in ascending order, or -S for descending order.\n"
"use -h to reliably display this helpful text.\n"
"use -c to get complete (vs. partial) time matching for -A and -B\n",
program_name);
my_exit(1, NULL);
}
/* my_exit -- free() the heap objects supplied as arguments, then exit.
*/
static __attribute__((noreturn)) void
my_exit(int code, ...) {
va_list ap;
void *p;
/* our varargs are things to be free()'d. */
va_start(ap, code);
while (p = va_arg(ap, void *), p != NULL)
free(p);
va_end(ap);
/* globals which may have been initialized, are to be free()'d. */
DESTROY(key_header);
DESTROY(api_key);
DESTROY(dnsdb_server);
/* writers and readers which are still known, must be free()'d. */
while (writers != NULL)
writer_fini(writers);
/* if curl is operating, it must be shut down. */
unmake_curl();
/* terminate process. */
if (debuglev > 0)
fprintf(stderr, "about to call exit(%d)\n", code);
exit(code);
}
/* server_setup -- learn the server name and API key by various means.
*/
static void
server_setup(void) {
read_configs();
read_environ();
if (asprintf(&key_header, "X-Api-Key: %s", api_key) < 0) {
perror("asprintf");
my_exit(1, NULL);
}
}
/* read_configs -- try to find a config file in static path, then parse it.
*/
static void
read_configs(void) {
const char * const *conf;
char *cf;
cf = NULL;
for (conf = conf_files; *conf != NULL; conf++) {
wordexp_t we;
wordexp(*conf, &we, WRDE_NOCMD);
cf = strdup(we.we_wordv[0]);
wordfree(&we);
if (access(cf, R_OK) == 0) {
if (debuglev > 0)
fprintf(stderr, "conf found: '%s'\n", cf);
break;
}
}
if (*conf != NULL) {
char *cmd, *tok, *line;
size_t n;
FILE *f;
int x;
x = asprintf(&cmd,
". %s;"
"echo apikey $APIKEY;"
"echo server $DNSDB_SERVER",
cf);
if (x < 0) {
perror("asprintf");
my_exit(1, NULL);
}
f = popen(cmd, "r");
if (f == NULL) {
perror(cmd);
my_exit(1, cmd, NULL);
}
if (debuglev > 0)
fprintf(stderr, "conf cmd = '%s'\n", cmd);
DESTROY(cmd);
line = NULL;
n = 0;
while (getline(&line, &n, f) > 0) {
if (strchr(line, '\n') == NULL) {
fprintf(stderr, "%s: line too long\n", cf);
my_exit(1, cf, NULL);
}
if (debuglev > 0)
fprintf(stderr, "conf line: %s", line);
tok = strtok(line, "\040\012");
if (tok != NULL && strcmp(tok, "apikey") == 0) {
tok = strtok(NULL, "\040\012");
if (tok != NULL)
api_key = strdup(tok);
} else if (tok != NULL && strcmp(tok, "server") == 0) {
tok = strtok(NULL, "\040\012");
if (tok != NULL)
dnsdb_server = strdup(tok);
} else {
fprintf(stderr, "%s: line malformed\n", cf);
my_exit(1, cf, NULL);
}
}
DESTROY(line);
pclose(f);
}
DESTROY(cf);
}
/* read_environ -- override the config file from environment variables?
*/
static void
read_environ() {
const char *val;
val = getenv(env_api_key);
if (val != NULL) {
if (api_key != NULL)
free(api_key);
api_key = strdup(val);
if (debuglev > 0)
fprintf(stderr, "conf env api_key = '%s'\n", api_key);
}
val = getenv(env_dnsdb_server);
if (val != NULL) {
if (dnsdb_server != NULL)
free(dnsdb_server);
dnsdb_server = strdup(val);
if (debuglev > 0)
fprintf(stderr, "conf env dnsdb_server = '%s'\n",
dnsdb_server);
}
if (api_key == NULL) {
fprintf(stderr, "no API key given\n");
my_exit(1, NULL);
}
if (dnsdb_server == NULL) {
dnsdb_server = strdup(default_server);
if (debuglev > 0)
fprintf(stderr, "conf default dnsdb_server = '%s'\n",
dnsdb_server);
}
}
/* do_batch -- implement "filter" mode, reading commands from a batch file.
*/
static void
do_batch(FILE *f, u_long after, u_long before) {
writer_t writer = NULL;
char *command = NULL;
size_t n = 0;
/* if merging, start a writer. */
if (merge)
writer = writer_init(after, before);
while (getline(&command, &n, f) > 0) {
char *nl = strchr(command, '\n');
if (nl == NULL) {
fprintf(stderr, "batch line too long: %s\n", command);
continue;
}
*nl = '\0';
if (debuglev > 0)
fprintf(stderr, "do_batch(%s)\n", command);
/* if not merging, start a writer here instead. */
if (!merge)
writer = writer_init(after, before);
/* start one or two curl jobs based on this search. */
query_launcher(command, writer, after, before);
/* if merging, drain some jobs; else, drain all jobs. */
if (merge) {
io_engine(MAX_JOBS);
} else {
io_engine(0);
writer_fini(writer);
writer = NULL;
fprintf(stdout, "--\n");
fflush(stdout);
}
}
DESTROY(command);
/* if merging, run remaining jobs to completion, then finish up. */
if (merge) {
io_engine(0);
writer_fini(writer);
}
}
/* restful -- make a RESTful URI that describes these search parameters
*/
static char *
restful(mode_e mode, const char *name, const char *type,
const char *bailiwick, const char *length)
{
char *command;
int x;
switch (mode) {
case rdata_mode:
if (type != NULL && bailiwick != NULL)
x = asprintf(&command, "rrset/name/%s/%s/%s",
name, type, bailiwick);
else if (type != NULL)
x = asprintf(&command, "rrset/name/%s/%s",
name, type);
else
x = asprintf(&command, "rrset/name/%s",
name);
if (x < 0) {
perror("asprintf");
my_exit(1, NULL);
}
break;
case name_mode:
if (type != NULL)
x = asprintf(&command, "rdata/name/%s/%s",
name, type);
else
x = asprintf(&command, "rdata/name/%s",
name);
if (x < 0) {
perror("asprintf");
my_exit(1, NULL);
}
break;
case ip_mode:
if (length != NULL)
x = asprintf(&command, "rdata/ip/%s,%s",
name, length);
else
x = asprintf(&command, "rdata/ip/%s",
name);
if (x < 0) {
perror("asprintf");
my_exit(1, NULL);
}
break;
case no_mode:
/*FALLTHROUGH*/
default:
abort();
}
return (command);
}
/* make_curl -- perform global initializations of libcurl.
*/
static void
make_curl(void) {
curl_global_init(CURL_GLOBAL_DEFAULT);
curl_cleanup_needed++;
multi = curl_multi_init();
if (multi == NULL) {
fprintf(stderr, "curl_multi_init() failed\n");
my_exit(1, NULL);
}
}
/* unmake_curl -- clean up and discard libcurl's global state.
*/
static void
unmake_curl(void) {
if (multi != NULL) {
curl_multi_cleanup(multi);
multi = NULL;
}
if (curl_cleanup_needed) {
curl_global_cleanup();
curl_cleanup_needed = 0;
}
}
/* dnsdb_query -- launch one or more libcurl jobs to fulfill this DNSDB query.
*/
static void
dnsdb_query(const char *command, u_long after, u_long before) {
writer_t writer;
if (debuglev > 0)
fprintf(stderr, "dnsdb_query(%s)\n", command);
/* start a writer, which might be format functions, or POSIX sort. */
writer = writer_init(after, before);
/* start a small finite number of readers on that writer. */
query_launcher(command, writer, after, before);
/* run all jobs to completion. */
io_engine(0);
/* stop the writer, which might involve reading POSIX sort's output. */
writer_fini(writer);
}
/* query_launcher -- fork off some curl jobs via launch() for this query.
*/
static void
query_launcher(const char *command, writer_t writer,
u_long after, u_long before)
{
/* figure out from time fencing which job(s) we'll be starting.
*
* the 4-tuple is: first_after, first_before, last_after, last_before
*/
if (after != 0 && before != 0) {
if (complete) {
/* each db tuple must be enveloped by time fence. */
launch(command, writer, after, 0, 0, before);
} else {
/* we need tuples that end after fence start... */
launch(command, writer, 0, 0, after, 0);
/* ...and that begin before the time fence end. */
launch(command, writer, 0, before, 0, 0);
/* and we will filter in reader_func() to
* select only those tuples which either:
* ...(start within), or (end within), or
* ...(start before and end after).
*/
}
} else if (after != 0) {
if (complete) {
/* each db tuple must begin after the fence-start. */
launch(command, writer, after, 0, 0, 0);
} else {
/* each db tuple must end after the fence-start. */
launch(command, writer, 0, 0, after, 0);
}
} else if (before != 0) {
if (complete) {
/* each db tuple must end before the fence-end. */
launch(command, writer, 0, 0, 0, before);
} else {
/* each db tuple must begin before the fence-end. */
launch(command, writer, 0, before, 0, 0);
}
} else {
/* no time fencing. */
launch(command, writer, 0, 0, 0, 0);
}
}
/* launch -- actually launch a libcurl job, given a command and time fences.
*/
static void
launch(const char *command, writer_t writer,
u_long first_after, u_long first_before,
u_long last_after, u_long last_before)
{
reader_t reader;
CURLMcode res;
char sep;
int x;
reader = malloc(sizeof *reader);
if (reader == NULL) {
perror("malloc");
my_exit(1, NULL);
}
memset(reader, 0, sizeof *reader);
reader->writer = writer;
reader->easy = curl_easy_init();
if (reader->easy == NULL) {
/* an error will have been output by libcurl in this case. */
my_exit(1, reader, NULL);
}
x = asprintf(&reader->url, "%s/lookup/%s", dnsdb_server, command);
if (x < 0) {
perror("asprintf");
my_exit(1, reader, NULL);
}
sep = '?';
/* only say ?limit= if it was specified and we aren't sorting. if we
* are sorting, we'll implement this on the output of the sort.
*/
if (limit != 0 && sorted == no_sort) {
char *tmp;
x = asprintf(&tmp, "%s%c" "limit=%d", reader->url, sep, limit);
if (x < 0) {
perror("asprintf");
my_exit(1, reader->url, reader, NULL);
}
free(reader->url);
reader->url = tmp;
tmp = NULL;
sep = '&';
}
if (first_after != 0) {
char *tmp;
x = asprintf(&tmp, "%s%c" "time_first_after=%lu",
reader->url, sep, (u_long)first_after);
if (x < 0) {
perror("asprintf");
my_exit(1, reader->url, reader, NULL);
}
free(reader->url);
reader->url = tmp;
tmp = NULL;
sep = '&';
}
if (first_before != 0) {
char *tmp;
x = asprintf(&tmp, "%s%c" "time_first_before=%lu",
reader->url, sep, (u_long)first_before);
if (x < 0) {
perror("asprintf");
my_exit(1, reader->url, reader, NULL);
}
free(reader->url);
reader->url = tmp;
tmp = NULL;
sep = '&';
}
if (last_after != 0) {
char *tmp;
x = asprintf(&tmp, "%s%c" "time_last_after=%lu",
reader->url, sep, (u_long)last_after);
if (x < 0) {
perror("asprintf");
my_exit(1, reader->url, reader, NULL);
}
free(reader->url);
reader->url = tmp;
tmp = NULL;
sep = '&';
}
if (last_before != 0) {
char *tmp;
x = asprintf(&tmp, "%s%c" "time_last_before=%lu",
reader->url, sep, (u_long)last_before);
if (x < 0) {
perror("asprintf");
my_exit(1, reader->url, reader, NULL);
}
free(reader->url);
reader->url = tmp;
tmp = NULL;
sep = '&';
}
if (debuglev > 0)
fprintf(stderr, "url [%s]\n", reader->url);
curl_easy_setopt(reader->easy, CURLOPT_URL, reader->url);
curl_easy_setopt(reader->easy, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(reader->easy, CURLOPT_SSL_VERIFYHOST, 0L);
reader->hdrs = curl_slist_append(reader->hdrs, key_header);
reader->hdrs = curl_slist_append(reader->hdrs, json_header);
curl_easy_setopt(reader->easy, CURLOPT_HTTPHEADER, reader->hdrs);
curl_easy_setopt(reader->easy, CURLOPT_WRITEFUNCTION, writer_func);
curl_easy_setopt(reader->easy, CURLOPT_WRITEDATA, reader);
reader->next = writer->readers;
writer->readers = reader;
reader = NULL;
res = curl_multi_add_handle(multi, writer->readers->easy);
if (res != CURLM_OK) {
fprintf(stderr, "curl_multi_add_handle() failed: %s\n",
curl_multi_strerror(res));
writer_fini(writer);
writer = NULL;
my_exit(1, NULL);
}
}
/* rendezvous -- reap one reader.
*/
static void
rendezvous(reader_t reader) {
if (reader->easy != NULL) {
curl_multi_remove_handle(multi, reader->easy);
curl_easy_cleanup(reader->easy);
reader->easy = NULL;
}
if (reader->hdrs != NULL) {
curl_slist_free_all(reader->hdrs);
reader->hdrs = NULL;
}
DESTROY(reader->url);
free(reader);
}
/* ruminate_json -- process a json file from the filesys rather than the API.
*/
static void
ruminate_json(int json_fd, u_long after, u_long before) {
reader_t reader;
writer_t writer;
char buf[65536];
ssize_t len;
writer = writer_init(after, before);
reader = malloc(sizeof(struct reader));
if (reader == NULL) {