-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
nsd.c
1725 lines (1583 loc) · 45 KB
/
nsd.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
/*
* nsd.c -- nsd(8)
*
* Copyright (c) 2001-2024, NLnet Labs. All rights reserved.
*
* See LICENSE for the license.
*
*/
#include "config.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef HAVE_GRP_H
#include <grp.h>
#endif /* HAVE_GRP_H */
#ifdef HAVE_SETUSERCONTEXT
#ifdef HAVE_LOGIN_CAP_H
#include <login_cap.h>
#endif /* HAVE_LOGIN_CAP_H */
#endif /* HAVE_SETUSERCONTEXT */
#ifdef HAVE_OPENSSL_RAND_H
#include <openssl/rand.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <pwd.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef HAVE_IFADDRS_H
#include <ifaddrs.h>
#endif
#include "nsd.h"
#include "options.h"
#include "tsig.h"
#include "remote.h"
#include "xfrd-disk.h"
#include "ipc.h"
#ifdef USE_DNSTAP
#include "dnstap/dnstap_collector.h"
#endif
#include "util/proxy_protocol.h"
/* The server handler... */
struct nsd nsd;
static char hostname[MAXHOSTNAMELEN];
extern config_parser_state_type* cfg_parser;
static void version(void) ATTR_NORETURN;
/*
* Print the help text.
*
*/
static void
usage (void)
{
fprintf(stderr, "Usage: nsd [OPTION]...\n");
fprintf(stderr, "Name Server Daemon.\n\n");
fprintf(stderr,
"Supported options:\n"
" -4 Only listen to IPv4 connections.\n"
" -6 Only listen to IPv6 connections.\n"
" -a ip-address[@port] Listen to the specified incoming IP address (and port)\n"
" May be specified multiple times).\n"
" -c configfile Read specified configfile instead of %s.\n"
" -d do not fork as a daemon process.\n"
#ifndef NDEBUG
" -F facilities Specify the debug facilities.\n"
#endif /* NDEBUG */
" -h Print this help information.\n"
, CONFIGFILE);
fprintf(stderr,
" -i identity Specify the identity when queried for id.server CHAOS TXT.\n"
" -I nsid Specify the NSID. This must be a hex string.\n"
#ifndef NDEBUG
" -L level Specify the debug level.\n"
#endif /* NDEBUG */
" -l filename Specify the log file.\n"
" -N server-count The number of servers to start.\n"
" -n tcp-count The maximum number of TCP connections per server.\n"
" -P pidfile Specify the PID file to write.\n"
" -p port Specify the port to listen to.\n"
" -s seconds Dump statistics every SECONDS seconds.\n"
" -t chrootdir Change root to specified directory on startup.\n"
);
fprintf(stderr,
" -u user Change effective uid to the specified user.\n"
" -V level Specify verbosity level.\n"
" -v Print version information.\n"
);
fprintf(stderr, "Version %s. Report bugs to <%s>.\n",
PACKAGE_VERSION, PACKAGE_BUGREPORT);
}
/*
* Print the version exit.
*
*/
static void
version(void)
{
fprintf(stderr, "%s version %s\n", PACKAGE_NAME, PACKAGE_VERSION);
fprintf(stderr, "Written by NLnet Labs.\n\n");
fprintf(stderr, "Configure line: %s\n", CONFCMDLINE);
#ifdef USE_MINI_EVENT
fprintf(stderr, "Event loop: internal (uses select)\n");
#else
# if defined(HAVE_EV_LOOP) || defined(HAVE_EV_DEFAULT_LOOP)
fprintf(stderr, "Event loop: %s %s (uses %s)\n",
"libev",
nsd_event_vs(),
nsd_event_method());
# else
fprintf(stderr, "Event loop: %s %s (uses %s)\n",
"libevent",
nsd_event_vs(),
nsd_event_method());
# endif
#endif
#ifdef HAVE_SSL
fprintf(stderr, "Linked with %s\n\n",
# ifdef SSLEAY_VERSION
SSLeay_version(SSLEAY_VERSION)
# else
OpenSSL_version(OPENSSL_VERSION)
# endif
);
#endif
fprintf(stderr,
"Copyright (C) 2001-2024 NLnet Labs. This is free software.\n"
"There is NO warranty; not even for MERCHANTABILITY or FITNESS\n"
"FOR A PARTICULAR PURPOSE.\n");
exit(0);
}
static void
setup_verifier_environment(void)
{
size_t i;
int ret, ip4, ip6;
char *buf, host[NI_MAXHOST], serv[NI_MAXSERV];
size_t size, cnt = 0;
/* allocate large enough buffer to hold a list of all ip addresses.
((" " + INET6_ADDRSTRLEN + "@" + "65535") * n) + "\0" */
size = ((INET6_ADDRSTRLEN + 1 + 5 + 1) * nsd.verify_ifs) + 1;
buf = xalloc(size);
ip4 = ip6 = 0;
for(i = 0; i < nsd.verify_ifs; i++) {
ret = getnameinfo(
(struct sockaddr *)&nsd.verify_udp[i].addr.ai_addr,
nsd.verify_udp[i].addr.ai_addrlen,
host, sizeof(host), serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV);
if(ret != 0) {
log_msg(LOG_ERR, "error in getnameinfo: %s",
gai_strerror(ret));
continue;
}
buf[cnt++] = ' ';
cnt += strlcpy(&buf[cnt], host, size - cnt);
assert(cnt < size);
buf[cnt++] = '@';
cnt += strlcpy(&buf[cnt], serv, size - cnt);
assert(cnt < size);
#ifdef INET6
if (nsd.verify_udp[i].addr.ai_family == AF_INET6 && !ip6) {
setenv("VERIFY_IPV6_ADDRESS", host, 1);
setenv("VERIFY_IPV6_PORT", serv, 1);
setenv("VERIFY_IP_ADDRESS", host, 1);
setenv("VERIFY_PORT", serv, 1);
ip6 = 1;
} else
#endif
if (!ip4) {
assert(nsd.verify_udp[i].addr.ai_family == AF_INET);
setenv("VERIFY_IPV4_ADDRESS", host, 1);
setenv("VERIFY_IPV4_PORT", serv, 1);
if (!ip6) {
setenv("VERIFY_IP_ADDRESS", host, 1);
setenv("VERIFY_PORT", serv, 1);
}
ip4 = 1;
}
}
setenv("VERIFY_IP_ADDRESSES", &buf[1], 1);
free(buf);
}
static void
copyaddrinfo(struct nsd_addrinfo *dest, struct addrinfo *src)
{
dest->ai_flags = src->ai_flags;
dest->ai_family = src->ai_family;
dest->ai_socktype = src->ai_socktype;
dest->ai_addrlen = src->ai_addrlen;
memcpy(&dest->ai_addr, src->ai_addr, src->ai_addrlen);
}
static void
setup_socket(
struct nsd_socket *sock, const char *node, const char *port,
struct addrinfo *hints)
{
int ret;
char *host;
char host_buf[sizeof("65535") + INET6_ADDRSTRLEN + 1 /* '\0' */];
const char *service;
struct addrinfo *addr = NULL;
sock->fib = -1;
if(node) {
char *sep;
if (strlcpy(host_buf, node, sizeof(host_buf)) >= sizeof(host_buf)) {
error("cannot parse address '%s': %s", node,
strerror(ENAMETOOLONG));
}
host = host_buf;
sep = strchr(host_buf, '@');
if(sep != NULL) {
*sep = '\0';
service = sep + 1;
} else {
service = port;
}
} else {
host = NULL;
service = port;
}
if((ret = getaddrinfo(host, service, hints, &addr)) == 0) {
copyaddrinfo(&sock->addr, addr);
freeaddrinfo(addr);
} else {
error("cannot parse address '%s': getaddrinfo: %s %s",
host ? host : "(null)",
gai_strerror(ret),
ret==EAI_SYSTEM ? strerror(errno) : "");
}
}
static void
figure_socket_servers(
struct nsd_socket *sock, struct ip_address_option *ip)
{
int i;
struct range_option *server;
sock->servers = xalloc_zero(nsd_bitset_size(nsd.child_count));
region_add_cleanup(nsd.region, free, sock->servers);
nsd_bitset_init(sock->servers, nsd.child_count);
if(!ip || !ip->servers) {
/* every server must listen on this socket */
for(i = 0; i < (int)nsd.child_count; i++) {
nsd_bitset_set(sock->servers, i);
}
return;
}
/* only specific servers must listen on this socket */
for(server = ip->servers; server; server = server->next) {
if(server->first == server->last) {
if(server->first <= 0) {
error("server %d specified for ip-address %s "
"is invalid; server ranges are 1-based",
server->first, ip->address);
} else if(server->last > (int)nsd.child_count) {
error("server %d specified for ip-address %s "
"exceeds number of servers configured "
"in server-count",
server->first, ip->address);
}
} else {
/* parse_range must ensure range itself is valid */
assert(server->first < server->last);
if(server->first <= 0) {
error("server range %d-%d specified for "
"ip-address %s is invalid; server "
"ranges are 1-based",
server->first, server->last, ip->address);
} else if(server->last > (int)nsd.child_count) {
error("server range %d-%d specified for "
"ip-address %s exceeds number of servers "
"configured in server-count",
server->first, server->last, ip->address);
}
}
for(i = server->first - 1; i < server->last; i++) {
nsd_bitset_set(sock->servers, i);
}
}
}
static void
figure_default_sockets(
struct nsd_socket **udp, struct nsd_socket **tcp, size_t *ifs,
const char *node, const char *udp_port, const char *tcp_port,
const struct addrinfo *hints)
{
size_t i = 0, n = 1;
struct addrinfo ai[2] = { *hints, *hints };
assert(udp != NULL);
assert(tcp != NULL);
assert(ifs != NULL);
ai[0].ai_socktype = SOCK_DGRAM;
ai[1].ai_socktype = SOCK_STREAM;
#ifdef INET6
#ifdef IPV6_V6ONLY
if (hints->ai_family == AF_UNSPEC) {
ai[0].ai_family = AF_INET6;
ai[1].ai_family = AF_INET6;
n++;
}
#endif /* IPV6_V6ONLY */
#endif /* INET6 */
*udp = xalloc_zero((n + 1) * sizeof(struct nsd_socket));
*tcp = xalloc_zero((n + 1) * sizeof(struct nsd_socket));
region_add_cleanup(nsd.region, free, *udp);
region_add_cleanup(nsd.region, free, *tcp);
#ifdef INET6
if(hints->ai_family == AF_UNSPEC) {
/*
* With IPv6 we'd like to open two separate sockets, one for
* IPv4 and one for IPv6, both listening to the wildcard
* address (unless the -4 or -6 flags are specified).
*
* However, this is only supported on platforms where we can
* turn the socket option IPV6_V6ONLY _on_. Otherwise we just
* listen to a single IPv6 socket and any incoming IPv4
* connections will be automatically mapped to our IPv6
* socket.
*/
#ifdef IPV6_V6ONLY
int r;
struct addrinfo *addrs[2] = { NULL, NULL };
if((r = getaddrinfo(node, udp_port, &ai[0], &addrs[0])) == 0 &&
(r = getaddrinfo(node, tcp_port, &ai[1], &addrs[1])) == 0)
{
(*udp)[i].flags |= NSD_SOCKET_IS_OPTIONAL;
(*udp)[i].fib = -1;
copyaddrinfo(&(*udp)[i].addr, addrs[0]);
figure_socket_servers(&(*udp)[i], NULL);
(*tcp)[i].flags |= NSD_SOCKET_IS_OPTIONAL;
(*tcp)[i].fib = -1;
copyaddrinfo(&(*tcp)[i].addr, addrs[1]);
figure_socket_servers(&(*tcp)[i], NULL);
i++;
} else {
log_msg(LOG_WARNING, "No IPv6, fallback to IPv4. getaddrinfo: %s",
r == EAI_SYSTEM ? strerror(errno) : gai_strerror(r));
}
if(addrs[0])
freeaddrinfo(addrs[0]);
if(addrs[1])
freeaddrinfo(addrs[1]);
ai[0].ai_family = AF_INET;
ai[1].ai_family = AF_INET;
#endif /* IPV6_V6ONLY */
}
#endif /* INET6 */
*ifs = i + 1;
setup_socket(&(*udp)[i], node, udp_port, &ai[0]);
figure_socket_servers(&(*udp)[i], NULL);
setup_socket(&(*tcp)[i], node, tcp_port, &ai[1]);
figure_socket_servers(&(*tcp)[i], NULL);
}
#ifdef HAVE_GETIFADDRS
static int
find_device(
struct nsd_socket *sock,
const struct ifaddrs *ifa)
{
for(; ifa != NULL; ifa = ifa->ifa_next) {
if((ifa->ifa_addr == NULL) ||
(ifa->ifa_addr->sa_family != sock->addr.ai_family) ||
((ifa->ifa_flags & IFF_UP) == 0 ||
(ifa->ifa_flags & IFF_LOOPBACK) != 0 ||
(ifa->ifa_flags & IFF_RUNNING) == 0))
{
continue;
}
#ifdef INET6
if(ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *sa1, *sa2;
size_t sz = sizeof(struct in6_addr);
sa1 = (struct sockaddr_in6 *)ifa->ifa_addr;
sa2 = (struct sockaddr_in6 *)&sock->addr.ai_addr;
if(memcmp(&sa1->sin6_addr, &sa2->sin6_addr, sz) == 0) {
break;
}
} else
#endif
if(ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in *sa1, *sa2;
sa1 = (struct sockaddr_in *)ifa->ifa_addr;
sa2 = (struct sockaddr_in *)&sock->addr.ai_addr;
if(sa1->sin_addr.s_addr == sa2->sin_addr.s_addr) {
break;
}
}
}
if(ifa != NULL) {
size_t len = strlcpy(sock->device, ifa->ifa_name, sizeof(sock->device));
if(len < sizeof(sock->device)) {
char *colon = strchr(sock->device, ':');
if(colon != NULL)
*colon = '\0';
return 1;
}
}
return 0;
}
#endif /* HAVE_GETIFADDRS */
static void
figure_sockets(
struct nsd_socket **udp, struct nsd_socket **tcp, size_t *ifs,
struct ip_address_option *ips,
const char *node, const char *udp_port, const char *tcp_port,
const struct addrinfo *hints)
{
size_t i = 0;
struct addrinfo ai = *hints;
struct ip_address_option *ip;
#ifdef HAVE_GETIFADDRS
struct ifaddrs *ifa = NULL;
#endif
int bind_device = 0;
if(!ips) {
figure_default_sockets(
udp, tcp, ifs, node, udp_port, tcp_port, hints);
return;
}
*ifs = 0;
for(ip = ips; ip; ip = ip->next) {
(*ifs)++;
bind_device |= (ip->dev != 0);
}
#ifdef HAVE_GETIFADDRS
if(bind_device && getifaddrs(&ifa) == -1) {
error("getifaddrs failed: %s", strerror(errno));
}
#endif
*udp = xalloc_zero((*ifs + 1) * sizeof(struct nsd_socket));
*tcp = xalloc_zero((*ifs + 1) * sizeof(struct nsd_socket));
region_add_cleanup(nsd.region, free, *udp);
region_add_cleanup(nsd.region, free, *tcp);
ai.ai_flags |= AI_NUMERICHOST;
for(ip = ips, i = 0; ip; ip = ip->next, i++) {
ai.ai_socktype = SOCK_DGRAM;
setup_socket(&(*udp)[i], ip->address, udp_port, &ai);
figure_socket_servers(&(*udp)[i], ip);
ai.ai_socktype = SOCK_STREAM;
setup_socket(&(*tcp)[i], ip->address, tcp_port, &ai);
figure_socket_servers(&(*tcp)[i], ip);
if(ip->fib != -1) {
(*udp)[i].fib = ip->fib;
(*tcp)[i].fib = ip->fib;
}
#ifdef HAVE_GETIFADDRS
if(ip->dev != 0) {
(*udp)[i].flags |= NSD_BIND_DEVICE;
(*tcp)[i].flags |= NSD_BIND_DEVICE;
if(ifa != NULL && (find_device(&(*udp)[i], ifa) == 0 ||
find_device(&(*tcp)[i], ifa) == 0))
{
error("cannot find device for ip-address %s",
ip->address);
}
}
#endif
}
assert(i == *ifs);
#ifdef HAVE_GETIFADDRS
if(ifa != NULL) {
freeifaddrs(ifa);
}
#endif
}
/* print server affinity for given socket. "*" if socket has no affinity with
any specific server, "x-y" if socket has affinity with more than two
consecutively numbered servers, "x" if socket has affinity with a specific
server number, which is not necessarily just one server. e.g. "1 3" is
printed if socket has affinity with servers number one and three, but not
server number two. */
static ssize_t
print_socket_servers(struct nsd_socket *sock, char *buf, size_t bufsz)
{
int i, x, y, z, n = (int)(sock->servers->size);
char *sep = "";
size_t off, tot;
ssize_t cnt = 0;
assert(bufsz != 0);
off = tot = 0;
x = y = z = -1;
for (i = 0; i <= n; i++) {
if (i == n || !nsd_bitset_isset(sock->servers, i)) {
cnt = 0;
if (i == n && x == -1) {
assert(y == -1);
assert(z == -1);
cnt = snprintf(buf, bufsz, "-");
} else if (y > z) {
assert(x > z);
if (x == 0 && y == (n - 1)) {
assert(z == -1);
cnt = snprintf(buf+off, bufsz-off,
"*");
} else if (x == y) {
cnt = snprintf(buf+off, bufsz-off,
"%s%d", sep, x+1);
} else if (x == (y - 1)) {
cnt = snprintf(buf+off, bufsz-off,
"%s%d %d", sep, x+1, y+1);
} else {
assert(y > (x + 1));
cnt = snprintf(buf+off, bufsz-off,
"%s%d-%d", sep, x+1, y+1);
}
}
z = i;
if (cnt > 0) {
tot += (size_t)cnt;
off = (tot < bufsz) ? tot : bufsz - 1;
sep = " ";
} else if (cnt < 0) {
return -1;
}
} else if (x <= z) {
x = y = i;
} else {
assert(x > z);
y = i;
}
}
return tot;
}
static void
print_sockets(
struct nsd_socket *udp, struct nsd_socket *tcp, size_t ifs)
{
char sockbuf[INET6_ADDRSTRLEN + 6 + 1];
char *serverbuf;
size_t i, serverbufsz, servercnt;
const char *fmt = "listen on ip-address %s (%s) with server(s): %s";
struct nsd_bitset *servers;
if(ifs == 0) {
return;
}
assert(udp != NULL);
assert(tcp != NULL);
servercnt = udp[0].servers->size;
serverbufsz = (((servercnt / 10) * servercnt) + servercnt) + 1;
serverbuf = xalloc(serverbufsz);
/* warn user of unused servers */
servers = xalloc(nsd_bitset_size(servercnt));
nsd_bitset_init(servers, (size_t)servercnt);
for(i = 0; i < ifs; i++) {
assert(udp[i].servers->size == servercnt);
addrport2str((void*)&udp[i].addr.ai_addr, sockbuf, sizeof(sockbuf));
print_socket_servers(&udp[i], serverbuf, serverbufsz);
nsd_bitset_or(servers, servers, udp[i].servers);
VERBOSITY(3, (LOG_NOTICE, fmt, sockbuf, "udp", serverbuf));
assert(tcp[i].servers->size == servercnt);
addrport2str((void*)&tcp[i].addr.ai_addr, sockbuf, sizeof(sockbuf));
print_socket_servers(&tcp[i], serverbuf, serverbufsz);
nsd_bitset_or(servers, servers, tcp[i].servers);
VERBOSITY(3, (LOG_NOTICE, fmt, sockbuf, "tcp", serverbuf));
}
/* warn user of unused servers */
for(i = 0; i < servercnt; i++) {
if(!nsd_bitset_isset(servers, i)) {
log_msg(LOG_WARNING, "server %zu will not listen on "
"any specified ip-address", i+1);
}
}
free(serverbuf);
free(servers);
}
#ifdef HAVE_CPUSET_T
static void free_cpuset(void *ptr)
{
cpuset_t *set = (cpuset_t *)ptr;
cpuset_destroy(set);
}
#endif
/*
* Fetch the nsd parent process id from the nsd pidfile
*
*/
pid_t
readpid(const char *file)
{
int fd;
pid_t pid;
char pidbuf[16];
char *t;
int l;
if ((fd = open(file, O_RDONLY)) == -1) {
return -1;
}
if (((l = read(fd, pidbuf, sizeof(pidbuf)))) == -1) {
close(fd);
return -1;
}
close(fd);
/* Empty pidfile means no pidfile... */
if (l == 0) {
errno = ENOENT;
return -1;
}
pid = (pid_t) strtol(pidbuf, &t, 10);
if (*t && *t != '\n') {
return -1;
}
return pid;
}
/*
* Store the nsd parent process id in the nsd pidfile
*
*/
int
writepid(struct nsd *nsd)
{
int fd;
char pidbuf[32];
size_t count = 0;
if(!nsd->pidfile || !nsd->pidfile[0])
return 0;
snprintf(pidbuf, sizeof(pidbuf), "%lu\n", (unsigned long) nsd->pid);
if((fd = open(nsd->pidfile, O_WRONLY | O_CREAT | O_TRUNC
#ifdef O_NOFOLLOW
| O_NOFOLLOW
#endif
, 0644)) == -1) {
log_msg(LOG_ERR, "cannot open pidfile %s: %s",
nsd->pidfile, strerror(errno));
return -1;
}
while(count < strlen(pidbuf)) {
ssize_t r = write(fd, pidbuf+count, strlen(pidbuf)-count);
if(r == -1) {
if(errno == EAGAIN || errno == EINTR)
continue;
log_msg(LOG_ERR, "cannot write pidfile %s: %s",
nsd->pidfile, strerror(errno));
close(fd);
return -1;
} else if(r == 0) {
log_msg(LOG_ERR, "cannot write any bytes to "
"pidfile %s: write returns 0 bytes written",
nsd->pidfile);
close(fd);
return -1;
}
count += r;
}
close(fd);
return 0;
}
void
unlinkpid(const char* file, const char* username)
{
int fd = -1;
if (file && file[0]) {
/* truncate pidfile */
fd = open(file, O_WRONLY | O_TRUNC
#ifdef O_NOFOLLOW
| O_NOFOLLOW
#endif
, 0644);
if (fd == -1) {
/* Truncate the pid file. */
/* If there is a username configured, we assume that
* due to privilege drops, NSD cannot truncate or
* unlink the pid file. NSD does not chown the file
* because that creates a privilege escape. */
if(username && username[0]) {
VERBOSITY(5, (LOG_INFO, "can not truncate the pid file %s: %s", file, strerror(errno)));
} else {
log_msg(LOG_ERR, "can not truncate the pid file %s: %s", file, strerror(errno));
}
} else {
close(fd);
}
/* unlink pidfile */
if (unlink(file) == -1) {
/* this unlink may not work if the pidfile is located
* outside of the chroot/workdir or we no longer
* have permissions */
if(username && username[0]) {
VERBOSITY(5, (LOG_INFO,
"failed to unlink pidfile %s: %s",
file, strerror(errno)));
} else {
VERBOSITY(3, (LOG_WARNING,
"failed to unlink pidfile %s: %s",
file, strerror(errno)));
}
}
}
}
/*
* Incoming signals, set appropriate actions.
*
*/
void
sig_handler(int sig)
{
/* To avoid race cond. We really don't want to use log_msg() in this handler */
/* Are we a child server? */
if (nsd.server_kind != NSD_SERVER_MAIN) {
switch (sig) {
case SIGCHLD:
nsd.signal_hint_child = 1;
break;
case SIGALRM:
break;
case SIGINT:
case SIGTERM:
nsd.signal_hint_quit = 1;
break;
case SIGILL:
case SIGUSR1: /* Dump stats on SIGUSR1. */
nsd.signal_hint_statsusr = 1;
break;
default:
break;
}
return;
}
/* We are the main process */
switch (sig) {
case SIGCHLD:
nsd.signal_hint_child = 1;
return;
case SIGHUP:
nsd.signal_hint_reload_hup = 1;
return;
case SIGALRM:
nsd.signal_hint_stats = 1;
break;
case SIGILL:
/*
* For backwards compatibility with BIND 8 and older
* versions of NSD.
*/
nsd.signal_hint_statsusr = 1;
break;
case SIGUSR1:
/* Dump statistics. */
nsd.signal_hint_statsusr = 1;
break;
case SIGINT:
case SIGTERM:
default:
nsd.signal_hint_shutdown = 1;
break;
}
}
/*
* Statistic output...
*
*/
#ifdef BIND8_STATS
void
bind8_stats (struct nsd *nsd)
{
char buf[MAXSYSLOGMSGLEN];
char *msg, *t;
int i, len;
struct nsdst st;
/* Current time... */
time_t now;
if(!nsd->st_period)
return;
time(&now);
memcpy(&st, nsd->st, sizeof(st));
stats_subtract(&st, &nsd->stat_proc);
/* NSTATS */
t = msg = buf + snprintf(buf, MAXSYSLOGMSGLEN, "NSTATS %lld %lu",
(long long) now, (unsigned long) st.boot);
for (i = 0; i <= 255; i++) {
/* How much space left? */
if ((len = buf + MAXSYSLOGMSGLEN - t) < 32) {
log_msg(LOG_INFO, "%s", buf);
t = msg;
len = buf + MAXSYSLOGMSGLEN - t;
}
if (st.qtype[i] != 0) {
t += snprintf(t, len, " %s=%lu", rrtype_to_string(i), st.qtype[i]);
}
}
if (t > msg)
log_msg(LOG_INFO, "%s", buf);
/* XSTATS */
/* Only print it if we're in the main daemon or have anything to report... */
if (nsd->server_kind == NSD_SERVER_MAIN
|| st.dropped || st.raxfr || st.rixfr || (st.qudp + st.qudp6 - st.dropped)
|| st.txerr || st.opcode[OPCODE_QUERY] || st.opcode[OPCODE_IQUERY]
|| st.wrongzone || st.ctcp + st.ctcp6 || st.rcode[RCODE_SERVFAIL]
|| st.rcode[RCODE_FORMAT] || st.nona || st.rcode[RCODE_NXDOMAIN]
|| st.opcode[OPCODE_UPDATE]) {
log_msg(LOG_INFO, "XSTATS %lld %lu"
" RR=%lu RNXD=%lu RFwdR=%lu RDupR=%lu RFail=%lu RFErr=%lu RErr=%lu RAXFR=%lu RIXFR=%lu"
" RLame=%lu ROpts=%lu SSysQ=%lu SAns=%lu SFwdQ=%lu SDupQ=%lu SErr=%lu RQ=%lu"
" RIQ=%lu RFwdQ=%lu RDupQ=%lu RTCP=%lu SFwdR=%lu SFail=%lu SFErr=%lu SNaAns=%lu"
" SNXD=%lu RUQ=%lu RURQ=%lu RUXFR=%lu RUUpd=%lu",
(long long) now, (unsigned long) st.boot,
st.dropped, (unsigned long)0, (unsigned long)0, (unsigned long)0, (unsigned long)0,
(unsigned long)0, (unsigned long)0, st.raxfr, st.rixfr, (unsigned long)0, (unsigned long)0,
(unsigned long)0, st.qudp + st.qudp6 - st.dropped, (unsigned long)0,
(unsigned long)0, st.txerr,
st.opcode[OPCODE_QUERY], st.opcode[OPCODE_IQUERY], st.wrongzone,
(unsigned long)0, st.ctcp + st.ctcp6,
(unsigned long)0, st.rcode[RCODE_SERVFAIL], st.rcode[RCODE_FORMAT],
st.nona, st.rcode[RCODE_NXDOMAIN],
(unsigned long)0, (unsigned long)0, (unsigned long)0, st.opcode[OPCODE_UPDATE]);
}
}
#endif /* BIND8_STATS */
extern char *optarg;
extern int optind;
int
main(int argc, char *argv[])
{
/* Scratch variables... */
int c;
pid_t oldpid;
size_t i;
struct sigaction action;
#ifdef HAVE_GETPWNAM
struct passwd *pwd = NULL;
#endif /* HAVE_GETPWNAM */
struct ip_address_option *ip;
struct addrinfo hints;
const char *udp_port = 0;
const char *tcp_port = 0;
const char *verify_port = 0;
const char *configfile = CONFIGFILE;
char* argv0 = (argv0 = strrchr(argv[0], '/')) ? argv0 + 1 : argv[0];
log_init(argv0);
/* Initialize the server handler... */
memset(&nsd, 0, sizeof(struct nsd));
nsd.region = region_create(xalloc, free);
nsd.pidfile = 0;
nsd.server_kind = NSD_SERVER_MAIN;
memset(&hints, 0, sizeof(hints));
hints.ai_family = DEFAULT_AI_FAMILY;
hints.ai_flags = AI_PASSIVE;
nsd.identity = 0;
nsd.version = VERSION;
nsd.username = 0;
nsd.chrootdir = 0;
nsd.nsid = NULL;
nsd.nsid_len = 0;
nsd.do_answer_cookie = 0;
nsd.cookie_count = 0;
nsd.cookie_secrets_source = COOKIE_SECRETS_NONE;
nsd.cookie_secrets_filename = NULL;
nsd.child_count = 0;
nsd.maximum_tcp_count = 0;
nsd.current_tcp_count = 0;
nsd.file_rotation_ok = 0;
/* Set up our default identity to gethostname(2) */
if (gethostname(hostname, MAXHOSTNAMELEN) == 0) {
nsd.identity = hostname;
} else {
log_msg(LOG_ERR,
"failed to get the host name: %s - using default identity",
strerror(errno));
nsd.identity = IDENTITY;
}
/* Create region where options will be stored and set defaults */
nsd.options = nsd_options_create(region_create_custom(xalloc, free,
DEFAULT_CHUNK_SIZE, DEFAULT_LARGE_OBJECT_SIZE,
DEFAULT_INITIAL_CLEANUP_SIZE, 1));
/* Parse the command line... */
while ((c = getopt(argc, argv, "46a:c:df:hi:I:l:N:n:P:p:s:u:t:X:V:v"
#ifndef NDEBUG /* <mattthijs> only when configured with --enable-checking */
"F:L:"
#endif /* NDEBUG */
)) != -1) {
switch (c) {
case '4':
hints.ai_family = AF_INET;
break;
case '6':
#ifdef INET6
hints.ai_family = AF_INET6;
#else /* !INET6 */
error("IPv6 support not enabled.");
#endif /* INET6 */
break;
case 'a':
ip = region_alloc_zero(
nsd.options->region, sizeof(*ip));
ip->address = region_strdup(
nsd.options->region, optarg);
ip->next = nsd.options->ip_addresses;
nsd.options->ip_addresses = ip;
break;
case 'c':
configfile = optarg;
break;
case 'd':