Debian Codegraph @

src/util.c

raw
1 /* dnsmasq is Copyright (c) 2000-2026 Simon Kelley
2
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.
7
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.
12
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/>.
15 */
16
17 /* The SURF random number generator was taken from djbdns-1.05, by
18 Daniel J Bernstein, which is public domain. */
19
20
21 #include "dnsmasq.h"
22
23 #ifdef HAVE_BROKEN_RTC
24 #include <sys/times.h>
25 #endif
26
27 #if defined(HAVE_LIBIDN2)
28 #include <idn2.h>
29 #elif defined(HAVE_IDN)
30 #include <idna.h>
31 #endif
32
33 #ifdef HAVE_LINUX_NETWORK
34 #include <sys/utsname.h>
35 #endif
36
37 #ifdef HAVE_BSD_NETWORK
38 #include <libgen.h>
39 #endif
40
41 /* SURF random number generator */
42
43 static u32 seed[32];
44 static u32 in[12];
45 static u32 out[8];
46 static int outleft = 0;
47
48 void rand_init(void)
49 {
50 int fd = open(RANDFILE, O_RDONLY);
51
52 if (fd == -1 ||
53 !read_write(fd, (unsigned char *)&seed, sizeof(seed), RW_READ) ||
54 !read_write(fd, (unsigned char *)&in, sizeof(in), RW_READ))
55 die(_("failed to seed the random number generator: %s"), NULL, EC_MISC);
56
57 close(fd);
58 }
59
60 #define ROTATE(x,b) (((x) << (b)) | ((x) >> (32 - (b))))
61 #define MUSH(i,b) x = t[i] += (((x ^ seed[i]) + sum) ^ ROTATE(x,b));
62
63 static void surf(void)
64 {
65 u32 t[12]; u32 x; u32 sum = 0;
66 int r; int i; int loop;
67
68 for (i = 0;i < 12;++i) t[i] = in[i] ^ seed[12 + i];
69 for (i = 0;i < 8;++i) out[i] = seed[24 + i];
70 x = t[11];
71 for (loop = 0;loop < 2;++loop) {
72 for (r = 0;r < 16;++r) {
73 sum += 0x9e3779b9;
74 MUSH(0,5) MUSH(1,7) MUSH(2,9) MUSH(3,13)
75 MUSH(4,5) MUSH(5,7) MUSH(6,9) MUSH(7,13)
76 MUSH(8,5) MUSH(9,7) MUSH(10,9) MUSH(11,13)
77 }
78 for (i = 0;i < 8;++i) out[i] ^= t[i + 4];
79 }
80 }
81
82 unsigned short rand16(void)
83 {
84 if (!outleft)
85 {
86 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
87 surf();
88 outleft = 8;
89 }
90
91 return (unsigned short) out[--outleft];
92 }
93
94 u32 rand32(void)
95 {
96 if (!outleft)
97 {
98 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
99 surf();
100 outleft = 8;
101 }
102
103 return out[--outleft];
104 }
105
106 u64 rand64(void)
107 {
108 if (outleft < 2)
109 {
110 if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
111 surf();
112 outleft = 8;
113 }
114
115 outleft -= 2;
116
117 return (u64)out[outleft+1] + (((u64)out[outleft]) << 32);
118 }
119
120 int rr_on_list(struct rrlist *list, unsigned short rr)
121 {
122 while (list)
123 {
124 if (list->rr != 0 && list->rr == rr)
125 return 1;
126
127 list = list->next;
128 }
129
130 return 0;
131 }
132
133 /* returns 1 if name is OK and ascii printable
134 * returns 2 if name should be processed by IDN */
135 static int check_name(char *in)
136 {
137 /* remove trailing .
138 also fail empty string and label > 63 chars */
139 size_t dotgap = 0, wiresize = 0, l = strlen(in);
140 char c;
141 int nowhite = 0;
142 int idn_encode = 0;
143 int hasuscore = 0;
144 int hasucase = 0;
145
146 if (l == 0)
147 return 0;
148
149 if (in[l-1] == '.')
150 {
151 in[l-1] = 0;
152 nowhite = 1;
153 }
154
155 for (; (c = *in); in++)
156 {
157 if (c == '.')
158 {
159 wiresize += dotgap + 1;
160 dotgap = 0;
161 }
162 else if (++dotgap > MAXLABEL)
163 return 0;
164 else if (isascii((unsigned char)c) && iscntrl((unsigned char)c))
165 /* iscntrl only gives expected results for ascii */
166 return 0;
167 else if (!isascii((unsigned char)c))
168 #if !defined(HAVE_IDN) && !defined(HAVE_LIBIDN2)
169 return 0;
170 #else
171 idn_encode = 1;
172 #endif
173 else if (c != ' ')
174 {
175 nowhite = 1;
176 #if defined(HAVE_LIBIDN2) && (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
177 if (c == '_')
178 hasuscore = 1;
179 #else
180 (void)hasuscore;
181 #endif
182
183 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2)
184 if (c >= 'A' && c <= 'Z')
185 hasucase = 1;
186 #else
187 (void)hasucase;
188 #endif
189 }
190 }
191
192 if (!nowhite)
193 return 0;
194
195 #if defined(HAVE_LIBIDN2) && (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
196 /* Older libidn2 strips underscores, so don't do IDN processing
197 if the name has an underscore unless it also has non-ascii characters. */
198 idn_encode = idn_encode || (hasucase && !hasuscore);
199 #else
200 idn_encode = idn_encode || hasucase;
201 #endif
202
203 /* length of final label and terminaton added */
204 if (!idn_encode && wiresize + dotgap + 2 > MAXDNAME)
205 return 0; /* wire representation too long */
206
207 return (idn_encode) ? 2 : 1;
208 }
209
210 /* Hostnames have a more limited valid charset than domain names
211 so check for legal char a-z A-Z 0-9 - _
212 Note that this may receive a FQDN, so only check the first label
213 for the tighter criteria. */
214 int legal_hostname(char *name)
215 {
216 char c;
217 int first;
218
219 if (!check_name(name))
220 return 0;
221
222 for (first = 1; (c = *name); name++, first = 0)
223 /* check for legal char a-z A-Z 0-9 - _ . */
224 {
225 if ((c >= 'A' && c <= 'Z') ||
226 (c >= 'a' && c <= 'z') ||
227 (c >= '0' && c <= '9'))
228 continue;
229
230 if (!first && (c == '-' || c == '_'))
231 continue;
232
233 /* end of hostname part */
234 if (c == '.')
235 return 1;
236
237 return 0;
238 }
239
240 return 1;
241 }
242
243 char *canonicalise(char *in, int *nomem)
244 {
245 char *ret = NULL;
246 int rc;
247
248 if (nomem)
249 *nomem = 0;
250
251 if (!(rc = check_name(in)))
252 return NULL;
253
254 #if defined(HAVE_IDN) || defined(HAVE_LIBIDN2)
255 if (rc == 2)
256 {
257 # ifdef HAVE_LIBIDN2
258 rc = idn2_to_ascii_lz(in, &ret, IDN2_NONTRANSITIONAL);
259 # else
260 rc = idna_to_ascii_lz(in, &ret, 0);
261 # endif
262 if (rc != IDNA_SUCCESS)
263 {
264 if (ret)
265 free(ret);
266
267 if (nomem && (rc == IDNA_MALLOC_ERROR || rc == IDNA_DLOPEN_ERROR))
268 {
269 my_syslog(LOG_ERR, _("failed to allocate memory"));
270 *nomem = 1;
271 }
272
273 return NULL;
274 }
275
276 /* IDN library doesnt call our malloc wrapper, so log this by steam */
277 if (ret)
278 malloc_log(ret, strlen(ret)+1);
279
280 return ret;
281 }
282 #else
283 (void)rc;
284 #endif
285
286 if ((ret = whine_malloc(strlen(in)+1)))
287 strcpy(ret, in);
288 else if (nomem)
289 *nomem = 1;
290
291 return ret;
292 }
293
294 unsigned char *do_rfc1035_name(unsigned char *p, char *sval, unsigned char *limit)
295 {
296 int j;
297
298 /* Never make a name larger than the RFC limit */
299 if (!limit || (limit - p > MAXDNAME))
300 limit = p + MAXDNAME;
301
302 while (sval && *sval)
303 {
304 unsigned char *cp = p++;
305
306 if (p > limit)
307 return NULL;
308
309 for (j = 0; *sval && (*sval != '.'); sval++, j++)
310 {
311 if (p + 1 > limit)
312 return NULL;
313
314 if (*sval == NAME_ESCAPE)
315 *p++ = (*(++sval))-1;
316 else
317 *p++ = *sval;
318 }
319
320 *cp = j;
321 if (*sval)
322 sval++;
323 }
324
325 return p;
326 }
327
328 /* for use during startup */
329 void *safe_malloc(size_t size)
330 {
331 void *ret = calloc(1, size);
332
333 if (!ret)
334 die(_("could not get memory"), NULL, EC_NOMEM);
335
336 return ret;
337 }
338
339 /* Ensure limited size string is always terminated.
340 Can be replaced by (void)strlcpy() on some platforms.
341 src may be NULL in which case we return an empty string. */
342 void safe_strncpy(char *dest, const char *src, size_t size)
343 {
344 if (size != 0)
345 {
346 dest[0] = dest[size-1] = '\0';
347 if (src)
348 strncpy(dest, src, size-1);
349 }
350 }
351
352 void safe_pipe(int *fd, int read_noblock)
353 {
354 if (pipe(fd) == -1 ||
355 !fix_fd(fd[1]) ||
356 (read_noblock && !fix_fd(fd[0])))
357 die(_("cannot create pipe: %s"), NULL, EC_MISC);
358 }
359
360 int sockaddr_isequal(const union mysockaddr *s1, const union mysockaddr *s2)
361 {
362 if (s1->sa.sa_family == s2->sa.sa_family)
363 {
364 if (s1->sa.sa_family == AF_INET &&
365 s1->in.sin_port == s2->in.sin_port &&
366 s1->in.sin_addr.s_addr == s2->in.sin_addr.s_addr)
367 return 1;
368
369 if (s1->sa.sa_family == AF_INET6 &&
370 s1->in6.sin6_port == s2->in6.sin6_port &&
371 s1->in6.sin6_scope_id == s2->in6.sin6_scope_id &&
372 IN6_ARE_ADDR_EQUAL(&s1->in6.sin6_addr, &s2->in6.sin6_addr))
373 return 1;
374 }
375 return 0;
376 }
377
378 int sockaddr_isnull(const union mysockaddr *s)
379 {
380 if (s->sa.sa_family == AF_INET &&
381 s->in.sin_addr.s_addr == 0)
382 return 1;
383
384 if (s->sa.sa_family == AF_INET6 &&
385 IN6_IS_ADDR_UNSPECIFIED(&s->in6.sin6_addr))
386 return 1;
387
388 return 0;
389 }
390
391 int sa_len(union mysockaddr *addr)
392 {
393 #ifdef HAVE_SOCKADDR_SA_LEN
394 return addr->sa.sa_len;
395 #else
396 if (addr->sa.sa_family == AF_INET6)
397 return sizeof(addr->in6);
398 else
399 return sizeof(addr->in);
400 #endif
401 }
402
403 /* don't use strcasecmp and friends here - they may be messed up by LOCALE */
404 int hostname_order(const char *a, const char *b)
405 {
406 unsigned int c1, c2;
407
408 do {
409 c1 = (unsigned char) *a++;
410 c2 = (unsigned char) *b++;
411
412 if (c1 >= 'A' && c1 <= 'Z')
413 c1 += 'a' - 'A';
414 if (c2 >= 'A' && c2 <= 'Z')
415 c2 += 'a' - 'A';
416
417 if (c1 < c2)
418 return -1;
419 else if (c1 > c2)
420 return 1;
421
422 } while (c1);
423
424 return 0;
425 }
426
427 int hostname_isequal(const char *a, const char *b)
428 {
429 return strlen(a) == strlen(b) && hostname_order(a, b) == 0;
430 }
431
432 /* is b equal to or a subdomain of a return 2 for equal, 1 for subdomain */
433 int hostname_issubdomain(char *a, char *b)
434 {
435 char *ap, *bp;
436 unsigned int c1, c2;
437
438 /* move to the end */
439 for (ap = a; *ap; ap++);
440 for (bp = b; *bp; bp++);
441
442 /* anything is a subdomain of the root domain. */
443 if (ap == a)
444 return (bp == b) ? 2 : 1;
445
446 /* b shorter than a */
447 if ((bp - b) < (ap - a))
448 return 0;
449
450 do
451 {
452 c1 = (unsigned char) *(--ap);
453 c2 = (unsigned char) *(--bp);
454
455 if (c1 >= 'A' && c1 <= 'Z')
456 c1 += 'a' - 'A';
457 if (c2 >= 'A' && c2 <= 'Z')
458 c2 += 'a' - 'A';
459
460 if (c1 != c2)
461 return 0;
462 } while (ap != a);
463
464 if (bp == b)
465 return 2;
466
467 if (*(--bp) == '.')
468 return 1;
469
470 return 0;
471 }
472
473 time_t dnsmasq_time(void)
474 {
475 #ifdef HAVE_BROKEN_RTC
476 struct timespec ts;
477
478 if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
479 die(_("cannot read monotonic clock: %s"), NULL, EC_MISC);
480
481 return ts.tv_sec;
482 #else
483 return time(NULL);
484 #endif
485 }
486
487 u32 dnsmasq_milliseconds(void)
488 {
489 struct timeval tv;
490
491 gettimeofday(&tv, NULL);
492
493 return (tv.tv_sec) * 1000 + (tv.tv_usec / 1000);
494 }
495
496 int netmask_length(struct in_addr mask)
497 {
498 int zero_count = 0;
499
500 while (0x0 == (mask.s_addr & 0x1) && zero_count < 32)
501 {
502 mask.s_addr >>= 1;
503 zero_count++;
504 }
505
506 return 32 - zero_count;
507 }
508
509 int is_same_net(struct in_addr a, struct in_addr b, struct in_addr mask)
510 {
511 return (a.s_addr & mask.s_addr) == (b.s_addr & mask.s_addr);
512 }
513
514 int is_same_net_prefix(struct in_addr a, struct in_addr b, int prefix)
515 {
516 struct in_addr mask;
517
518 mask.s_addr = htonl(~((1 << (32 - prefix)) - 1));
519
520 return is_same_net(a, b, mask);
521 }
522
523
524 int is_same_net6(struct in6_addr *a, struct in6_addr *b, int prefixlen)
525 {
526 int pfbytes = prefixlen >> 3;
527 int pfbits = prefixlen & 7;
528
529 if (memcmp(&a->s6_addr, &b->s6_addr, pfbytes) != 0)
530 return 0;
531
532 if (pfbits == 0 ||
533 (a->s6_addr[pfbytes] >> (8 - pfbits) == b->s6_addr[pfbytes] >> (8 - pfbits)))
534 return 1;
535
536 return 0;
537 }
538
539 /* return least significant 64 bits if IPv6 address */
540 u64 addr6part(struct in6_addr *addr)
541 {
542 int i;
543 u64 ret = 0;
544
545 for (i = 8; i < 16; i++)
546 ret = (ret << 8) + addr->s6_addr[i];
547
548 return ret;
549 }
550
551 void setaddr6part(struct in6_addr *addr, u64 host)
552 {
553 int i;
554
555 for (i = 15; i >= 8; i--)
556 {
557 addr->s6_addr[i] = host;
558 host = host >> 8;
559 }
560 }
561
562
563 /* returns port number from address */
564 int prettyprint_addr(union mysockaddr *addr, char *buf)
565 {
566 int port = 0;
567
568 if (addr->sa.sa_family == AF_INET)
569 {
570 inet_ntop(AF_INET, &addr->in.sin_addr, buf, ADDRSTRLEN);
571 port = ntohs(addr->in.sin_port);
572 }
573 else if (addr->sa.sa_family == AF_INET6)
574 {
575 char name[IF_NAMESIZE];
576 inet_ntop(AF_INET6, &addr->in6.sin6_addr, buf, ADDRSTRLEN);
577 if (addr->in6.sin6_scope_id != 0 &&
578 if_indextoname(addr->in6.sin6_scope_id, name) &&
579 strlen(buf) + strlen(name) + 2 <= ADDRSTRLEN)
580 {
581 strcat(buf, "%");
582 strcat(buf, name);
583 }
584 port = ntohs(addr->in6.sin6_port);
585 }
586
587 return port;
588 }
589
590 void prettyprint_time(char *buf, unsigned int t)
591 {
592 if (t == 0xffffffff)
593 sprintf(buf, _("infinite"));
594 else
595 {
596 unsigned int x, p = 0;
597 buf[0] = '\0';
598 if ((x = t/86400))
599 p += sprintf(&buf[p], "%ud", x);
600 if ((x = (t/3600)%24))
601 p += sprintf(&buf[p], "%uh", x);
602 if ((x = (t/60)%60))
603 p += sprintf(&buf[p], "%um", x);
604 if ((x = t%60))
605 sprintf(&buf[p], "%us", x);
606 }
607 }
608
609
610 /* in may equal out, when maxlen may be -1 (No max len).
611 Return -1 for extraneous no-hex chars found. */
612 int parse_hex(char *in, unsigned char *out, int maxlen,
613 unsigned int *wildcard_mask, int *mac_type)
614 {
615 int done = 0, mask = 0, i = 0;
616 char *r;
617
618 if (mac_type)
619 *mac_type = 0;
620
621 while (!done && (maxlen == -1 || i < maxlen))
622 {
623 for (r = in; *r != 0 && *r != ':' && *r != '-' && *r != ' '; r++)
624 if (*r != '*' && !isxdigit((unsigned char)*r))
625 return -1;
626
627 if (*r == 0)
628 done = 1;
629
630 if (r != in )
631 {
632 if (*r == '-' && i == 0 && mac_type)
633 {
634 *r = 0;
635 *mac_type = strtol(in, NULL, 16);
636 mac_type = NULL;
637 }
638 else
639 {
640 *r = 0;
641 if (strcmp(in, "*") == 0)
642 {
643 mask = (mask << 1) | 1;
644 i++;
645 }
646 else
647 {
648 int j, bytes = (1 + (r - in))/2;
649 for (j = 0; j < bytes; j++)
650 {
651 char sav;
652 if (j < bytes - 1)
653 {
654 sav = in[(j+1)*2];
655 in[(j+1)*2] = 0;
656 }
657 /* checks above allow mix of hexdigit and *, which
658 is illegal. */
659 if (strchr(&in[j*2], '*'))
660 return -1;
661 out[i] = strtol(&in[j*2], NULL, 16);
662 mask = mask << 1;
663 if (++i == maxlen)
664 break;
665 if (j < bytes - 1)
666 in[(j+1)*2] = sav;
667 }
668 }
669 }
670 }
671 in = r+1;
672 }
673
674 if (wildcard_mask)
675 *wildcard_mask = mask;
676
677 return i;
678 }
679
680 /* return 0 for no match, or (no matched octets) + 1 */
681 int memcmp_masked(unsigned char *a, unsigned char *b, int len, unsigned int mask)
682 {
683 int i, count;
684 for (count = 1, i = len - 1; i >= 0; i--, mask = mask >> 1)
685 if (!(mask & 1))
686 {
687 if (a[i] == b[i])
688 count++;
689 else
690 return 0;
691 }
692 return count;
693 }
694
695 char *print_mac(unsigned char *mac, int len)
696 {
697 static struct iovec buff = { NULL, 0 };
698
699 /* each byte is two digits plus ':' except that last
700 which is two digits plus terminator. */
701 if (len == 0 || !expand_buf(&buff, len*3))
702 return "<null>";
703 else
704 {
705 char *p = buff.iov_base;
706 int i;
707
708 for (i = 0; i < len; i++)
709 p += sprintf(p, "%.2x%s", mac[i], (i == len - 1) ? "" : ":");
710 }
711
712 return buff.iov_base;
713 }
714
715 /* rc is return from sendto and friends.
716 Return 1 if we should retry.
717 Set errno to zero if we succeeded. */
718 int retry_send(ssize_t rc)
719 {
720 static int retries = 0;
721 struct timespec waiter;
722
723 if (rc != -1)
724 {
725 retries = 0;
726 errno = 0;
727 return 0;
728 }
729
730 /* Linux kernels can return EAGAIN in perpetuity when calling
731 sendmsg() and the relevant interface has gone. Here we loop
732 retrying in EAGAIN for 1 second max, to avoid this hanging
733 dnsmasq. */
734
735 if (errno == EAGAIN || errno == EWOULDBLOCK)
736 {
737 waiter.tv_sec = 0;
738 waiter.tv_nsec = 10000;
739 nanosleep(&waiter, NULL);
740 if (retries++ < 1000)
741 return 1;
742 }
743
744 retries = 0;
745
746 if (errno == EINTR)
747 return 1;
748
749 return 0;
750 }
751
752 /* rw = 0 -> write
753 rw = 1 -> read
754 rw = 2 -> write once
755 rw = 3 -> read once
756
757 "once" fails on EAGAIN, as this a timeout.
758 This indicates a timeout of a TCP socket.
759 */
760 int read_writev(int fd, struct iovec *iov, int iovcnt, int rw)
761 {
762 int cur = 0;
763 ssize_t n, done = 0;
764
765 while (cur < iovcnt)
766 {
767 iov[cur].iov_len -= done;
768 iov[cur].iov_base = ((char *)iov[cur].iov_base) + done;
769
770 if (rw & 1)
771 n = readv(fd, &iov[cur], iovcnt - cur);
772 else
773 n = writev(fd, &iov[cur], iovcnt - cur);
774
775 iov[cur].iov_len += done;
776 iov[cur].iov_base = ((char *)iov[cur].iov_base) - done;
777
778 if (n == -1)
779 {
780 if (errno == EINTR || errno == ENOMEM || errno == ENOBUFS)
781 continue;
782
783 if (!(rw & 2) && (errno == EAGAIN || errno == EWOULDBLOCK))
784 continue;
785
786 return 0;
787 }
788
789 if (n == 0 && (rw & 1))
790 return 0;
791
792 done += n;
793 while (cur < iovcnt && (size_t)done >= iov[cur].iov_len)
794 done -= iov[cur++].iov_len;
795 }
796
797 return 1;
798 }
799
800 int read_write(int fd, unsigned char *packet, int size, int rw)
801 {
802 struct iovec iov;
803
804 /* size == 0 is not an error, just a NOOP. */
805 if (size == 0)
806 return 1;
807
808 iov.iov_len = (size_t)size;
809 iov.iov_base = packet;
810
811 return read_writev(fd, &iov, 1, rw);
812 }
813
814 /* close all fds except STDIN, STDOUT and STDERR, spare1, spare2 and spare3 */
815 void close_fds(long max_fd, int spare1, int spare2, int spare3)
816 {
817 /* On Linux, use the /proc/ filesystem to find which files
818 are actually open, rather than iterate over the whole space,
819 for efficiency reasons.
820
821 On *BSD, the same facility is found at /dev/fd.
822
823 If this fails we drop back to the dumb code.
824 */
825
826 #ifdef HAVE_LINUX_NETWORK
827 #define FDESCFS "/proc/self/fd"
828 #endif
829
830 #ifdef HAVE_BSD_NETWORK
831 #define FDESCFS "/dev/fd"
832 #endif
833
834 #ifdef FDESCFS
835 DIR *d = NULL;
836
837 # ifdef HAVE_BSD_NETWORK
838 dev_t dirdev = 0;
839 char fdescfs[] = FDESCFS; /* string must be writable */
840 struct stat statbuf;
841
842 /* On BSD, fdescfs is normally mounted at /dev/fd. However
843 if it is NOT mounted, devfs creates a directory at /dev/fd
844 which contains (only) the file descriptors 0,1 and 2.
845
846 Under these conditions, opendir() will succeed, and
847 if we proceed we will fail to close extant
848 file descriptors which should be closed.
849
850 Check that there is a filesystem mounted at /dev/fd
851 by checking that the device changes between /dev/fd
852 and /dev. If if doesn't, fall back to the dumb path. */
853
854 if (stat(fdescfs, &statbuf) != -1)
855 dirdev = statbuf.st_dev;
856
857 if (stat(dirname(fdescfs), &statbuf) != -1 &&
858 dirdev != statbuf.st_dev)
859 # endif
860 d = opendir(FDESCFS);
861
862 if (d)
863 {
864 struct dirent *de;
865
866 while ((de = readdir(d)))
867 {
868 long fd;
869 char *e = NULL;
870
871 errno = 0;
872 fd = strtol(de->d_name, &e, 10);
873
874 if (errno != 0 || !e || *e || fd == dirfd(d) ||
875 fd == STDOUT_FILENO || fd == STDERR_FILENO || fd == STDIN_FILENO ||
876 fd == spare1 || fd == spare2 || fd == spare3)
877 continue;
878
879 close(fd);
880 }
881
882 closedir(d);
883 return;
884 }
885 #endif
886
887 /* fallback, dumb code. */
888 for (max_fd--; max_fd >= 0; max_fd--)
889 if (max_fd != STDOUT_FILENO && max_fd != STDERR_FILENO && max_fd != STDIN_FILENO &&
890 max_fd != spare1 && max_fd != spare2 && max_fd != spare3)
891 close(max_fd);
892 }
893
894 /* Basically match a string value against a wildcard pattern. */
895 int wildcard_match(const char* wildcard, const char* match)
896 {
897 while (*wildcard && *match)
898 {
899 if (*wildcard == '*')
900 return 1;
901
902 if (*wildcard != *match)
903 return 0;
904
905 ++wildcard;
906 ++match;
907 }
908
909 return *wildcard == *match;
910 }
911
912 /* The same but comparing a maximum of NUM characters, like strncmp. */
913 int wildcard_matchn(const char* wildcard, const char* match, int num)
914 {
915 while (*wildcard && *match && num)
916 {
917 if (*wildcard == '*')
918 return 1;
919
920 if (*wildcard != *match)
921 return 0;
922
923 ++wildcard;
924 ++match;
925 --num;
926 }
927
928 return (!num) || (*wildcard == *match);
929 }
930
931 #ifdef HAVE_LINUX_NETWORK
932 int kernel_version(void)
933 {
934 struct utsname utsname;
935 int version;
936 char *split;
937
938 if (uname(&utsname) < 0)
939 die(_("failed to find kernel version: %s"), NULL, EC_MISC);
940
941 split = strtok(utsname.release, ".");
942 version = (split ? atoi(split) : 0);
943 split = strtok(NULL, ".");
944 version = version * 256 + (split ? atoi(split) : 0);
945 split = strtok(NULL, ".");
946 return version * 256 + (split ? atoi(split) : 0);
947 }
948 #endif
949
950 #define hash_ptr(x) (((uintptr_t)(x)) & 0xffffff)
951
952 void *whine_malloc_real(const char *func, unsigned int line, size_t size)
953 {
954 void *ret = calloc(1, size);
955
956 if (!ret)
957 my_syslog(LOG_ERR, _("failed to allocate %d bytes"), (int) size);
958 else if (daemon->log_malloc)
959 my_syslog(LOG_INFO, _("malloc: %s:%u %zu bytes at %x"), func, line, size, hash_ptr(ret));
960
961 return ret;
962 }
963
964 void *whine_realloc_real(const char *wrapper, const char *func, unsigned int line, void *ptr, size_t size)
965 {
966 unsigned int old = hash_ptr(ptr);
967 void *ret = realloc(ptr, size);
968
969 if (!ret)
970 my_syslog(LOG_ERR, _("failed to reallocate %d bytes"), (int) size);
971 else if (daemon->log_malloc)
972 {
973 if (!wrapper)
974 wrapper = "realloc";
975 my_syslog(LOG_INFO, _("%s: %s:%u %zu bytes from %x to %x"), wrapper, func, line, size, old, hash_ptr(ret));
976 }
977
978 return ret;
979 }
980
981 /* _note_ may copy buffer */
982 int expand_buf_real(const char *func, unsigned int line, struct iovec *iov, size_t size)
983 {
984 void *new;
985
986 if (size <= (size_t)iov->iov_len)
987 return 1;
988
989 if (!(new = whine_realloc_real("expand_buf", func, line, iov->iov_base, size)))
990 {
991 errno = ENOMEM;
992 return 0;
993 }
994
995 iov->iov_base = new;
996 iov->iov_len = size;
997
998 return 1;
999 }
1000
1001 int expand_workspace_real(const char *func, unsigned int line, unsigned char ***wkspc, int *szp, int new)
1002 {
1003 unsigned char **p;
1004 int old = *szp;
1005
1006 if (old >= new+1)
1007 return 1;
1008
1009 new += 5;
1010
1011 if (!(p = whine_realloc_real("expand_workspace", func, line, *wkspc, new * sizeof(unsigned char *))))
1012 return 0;
1013
1014 memset(p+old, 0, (new-old) * sizeof(unsigned char *));
1015
1016 *wkspc = p;
1017 *szp = new;
1018
1019 return 1;
1020 }
1021
1022 void malloc_log_real(const char *func, unsigned int line, void *mem, size_t size)
1023 {
1024 if (mem && daemon->log_malloc)
1025 my_syslog(LOG_INFO, _("malloc: %s:%u %zu bytes at %x"), func, line, size, hash_ptr(mem));
1026 }
1027
1028 #undef free
1029 void free_real(const char *func, unsigned int line, void *ptr)
1030 {
1031 if (ptr)
1032 {
1033 if (daemon->log_malloc)
1034 my_syslog(LOG_INFO, _("free: %s:%u block at %x"), func, line, hash_ptr(ptr));
1035
1036 free(ptr);
1037 }
1038 }
1039
1040 /* get lines from f, expand buffer as required. Buffer is freed when
1041 EOF reached and we return zero. Buffer also freed if f == NULL. */
1042 int get_line_alloc(FILE *f, char **buffp, size_t *sizep)
1043 {
1044 size_t cnt = 0;
1045 char *buff = *buffp;
1046
1047 while (1) {
1048 int c = f ? getc(f) : EOF;
1049
1050 if (cnt == *sizep)
1051 {
1052 void *new;
1053
1054 if ((new = whine_realloc(buff, cnt + 1024)))
1055 {
1056 buff = *buffp = new;
1057 *sizep = cnt + 1024;
1058 }
1059 else
1060 {
1061 /* allocation failed, ignore line.
1062 Whine_realloc will have complained. */
1063 while (c != '\n' && c != EOF)
1064 c = getc(f);
1065
1066 cnt = 0;
1067 continue;
1068 }
1069 }
1070
1071 buff[cnt] = 0;
1072
1073 if (c == '\n')
1074 return 1;
1075
1076 if (c == EOF)
1077 {
1078 /* handle last line without '\n' */
1079 if (cnt != 0)
1080 return 1;
1081
1082 free(buff);
1083 *buffp = NULL;
1084 *sizep = 0;
1085 return 0;
1086 }
1087
1088 buff[cnt++] = c;
1089 }
1090 }