[package] owipcalc: add "prefix" operation to set prefix of base address during calcu...
[openwrt.git] / package / owipcalc / src / owipcalc.c
1 /*
2  * owipcalc - OpenWrt IP Calculator
3  *
4  *   Copyright (C) 2012 Jo-Philipp Wich <jow@openwrt.org>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  */
18
19 #include <stdio.h>
20 #include <stdint.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23
24 #include <string.h>
25 #include <unistd.h>
26
27 #include <arpa/inet.h>
28
29
30 struct cidr {
31         uint8_t family;
32         uint32_t prefix;
33         union {
34                 struct in_addr v4;
35                 struct in6_addr v6;
36         } addr;
37         union {
38                 char v4[sizeof("255.255.255.255/255.255.255.255 ")];
39                 char v6[sizeof("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF/128 ")];
40         } buf;
41 };
42
43 struct op {
44         const char *name;
45         const char *desc;
46         struct {
47                 bool (*a1)(struct cidr *a);
48                 bool (*a2)(struct cidr *a, struct cidr *b);
49         } f4;
50         struct {
51                 bool (*a1)(struct cidr *a);
52                 bool (*a2)(struct cidr *a, struct cidr *b);
53         } f6;
54 };
55
56
57 static bool quiet = false;
58 static bool printed = false;
59
60
61 static struct cidr * cidr_parse4(const char *s)
62 {
63         char *p = NULL, *r;
64         struct in_addr mask;
65         struct cidr *addr = malloc(sizeof(struct cidr));
66
67         if (!addr || (strlen(s) >= sizeof(addr->buf.v4)))
68                 goto err;
69
70         snprintf(addr->buf.v4, sizeof(addr->buf.v4), "%s", s);
71
72         addr->family = AF_INET;
73
74         if ((p = strchr(addr->buf.v4, '/')) != NULL)
75         {
76                 *p++ = 0;
77
78                 if (strchr(p, '.') != NULL)
79                 {
80                         if (inet_pton(AF_INET, p, &mask) != 1)
81                                 goto err;
82
83                         for (addr->prefix = 0; mask.s_addr; mask.s_addr >>= 1)
84                                 addr->prefix += (mask.s_addr & 1);
85                 }
86                 else
87                 {
88                         addr->prefix = strtoul(p, &r, 10);
89
90                         if ((p == r) || (*r != 0) || (addr->prefix > 32))
91                                 goto err;
92                 }
93         }
94         else
95         {
96                 addr->prefix = 32;
97         }
98
99         if (p == addr->buf.v4+1)
100                 memset(&addr->addr.v4, 0, sizeof(addr->addr.v4));
101         else if (inet_pton(AF_INET, addr->buf.v4, &addr->addr.v4) != 1)
102                 goto err;
103
104         return addr;
105
106 err:
107         if (addr)
108                 free(addr);
109
110         return NULL;
111 }
112
113 static bool cidr_add4(struct cidr *a, struct cidr *b)
114 {
115         uint32_t x = ntohl(a->addr.v4.s_addr);
116         uint32_t y = ntohl(b->addr.v4.s_addr);
117
118         if ((a->family != AF_INET) || (b->family != AF_INET))
119                 return false;
120
121         if ((uint32_t)(x + y) < x)
122         {
123                 fprintf(stderr, "overflow during 'add'\n");
124                 return false;
125         }
126
127         a->addr.v4.s_addr = htonl(x + y);
128         return true;
129 }
130
131 static bool cidr_sub4(struct cidr *a, struct cidr *b)
132 {
133         uint32_t x = ntohl(a->addr.v4.s_addr);
134         uint32_t y = ntohl(b->addr.v4.s_addr);
135
136         if ((a->family != AF_INET) || (b->family != AF_INET))
137                 return false;
138
139         if ((uint32_t)(x - y) > x)
140         {
141                 fprintf(stderr, "underflow during 'sub'\n");
142                 return false;
143         }
144
145         a->addr.v4.s_addr = htonl(x - y);
146         return true;
147 }
148
149 static bool cidr_network4(struct cidr *a)
150 {
151         a->addr.v4.s_addr &= htonl(~((1 << (32 - a->prefix)) - 1));
152         a->prefix = 32;
153         return true;
154 }
155
156 static bool cidr_broadcast4(struct cidr *a)
157 {
158         a->addr.v4.s_addr |= htonl(((1 << (32 - a->prefix)) - 1));
159         a->prefix = 32;
160         return true;
161 }
162
163 static bool cidr_contains4(struct cidr *a, struct cidr *b)
164 {
165         uint32_t net1 = a->addr.v4.s_addr & htonl(~((1 << (32 - a->prefix)) - 1));
166         uint32_t net2 = b->addr.v4.s_addr & htonl(~((1 << (32 - a->prefix)) - 1));
167
168         printed = true;
169
170         if ((b->prefix >= a->prefix) && (net1 == net2))
171         {
172                 if (!quiet) printf("1\n");
173                 return true;
174         }
175         else
176         {
177                 if (!quiet) printf("0\n");
178                 return false;
179         }
180 }
181
182 static bool cidr_netmask4(struct cidr *a)
183 {
184         struct in_addr mask;
185         char buf[sizeof("255.255.255.255 ")];
186
187         mask.s_addr = htonl(~((1 << (32 - a->prefix)) - 1));
188
189         if (!quiet)
190                 printf("%s\n", inet_ntop(AF_INET, &mask, buf, sizeof(buf)));
191
192         printed = true;
193
194         return true;
195 }
196
197 static bool cidr_private4(struct cidr *a)
198 {
199         uint32_t x = ntohl(a->addr.v4.s_addr);
200
201         printed = true;
202
203         if (((x >= 0x0A000000) && (x <= 0x0AFFFFFF)) ||
204             ((x >= 0xAC100000) && (x <= 0xAC1FFFFF)) ||
205             ((x >= 0xC0A80000) && (x <= 0xC0A8FFFF)))
206         {
207                 if (!quiet) printf("1\n");
208                 return true;
209         }
210         else
211         {
212                 if (!quiet) printf("0\n");
213                 return false;
214         }
215 }
216
217 static bool cidr_linklocal4(struct cidr *a)
218 {
219         uint32_t x = ntohl(a->addr.v4.s_addr);
220
221         printed = true;
222
223         if ((x >= 0xA9FE0000) && (x <= 0xA9FEFFFF))
224         {
225                 if (!quiet) printf("1\n");
226                 return true;
227         }
228         else
229         {
230                 if (!quiet) printf("0\n");
231                 return false;
232         }
233 }
234
235 static bool cidr_print4(struct cidr *a)
236 {
237         char *p;
238
239         if (a->family != AF_INET)
240                 return false;
241
242         if (!(p = (char *)inet_ntop(AF_INET, &a->addr.v4, a->buf.v4, sizeof(a->buf.v4))))
243                 return false;
244
245         if (!quiet)
246                 printf("%s", p);
247
248         if (!quiet && (a->prefix < 32))
249                 printf("/%u", a->prefix);
250
251         if (!quiet)
252                 printf("\n");
253
254         printed = true;
255
256         return true;
257 }
258
259
260 static struct cidr * cidr_parse6(const char *s)
261 {
262         char *p = NULL, *r;
263         struct cidr *addr = malloc(sizeof(struct cidr));
264
265         if (!addr || (strlen(s) >= sizeof(addr->buf.v6)))
266                 goto err;
267
268         snprintf(addr->buf.v6, sizeof(addr->buf.v6), "%s", s);
269
270         addr->family = AF_INET6;
271
272         if ((p = strchr(addr->buf.v6, '/')) != NULL)
273         {
274                 *p++ = 0;
275
276                 addr->prefix = strtoul(p, &r, 10);
277
278                 if ((p == r) || (*r != 0) || (addr->prefix > 128))
279                         goto err;
280         }
281         else
282         {
283                 addr->prefix = 128;
284         }
285
286         if (p == addr->buf.v6+1)
287                 memset(&addr->addr.v6, 0, sizeof(addr->addr.v6));
288         else if (inet_pton(AF_INET6, addr->buf.v6, &addr->addr.v6) != 1)
289                 goto err;
290
291         return addr;
292
293 err:
294         if (addr)
295                 free(addr);
296
297         return NULL;
298 }
299
300 static bool cidr_add6(struct cidr *a, struct cidr *b)
301 {
302         uint8_t idx = 15, carry = 0, overflow = 0;
303
304         struct in6_addr *x = &a->addr.v6;
305         struct in6_addr *y = &b->addr.v6;
306
307         if ((a->family != AF_INET6) || (b->family != AF_INET6))
308                 return false;
309
310         do {
311                 overflow = !!((x->s6_addr[idx] + y->s6_addr[idx] + carry) >= 256);
312                 x->s6_addr[idx] += y->s6_addr[idx] + carry;
313                 carry = overflow;
314         }
315         while (idx-- > 0);
316
317         if (carry)
318         {
319                 fprintf(stderr, "overflow during 'add'\n");
320                 return false;
321         }
322
323         return true;
324 }
325
326 static bool cidr_sub6(struct cidr *a, struct cidr *b)
327 {
328         uint8_t idx = 15, carry = 0, underflow = 0;
329
330         struct in6_addr *x = &a->addr.v6;
331         struct in6_addr *y = &b->addr.v6;
332
333         if ((a->family != AF_INET6) || (b->family != AF_INET6))
334                 return false;
335
336         do {
337                 underflow = !!((x->s6_addr[idx] - y->s6_addr[idx] - carry) < 0);
338                 x->s6_addr[idx] -= y->s6_addr[idx] + carry;
339                 carry = underflow;
340         }
341         while (idx-- > 0);
342
343         if (carry)
344         {
345                 fprintf(stderr, "underflow during 'sub'\n");
346                 return false;
347         }
348
349         return true;
350 }
351
352 static bool cidr_network6(struct cidr *a)
353 {
354         uint8_t i;
355
356         for (i = 0; i < (128 - a->prefix) / 8; i++)
357                 a->addr.v6.s6_addr[15-i] = 0;
358
359         if ((128 - a->prefix) % 8)
360                 a->addr.v6.s6_addr[15-i] &= ~((1 << ((128 - a->prefix) % 8)) - 1);
361
362         return true;
363 }
364
365 static bool cidr_contains6(struct cidr *a, struct cidr *b)
366 {
367         struct in6_addr *x = &a->addr.v6;
368         struct in6_addr *y = &b->addr.v6;
369
370         uint8_t i = (128 - a->prefix) / 8;
371         uint8_t m = ~((1 << ((128 - a->prefix) % 8)) - 1);
372         uint8_t net1 = x->s6_addr[15-i] & m;
373         uint8_t net2 = y->s6_addr[15-i] & m;
374
375         printed = true;
376
377         if ((b->prefix >= a->prefix) && (net1 == net2) &&
378             ((i == 15) || !memcmp(&x->s6_addr, &y->s6_addr, 15-i)))
379         {
380                 if (!quiet) printf("1\n");
381                 return true;
382         }
383         else
384         {
385                 if (!quiet) printf("0\n");
386                 return false;
387         }
388 }
389
390 static bool cidr_linklocal6(struct cidr *a)
391 {
392         printed = true;
393
394         if ((a->addr.v6.s6_addr[0] == 0xFE) &&
395             (a->addr.v6.s6_addr[1] >= 0x80) &&
396             (a->addr.v6.s6_addr[1] <= 0xBF))
397         {
398                 if (!quiet) printf("1\n");
399                 return true;
400         }
401         else
402         {
403                 if (!quiet) printf("0\n");
404                 return false;
405         }
406 }
407
408 static bool cidr_ula6(struct cidr *a)
409 {
410         printed = true;
411
412         if ((a->addr.v6.s6_addr[0] >= 0xFC) &&
413             (a->addr.v6.s6_addr[0] <= 0xFD))
414         {
415                 if (!quiet) printf("1\n");
416                 return true;
417         }
418         else
419         {
420                 if (!quiet) printf("0\n");
421                 return false;
422         }
423 }
424
425 static bool cidr_print6(struct cidr *a)
426 {
427         char *p;
428
429         if (a->family != AF_INET6)
430                 return NULL;
431
432         if (!(p = (char *)inet_ntop(AF_INET6, &a->addr.v6, a->buf.v6, sizeof(a->buf.v6))))
433                 return false;
434
435         if (!quiet)
436                 printf("%s", p);
437
438         if (!quiet && (a->prefix < 128))
439                 printf("/%u", a->prefix);
440
441         if (!quiet)
442                 printf("\n");
443
444         printed = true;
445
446         return true;
447 }
448
449
450 static struct cidr * cidr_parse(const char *op, const char *s, int af_hint)
451 {
452         char *r;
453         struct cidr *a;
454
455         uint8_t i;
456         uint32_t sum = strtoul(s, &r, 0);
457
458         if ((r > s) && (*r == 0))
459         {
460                 a = malloc(sizeof(struct cidr));
461
462                 if (!a)
463                         return NULL;
464
465                 if (af_hint == AF_INET)
466                 {
467                         a->family = AF_INET;
468                         a->prefix = 32;
469                         a->addr.v4.s_addr = htonl(sum);
470                 }
471                 else
472                 {
473                         a->family = AF_INET6;
474                         a->prefix = 128;
475
476                         for (i = 0; i <= 15; i++)
477                         {
478                                 a->addr.v6.s6_addr[15-i] = sum % 256;
479                                 sum >>= 8;
480                         }
481                 }
482
483                 return a;
484         }
485
486         if (strchr(s, ':'))
487                 a = cidr_parse6(s);
488         else
489                 a = cidr_parse4(s);
490
491         if (!a)
492                 return NULL;
493
494         if (a->family != af_hint)
495         {
496                 fprintf(stderr, "attempt to '%s' %s with %s address\n",
497                                 op,
498                                 (af_hint == AF_INET) ? "ipv4" : "ipv6",
499                                 (af_hint != AF_INET) ? "ipv4" : "ipv6");
500                 exit(4);
501         }
502
503         return a;
504 }
505
506 static bool cidr_howmany(struct cidr *a, struct cidr *b)
507 {
508         if (!quiet)
509         {
510                 if (b->prefix < a->prefix)
511                         printf("0\n");
512                 else
513                         printf("%u\n", 1 << (b->prefix - a->prefix));
514         }
515
516         printed = true;
517
518         return true;
519 }
520
521 static bool cidr_prefix(struct cidr *a, struct cidr *b)
522 {
523         a->prefix = b->prefix;
524         return true;
525 }
526
527 static bool cidr_quiet(struct cidr *a)
528 {
529         quiet = true;
530         return true;
531 }
532
533
534 struct op ops[] = {
535         { .name = "add",
536           .desc = "Add argument to base address",
537           .f4.a2 = cidr_add4,
538           .f6.a2 = cidr_add6 },
539
540         { .name = "sub",
541           .desc = "Substract argument from base address",
542           .f4.a2 = cidr_sub4,
543           .f6.a2 = cidr_sub6 },
544
545         { .name = "network",
546           .desc = "Turn base address into network address",
547           .f4.a1 = cidr_network4,
548           .f6.a1 = cidr_network6 },
549
550         { .name = "broadcast",
551           .desc = "Turn base address into broadcast address",
552           .f4.a1 = cidr_broadcast4 },
553
554         { .name = "prefix",
555           .desc = "Set the prefix of base address to argument",
556           .f4.a2 = cidr_prefix,
557           .f6.a2 = cidr_prefix },
558
559         { .name = "netmask",
560           .desc = "Print netmask of base address, does not change base address",
561           .f4.a1 = cidr_netmask4 },
562
563         { .name = "howmany",
564           .desc = "Print amount of righ-hand prefixes that fit into base address, "
565                   "does not change base address",
566           .f4.a2 = cidr_howmany,
567           .f6.a2 = cidr_howmany },
568
569         { .name = "contains",
570           .desc = "Print '1' if argument fits into base address or '0' "
571                   "if not, does not change base address",
572           .f4.a2 = cidr_contains4,
573           .f6.a2 = cidr_contains6 },
574
575         { .name = "private",
576           .desc = "Print '1' if base address is in RFC1918 private space or '0' "
577                   "if not, does not change base address",
578           .f4.a1 = cidr_private4 },
579
580         { .name = "linklocal",
581           .desc = "Print '1' if base address is in 169.254.0.0/16 or FE80::/10 "
582                   "link local space or '0' if not, does not change base address",
583           .f4.a1 = cidr_linklocal4,
584           .f6.a1 = cidr_linklocal6 },
585
586         { .name = "ula",
587           .desc = "Print '1' if base address is in FC00::/7 unique local address "
588                   "(ULA) space or '0' if not, does not change base address",
589           .f6.a1 = cidr_ula6 },
590
591         { .name = "quiet",
592           .desc = "Suppress output, useful for test operation where the result can "
593                   "be inferred from the exit code, does not change base address",
594           .f4.a1 = cidr_quiet,
595           .f6.a1 = cidr_quiet },
596
597         { .name = "print",
598           .desc = "Print intermediate result, invoked implicitely at the end of "
599                   "calculation if no intermediate prints happened",
600           .f4.a1 = cidr_print4,
601           .f6.a1 = cidr_print6 },
602 };
603
604 static void usage(const char *prog)
605 {
606         int i;
607
608         fprintf(stderr,
609                 "\n"
610                 "Usage:\n\n"
611                 "  %s {base address} operation [argument] "
612                 "[operation [argument] ...]\n\n"
613                 "Operations:\n\n",
614                 prog);
615
616         for (i = 0; i < sizeof(ops) / sizeof(ops[0]); i++)
617         {
618                 if (ops[i].f4.a2 || ops[i].f6.a2)
619                 {
620                         fprintf(stderr, "  %s %s\n",
621                                 ops[i].name,
622                                 (ops[i].f4.a2 && ops[i].f6.a2) ? "{ipv4/ipv6/amount}" :
623                                  (ops[i].f6.a2 ? "{ipv6/amount}" : "{ipv4/amount}"));
624                 }
625                 else
626                 {
627                         fprintf(stderr, "  %s\n", ops[i].name);
628                 }
629
630                 fprintf(stderr, "    %s.\n", ops[i].desc);
631
632                 if ((ops[i].f4.a1 && ops[i].f6.a1) || (ops[i].f4.a2 && ops[i].f6.a2))
633                         fprintf(stderr, "    Applicable to ipv4- and ipv6-addresses.\n\n");
634                 else if (ops[i].f6.a2 || ops[i].f6.a1)
635                         fprintf(stderr, "    Only applicable to ipv6-addresses.\n\n");
636                 else
637                         fprintf(stderr, "    Only applicable to ipv4-addresses.\n\n");
638         }
639
640         fprintf(stderr,
641                 "Examples:\n\n"
642                 " Calculate a DHCP range:\n\n"
643                 "  $ %s 192.168.1.1/255.255.255.0 network add 100 print add 150 print\n"
644                         "  192.168.1.100\n"
645                         "  192.168.1.250\n\n"
646                         " Count number of prefixes:\n\n"
647                         "  $ %s 2001:0DB8:FDEF::/48 howmany ::/64\n"
648                         "  65536\n\n",
649                 prog, prog);
650
651         exit(1);
652 }
653
654 static bool runop(struct cidr *a, char ***arg, int *status)
655 {
656         int i;
657         char *arg1 = **arg;
658         char *arg2 = *(*arg+1);
659         struct cidr *b = NULL;
660
661         if (!arg1)
662                 return false;
663
664         for (i = 0; i < sizeof(ops) / sizeof(ops[0]); i++)
665         {
666                 if (!strcmp(ops[i].name, arg1))
667                 {
668                         if (ops[i].f4.a2 || ops[i].f6.a2)
669                         {
670                                 if (!arg2)
671                                 {
672                                         fprintf(stderr, "'%s' requires an argument\n",
673                                                         ops[i].name);
674
675                                         *status = 2;
676                                         return false;
677                                 }
678
679                                 b = cidr_parse(ops[i].name, arg2, a->family);
680
681                                 if (!b)
682                                 {
683                                         fprintf(stderr, "invalid address argument for '%s'\n",
684                                                         ops[i].name);
685
686                                         *status = 3;
687                                         return false;
688                                 }
689
690                                 *arg += 2;
691
692                                 if (((a->family == AF_INET)  && !ops[i].f4.a2) ||
693                                         ((a->family == AF_INET6) && !ops[i].f6.a2))
694                                 {
695                                         fprintf(stderr, "'%s' not supported for %s addresses\n",
696                                                 ops[i].name,
697                                                         (a->family == AF_INET) ? "ipv4" : "ipv6");
698
699                                         *status = 5;
700                                         return false;
701                                 }
702
703                                 *status = !((a->family == AF_INET) ? ops[i].f4.a2(a, b)
704                                                                    : ops[i].f6.a2(a, b));
705
706                                 return true;
707                         }
708                         else
709                         {
710                                 *arg += 1;
711
712                                 if (((a->family == AF_INET)  && !ops[i].f4.a1) ||
713                                         ((a->family == AF_INET6) && !ops[i].f6.a1))
714                                 {
715                                         fprintf(stderr, "'%s' not supported for %s addresses\n",
716                                                 ops[i].name,
717                                                         (a->family == AF_INET) ? "ipv4" : "ipv6");
718
719                                         *status = 5;
720                                         return false;
721                                 }
722
723                                 *status = !((a->family == AF_INET) ? ops[i].f4.a1(a)
724                                                                    : ops[i].f6.a1(a));
725
726                                 return true;
727                         }
728                 }
729         }
730
731         return false;
732 }
733
734 int main(int argc, char **argv)
735 {
736         int status = 0;
737         char **arg = argv+2;
738         struct cidr *a;
739
740         if (argc < 3)
741                 usage(argv[0]);
742
743         a = strchr(argv[1], ':') ? cidr_parse6(argv[1]) : cidr_parse4(argv[1]);
744
745         if (!a)
746                 usage(argv[0]);
747
748         while (runop(a, &arg, &status));
749
750         if (*arg)
751         {
752                 fprintf(stderr, "unknown operation '%s'\n", *arg);
753                 exit(6);
754         }
755
756         if (!printed && (status < 2))
757         {
758                 if (a->family == AF_INET)
759                         cidr_print4(a);
760                 else
761                         cidr_print6(a);
762         }
763
764         exit(status);
765 }