1 /* dnsmasq is Copyright (c) 2000-2022 Simon Kelley
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 /* The SURF random number generator was taken from djbdns-1.05, by
18 Daniel J Bernstein, which is public domain. */
23 #ifdef HAVE_BROKEN_RTC
24 #include <sys/times.h>
27 #if defined(HAVE_LIBIDN2)
29 #elif defined(HAVE_IDN)
33 #ifdef HAVE_LINUX_NETWORK
34 #include <sys/utsname.h>
37 /* SURF random number generator */
42 static int outleft = 0;
46 int fd = open(RANDFILE, O_RDONLY);
49 !read_write(fd, (unsigned char *)&seed, sizeof(seed), 1) ||
50 !read_write(fd, (unsigned char *)&in, sizeof(in), 1))
51 die(_("failed to seed the random number generator: %s"), NULL, EC_MISC);
56 #define ROTATE(x,b) (((x) << (b)) | ((x) >> (32 - (b))))
57 #define MUSH(i,b) x = t[i] += (((x ^ seed[i]) + sum) ^ ROTATE(x,b));
59 static void surf(void)
61 u32 t[12]; u32 x; u32 sum = 0;
62 int r; int i; int loop;
64 for (i = 0;i < 12;++i) t[i] = in[i] ^ seed[12 + i];
65 for (i = 0;i < 8;++i) out[i] = seed[24 + i];
67 for (loop = 0;loop < 2;++loop) {
68 for (r = 0;r < 16;++r) {
70 MUSH(0,5) MUSH(1,7) MUSH(2,9) MUSH(3,13)
71 MUSH(4,5) MUSH(5,7) MUSH(6,9) MUSH(7,13)
72 MUSH(8,5) MUSH(9,7) MUSH(10,9) MUSH(11,13)
74 for (i = 0;i < 8;++i) out[i] ^= t[i + 4];
78 unsigned short rand16(void)
82 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
87 return (unsigned short) out[--outleft];
94 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
99 return out[--outleft];
104 static int outleft = 0;
108 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
115 return (u64)out[outleft+1] + (((u64)out[outleft]) << 32);
118 /* returns 1 if name is OK and ascii printable
119 * returns 2 if name should be processed by IDN */
120 static int check_name(char *in)
123 also fail empty string and label > 63 chars */
124 size_t dotgap = 0, l = strlen(in);
131 if (l == 0 || l > MAXDNAME) return 0;
139 for (; (c = *in); in++)
143 else if (++dotgap > MAXLABEL)
145 else if (isascii((unsigned char)c) && iscntrl((unsigned char)c))
146 /* iscntrl only gives expected results for ascii */
148 else if (!isascii((unsigned char)c))
149 #if !defined(HAVE_IDN) && !defined(HAVE_LIBIDN2)
157 #if defined(HAVE_LIBIDN2) && (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
164 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2)
165 if (c >= 'A' && c <= 'Z')
176 #if defined(HAVE_LIBIDN2) && (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
177 /* Older libidn2 strips underscores, so don't do IDN processing
178 if the name has an underscore unless it also has non-ascii characters. */
179 idn_encode = idn_encode || (hasucase && !hasuscore);
181 idn_encode = idn_encode || hasucase;
184 return (idn_encode) ? 2 : 1;
187 /* Hostnames have a more limited valid charset than domain names
188 so check for legal char a-z A-Z 0-9 - _
189 Note that this may receive a FQDN, so only check the first label
190 for the tighter criteria. */
191 int legal_hostname(char *name)
196 if (!check_name(name))
199 for (first = 1; (c = *name); name++, first = 0)
200 /* check for legal char a-z A-Z 0-9 - _ . */
202 if ((c >= 'A' && c <= 'Z') ||
203 (c >= 'a' && c <= 'z') ||
204 (c >= '0' && c <= '9'))
207 if (!first && (c == '-' || c == '_'))
210 /* end of hostname part */
220 char *canonicalise(char *in, int *nomem)
228 if (!(rc = check_name(in)))
231 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2)
235 rc = idn2_to_ascii_lz(in, &ret, IDN2_NONTRANSITIONAL);
237 rc = idna_to_ascii_lz(in, &ret, 0);
239 if (rc != IDNA_SUCCESS)
244 if (nomem && (rc == IDNA_MALLOC_ERROR || rc == IDNA_DLOPEN_ERROR))
246 my_syslog(LOG_ERR, _("failed to allocate memory"));
259 if ((ret = whine_malloc(strlen(in)+1)))
267 unsigned char *do_rfc1035_name(unsigned char *p, char *sval, char *limit)
271 while (sval && *sval)
273 unsigned char *cp = p++;
275 if (limit && p > (unsigned char*)limit)
278 for (j = 0; *sval && (*sval != '.'); sval++, j++)
280 if (limit && p + 1 > (unsigned char*)limit)
284 if (option_bool(OPT_DNSSEC_VALID) && *sval == NAME_ESCAPE)
285 *p++ = (*(++sval))-1;
299 /* for use during startup */
300 void *safe_malloc(size_t size)
302 void *ret = calloc(1, size);
305 die(_("could not get memory"), NULL, EC_NOMEM);
310 /* Ensure limited size string is always terminated.
311 * Can be replaced by (void)strlcpy() on some platforms */
312 void safe_strncpy(char *dest, const char *src, size_t size)
317 strncpy(dest, src, size-1);
321 void safe_pipe(int *fd, int read_noblock)
323 if (pipe(fd) == -1 ||
325 (read_noblock && !fix_fd(fd[0])))
326 die(_("cannot create pipe: %s"), NULL, EC_MISC);
329 void *whine_malloc(size_t size)
331 void *ret = calloc(1, size);
334 my_syslog(LOG_ERR, _("failed to allocate %d bytes"), (int) size);
339 void *whine_realloc(void *ptr, size_t size)
341 void *ret = realloc(ptr, size);
344 my_syslog(LOG_ERR, _("failed to reallocate %d bytes"), (int) size);
349 int sockaddr_isequal(const union mysockaddr *s1, const union mysockaddr *s2)
351 if (s1->sa.sa_family == s2->sa.sa_family)
353 if (s1->sa.sa_family == AF_INET &&
354 s1->in.sin_port == s2->in.sin_port &&
355 s1->in.sin_addr.s_addr == s2->in.sin_addr.s_addr)
358 if (s1->sa.sa_family == AF_INET6 &&
359 s1->in6.sin6_port == s2->in6.sin6_port &&
360 s1->in6.sin6_scope_id == s2->in6.sin6_scope_id &&
361 IN6_ARE_ADDR_EQUAL(&s1->in6.sin6_addr, &s2->in6.sin6_addr))
367 int sockaddr_isnull(const union mysockaddr *s)
369 if (s->sa.sa_family == AF_INET &&
370 s->in.sin_addr.s_addr == 0)
373 if (s->sa.sa_family == AF_INET6 &&
374 IN6_IS_ADDR_UNSPECIFIED(&s->in6.sin6_addr))
380 int sa_len(union mysockaddr *addr)
382 #ifdef HAVE_SOCKADDR_SA_LEN
383 return addr->sa.sa_len;
385 if (addr->sa.sa_family == AF_INET6)
386 return sizeof(addr->in6);
388 return sizeof(addr->in);
392 /* don't use strcasecmp and friends here - they may be messed up by LOCALE */
393 int hostname_order(const char *a, const char *b)
398 c1 = (unsigned char) *a++;
399 c2 = (unsigned char) *b++;
401 if (c1 >= 'A' && c1 <= 'Z')
403 if (c2 >= 'A' && c2 <= 'Z')
416 int hostname_isequal(const char *a, const char *b)
418 return hostname_order(a, b) == 0;
421 /* is b equal to or a subdomain of a return 2 for equal, 1 for subdomain */
422 int hostname_issubdomain(char *a, char *b)
427 /* move to the end */
428 for (ap = a; *ap; ap++);
429 for (bp = b; *bp; bp++);
431 /* a shorter than b or a empty. */
432 if ((bp - b) < (ap - a) || ap == a)
437 c1 = (unsigned char) *(--ap);
438 c2 = (unsigned char) *(--bp);
440 if (c1 >= 'A' && c1 <= 'Z')
442 if (c2 >= 'A' && c2 <= 'Z')
459 time_t dnsmasq_time(void)
461 #ifdef HAVE_BROKEN_RTC
464 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
465 die(_("cannot read monotonic clock: %s"), NULL, EC_MISC);
473 u32 dnsmasq_milliseconds(void)
477 gettimeofday(&tv, NULL);
479 return (tv.tv_sec) * 1000 + (tv.tv_usec / 1000);
482 int netmask_length(struct in_addr mask)
486 while (0x0 == (mask.s_addr & 0x1) && zero_count < 32)
492 return 32 - zero_count;
495 int is_same_net(struct in_addr a, struct in_addr b, struct in_addr mask)
497 return (a.s_addr & mask.s_addr) == (b.s_addr & mask.s_addr);
500 int is_same_net_prefix(struct in_addr a, struct in_addr b, int prefix)
504 mask.s_addr = htonl(~((1 << (32 - prefix)) - 1));
506 return is_same_net(a, b, mask);
510 int is_same_net6(struct in6_addr *a, struct in6_addr *b, int prefixlen)
512 int pfbytes = prefixlen >> 3;
513 int pfbits = prefixlen & 7;
515 if (memcmp(&a->s6_addr, &b->s6_addr, pfbytes) != 0)
519 (a->s6_addr[pfbytes] >> (8 - pfbits) == b->s6_addr[pfbytes] >> (8 - pfbits)))
525 /* return least significant 64 bits if IPv6 address */
526 u64 addr6part(struct in6_addr *addr)
531 for (i = 8; i < 16; i++)
532 ret = (ret << 8) + addr->s6_addr[i];
537 void setaddr6part(struct in6_addr *addr, u64 host)
541 for (i = 15; i >= 8; i--)
543 addr->s6_addr[i] = host;
549 /* returns port number from address */
550 int prettyprint_addr(union mysockaddr *addr, char *buf)
554 if (addr->sa.sa_family == AF_INET)
556 inet_ntop(AF_INET, &addr->in.sin_addr, buf, ADDRSTRLEN);
557 port = ntohs(addr->in.sin_port);
559 else if (addr->sa.sa_family == AF_INET6)
561 char name[IF_NAMESIZE];
562 inet_ntop(AF_INET6, &addr->in6.sin6_addr, buf, ADDRSTRLEN);
563 if (addr->in6.sin6_scope_id != 0 &&
564 if_indextoname(addr->in6.sin6_scope_id, name) &&
565 strlen(buf) + strlen(name) + 2 <= ADDRSTRLEN)
570 port = ntohs(addr->in6.sin6_port);
576 void prettyprint_time(char *buf, unsigned int t)
579 sprintf(buf, _("infinite"));
582 unsigned int x, p = 0;
584 p += sprintf(&buf[p], "%ud", x);
585 if ((x = (t/3600)%24))
586 p += sprintf(&buf[p], "%uh", x);
588 p += sprintf(&buf[p], "%um", x);
590 sprintf(&buf[p], "%us", x);
595 /* in may equal out, when maxlen may be -1 (No max len).
596 Return -1 for extraneous no-hex chars found. */
597 int parse_hex(char *in, unsigned char *out, int maxlen,
598 unsigned int *wildcard_mask, int *mac_type)
600 int done = 0, mask = 0, i = 0;
606 while (!done && (maxlen == -1 || i < maxlen))
608 for (r = in; *r != 0 && *r != ':' && *r != '-' && *r != ' '; r++)
609 if (*r != '*' && !isxdigit((unsigned char)*r))
617 if (*r == '-' && i == 0 && mac_type)
620 *mac_type = strtol(in, NULL, 16);
626 if (strcmp(in, "*") == 0)
628 mask = (mask << 1) | 1;
633 int j, bytes = (1 + (r - in))/2;
634 for (j = 0; j < bytes; j++)
642 /* checks above allow mix of hexdigit and *, which
644 if (strchr(&in[j*2], '*'))
646 out[i] = strtol(&in[j*2], NULL, 16);
660 *wildcard_mask = mask;
665 /* return 0 for no match, or (no matched octets) + 1 */
666 int memcmp_masked(unsigned char *a, unsigned char *b, int len, unsigned int mask)
669 for (count = 1, i = len - 1; i >= 0; i--, mask = mask >> 1)
680 /* _note_ may copy buffer */
681 int expand_buf(struct iovec *iov, size_t size)
685 if (size <= (size_t)iov->iov_len)
688 if (!(new = whine_malloc(size)))
696 memcpy(new, iov->iov_base, iov->iov_len);
706 char *print_mac(char *buff, unsigned char *mac, int len)
712 sprintf(p, "<null>");
714 for (i = 0; i < len; i++)
715 p += sprintf(p, "%.2x%s", mac[i], (i == len - 1) ? "" : ":");
720 /* rc is return from sendto and friends.
721 Return 1 if we should retry.
722 Set errno to zero if we succeeded. */
723 int retry_send(ssize_t rc)
725 static int retries = 0;
726 struct timespec waiter;
735 /* Linux kernels can return EAGAIN in perpetuity when calling
736 sendmsg() and the relevant interface has gone. Here we loop
737 retrying in EAGAIN for 1 second max, to avoid this hanging
740 if (errno == EAGAIN || errno == EWOULDBLOCK)
743 waiter.tv_nsec = 10000;
744 nanosleep(&waiter, NULL);
745 if (retries++ < 1000)
757 int read_write(int fd, unsigned char *packet, int size, int rw)
761 for (done = 0; done < size; done += n)
765 n = read(fd, &packet[done], (size_t)(size - done));
767 n = write(fd, &packet[done], (size_t)(size - done));
772 } while (retry_send(n) || errno == ENOMEM || errno == ENOBUFS);
781 /* close all fds except STDIN, STDOUT and STDERR, spare1, spare2 and spare3 */
782 void close_fds(long max_fd, int spare1, int spare2, int spare3)
784 /* On Linux, use the /proc/ filesystem to find which files
785 are actually open, rather than iterate over the whole space,
786 for efficiency reasons. If this fails we drop back to the dumb code. */
787 #ifdef HAVE_LINUX_NETWORK
790 if ((d = opendir("/proc/self/fd")))
794 while ((de = readdir(d)))
800 fd = strtol(de->d_name, &e, 10);
802 if (errno != 0 || !e || *e || fd == dirfd(d) ||
803 fd == STDOUT_FILENO || fd == STDERR_FILENO || fd == STDIN_FILENO ||
804 fd == spare1 || fd == spare2 || fd == spare3)
815 /* fallback, dumb code. */
816 for (max_fd--; max_fd >= 0; max_fd--)
817 if (max_fd != STDOUT_FILENO && max_fd != STDERR_FILENO && max_fd != STDIN_FILENO &&
818 max_fd != spare1 && max_fd != spare2 && max_fd != spare3)
822 /* Basically match a string value against a wildcard pattern. */
823 int wildcard_match(const char* wildcard, const char* match)
825 while (*wildcard && *match)
827 if (*wildcard == '*')
830 if (*wildcard != *match)
837 return *wildcard == *match;
840 /* The same but comparing a maximum of NUM characters, like strncmp. */
841 int wildcard_matchn(const char* wildcard, const char* match, int num)
843 while (*wildcard && *match && num)
845 if (*wildcard == '*')
848 if (*wildcard != *match)
856 return (!num) || (*wildcard == *match);
859 #ifdef HAVE_LINUX_NETWORK
860 int kernel_version(void)
862 struct utsname utsname;
866 if (uname(&utsname) < 0)
867 die(_("failed to find kernel version: %s"), NULL, EC_MISC);
869 split = strtok(utsname.release, ".");
870 version = (split ? atoi(split) : 0);
871 split = strtok(NULL, ".");
872 version = version * 256 + (split ? atoi(split) : 0);
873 split = strtok(NULL, ".");
874 return version * 256 + (split ? atoi(split) : 0);