-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.c
2105 lines (1895 loc) · 71.8 KB
/
main.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
#define _GNU_SOURCE
#ifdef DEBUG
#include <sys/resource.h>
#endif
#include "massdns.h"
#include "string.h"
#include "random.h"
#include "net.h"
#include "cmd.h"
#include "dns.h"
#include "list.h"
#include "flow.h"
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <sys/ioctl.h>
#include <stddef.h>
#ifdef HAVE_SYSINFO
#include <sys/sysinfo.h>
#endif
#include <limits.h>
#include <stdarg.h>
#ifdef PCAP_SUPPORT
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/udp.h>
#include <net/if.h>
#endif
void print_help()
{
fprintf(stderr, ""
"Usage: %s [options] [domainlist]\n"
" -b --bindto Bind to IP address and port. (Default: 0.0.0.0:0)\n"
#ifdef HAVE_EPOLL
" --busy-poll Use busy-wait polling instead of epoll.\n"
#endif
" -c --resolve-count Number of resolves for a name before giving up. (Default: 50)\n"
" --drop-group Group to drop privileges to when running as root. (Default: nogroup)\n"
" --drop-user User to drop privileges to when running as root. (Default: nobody)\n"
" --flush Flush the output file whenever a response was received.\n"
" -h --help Show this help.\n"
" -i --interval Interval in milliseconds to wait between multiple resolves of the same\n"
" domain. (Default: 500)\n"
" -l --error-log Error log file path. (Default: /dev/stderr)\n"
" --norecurse Use non-recursive queries. Useful for DNS cache snooping.\n"
" -o --output Flags for output formatting.\n"
" --predictable Use resolvers incrementally. Useful for resolver tests.\n"
" --processes Number of processes to be used for resolving. (Default: 1)\n"
" -q --quiet Quiet mode.\n"
" --rcvbuf Size of the receive buffer in bytes.\n"
" --retry Unacceptable DNS response codes. (Default: REFUSED)\n"
" -r --resolvers Text file containing DNS resolvers.\n"
" --root Do not drop privileges when running as root. Not recommended.\n"
" -s --hashmap-size Number of concurrent lookups. (Default: 10000)\n"
" --sndbuf Size of the send buffer in bytes.\n"
" --sticky Do not switch the resolver when retrying.\n"
" --socket-count Socket count per process. (Default: 1)\n"
" -t --type Record type to be resolved. (Default: A)\n"
#ifdef PCAP_SUPPORT
" --use-pcap Enable pcap usage.\n"
#endif
" --verify-ip Verify IP addresses of incoming replies.\n"
" -w --outfile Write to the specified output file instead of standard output.\n"
"\n"
"Output flags:\n"
" S - simple text output\n"
" F - full text output\n"
" B - binary output\n"
" J - ndjson output\n"
"\n"
"Advanced flags for the simple output mode:\n"
" d - Include records from the additional section.\n"
" i - Indent any reply record.\n"
" l - Separate replies using a line feed.\n"
" m - Only output reply records that match the question name.\n"
" n - Include records from the answer section.\n"
" q - Print the question.\n"
" r - Prepend resolver IP address, Unix timestamp and return code to the question line.\n"
" s - Separate packet sections using a line feed.\n"
" t - Include TTL and record class within the output.\n"
" u - Include records from the authority section.\n",
context.cmd_args.argv[0] ? context.cmd_args.argv[0] : "massdns"
);
}
void cleanup()
{
#ifdef PCAP_SUPPORT
if(context.pcap != NULL)
{
pcap_close(context.pcap);
}
#endif
if(context.map)
{
hashmapFree(context.map);
}
if(context.resolver_map)
{
hashmapFree(context.resolver_map);
}
timed_ring_destroy(&context.ring);
free(context.resolvers.data);
free(context.sockets.interfaces4.data);
free(context.sockets.interfaces6.data);
urandom_close();
if(context.domainfile)
{
fclose(context.domainfile);
}
if(context.outfile)
{
fclose(context.outfile);
}
if(context.logfile)
{
fclose(context.logfile);
}
free(context.stat_messages);
free(context.lookup_pool.data);
free(context.lookup_space);
for (size_t i = 0; i < context.cmd_args.num_processes * 2; i++)
{
if(context.sockets.pipes && context.sockets.pipes[i] >= 0)
{
close(context.sockets.pipes[i]);
}
}
free(context.sockets.pipes);
free(context.sockets.master_pipes_read);
free(context.pids);
free(context.done);
}
void log_msg(const char* format, ...)
{
if(context.logfile != stderr)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
}
if(context.logfile)
{
va_list args;
va_start(args, format);
vfprintf(context.logfile, format, args);
va_end(args);
}
}
void clean_exit(int status)
{
cleanup();
exit(status);
}
// Adaption of djb2 for sockaddr_storage
int hash_address(void *param)
{
struct sockaddr_storage *address = param;
unsigned long hash = 5381;
uint8_t *addr_ptr;
uint8_t *addr_end;
if(address->ss_family == AF_INET)
{
struct sockaddr_in *addr4 = param;
addr_ptr = (uint8_t*)&addr4->sin_addr;
addr_end = addr_ptr + sizeof(addr4->sin_addr);
hash = ((hash << 5) + hash) + ((addr4->sin_port & 0xFF00) >> 8);
hash = ((hash << 5) + hash) + (addr4->sin_port & 0x00FF);
}
else if(address->ss_family == AF_INET6)
{
struct sockaddr_in6 *addr6 = param;
addr_ptr = (uint8_t*)&addr6->sin6_addr;
addr_end = addr_ptr + sizeof(addr6->sin6_addr);
hash = ((hash << 5) + hash) + ((addr6->sin6_port & 0xFF00) >> 8);
hash = ((hash << 5) + hash) + (addr6->sin6_port & 0x00FF);
}
else
{
log_msg("Unsupported address for hashing.\n");
abort();
}
while (addr_ptr < addr_end)
{
hash = ((hash << 5) + hash) + *addr_ptr; /* hash * 33 + c */
addr_ptr++;
}
return (int)hash;
}
// Expects valid (non-NULL) pointers to sockaddr storages of family AF_INET / AF_INET6
bool addresses_equal(void *param1, void *param2)
{
struct sockaddr_storage *addr1 = param1;
struct sockaddr_storage *addr2 = param2;
if(addr1->ss_family != addr2->ss_family)
{
return false;
}
if(addr1->ss_family == AF_INET)
{
return memcmp(&((struct sockaddr_in*)addr1)->sin_addr,
&((struct sockaddr_in*)addr2)->sin_addr, sizeof(((struct sockaddr_in*)addr1)->sin_addr)) == 0
&& ((struct sockaddr_in*)addr1)->sin_port == ((struct sockaddr_in*)addr2)->sin_port;
}
else // Must be AF_INET6
{
return memcmp(&((struct sockaddr_in6*)addr1)->sin6_addr,
&((struct sockaddr_in6*)addr2)->sin6_addr, sizeof(((struct sockaddr_in6*)addr1)->sin6_addr)) == 0
&& ((struct sockaddr_in6*)addr1)->sin6_port == ((struct sockaddr_in6*)addr2)->sin6_port;
}
return false;
}
buffer_t massdns_resolvers_from_file(char *filename)
{
char line[4096];
FILE *f = fopen(filename, "r");
if (f == NULL)
{
log_msg("Failed to open resolver file: %s\n", strerror(errno));
clean_exit(EXIT_FAILURE);
}
single_list_t *list = single_list_new();
while (!feof(f))
{
if (fgets(line, sizeof(line), f))
{
trim_end(line);
resolver_t *resolver = safe_calloc(sizeof(*resolver));
struct sockaddr_storage *addr = &resolver->address;
if (str_to_addr(line, 53, addr))
{
if((addr->ss_family == AF_INET && context.sockets.interfaces4.len > 0)
|| (addr->ss_family == AF_INET6 && context.sockets.interfaces6.len > 0))
{
single_list_push_back(list, resolver);
}
else
{
log_msg("No query socket for resolver \"%s\" found.\n", line);
}
}
else
{
log_msg("\"%s\" is not a valid resolver. Skipped.\n", line);
}
}
}
fclose(f);
buffer_t resolvers = single_list_to_array_copy(list, sizeof(resolver_t));
if(single_list_count(list) == 0)
{
log_msg("No usable resolvers were found. Terminating.\n");
clean_exit(EXIT_FAILURE);
}
if(context.cmd_args.verify_ip)
{
context.resolver_map = hashmapCreate(resolvers.len, hash_address, addresses_equal);
if(!context.resolver_map)
{
log_msg("Failed to create resolver lookup map: %s\n", strerror(errno));
abort();
}
for (size_t i = 0; i < resolvers.len; i++)
{
resolver_t *resolver = ((resolver_t*)resolvers.data) + i;
errno = 0;
hashmapPut(context.resolver_map, &resolver->address, resolver);
if (errno != 0)
{
log_msg("Error putting resolver into hashmap: %s\n", strerror(errno));
abort();
}
}
}
single_list_free_with_elements(list);
return resolvers;
}
void set_sndbuf(int fd)
{
if(context.cmd_args.sndbuf
&& setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &context.cmd_args.sndbuf, sizeof(context.cmd_args.sndbuf)) != 0)
{
log_msg("Failed to adjust send buffer size: %s\n", strerror(errno));
}
}
void set_rcvbuf(int fd)
{
if(context.cmd_args.rcvbuf
&& setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &context.cmd_args.rcvbuf, sizeof(context.cmd_args.rcvbuf)) != 0)
{
log_msg("Failed to adjust receive buffer size: %s\n", strerror(errno));
}
}
void add_default_socket(int version)
{
socket_info_t info;
info.descriptor = socket(version == 4 ? PF_INET : PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
info.protocol = version == 4 ? PROTO_IPV4 : PROTO_IPV6;
info.type = SOCKET_TYPE_QUERY;
if(info.descriptor >= 0)
{
buffer_t *buffer = version == 4 ? &context.sockets.interfaces4 : &context.sockets.interfaces6;
buffer->data = safe_realloc(buffer->data, (buffer->len + 1) * sizeof(info));
((socket_info_t*)buffer->data)[buffer->len++] = info;
set_rcvbuf(info.descriptor);
set_sndbuf(info.descriptor);
}
else
{
log_msg("Failed to create IPv%d socket: %s\n", version, strerror(errno));
}
}
void set_user_sockets(single_list_t *bind_addrs, buffer_t *buffer)
{
single_list_t sockets;
single_list_init(&sockets);
single_list_ref_foreach_free(bind_addrs, element)
{
struct sockaddr_storage* addr = element->data;
socket_info_t info;
info.descriptor = socket(addr->ss_family, SOCK_DGRAM, IPPROTO_UDP);
info.protocol = addr->ss_family == AF_INET ? PROTO_IPV4 : PROTO_IPV6;
info.type = SOCKET_TYPE_QUERY;
if(info.descriptor >= 0)
{
if(bind(info.descriptor, (struct sockaddr*)addr, sizeof(*addr)) != 0)
{
log_msg("Not adding socket %s due to bind failure: %s\n", sockaddr2str(addr), strerror(errno));
}
else
{
set_rcvbuf(info.descriptor);
set_sndbuf(info.descriptor);
single_list_push_back(&sockets, flatcopy(&info, sizeof(info)));
}
}
else
{
log_msg("Failed to create IPv%d socket: %s\n", info.protocol, strerror(errno));
}
free(element->data);
}
single_list_init(bind_addrs);
*buffer = single_list_to_array_copy(&sockets, sizeof(socket_info_t));
single_list_clear(&sockets);
}
void query_sockets_setup()
{
if(single_list_count(&context.cmd_args.bind_addrs4) == 0 && single_list_count(&context.cmd_args.bind_addrs6) == 0)
{
for(size_t i = 0; i < context.cmd_args.socket_count; i++)
{
add_default_socket(4);
add_default_socket(6);
}
}
else
{
set_user_sockets(&context.cmd_args.bind_addrs4, &context.sockets.interfaces4);
set_user_sockets(&context.cmd_args.bind_addrs6, &context.sockets.interfaces6);
}
}
bool next_query(char **qname)
{
static char line[512];
static size_t line_index = 0;
while (fgets(line, sizeof(line), context.domainfile))
{
if(line_index >= context.cmd_args.num_processes)
{
line_index = 0;
}
if (context.fork_index != line_index++)
{
continue;
}
trim_end(line);
if (*line == 0)
{
continue;
}
*qname = line;
return true;
}
return false;
}
// This is the djb2 hashing method treating the DNS type as two extra characters
int hash_lookup_key(void *key)
{
unsigned long hash = 5381;
uint8_t *entry = ((lookup_key_t *)key)->name.name;
int c;
while ((c = *entry++) != 0)
{
hash = ((hash << 5) + hash) + tolower(c); /* hash * 33 + c */
}
hash = ((hash << 5) + hash) + ((((lookup_key_t *)key)->type & 0xFF00) >> 8);
hash = ((hash << 5) + hash) + (((lookup_key_t *)key)->type & 0x00FF);
hash = ((hash << 5) + hash) + ((lookup_key_t *)key)->name.length;
return (int)hash;
}
void end_warmup()
{
context.state = STATE_QUERYING;
if(context.cmd_args.extreme <= 1 && !context.cmd_args.busypoll)
{
// Reduce our CPU load from epoll interrupts by removing the EPOLLOUT event
#ifdef PCAP_SUPPORT
if(!context.pcap)
#endif
#ifdef HAVE_EPOLL
{
add_sockets(context.epollfd, EPOLLIN, EPOLL_CTL_MOD, &context.sockets.interfaces4);
add_sockets(context.epollfd, EPOLLIN, EPOLL_CTL_MOD, &context.sockets.interfaces6);
}
#endif
}
}
lookup_t *new_lookup(const char *qname, dns_record_type type, bool *new)
{
if(context.lookup_pool.len == 0)
{
log_msg("Empty lookup pool.\n");
clean_exit(EXIT_FAILURE);
}
lookup_entry_t *entry = ((lookup_entry_t**)context.lookup_pool.data)[--context.lookup_pool.len];
lookup_key_t *key = &entry->key;
key->name.length = (uint8_t)string_copy((char*)key->name.name, qname, sizeof(key->name.name));
if(key->name.name[key->name.length - 1] != '.')
{
key->name.name[key->name.length] = '.';
key->name.name[++key->name.length] = 0;
}
key->type = type;
if(hashmapGet(context.map, key) != NULL)
{
context.lookup_pool.len++;
*new = false;
return NULL;
}
*new = true;
lookup_t *value = &entry->value;
bzero(value, sizeof(*value));
value->ring_entry = timed_ring_add(&context.ring, context.cmd_args.interval_ms * TIMED_RING_MS, value);
urandom_get(&value->transaction, sizeof(value->transaction));
value->key = key;
errno = 0;
hashmapPut(context.map, key, value);
if(errno != 0)
{
log_msg("Error putting lookup into hashmap: %s\n", strerror(errno));
abort();
}
context.lookup_index++;
context.stats.timeouts[0]++;
if(context.lookup_index >= context.cmd_args.hashmap_size)
{
end_warmup();
}
return value;
}
void send_query(lookup_t *lookup)
{
static uint8_t query_buffer[0x200];
// Choose random resolver
// Pool of resolvers cannot be empty due to check after parsing resolvers.
if(!context.cmd_args.sticky || lookup->resolver == NULL)
{
if(context.cmd_args.predictable_resolver)
{
lookup->resolver = ((resolver_t *) context.resolvers.data) + context.lookup_index % context.resolvers.len;
}
else
{
lookup->resolver = ((resolver_t *) context.resolvers.data) + urandom_size_t() % context.resolvers.len;
}
}
// We need to select the correct socket pool: IPv4 socket pool for IPv4 resolver/IPv6 socket pool for IPv6 resolver
buffer_t *interfaces;
if(lookup->resolver->address.ss_family == AF_INET)
{
interfaces = &context.sockets.interfaces4;
}
else
{
interfaces = &context.sockets.interfaces6;
}
if(lookup->socket == NULL)
{
// Pick a random socket from that pool
// Pool of sockets cannot be empty due to check when parsing resolvers. Socket creation must have succeeded.
size_t socket_index = urandom_size_t() % interfaces->len;
lookup->socket = (socket_info_t *) interfaces->data + socket_index;
}
ssize_t result = dns_question_create(query_buffer, (char*)lookup->key->name.name, lookup->key->type,
lookup->transaction);
if (result < DNS_PACKET_MINIMUM_SIZE)
{
log_msg("Failed to create DNS question for query \"%s\".", lookup->key->name.name);
return;
}
// Set or unset the QD bit based on user preference
dns_buf_set_rd(query_buffer, !context.cmd_args.norecurse);
errno = 0;
ssize_t sent = sendto(lookup->socket->descriptor, query_buffer, (size_t) result, 0,
(struct sockaddr *) &lookup->resolver->address,
sockaddr_storage_size(&lookup->resolver->address));
if(sent != result)
{
if(errno != EAGAIN && errno != EWOULDBLOCK)
{
log_msg("Error sending: %s\n", strerror(errno));
}
}
}
#define STAT_IDX_OK 0
#define STAT_IDX_NXDOMAIN 1
#define STAT_IDX_SERVFAIL 2
#define STAT_IDX_REFUSED 3
#define STAT_IDX_FORMERR 4
void my_stats_to_msg(stats_exchange_t *stats_msg)
{
stats_msg->finished = context.stats.finished;
stats_msg->finished_success = context.stats.finished_success;
stats_msg->fork_index = context.fork_index;
stats_msg->mismatch_domain = context.stats.mismatch_domain;
stats_msg->mismatch_id = context.stats.mismatch_id;
stats_msg->numdomains = context.stats.numdomains;
stats_msg->numreplies = context.stats.numreplies;
stats_msg->all_rcodes[STAT_IDX_OK] = context.stats.all_rcodes[DNS_RCODE_OK];
stats_msg->all_rcodes[STAT_IDX_NXDOMAIN] = context.stats.all_rcodes[DNS_RCODE_NXDOMAIN];
stats_msg->all_rcodes[STAT_IDX_SERVFAIL] = context.stats.all_rcodes[DNS_RCODE_SERVFAIL];
stats_msg->all_rcodes[STAT_IDX_REFUSED] = context.stats.all_rcodes[DNS_RCODE_REFUSED];
stats_msg->all_rcodes[STAT_IDX_FORMERR] = context.stats.all_rcodes[DNS_RCODE_FORMERR];
stats_msg->final_rcodes[STAT_IDX_OK] = context.stats.final_rcodes[DNS_RCODE_OK];
stats_msg->final_rcodes[STAT_IDX_NXDOMAIN] = context.stats.final_rcodes[DNS_RCODE_NXDOMAIN];
stats_msg->final_rcodes[STAT_IDX_SERVFAIL] = context.stats.final_rcodes[DNS_RCODE_SERVFAIL];
stats_msg->final_rcodes[STAT_IDX_REFUSED] = context.stats.final_rcodes[DNS_RCODE_REFUSED];
stats_msg->final_rcodes[STAT_IDX_FORMERR] = context.stats.final_rcodes[DNS_RCODE_FORMERR];
stats_msg->current_rate = context.stats.current_rate;
stats_msg->success_rate = context.stats.success_rate;
stats_msg->numparsed = context.stats.numparsed;
stats_msg->done = (context.state >= STATE_DONE);
for(size_t i = 0; i <= context.cmd_args.resolve_count; i++)
{
stats_msg->timeouts[i] = context.stats.timeouts[i];
}
}
void send_stats()
{
static stats_exchange_t stats_msg;
my_stats_to_msg(&stats_msg);
if(write(context.sockets.write_pipe.descriptor, &stats_msg, sizeof(stats_msg)) != sizeof(stats_msg))
{
log_msg("Could not send stats atomically.\n");
}
}
void check_progress()
{
static struct timespec last_time;
static char timeouts[4096];
static struct timespec now;
static const char* stats_format = "\033[H\033[2J" // Clear screen (probably simplest and most portable solution)
"Processed queries: %zu\n"
"Received packets: %zu\n"
"Progress: %.2f%% (%02lld h %02lld min %02lld sec / %02lld h %02lld min %02lld sec)\n"
"Current incoming rate: %zu pps, average: %zu pps\n"
"Current success rate: %zu pps, average: %zu pps\n"
"Finished total: %zu, success: %zu (%.2f%%)\n"
"Mismatched domains: %zu (%.2f%%), IDs: %zu (%.2f%%)\n"
"Failures: %s\n"
"Response: | Success: | Total:\n"
"OK: | %12zu (%6.2f%%) | %12zu (%6.2f%%)\n"
"NXDOMAIN: | %12zu (%6.2f%%) | %12zu (%6.2f%%)\n"
"SERVFAIL: | %12zu (%6.2f%%) | %12zu (%6.2f%%)\n"
"REFUSED: | %12zu (%6.2f%%) | %12zu (%6.2f%%)\n"
"FORMERR: | %12zu (%6.2f%%) | %12zu (%6.2f%%)\n";
clock_gettime(CLOCK_MONOTONIC, &now);
time_t elapsed_ns = (now.tv_sec - last_time.tv_sec) * 1000000000 + (now.tv_nsec - last_time.tv_nsec);
size_t rate_pps = elapsed_ns == 0 ? 0 : context.stats.current_rate * TIMED_RING_S / elapsed_ns;
size_t rate_success = elapsed_ns == 0 ? 0 : context.stats.success_rate * TIMED_RING_S / elapsed_ns;
last_time = now;
// Send the stats of the child to the parent process
if(context.cmd_args.num_processes > 1 && context.fork_index != 0)
{
send_stats();
goto end_stats;
}
if(context.cmd_args.quiet)
{
return;
}
// Go on with printing stats.
float progress = context.state == STATE_DONE ? 1 : 0;
if(context.domainfile_size > 0) // If the domain file is not a real file, the progress cannot be estimated.
{
// Get a rough estimate of the progress, only roughly proportional to the number of domains.
// Will be very inaccurate if the domain file is sorted per domain name length.
long int domain_file_position = ftell(context.domainfile);
if (domain_file_position >= 0)
{
progress = domain_file_position / (float)context.domainfile_size;
}
}
time_t total_elapsed_ns = (now.tv_sec - context.stats.start_time.tv_sec) * 1000000000
+ (now.tv_nsec - context.stats.start_time.tv_nsec); // since last output
long long elapsed = now.tv_sec - context.stats.start_time.tv_sec; // resolution of one second should be okay
long long sec = elapsed % 60;
long long min = (elapsed / 60) % 60;
long long h = elapsed / 3600;
long long estimated_time = progress == 0 ? 0 : (long long)(elapsed / progress);
if(estimated_time < elapsed)
{
estimated_time = elapsed;
}
long long prog_sec = estimated_time % 60;
long long prog_min = (estimated_time / 60) % 60;
long long prog_h = (estimated_time / 3600);
#define stats_percent(a, b) ((b) == 0 ? 0 : (a) / (float) (b) * 100)
#define stat_abs_share(a, b) a, stats_percent(a, b)
#define rcode_stat(code) stat_abs_share(context.stats.final_rcodes[(code)], context.stats.finished_success),\
stat_abs_share(context.stats.all_rcodes[(code)], context.stats.numparsed)
#define rcode_stat_multi(code) stat_abs_share(context.stat_messages[0].final_rcodes[(code)], \
context.stat_messages[0].finished_success),\
stat_abs_share(context.stat_messages[0].all_rcodes[(code)], context.stat_messages[0].numparsed)
if(context.cmd_args.num_processes == 1)
{
size_t average_pps = elapsed == 0 ? rate_pps : context.stats.numreplies * TIMED_RING_S / total_elapsed_ns;
size_t average_success = elapsed == 0 ? rate_success : context.stats.finished_success * TIMED_RING_S / total_elapsed_ns;
// Print the detailed timeout stats (number of tries before timeout) to the timeouts buffer.
int offset = 0;
for (size_t i = 0; i <= context.cmd_args.resolve_count; i++)
{
float share = stats_percent(context.stats.timeouts[i], context.stats.finished);
int result = snprintf(timeouts + offset, sizeof(timeouts) - offset, "%zu: %.2f%%, ", i, share);
if (result <= 0 || result >= sizeof(timeouts) - offset)
{
break;
}
offset += result;
}
fprintf(stderr,
stats_format,
context.stats.numdomains,
context.stats.numreplies,
progress * 100, h, min, sec, prog_h, prog_min, prog_sec, rate_pps, average_pps,
rate_success, average_success,
context.stats.finished,
stat_abs_share(context.stats.finished_success, context.stats.finished),
stat_abs_share(context.stats.mismatch_domain, context.stats.numparsed),
stat_abs_share(context.stats.mismatch_id, context.stats.numparsed),
timeouts,
rcode_stat(DNS_RCODE_OK),
rcode_stat(DNS_RCODE_NXDOMAIN),
rcode_stat(DNS_RCODE_SERVFAIL),
rcode_stat(DNS_RCODE_REFUSED),
rcode_stat(DNS_RCODE_FORMERR)
);
}
else
{
my_stats_to_msg(&context.stat_messages[0]);
for(size_t j = 1; j < context.cmd_args.num_processes; j++)
{
for (size_t i = 0; i <= context.cmd_args.resolve_count; i++)
{
context.stat_messages[0].timeouts[i] += context.stat_messages[j].timeouts[i];
}
context.stat_messages[0].numreplies += context.stat_messages[j].numreplies;
context.stat_messages[0].numparsed += context.stat_messages[j].numparsed;
context.stat_messages[0].numdomains += context.stat_messages[j].numdomains;
context.stat_messages[0].mismatch_id += context.stat_messages[j].mismatch_id;
context.stat_messages[0].mismatch_domain += context.stat_messages[j].mismatch_domain;
context.stat_messages[0].finished_success += context.stat_messages[j].finished_success;
context.stat_messages[0].finished += context.stat_messages[j].finished;
for(size_t i = 0; i < 5; i++)
{
context.stat_messages[0].all_rcodes[i] += context.stat_messages[j].all_rcodes[i];
}
for(size_t i = 0; i < 5; i++)
{
context.stat_messages[0].final_rcodes[i] += context.stat_messages[j].final_rcodes[i];
}
rate_pps += context.stat_messages[j].current_rate;
rate_success += context.stat_messages[j].success_rate;
}
size_t average_pps = elapsed == 0 ? rate_pps :
context.stat_messages[0].numreplies * TIMED_RING_S / total_elapsed_ns;
size_t average_success = elapsed == 0 ? rate_pps :
context.stat_messages[0].finished_success * TIMED_RING_S / total_elapsed_ns;
// Print the detailed timeout stats (number of tries before timeout) to the timeouts buffer.
int offset = 0;
for (size_t i = 0; i <= context.cmd_args.resolve_count; i++)
{
float share = stats_percent(context.stat_messages[0].timeouts[i], context.stat_messages[0].finished);
int result = snprintf(timeouts + offset, sizeof(timeouts) - offset, "%zu: %.2f%%, ", i, share);
if (result <= 0 || result >= sizeof(timeouts) - offset)
{
break;
}
offset += result;
}
fprintf(stderr,
stats_format,
context.stat_messages[0].numdomains,
context.stat_messages[0].numreplies,
progress * 100, h, min, sec, prog_h, prog_min, prog_sec, rate_pps, average_pps,
rate_success, average_success,
context.stat_messages[0].finished,
stat_abs_share(context.stat_messages[0].finished_success, context.stat_messages[0].finished),
stat_abs_share(context.stat_messages[0].mismatch_domain, context.stat_messages[0].numparsed),
stat_abs_share(context.stat_messages[0].mismatch_id, context.stat_messages[0].numparsed),
timeouts,
rcode_stat_multi(STAT_IDX_OK),
rcode_stat_multi(STAT_IDX_NXDOMAIN),
rcode_stat_multi(STAT_IDX_SERVFAIL),
rcode_stat_multi(STAT_IDX_REFUSED),
rcode_stat_multi(STAT_IDX_FORMERR)
);
}
end_stats:
context.stats.current_rate = 0;
context.stats.success_rate = 0;
// Call this function in about one second again
timed_ring_add(&context.ring, TIMED_RING_S, check_progress);
}
void done()
{
context.done[context.fork_index] = true;
if(context.fork_index != 0 || context.cmd_args.num_processes == 1)
{
context.state = STATE_DONE;
}
else
{
context.finished++;
context.state = (context.finished < context.cmd_args.num_processes ? STATE_WAIT_CHILDREN : STATE_DONE);
}
if(context.cmd_args.num_processes > 1 && context.fork_index != 0)
{
send_stats();
}
check_progress();
}
void can_send()
{
char *qname;
bool new;
while (hashmapSize(context.map) < context.cmd_args.hashmap_size && context.state <= STATE_QUERYING)
{
if(!next_query(&qname))
{
context.state = STATE_COOLDOWN; // We will not create any new queries
break;
}
context.stats.numdomains++;
lookup_t *lookup = new_lookup(qname, context.cmd_args.record_type, &new);
if(!new)
{
continue;
}
send_query(lookup);
}
}
bool is_unacceptable(dns_pkt_t *packet)
{
return context.cmd_args.retry_codes[packet->head.header.rcode];
}
void lookup_done(lookup_t *lookup)
{
context.stats.finished++;
hashmapRemove(context.map, lookup->key);
// Return lookup to pool.
// According to ISO/IEC 9899:TC2 §6.7.2.1 (13), structs are not padded at the beginning
((lookup_key_t**)context.lookup_pool.data)[context.lookup_pool.len++] = lookup->key;
// When transmission is not aggressive, we only start a new lookup after another one has finished.
// When our transmission is very aggressive, we also start a new lookup, although we listen for EPOLLOUT
// events as well.
if(context.cmd_args.extreme == 0 || context.cmd_args.extreme == 2)
{
can_send();
}
if(context.state == STATE_COOLDOWN && hashmapSize(context.map) <= 0)
{
done();
}
}
bool retry(lookup_t *lookup)
{
context.stats.timeouts[lookup->tries]--;
context.stats.timeouts[++lookup->tries]++;
if(lookup->tries < context.cmd_args.resolve_count)
{
lookup->ring_entry = timed_ring_add(&context.ring, context.cmd_args.interval_ms * TIMED_RING_MS, lookup);
send_query(lookup);
return true;
}
return false;
}
void ring_timeout(void *param)
{
if(param == check_progress)
{
check_progress();
return;
}
lookup_t *lookup = param;
if(!retry(lookup))
{
lookup_done(lookup);
}
}
void do_read(uint8_t *offset, size_t len, struct sockaddr_storage *recvaddr)
{
static dns_pkt_t packet;
static uint8_t *parse_offset;
static lookup_t *lookup;
static resolver_t* resolver;
static char json_buffer[0xFFFF];
context.stats.current_rate++;
context.stats.numreplies++;
if(context.cmd_args.verify_ip)
{
resolver = hashmapGet(context.resolver_map, recvaddr);
if(resolver == NULL)
{
//log_msg("Fake/NAT reply from %s\n", sockaddr2str(recvaddr));
return;
}
}
if(!dns_parse_question(offset, len, &packet.head, &parse_offset))
{
return;
}
context.stats.numparsed++;
context.stats.all_rcodes[packet.head.header.rcode]++;
// TODO: Remove unnecessary copy.
//search_key.domain = (char*)packet.head.question.name.name;
lookup = hashmapGet(context.map, &packet.head.question);
if(!lookup) // Most likely reason: delayed response after duplicate query
{
context.stats.mismatch_domain++;
return;
}
if(lookup->transaction != packet.head.header.id)
{
context.stats.mismatch_id++;
return;
}
timed_ring_remove(&context.ring, lookup->ring_entry); // Clear timeout trigger
// Check whether we want to retry resending the packet
if(is_unacceptable(&packet))
{
// We may have tried to many times already.
if(!retry(lookup))
{
// If this is the case, we will not try again.
lookup_done(lookup);
}
}
else
{
// We are done with the lookup because we received an acceptable reply.
context.stats.finished_success++;
context.stats.final_rcodes[packet.head.header.rcode]++;
context.stats.success_rate++;
// Print packet
time_t now = time(NULL);
uint16_t short_len = (uint16_t) len;
uint8_t *next = parse_offset;
dns_record_t rec;
size_t non_add_count = packet.head.header.ans_count + packet.head.header.auth_count;
dns_section_t section = DNS_SECTION_ANSWER;
switch(context.cmd_args.output)
{
case OUTPUT_BINARY:
// The output file is platform dependent for performance reasons.
fwrite(&now, sizeof(now), 1, context.outfile);
fwrite(recvaddr, sizeof(*recvaddr), 1, context.outfile);
fwrite(&short_len, sizeof(short_len), 1, context.outfile);
fwrite(offset, short_len, 1, context.outfile);
break;
case OUTPUT_TEXT_FULL: // Print packet similar to dig style
// Resolver and timestamp are not part of the packet, we therefore have to print it manually
fprintf(context.outfile, ";; Server: %s\n;; Size: %" PRIu16 "\n;; Unix time: %lu\n",
sockaddr2str(recvaddr), short_len, now);
dns_print_packet(context.outfile, &packet, offset, len, next);
break;
case OUTPUT_NDJSON: // Only print records from answer section that match the query name (in ndjson)
for(size_t rec_index = 0; dns_parse_record_raw(offset, next, offset + len, &next, &rec); rec_index++)
{