Coverage Report

Created: 2026-12-01 06:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/dnsmasq/src/util.c
Line
Count
Source
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
0
{
50
0
  int fd = open(RANDFILE, O_RDONLY);
51
  
52
0
  if (fd == -1 ||
53
0
      !read_write(fd, (unsigned char *)&seed, sizeof(seed), RW_READ) ||
54
0
      !read_write(fd, (unsigned char *)&in, sizeof(in), RW_READ))
55
0
    die(_("failed to seed the random number generator: %s"), NULL, EC_MISC);
56
  
57
0
  close(fd);
58
0
}
59
60
0
#define ROTATE(x,b) (((x) << (b)) | ((x) >> (32 - (b))))
61
0
#define MUSH(i,b) x = t[i] += (((x ^ seed[i]) + sum) ^ ROTATE(x,b));
62
63
static void surf(void)
64
0
{
65
0
  u32 t[12]; u32 x; u32 sum = 0;
66
0
  int r; int i; int loop;
67
68
0
  for (i = 0;i < 12;++i) t[i] = in[i] ^ seed[12 + i];
69
0
  for (i = 0;i < 8;++i) out[i] = seed[24 + i];
70
0
  x = t[11];
71
0
  for (loop = 0;loop < 2;++loop) {
72
0
    for (r = 0;r < 16;++r) {
73
0
      sum += 0x9e3779b9;
74
0
      MUSH(0,5) MUSH(1,7) MUSH(2,9) MUSH(3,13)
75
0
      MUSH(4,5) MUSH(5,7) MUSH(6,9) MUSH(7,13)
76
0
      MUSH(8,5) MUSH(9,7) MUSH(10,9) MUSH(11,13)
77
0
    }
78
0
    for (i = 0;i < 8;++i) out[i] ^= t[i + 4];
79
0
  }
80
0
}
81
82
unsigned short rand16(void)
83
0
{
84
0
  if (!outleft) 
85
0
    {
86
0
      if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
87
0
      surf();
88
0
      outleft = 8;
89
0
    }
90
  
91
0
  return (unsigned short) out[--outleft];
92
0
}
93
94
u32 rand32(void)
95
0
{
96
0
 if (!outleft) 
97
0
    {
98
0
      if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
99
0
      surf();
100
0
      outleft = 8;
101
0
    }
102
  
103
0
  return out[--outleft]; 
104
0
}
105
106
u64 rand64(void)
107
0
{
108
0
  if (outleft < 2)
109
0
    {
110
0
      if (!++in[0]) if (!++in[1]) if (!++in[2]) ++in[3];
111
0
      surf();
112
0
      outleft = 8;
113
0
    }
114
  
115
0
  outleft -= 2;
116
117
0
  return (u64)out[outleft+1] + (((u64)out[outleft]) << 32);
118
0
}
119
120
int rr_on_list(struct rrlist *list, unsigned short rr)
121
0
{
122
0
  while (list)
123
0
    {
124
0
      if (list->rr != 0 && list->rr == rr)
125
0
  return 1;
126
127
0
      list = list->next;
128
0
    }
129
130
0
  return 0;
131
0
}
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
1.05k
{
137
  /* remove trailing . 
138
     also fail empty string and label > 63 chars */
139
1.05k
  size_t dotgap = 0, wiresize = 0, l = strlen(in);
140
1.05k
  char c;
141
1.05k
  int nowhite = 0;
142
1.05k
  int idn_encode = 0;
143
1.05k
  int hasuscore = 0;
144
1.05k
  int hasucase = 0;
145
  
146
1.05k
  if (l == 0)
147
88
    return 0;
148
  
149
966
  if (in[l-1] == '.')
150
38
    {
151
38
      in[l-1] = 0;
152
38
      nowhite = 1;
153
38
    }
154
155
17.1k
  for (; (c = *in); in++)
156
16.5k
    {
157
16.5k
      if (c == '.')
158
2.61k
        {
159
2.61k
    wiresize += dotgap + 1;
160
2.61k
    dotgap = 0;
161
2.61k
  }
162
13.9k
      else if (++dotgap > MAXLABEL)
163
79
        return 0;
164
13.8k
      else if (isascii((unsigned char)c) && iscntrl((unsigned char)c)) 
165
        /* iscntrl only gives expected results for ascii */
166
56
        return 0;
167
13.7k
      else if (!isascii((unsigned char)c))
168
186
#if !defined(HAVE_IDN) && !defined(HAVE_LIBIDN2)
169
186
        return 0;
170
#else
171
        idn_encode = 1;
172
#endif
173
13.6k
      else if (c != ' ')
174
11.1k
        {
175
11.1k
          nowhite = 1;
176
#if defined(HAVE_LIBIDN2) && (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
177
          if (c == '_')
178
            hasuscore = 1;
179
#else
180
11.1k
          (void)hasuscore;
181
11.1k
#endif
182
183
#if defined(HAVE_IDN) || defined(HAVE_LIBIDN2)
184
          if (c >= 'A' && c <= 'Z')
185
            hasucase = 1;
186
#else
187
11.1k
          (void)hasucase;
188
11.1k
#endif
189
11.1k
        }
190
16.5k
    }
191
192
645
  if (!nowhite)
193
70
    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
575
  idn_encode = idn_encode || hasucase;
201
575
#endif
202
203
 /* length of final label and terminaton added */
204
575
  if (!idn_encode && wiresize + dotgap + 2 >  MAXDNAME)
205
8
    return 0; /* wire representation too long */
206
207
567
  return (idn_encode) ? 2 : 1;
208
575
}
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
527
{
216
527
  char c;
217
527
  int first;
218
219
527
  if (!check_name(name))
220
210
    return 0;
221
222
1.53k
  for (first = 1; (c = *name); name++, first = 0)
223
    /* check for legal char a-z A-Z 0-9 - _ . */
224
1.39k
    {
225
1.39k
      if ((c >= 'A' && c <= 'Z') ||
226
1.13k
    (c >= 'a' && c <= 'z') ||
227
788
    (c >= '0' && c <= '9'))
228
995
  continue;
229
230
404
      if (!first && (c == '-' || c == '_'))
231
225
  continue;
232
      
233
      /* end of hostname part */
234
179
      if (c == '.')
235
12
  return 1;
236
      
237
167
      return 0;
238
179
    }
239
  
240
138
  return 1;
241
317
}
242
  
243
char *canonicalise(char *in, int *nomem)
244
527
{
245
527
  char *ret = NULL;
246
527
  int rc;
247
  
248
527
  if (nomem)
249
0
    *nomem = 0;
250
  
251
527
  if (!(rc = check_name(in)))
252
277
    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
250
  (void)rc;
284
250
#endif
285
  
286
250
  if ((ret = whine_malloc(strlen(in)+1)))
287
250
    strcpy(ret, in);
288
0
  else if (nomem)
289
0
    *nomem = 1;
290
291
250
  return ret;
292
527
}
293
294
unsigned char *do_rfc1035_name(unsigned char *p, char *sval, unsigned char *limit)
295
0
{
296
0
  int j;
297
298
  /* Never make a name larger than the RFC limit */
299
0
  if (!limit || (limit - p > MAXDNAME))
300
0
    limit = p + MAXDNAME;
301
  
302
0
  while (sval && *sval)
303
0
    {
304
0
      unsigned char *cp = p++;
305
306
0
      if (p > limit)
307
0
        return NULL;
308
309
0
      for (j = 0; *sval && (*sval != '.'); sval++, j++)
310
0
  {
311
0
          if (p + 1 > limit)
312
0
            return NULL;
313
314
0
    if (*sval == NAME_ESCAPE)
315
0
      *p++ = (*(++sval))-1;
316
0
    else
317
0
      *p++ = *sval;
318
0
  }
319
      
320
0
      *cp  = j;
321
0
      if (*sval)
322
0
  sval++;
323
0
    }
324
  
325
0
  return p;
326
0
}
327
328
/* for use during startup */
329
void *safe_malloc(size_t size)
330
0
{
331
0
  void *ret = calloc(1, size);
332
  
333
0
  if (!ret)
334
0
    die(_("could not get memory"), NULL, EC_NOMEM);
335
      
336
0
  return ret;
337
0
}
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
0
{
344
0
  if (size != 0)
345
0
    {
346
0
      dest[0] = dest[size-1] = '\0';
347
0
      if (src)
348
0
  strncpy(dest, src, size-1);
349
0
    }
350
0
}
351
352
void safe_pipe(int *fd, int read_noblock)
353
0
{
354
0
  if (pipe(fd) == -1 || 
355
0
      !fix_fd(fd[1]) ||
356
0
      (read_noblock && !fix_fd(fd[0])))
357
0
    die(_("cannot create pipe: %s"), NULL, EC_MISC);
358
0
}
359
360
int sockaddr_isequal(const union mysockaddr *s1, const union mysockaddr *s2)
361
0
{
362
0
  if (s1->sa.sa_family == s2->sa.sa_family)
363
0
    { 
364
0
      if (s1->sa.sa_family == AF_INET &&
365
0
    s1->in.sin_port == s2->in.sin_port &&
366
0
    s1->in.sin_addr.s_addr == s2->in.sin_addr.s_addr)
367
0
  return 1;
368
      
369
0
      if (s1->sa.sa_family == AF_INET6 &&
370
0
    s1->in6.sin6_port == s2->in6.sin6_port &&
371
0
    s1->in6.sin6_scope_id == s2->in6.sin6_scope_id &&
372
0
    IN6_ARE_ADDR_EQUAL(&s1->in6.sin6_addr, &s2->in6.sin6_addr))
373
0
  return 1;
374
0
    }
375
0
  return 0;
376
0
}
377
378
int sockaddr_isnull(const union mysockaddr *s)
379
0
{
380
0
  if (s->sa.sa_family == AF_INET &&
381
0
      s->in.sin_addr.s_addr == 0)
382
0
    return 1;
383
  
384
0
  if (s->sa.sa_family == AF_INET6 &&
385
0
      IN6_IS_ADDR_UNSPECIFIED(&s->in6.sin6_addr))
386
0
    return 1;
387
  
388
0
  return 0;
389
0
}
390
391
int sa_len(union mysockaddr *addr)
392
0
{
393
#ifdef HAVE_SOCKADDR_SA_LEN
394
  return addr->sa.sa_len;
395
#else
396
0
  if (addr->sa.sa_family == AF_INET6)
397
0
    return sizeof(addr->in6);
398
0
  else
399
0
    return sizeof(addr->in); 
400
0
#endif
401
0
}
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
152
{
406
152
  unsigned int c1, c2;
407
  
408
4.10k
  do {
409
4.10k
    c1 = (unsigned char) *a++;
410
4.10k
    c2 = (unsigned char) *b++;
411
    
412
4.10k
    if (c1 >= 'A' && c1 <= 'Z')
413
375
      c1 += 'a' - 'A';
414
4.10k
    if (c2 >= 'A' && c2 <= 'Z')
415
376
      c2 += 'a' - 'A';
416
    
417
4.10k
    if (c1 < c2)
418
42
      return -1;
419
4.05k
    else if (c1 > c2)
420
52
      return 1;
421
    
422
4.10k
  } while (c1);
423
  
424
58
  return 0;
425
152
}
426
427
int hostname_isequal(const char *a, const char *b)
428
527
{
429
527
  return strlen(a) == strlen(b) && hostname_order(a, b) == 0;
430
527
}
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
527
{
435
527
  char *ap, *bp;
436
527
  unsigned int c1, c2;
437
  
438
  /* move to the end */
439
12.9k
  for (ap = a; *ap; ap++); 
440
17.3k
  for (bp = b; *bp; bp++);
441
442
  /* anything is a subdomain of the root domain. */
443
527
  if (ap == a)
444
41
    return (bp == b) ? 2 : 1;
445
  
446
  /* b shorter than a */
447
486
  if ((bp - b) < (ap - a))
448
198
    return 0;
449
  
450
288
  do
451
3.06k
    {
452
3.06k
      c1 = (unsigned char) *(--ap);
453
3.06k
      c2 = (unsigned char) *(--bp);
454
  
455
3.06k
       if (c1 >= 'A' && c1 <= 'Z')
456
398
   c1 += 'a' - 'A';
457
3.06k
       if (c2 >= 'A' && c2 <= 'Z')
458
402
   c2 += 'a' - 'A';
459
460
3.06k
       if (c1 != c2)
461
191
   return 0;
462
3.06k
    } while (ap != a);
463
464
97
  if (bp == b)
465
49
    return 2;
466
467
48
  if (*(--bp) == '.')
468
1
    return 1;
469
470
47
  return 0;
471
48
}
472
 
473
time_t dnsmasq_time(void)
474
0
{
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
0
  return time(NULL);
484
0
#endif
485
0
}
486
487
u32 dnsmasq_milliseconds(void)
488
0
{
489
0
  struct timeval tv;
490
491
0
  gettimeofday(&tv, NULL);
492
493
0
  return (tv.tv_sec) * 1000 + (tv.tv_usec / 1000);
494
0
}
495
496
int netmask_length(struct in_addr mask)
497
0
{
498
0
  int zero_count = 0;
499
500
0
  while (0x0 == (mask.s_addr & 0x1) && zero_count < 32) 
501
0
    {
502
0
      mask.s_addr >>= 1;
503
0
      zero_count++;
504
0
    }
505
  
506
0
  return 32 - zero_count;
507
0
}
508
509
int is_same_net(struct in_addr a, struct in_addr b, struct in_addr mask)
510
0
{
511
0
  return (a.s_addr & mask.s_addr) == (b.s_addr & mask.s_addr);
512
0
}
513
514
int is_same_net_prefix(struct in_addr a, struct in_addr b, int prefix)
515
0
{
516
0
  struct in_addr mask;
517
518
0
  mask.s_addr = htonl(~((1 << (32 - prefix)) - 1));
519
520
0
  return is_same_net(a, b, mask);
521
0
}
522
523
524
int is_same_net6(struct in6_addr *a, struct in6_addr *b, int prefixlen)
525
0
{
526
0
  int pfbytes = prefixlen >> 3;
527
0
  int pfbits = prefixlen & 7;
528
529
0
  if (memcmp(&a->s6_addr, &b->s6_addr, pfbytes) != 0)
530
0
    return 0;
531
532
0
  if (pfbits == 0 ||
533
0
      (a->s6_addr[pfbytes] >> (8 - pfbits) == b->s6_addr[pfbytes] >> (8 - pfbits)))
534
0
    return 1;
535
536
0
  return 0;
537
0
}
538
539
/* return least significant 64 bits if IPv6 address */
540
u64 addr6part(struct in6_addr *addr)
541
0
{
542
0
  int i;
543
0
  u64 ret = 0;
544
545
0
  for (i = 8; i < 16; i++)
546
0
    ret = (ret << 8) + addr->s6_addr[i];
547
548
0
  return ret;
549
0
}
550
551
void setaddr6part(struct in6_addr *addr, u64 host)
552
0
{
553
0
  int i;
554
555
0
  for (i = 15; i >= 8; i--)
556
0
    {
557
0
      addr->s6_addr[i] = host;
558
0
      host = host >> 8;
559
0
    }
560
0
}
561
562
563
/* returns port number from address */
564
int prettyprint_addr(union mysockaddr *addr, char *buf)
565
0
{
566
0
  int port = 0;
567
  
568
0
  if (addr->sa.sa_family == AF_INET)
569
0
    {
570
0
      inet_ntop(AF_INET, &addr->in.sin_addr, buf, ADDRSTRLEN);
571
0
      port = ntohs(addr->in.sin_port);
572
0
    }
573
0
  else if (addr->sa.sa_family == AF_INET6)
574
0
    {
575
0
      char name[IF_NAMESIZE];
576
0
      inet_ntop(AF_INET6, &addr->in6.sin6_addr, buf, ADDRSTRLEN);
577
0
      if (addr->in6.sin6_scope_id != 0 &&
578
0
    if_indextoname(addr->in6.sin6_scope_id, name) &&
579
0
    strlen(buf) + strlen(name) + 2 <= ADDRSTRLEN)
580
0
  {
581
0
    strcat(buf, "%");
582
0
    strcat(buf, name);
583
0
  }
584
0
      port = ntohs(addr->in6.sin6_port);
585
0
    }
586
  
587
0
  return port;
588
0
}
589
590
void prettyprint_time(char *buf, unsigned int t)
591
0
{
592
0
  if (t == 0xffffffff)
593
0
    sprintf(buf, _("infinite"));
594
0
  else
595
0
    {
596
0
      unsigned int x, p = 0;
597
0
      buf[0] = '\0';
598
0
       if ((x = t/86400))
599
0
  p += sprintf(&buf[p], "%ud", x);
600
0
       if ((x = (t/3600)%24))
601
0
  p += sprintf(&buf[p], "%uh", x);
602
0
      if ((x = (t/60)%60))
603
0
  p += sprintf(&buf[p], "%um", x);
604
0
      if ((x = t%60))
605
0
  sprintf(&buf[p], "%us", x);
606
0
    }
607
0
}
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
1.05k
{
615
1.05k
  int done = 0, mask = 0, i = 0;
616
1.05k
  char *r;
617
    
618
1.05k
  if (mac_type)
619
527
    *mac_type = 0;
620
  
621
5.44k
  while (!done && (maxlen == -1 || i < maxlen))
622
4.91k
    {
623
14.0k
      for (r = in; *r != 0 && *r != ':' && *r != '-' && *r != ' '; r++)
624
9.59k
  if (*r != '*' && !isxdigit((unsigned char)*r))
625
504
    return -1;
626
      
627
4.41k
      if (*r == 0)
628
543
  done = 1;
629
      
630
4.41k
      if (r != in )
631
786
  {
632
786
    if (*r == '-' && i == 0 && mac_type)
633
0
     {
634
0
        *r = 0;
635
0
        *mac_type = strtol(in, NULL, 16);
636
0
        mac_type = NULL;
637
0
     }
638
786
    else
639
786
      {
640
786
        *r = 0;
641
786
        if (strcmp(in, "*") == 0)
642
390
    {
643
390
      mask = (mask << 1) | 1;
644
390
      i++;
645
390
    }
646
396
        else
647
396
    {
648
396
      int j, bytes = (1 + (r - in))/2;
649
2.21k
      for (j = 0; j < bytes; j++)
650
1.87k
        { 
651
1.87k
          char sav;
652
1.87k
          if (j < bytes - 1)
653
1.50k
      {
654
1.50k
        sav = in[(j+1)*2];
655
1.50k
        in[(j+1)*2] = 0;
656
1.50k
      }
657
          /* checks above allow mix of hexdigit and *, which
658
       is illegal. */
659
1.87k
          if (strchr(&in[j*2], '*'))
660
17
      return -1;
661
1.85k
          out[i] = strtol(&in[j*2], NULL, 16);
662
1.85k
          mask = mask << 1;
663
1.85k
          if (++i == maxlen)
664
42
      break; 
665
1.81k
          if (j < bytes - 1)
666
1.47k
      in[(j+1)*2] = sav;
667
1.81k
        }
668
396
    }
669
786
      }
670
786
  }
671
4.39k
      in = r+1;
672
4.39k
    }
673
  
674
533
  if (wildcard_mask)
675
0
    *wildcard_mask = mask;
676
677
533
  return i;
678
1.05k
}
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
0
{
683
0
  int i, count;
684
0
  for (count = 1, i = len - 1; i >= 0; i--, mask = mask >> 1)
685
0
    if (!(mask & 1))
686
0
      {
687
0
  if (a[i] == b[i])
688
0
    count++;
689
0
  else
690
0
    return 0;
691
0
      }
692
0
  return count;
693
0
}
694
695
char *print_mac(unsigned char *mac, int len)
696
0
{
697
0
  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
0
  if (len == 0 || !expand_buf(&buff, len*3))
702
0
    return "<null>";
703
0
  else
704
0
    {
705
0
      char *p =  buff.iov_base;
706
0
      int i;
707
708
0
      for (i = 0; i < len; i++)
709
0
  p += sprintf(p, "%.2x%s", mac[i], (i == len - 1) ? "" : ":");
710
0
    }
711
  
712
0
  return buff.iov_base;
713
0
}
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
0
{
720
0
  static int retries = 0;
721
0
  struct timespec waiter;
722
  
723
0
  if (rc != -1)
724
0
    {
725
0
      retries = 0;
726
0
      errno = 0;
727
0
      return 0;
728
0
    }
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
0
  if (errno == EAGAIN || errno == EWOULDBLOCK)
736
0
     {
737
0
       waiter.tv_sec = 0;
738
0
       waiter.tv_nsec = 10000;
739
0
       nanosleep(&waiter, NULL);
740
0
       if (retries++ < 1000)
741
0
   return 1;
742
0
     }
743
  
744
0
  retries = 0;
745
  
746
0
  if (errno == EINTR)
747
0
    return 1;
748
  
749
0
  return 0;
750
0
}
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
0
{
762
0
  int cur = 0;
763
0
  ssize_t n, done = 0;
764
765
0
  while (cur < iovcnt)
766
0
    {
767
0
      iov[cur].iov_len -= done;
768
0
      iov[cur].iov_base =  ((char *)iov[cur].iov_base) + done;
769
770
0
      if (rw & 1)
771
0
  n = readv(fd, &iov[cur], iovcnt - cur);
772
0
      else
773
0
  n = writev(fd, &iov[cur], iovcnt - cur);
774
775
0
      iov[cur].iov_len += done;
776
0
      iov[cur].iov_base = ((char *)iov[cur].iov_base) - done;
777
      
778
0
      if (n == -1)
779
0
  {
780
0
    if (errno == EINTR || errno == ENOMEM || errno == ENOBUFS)
781
0
      continue;
782
    
783
0
    if (!(rw & 2) && (errno == EAGAIN || errno == EWOULDBLOCK))
784
0
      continue;
785
786
0
    return 0;
787
0
  }
788
      
789
0
      if (n == 0 && (rw & 1))
790
0
  return 0;
791
      
792
0
      done += n;
793
0
      while (cur < iovcnt && (size_t)done >= iov[cur].iov_len)
794
0
  done -= iov[cur++].iov_len;
795
0
    }
796
          
797
0
  return 1;
798
0
}
799
800
int read_write(int fd, unsigned char *packet, int size, int rw)
801
0
{
802
0
  struct iovec iov;
803
804
  /* size == 0 is not an error, just a NOOP. */
805
0
  if (size == 0)
806
0
    return 1;
807
  
808
0
  iov.iov_len = (size_t)size;
809
0
  iov.iov_base = packet;
810
811
0
  return read_writev(fd, &iov, 1, rw);
812
0
}
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
0
{
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
0
#ifdef HAVE_LINUX_NETWORK
827
0
#define FDESCFS "/proc/self/fd"
828
0
#endif
829
830
#ifdef HAVE_BSD_NETWORK
831
#define FDESCFS "/dev/fd"
832
#endif
833
834
0
#ifdef FDESCFS
835
0
  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
0
    d = opendir(FDESCFS);
861
      
862
0
  if (d)
863
0
    {
864
0
      struct dirent *de;
865
866
0
      while ((de = readdir(d)))
867
0
  {
868
0
    long fd;
869
0
    char *e = NULL;
870
    
871
0
    errno = 0;
872
0
    fd = strtol(de->d_name, &e, 10);
873
        
874
0
          if (errno != 0 || !e || *e || fd == dirfd(d) ||
875
0
        fd == STDOUT_FILENO || fd == STDERR_FILENO || fd == STDIN_FILENO ||
876
0
        fd == spare1 || fd == spare2 || fd == spare3)
877
0
      continue;
878
    
879
0
    close(fd);
880
0
  }
881
      
882
0
      closedir(d);
883
0
      return;
884
0
    }
885
0
#endif
886
  
887
  /* fallback, dumb code. */
888
0
  for (max_fd--; max_fd >= 0; max_fd--)
889
0
    if (max_fd != STDOUT_FILENO && max_fd != STDERR_FILENO && max_fd != STDIN_FILENO &&
890
0
  max_fd != spare1 && max_fd != spare2 && max_fd != spare3)
891
0
      close(max_fd);
892
0
}
893
894
/* Basically match a string value against a wildcard pattern.  */
895
int wildcard_match(const char* wildcard, const char* match)
896
527
{
897
3.84k
  while (*wildcard && *match)
898
3.64k
    {
899
3.64k
      if (*wildcard == '*')
900
47
        return 1;
901
902
3.59k
      if (*wildcard != *match)
903
275
        return 0; 
904
905
3.32k
      ++wildcard;
906
3.32k
      ++match;
907
3.32k
    }
908
909
205
  return *wildcard == *match;
910
527
}
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
527
{
915
3.84k
  while (*wildcard && *match && num)
916
3.64k
    {
917
3.64k
      if (*wildcard == '*')
918
47
        return 1;
919
920
3.59k
      if (*wildcard != *match)
921
275
        return 0; 
922
923
3.32k
      ++wildcard;
924
3.32k
      ++match;
925
3.32k
      --num;
926
3.32k
    }
927
928
205
  return (!num) || (*wildcard == *match);
929
527
}
930
931
#ifdef HAVE_LINUX_NETWORK
932
int kernel_version(void)
933
0
{
934
0
  struct utsname utsname;
935
0
  int version;
936
0
  char *split;
937
  
938
0
  if (uname(&utsname) < 0)
939
0
    die(_("failed to find kernel version: %s"), NULL, EC_MISC);
940
  
941
0
  split = strtok(utsname.release, ".");
942
0
  version = (split ? atoi(split) : 0);
943
0
  split = strtok(NULL, ".");
944
0
  version = version * 256 + (split ? atoi(split) : 0);
945
0
  split = strtok(NULL, ".");
946
0
  return version * 256 + (split ? atoi(split) : 0);
947
0
}
948
#endif
949
950
0
#define hash_ptr(x) (((uintptr_t)(x)) & 0xffffff)
951
952
void *whine_malloc_real(const char *func, unsigned int line, size_t size)
953
250
{
954
250
  void *ret = calloc(1, size);
955
  
956
250
  if (!ret)
957
0
    my_syslog(LOG_ERR, _("failed to allocate %d bytes"), (int) size);
958
250
  else if (daemon->log_malloc)
959
0
    my_syslog(LOG_INFO, _("malloc: %s:%u %zu bytes at %x"), func, line, size, hash_ptr(ret));
960
961
250
  return ret;
962
250
}
963
964
void *whine_realloc_real(const char *wrapper, const char *func, unsigned int line, void *ptr, size_t size)
965
0
{
966
0
  unsigned int old = hash_ptr(ptr);
967
0
  void *ret = realloc(ptr, size);
968
  
969
0
  if (!ret)
970
0
    my_syslog(LOG_ERR, _("failed to reallocate %d bytes"), (int) size);
971
0
  else if (daemon->log_malloc)
972
0
    {
973
0
      if (!wrapper)
974
0
  wrapper = "realloc";
975
0
      my_syslog(LOG_INFO, _("%s: %s:%u %zu bytes from %x to %x"), wrapper, func, line, size, old, hash_ptr(ret));
976
0
    }
977
  
978
0
  return ret;
979
0
}
980
981
/* _note_ may copy buffer */
982
int expand_buf_real(const char *func, unsigned int line, struct iovec *iov, size_t size)
983
0
{
984
0
  void *new;
985
986
0
  if (size <= (size_t)iov->iov_len)
987
0
    return 1;
988
989
0
  if (!(new = whine_realloc_real("expand_buf", func, line, iov->iov_base, size)))
990
0
    {
991
0
      errno = ENOMEM;
992
0
      return 0;
993
0
    }
994
995
0
  iov->iov_base = new;
996
0
  iov->iov_len = size;
997
998
0
  return 1;
999
0
}
1000
1001
int expand_workspace_real(const char *func, unsigned int line, unsigned char ***wkspc, int *szp, int new)
1002
0
{
1003
0
  unsigned char **p;
1004
0
  int old = *szp;
1005
1006
0
  if (old >= new+1)
1007
0
    return 1;
1008
1009
0
  new += 5;
1010
1011
0
  if (!(p = whine_realloc_real("expand_workspace", func, line, *wkspc, new * sizeof(unsigned char *))))
1012
0
    return 0;
1013
1014
0
  memset(p+old, 0, (new-old) * sizeof(unsigned char *));
1015
  
1016
0
  *wkspc = p;
1017
0
  *szp = new;
1018
1019
0
  return 1;
1020
0
}
1021
1022
void malloc_log_real(const char *func, unsigned int line, void *mem, size_t size)
1023
0
{
1024
0
  if (mem && daemon->log_malloc)
1025
0
    my_syslog(LOG_INFO, _("malloc: %s:%u %zu bytes at %x"), func, line, size, hash_ptr(mem));
1026
0
}
1027
1028
#undef free
1029
void free_real(const char *func, unsigned int line, void *ptr)
1030
28.3k
{
1031
28.3k
  if (ptr)
1032
28.3k
    {
1033
28.3k
      if (daemon->log_malloc)
1034
0
  my_syslog(LOG_INFO, _("free: %s:%u block at %x"), func, line, hash_ptr(ptr));
1035
  
1036
28.3k
      free(ptr);
1037
28.3k
    }
1038
28.3k
}
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
0
{
1044
0
  size_t cnt = 0;
1045
0
  char *buff = *buffp;
1046
1047
0
  while (1) {
1048
0
    int c = f ? getc(f) : EOF;
1049
        
1050
0
    if (cnt == *sizep)
1051
0
      {
1052
0
  void *new;
1053
  
1054
0
  if ((new = whine_realloc(buff, cnt + 1024)))
1055
0
    {
1056
0
      buff = *buffp = new;
1057
0
      *sizep = cnt + 1024; 
1058
0
    }
1059
0
  else
1060
0
    {
1061
      /* allocation failed, ignore line.
1062
         Whine_realloc will have complained. */
1063
0
      while (c != '\n' && c != EOF) 
1064
0
        c = getc(f);
1065
      
1066
0
      cnt = 0;
1067
0
      continue;
1068
0
    }
1069
0
      }
1070
1071
0
    buff[cnt] = 0;
1072
1073
0
    if (c == '\n')
1074
0
      return 1;
1075
    
1076
0
    if (c == EOF)
1077
0
      {
1078
  /* handle last line without '\n' */
1079
0
  if (cnt != 0)
1080
0
    return 1;
1081
1082
0
  free(buff);
1083
0
  *buffp = NULL;
1084
0
  *sizep = 0;
1085
0
  return 0;
1086
0
      }
1087
  
1088
0
    buff[cnt++] = c;
1089
0
  }
1090
0
}