Debian Codegraph @

src/other.c

raw symbols SCIP
1 /*
2 * The dhcpd-pools has BSD 2-clause license which also known as "Simplified
3 * BSD License" or "FreeBSD License".
4 *
5 * Copyright 2006- Sami Kerola. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
9 * met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the
17 * distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 *
31 * The views and conclusions contained in the software and documentation are
32 * those of the authors and should not be interpreted as representing
33 * official policies, either expressed or implied, of Sami Kerola.
34 */
35
36 /*! \file other.c
37 * \brief Collection of various functions.
38 */
39
40 #include <config.h>
41
42 #include <arpa/inet.h>
43 #include <errno.h>
44 #include <limits.h>
45 #include <netinet/in.h>
46 #include <stddef.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/stat.h>
51 #include <time.h>
52 #include <unistd.h>
53
54 #include "error.h"
55 #include "progname.h"
56 #include "quote.h"
57 #include "xalloc.h"
58
59 #include "dhcpd-pools.h"
60
61 static char *(*cidr_last) (union ipaddr_t *restrict addr, const int mask);
62 static char *cidr_last_v4(union ipaddr_t *restrict addr, const int mask);
63 static char *cidr_last_v6(union ipaddr_t *restrict addr, const int mask);
64
65 /*! \brief Set function pointers depending on IP version.
66 * \param ip IP version.
67 */
68 void set_ipv_functions(struct conf_t *state, int version)
69 {
70 switch (version) {
71
72 case IPv4:
73 state->ip_version = version;
74 add_lease = add_lease_v4;
75 copy_ipaddr = copy_ipaddr_v4;
76 find_lease = find_lease_v4;
77 get_range_size = get_range_size_v4;
78 ipcomp = ipcomp_v4;
79 leasecomp = leasecomp_v4;
80 ntop_ipaddr = ntop_ipaddr_v4;
81 parse_ipaddr = parse_ipaddr_v4;
82 cidr_last = cidr_last_v4;
83 xstrstr = xstrstr_v4;
84 break;
85
86 case IPv6:
87 state->ip_version = version;
88 add_lease = add_lease_v6;
89 copy_ipaddr = copy_ipaddr_v6;
90 find_lease = find_lease_v6;
91 get_range_size = get_range_size_v6;
92 ipcomp = ipcomp_v6;
93 leasecomp = leasecomp_v6;
94 ntop_ipaddr = ntop_ipaddr_v6;
95 parse_ipaddr = parse_ipaddr_v6;
96 cidr_last = cidr_last_v6;
97 xstrstr = xstrstr_v6;
98 break;
99
100 case IPvUNKNOWN:
101 state->ip_version = version;
102 add_lease = add_lease_init;
103 copy_ipaddr = copy_ipaddr_init;
104 find_lease = find_lease_init;
105 get_range_size = get_range_size_init;
106 ipcomp = ipcomp_init;
107 leasecomp = leasecomp_init;
108 ntop_ipaddr = ntop_ipaddr_init;
109 parse_ipaddr = parse_ipaddr_init;
110 cidr_last = NULL;
111 xstrstr = xstrstr_init;
112 break;
113
114 default:
115 abort();
116
117 }
118 return;
119 }
120
121 /*! \brief Convert text string IP address from either IPv4 or IPv6 to an integer.
122 * \param src An IP string in either format.
123 * \param dst An union which will hold conversion result.
124 * \return Was parsing successful.
125 */
126 int parse_ipaddr_init(struct conf_t *state, const char *restrict src, union ipaddr_t *restrict dst)
127 {
128 struct in_addr addr;
129 struct in6_addr addr6;
130
131 if (inet_aton(src, &addr) == 1)
132 set_ipv_functions(state, IPv4);
133 else if (inet_pton(AF_INET6, src, &addr6) == 1)
134 set_ipv_functions(state, IPv6);
135 else
136 return 0;
137 return parse_ipaddr(state, src, dst);
138 }
139
140 int parse_ipaddr_v4(struct conf_t *state
141 __attribute__ ((unused)), const char *restrict src,
142 union ipaddr_t *restrict dst)
143 {
144 int rv;
145 struct in_addr addr;
146
147 rv = inet_aton(src, &addr);
148 dst->v4 = ntohl(addr.s_addr);
149 return rv == 1;
150 }
151
152 int parse_ipaddr_v6(struct conf_t *state
153 __attribute__ ((unused)), const char *restrict src,
154 union ipaddr_t *restrict dst)
155 {
156 int rv;
157 struct in6_addr addr;
158
159 rv = inet_pton(AF_INET6, src, &addr);
160 memcpy(&dst->v6, addr.s6_addr, sizeof(addr.s6_addr));
161 return rv == 1;
162 }
163
164 /*! \brief Convert string to a desimal format network marks.
165 * \param src Digit that should be a network mask.
166 * \return Network mask, or -1 when failing.
167 */
168 static int strtol_mask(const char *str)
169 {
170 long num;
171 char *end = NULL;
172
173 errno = 0;
174 if (str == NULL || *str == '\0')
175 goto err;
176 num = strtol(str, &end, 10);
177
178 if (errno || str == end || (end && *end))
179 goto err;
180 if (num < 0 || 128 < num)
181 goto err;
182 return (int)num;
183 err:
184 return -1;
185 }
186
187 /*! \brief Find last address in IPv4 range by using cidr format.
188 * \param addr Pointer to memory where address needs to be stored.
189 * \return Allocated string format of the address.
190 */
191 static char *cidr_last_v4(union ipaddr_t *restrict addr, const int mask)
192 {
193 union ipaddr_t last_ip;
194 uint32_t netmask;
195 const char *ip;
196
197 if (mask)
198 netmask = (1U << (32 - mask)) - 1;
199 else
200 netmask = 0;
201 last_ip.v4 = addr->v4 | netmask;
202
203 ip = ntop_ipaddr(&last_ip);
204 return xstrdup(ip);
205 }
206
207 /*! \brief Find last address in IPv6 range by using cidr format.
208 * \param addr Pointer to memory where address needs to be stored.
209 * \return Allocated string format of the address.
210 */
211 static char *cidr_last_v6(union ipaddr_t *restrict addr, const int mask)
212 {
213 union ipaddr_t bitmask;
214 int i, j;
215 char ip[128];
216
217 memset(&bitmask, 0x0, sizeof(bitmask));
218 for (i = mask, j = 0; i > 0; i -= 8, j++) {
219 if (i >= 8)
220 bitmask.v6[j] = 0xff;
221 else
222 bitmask.v6[j] = (unsigned char)(0xffU << (8 - i));
223 }
224 for (i = 0; i < (int)sizeof(bitmask); i++)
225 addr->v6[i] |= ~bitmask.v6[i];
226 inet_ntop(AF_INET6, addr, ip, sizeof(ip));
227 return xstrdup(ip);
228 }
229
230 /*! \brief Convert a cidr notated address to a range.
231 * \param range_p Pointer to memory where addresses need to be stored.
232 * \param word A range as a cidr string.
233 */
234 void parse_cidr(struct conf_t *state, struct range_t *range_p, const char *word)
235 {
236 char *divider;
237 int mask;
238 union ipaddr_t addr;
239 char *last;
240
241 /* determine cidr */
242 divider = strchr(word, '/');
243 *divider++ = '\0';
244 mask = strtol_mask(divider);
245 if (mask < 0)
246 error(EXIT_FAILURE, 0, "cidr %s invalid mask %s", word, divider);
247 if (state->ip_version == IPvUNKNOWN) {
248 if (!strchr(word, ':'))
249 set_ipv_functions(state, IPv4);
250 else
251 set_ipv_functions(state, IPv6);
252 }
253
254 /* start of the range is easy */
255 parse_ipaddr(state, word, &addr);
256 copy_ipaddr(&range_p->first_ip, &addr);
257
258 /* end of the range depends cidr size */
259 last = cidr_last(&addr, mask);
260 parse_ipaddr(state, last, &addr);
261 copy_ipaddr(&range_p->last_ip, &addr);
262 free(last);
263 }
264
265 /*! \brief Copy IP address to union.
266 *
267 * \param dst Destination for a binary IP address.
268 * \param src Sourse of an IP address. */
269 void copy_ipaddr_init(union ipaddr_t *restrict dst __attribute__ ((unused)),
270 const union ipaddr_t *restrict src __attribute__ ((unused)))
271 {
272 }
273
274 void copy_ipaddr_v4(union ipaddr_t *restrict dst, const union ipaddr_t *restrict src)
275 {
276 dst->v4 = src->v4;
277 }
278
279 void copy_ipaddr_v6(union ipaddr_t *restrict dst, const union ipaddr_t *restrict src)
280 {
281 memcpy(&dst->v6, &src->v6, sizeof(src->v6));
282 }
283
284 /*! \brief Convert an address to string. This function will convert the
285 * IPv4 addresses to 123.45.65.78 format, and the IPv6 addresses to it's
286 * native format depending on which version of the addressing is found to
287 * be in use.
288 *
289 * \param ip Binary IP address.
290 * \return Printable address.
291 */
292 const char *ntop_ipaddr_init(const union ipaddr_t *ip __attribute__ ((unused)))
293 {
294 static char buffer = '\0';
295
296 return &buffer;
297 }
298
299 const char *ntop_ipaddr_v4(const union ipaddr_t *ip)
300 {
301 static char buffer[INET_ADDRSTRLEN];
302 struct in_addr addr;
303
304 addr.s_addr = htonl(ip->v4);
305 return inet_ntop(AF_INET, &addr, buffer, sizeof(buffer));
306 }
307
308 const char *ntop_ipaddr_v6(const union ipaddr_t *ip)
309 {
310 static char buffer[INET6_ADDRSTRLEN];
311 struct in6_addr addr;
312
313 memcpy(addr.s6_addr, ip->v6, sizeof(addr.s6_addr));
314 return inet_ntop(AF_INET6, &addr, buffer, sizeof(buffer));
315 }
316
317 /*! \brief Calculate how many addresses there are in a range.
318 *
319 * \param r Pointer to range structure, which has information about first
320 * and last IP in the range.
321 * \return Size of a range.
322 */
323 double get_range_size_init(const struct range_t *r __attribute__ ((unused)))
324 {
325 return 0;
326 }
327
328 double get_range_size_v4(const struct range_t *r)
329 {
330 return r->last_ip.v4 - r->first_ip.v4 + 1;
331 }
332
333 double get_range_size_v6(const struct range_t *r)
334 {
335 double size = 0;
336 int i;
337
338 /* When calculating the size of an IPv6 range overflow may occur.
339 * In that case only the last LONG_BIT bits are preserved, thus
340 * we just skip the first (16 - LONG_BIT) bits... */
341 for (i = 0; i < 16; i++) {
342 size *= 256;
343 size += (int)r->last_ip.v6[i] - (int)r->first_ip.v6[i];
344 }
345 return size + 1;
346 }
347
348 /*! \fn xstrstr_init(const char *restrict str)
349 * \brief Determine if the dhcpd is in IPv4 or IPv6 mode. This function
350 * may be needed when dhcpd.conf file has zero IP version hints.
351 *
352 * \param str A line from dhcpd.conf
353 * \return prefix_t enum value
354 */
355 int xstrstr_init(struct conf_t *state, const char *restrict str)
356 {
357 if (!memcmp("lease ", str, 6)) {
358 set_ipv_functions(state, IPv4);
359 return PREFIX_LEASE;
360 }
361 if (!memcmp(" iaaddr ", str, 9)) {
362 set_ipv_functions(state, IPv6);
363 return PREFIX_LEASE;
364 }
365 return NUM_OF_PREFIX;
366 }
367
368 /*! \fn xstrstr_v4(const char *restrict str)
369 * \brief parse lease file in IPv4 mode
370 *
371 * \param str A line from dhcpd.conf
372 * \return prefix_t enum value
373 */
374 int
375 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
376 __attribute__ ((hot))
377 #endif
378 xstrstr_v4(struct conf_t *state __attribute__ ((unused)), const char *restrict str)
379 {
380 size_t len;
381
382 if (str[2] == 'b' || str[2] == 'h')
383 len = strlen(str);
384 else
385 len = 0;
386 if (15 < len) {
387 switch (str[16]) {
388 case 'f':
389 if (!memcmp(" binding state free;", str, 21))
390 return PREFIX_BINDING_STATE_FREE;
391 break;
392 case 'a':
393 if (!memcmp(" binding state active;", str, 23))
394 return PREFIX_BINDING_STATE_ACTIVE;
395 if (!memcmp(" binding state abandoned;", str, 25))
396 return PREFIX_BINDING_STATE_ABANDONED;
397 break;
398 case 'e':
399 if (!memcmp(" binding state expired;", str, 24))
400 return PREFIX_BINDING_STATE_EXPIRED;
401 break;
402 case 'r':
403 if (!memcmp(" binding state released;", str, 25))
404 return PREFIX_BINDING_STATE_RELEASED;
405 break;
406 case 'b':
407 if (!memcmp(" binding state backup;", str, 23))
408 return PREFIX_BINDING_STATE_BACKUP;
409 break;
410 case 'n':
411 if (!memcmp(" hardware ethernet", str, 19))
412 return PREFIX_HARDWARE_ETHERNET;
413 break;
414 default:
415 break;
416 }
417 }
418 if (!memcmp("lease ", str, 6))
419 return PREFIX_LEASE;
420 return NUM_OF_PREFIX;
421 }
422
423 /*! \fn xstrstr_v4(const char *restrict str)
424 * \brief parse lease file in IPv6 mode
425 *
426 * \param str A line from dhcpd.conf
427 * \return prefix_t enum value
428 */
429 int
430 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
431 __attribute__ ((hot))
432 #endif
433 xstrstr_v6(struct conf_t *state __attribute__ ((unused)), const char *restrict str)
434 {
435 size_t len;
436
437 if (str[4] == 'b' || str[2] == 'h')
438 len = strlen(str);
439 else
440 len = 0;
441 if (17 < len) {
442 switch (str[18]) {
443 case 'f':
444 if (!memcmp(" binding state free;", str, 23))
445 return PREFIX_BINDING_STATE_FREE;
446 break;
447 case 'a':
448 if (!memcmp(" binding state active;", str, 25))
449 return PREFIX_BINDING_STATE_ACTIVE;
450 if (!memcmp(" binding state abandoned;", str, 27))
451 return PREFIX_BINDING_STATE_ABANDONED;
452 break;
453 case 'e':
454 if (!memcmp(" binding state expired;", str, 26))
455 return PREFIX_BINDING_STATE_EXPIRED;
456 break;
457 case 'r':
458 if (!memcmp(" binding state released;", str, 27))
459 return PREFIX_BINDING_STATE_RELEASED;
460 break;
461 case 'b':
462 if (!memcmp(" binding state backup;", str, 25))
463 return PREFIX_BINDING_STATE_BACKUP;
464 break;
465 case 'n':
466 if (!memcmp(" hardware ethernet", str, 19))
467 return PREFIX_HARDWARE_ETHERNET;
468 break;
469 default:
470 break;
471 }
472 }
473 if (!memcmp(" iaaddr ", str, 9))
474 return PREFIX_LEASE;
475 return NUM_OF_PREFIX;
476 }
477
478 /*! \brief Parse option argument color mode.
479 *
480 * \param Color mode string.
481 * \return color mode enum.
482 */
483 int parse_color_mode(const char *restrict arg)
484 {
485 if (!strcmp(arg, "always"))
486 return color_on;
487 if (!strcmp(arg, "auto"))
488 return color_auto;
489 if (!strcmp(arg, "never"))
490 return color_off;
491 return color_unknown;
492 }
493
494 /*! \brief Return a double floating point value.
495 *
496 * \param str String to be converted to a double.
497 * \param errmesg Exit error message if conversion fails.
498 * \return Binary result of string to double conversion.
499 */
500 double strtod_or_err(const char *restrict str, const char *restrict errmesg)
501 {
502 double num;
503 char *end = NULL;
504
505 if (str == NULL || *str == '\0')
506 goto err;
507 errno = 0;
508 num = strtod(str, &end);
509 if (errno || str == end || (end && *end))
510 goto err;
511 return num;
512 err:
513 error(EXIT_FAILURE, errno, "%s: %s", errmesg, quote(str));
514 return 0;
515 }
516
517 /*! \brief Reverse range.
518 * Used before output, if a caller has requested reverse sorting. */
519 void flip_ranges(struct conf_t *state)
520 {
521 unsigned int i = state->num_ranges - 1, j;
522 struct range_t *tmp_ranges;
523
524 tmp_ranges = xmalloc(sizeof(struct range_t) * state->num_ranges);
525 for (j = 0; j < state->num_ranges; j++, i--)
526 *(tmp_ranges + j) = *(state->ranges + i);
527 memcpy(state->ranges, tmp_ranges, state->num_ranges * sizeof(struct range_t));
528 free(tmp_ranges);
529 }
530
531 /*! \brief Free memory, flush buffers etc. */
532 void clean_up(struct conf_t *state)
533 {
534 struct output_sort *cur, *next;
535 struct shared_network_t *c, *n;
536
537 /* Just in case there something in buffers */
538 if (fflush(NULL))
539 error(EXIT_FAILURE, errno, "clean_up: fflush");
540 free(state->ranges);
541 delete_all_leases(state);
542 for (cur = state->sorts; cur; cur = next) {
543 next = cur->next;
544 free(cur);
545 }
546 for (c = state->shared_net_root; c; c = n) {
547 n = c->next;
548 free(c->name);
549 free(c);
550 }
551 }
552
553 /*! \brief Print a time stamp of a path or now to output file. */
554 void dp_time_tool(FILE *file, const char *path, const int epoch)
555 {
556 struct stat st;
557
558 if (path)
559 stat(path, &st);
560 else
561 clock_gettime(CLOCK_REALTIME, &st.st_mtim);
562 if (epoch)
563 fprintf(file, "%ld", st.st_mtim.tv_sec);
564 else {
565 char time_stamp[64];
566 const time_t mtime = st.st_mtim.tv_sec;
567 struct tm tm;
568
569 localtime_r(&mtime, &tm);
570 strftime(time_stamp, sizeof(time_stamp), "%FT%T%z", &tm);
571 fprintf(file, "%s", time_stamp);
572 }
573 }
574
575 /*! \brief A version printing. */
576 void __attribute__ ((__noreturn__)) print_version(void)
577 {
578 #define stringify(s) #s
579 #define stringify_value(s) stringify(s)
580 fprintf(stdout, "%s\n"
581 "Original design and maintainer Sami Kerola.\n"
582 "uthash %s by Troy D. Hanson.\n"
583 "XML support by Dominic Germain, Sogetel inc.\n"
584 "IPv6 support by Cheer Xiao.\n"
585 "Mustach templating support by Jose Bollo.\n"
586 " The dhcpd-pools is FreeBSD Licensed,\n"
587 " uthash uses BSD license,\n"
588 " gnulib parts are mostly GPL,\n"
589 " and mustache uses Apache License.\n", PACKAGE_STRING,
590 stringify_value(UTHASH_VERSION));
591 exit(EXIT_SUCCESS);
592 }
593
594 /*! \brief Command line help screen. */
595 void __attribute__ ((__noreturn__)) usage(int status)
596 {
597 FILE *out = status == EXIT_SUCCESS ? stdout : stderr;
598
599 fprintf(out, "Usage: %s [OPTIONS]\n", program_name);
600 fputs( "\n", out);
601 fputs( "This is ISC dhcpd pools usage analyzer.\n", out);
602 fputs( "\n", out);
603 fputs( " -c, --config=FILE path to the dhcpd.conf file\n", out);
604 fputs( " -l, --leases=FILE path to the dhcpd.leases file\n", out);
605 fputs( " -f, --format=[thHcxXjJ] output format\n", out);
606 fputs( " t for text\n", out);
607 fputs( " H for full html page\n", out);
608 fputs( " x for xml\n", out);
609 fputs( " X for xml with active lease details\n", out);
610 fputs( " j for json\n", out);
611 fputs( " J for json with active lease details\n", out);
612 fputs( " c for comma separated values\n", out);
613 #ifdef BUILD_MUSTACH
614 fputs( " --mustach=FILE output using mustach template file\n", out);
615 #endif
616 fputs( " -s, --sort=[nimcptTe] sort ranges by\n", out);
617 fputs( " n name\n", out);
618 fputs( " i IP\n", out);
619 fputs( " m maximum\n", out);
620 fputs( " c current\n", out);
621 fputs( " p percent\n", out);
622 fputs( " t touched\n", out);
623 fputs( " T t+c\n", out);
624 fputs( " e t+c perc\n", out);
625 fputs( " -r, --reverse reverse order sort\n", out);
626 fputs( " -o, --output=FILE output into a file\n", out);
627 fputs( " -L, --limit=NR output limit mask 77 - 00\n", out);
628 fputs( " --color=WHEN use colors 'always', 'never', or 'auto'\n", out);
629 fputs( " --warning=PERC set warning alarming threshold\n", out);
630 fputs( " --critical=PERC set critical alarming threshold\n", out);
631 fputs( " --skip=WHAT do not print threshold 'ok', 'warning', 'critical',\n", out);
632 fputs( " 'minsize', or 'suppressed'\n", out);
633 fputs( " --warn-count=NR a number of free leases before warning raised\n", out);
634 fputs( " --crit-count=NR a number of free leases before critical raised\n", out);
635 fputs( " --minsize=size disable alarms for small ranges and shared-nets\n", out);
636 fputs( " --snet-alarms suppress range alarms that are part of a shared-net\n", out);
637 fputs( " -p, --perfdata print additional perfdata in alarming mode\n", out);
638 fputs( " -A, --all-as-shared treat single subnets as shared-network with CIDR as their name\n", out);
639 fputs( " --ip-version=4|6 force analysis to use either IPv4 or IPv6 functions\n", out);
640 fputs( " -v, --version output version information and exit\n", out);
641 fputs( " -h, --help display this help and exit\n", out);
642 fputs( "\n", out);
643 fprintf(out, "Report bugs to <%s>\n", PACKAGE_BUGREPORT);
644 fprintf(out, "Homepage: %s\n", PACKAGE_URL);
645
646 exit(status);
647 }