tweaking makefile
[iptables.git] / xtables.c
1 /*
2  * (C) 2000-2006 by the netfilter coreteam <coreteam@netfilter.org>:
3  *
4  *      This program is free software; you can redistribute it and/or modify
5  *      it under the terms of the GNU General Public License as published by
6  *      the Free Software Foundation; either version 2 of the License, or
7  *      (at your option) any later version.
8  *
9  *      This program is distributed in the hope that it will be useful,
10  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *      GNU General Public License for more details.
13  *
14  *      You should have received a copy of the GNU General Public License
15  *      along with this program; if not, write to the Free Software
16  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <netdb.h>
22 #include <stdarg.h>
23 #include <stdbool.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <arpa/inet.h>
33
34 #include <xtables.h>
35
36 #ifndef NO_SHARED_LIBS
37 #include <dlfcn.h>
38 #endif
39
40 #define NPROTO  255
41
42 #ifndef PROC_SYS_MODPROBE
43 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
44 #endif
45
46 char *lib_dir;
47
48 /* the path to command to load kernel module */
49 const char *modprobe_program = NULL;
50
51 /* Keeping track of external matches and targets: linked lists.  */
52 struct xtables_match *xtables_matches;
53 struct xtables_target *xtables_targets;
54
55 void *fw_calloc(size_t count, size_t size)
56 {
57         void *p;
58
59         if ((p = calloc(count, size)) == NULL) {
60                 perror("ip[6]tables: calloc failed");
61                 exit(1);
62         }
63
64         return p;
65 }
66
67 void *fw_malloc(size_t size)
68 {
69         void *p;
70
71         if ((p = malloc(size)) == NULL) {
72                 perror("ip[6]tables: malloc failed");
73                 exit(1);
74         }
75
76         return p;
77 }
78
79 static char *get_modprobe(void)
80 {
81         int procfile;
82         char *ret;
83
84 #define PROCFILE_BUFSIZ 1024
85         procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
86         if (procfile < 0)
87                 return NULL;
88
89         ret = (char *) malloc(PROCFILE_BUFSIZ);
90         if (ret) {
91                 memset(ret, 0, PROCFILE_BUFSIZ);
92                 switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
93                 case -1: goto fail;
94                 case PROCFILE_BUFSIZ: goto fail; /* Partial read.  Wierd */
95                 }
96                 if (ret[strlen(ret)-1]=='\n') 
97                         ret[strlen(ret)-1]=0;
98                 close(procfile);
99                 return ret;
100         }
101  fail:
102         free(ret);
103         close(procfile);
104         return NULL;
105 }
106
107 int xtables_insmod(const char *modname, const char *modprobe, int quiet)
108 {
109         char *buf = NULL;
110         char *argv[4];
111         int status;
112
113         /* If they don't explicitly set it, read out of kernel */
114         if (!modprobe) {
115                 buf = get_modprobe();
116                 if (!buf)
117                         return -1;
118                 modprobe = buf;
119         }
120
121         switch (fork()) {
122         case 0:
123                 argv[0] = (char *)modprobe;
124                 argv[1] = (char *)modname;
125                 if (quiet) {
126                         argv[2] = "-q";
127                         argv[3] = NULL;
128                 } else {
129                         argv[2] = NULL;
130                         argv[3] = NULL;
131                 }
132                 execv(argv[0], argv);
133
134                 /* not usually reached */
135                 exit(1);
136         case -1:
137                 return -1;
138
139         default: /* parent */
140                 wait(&status);
141         }
142
143         free(buf);
144         if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
145                 return 0;
146         return -1;
147 }
148
149 int load_xtables_ko(const char *modprobe, int quiet)
150 {
151         static int loaded = 0;
152         static int ret = -1;
153
154         if (!loaded) {
155                 ret = xtables_insmod(afinfo.kmod, modprobe, quiet);
156                 loaded = (ret == 0);
157         }
158
159         return ret;
160 }
161
162 int string_to_number_ll(const char *s, unsigned long long min,
163                         unsigned long long max, unsigned long long *ret)
164 {
165         unsigned long long number;
166         char *end;
167
168         /* Handle hex, octal, etc. */
169         errno = 0;
170         number = strtoull(s, &end, 0);
171         if (*end == '\0' && end != s) {
172                 /* we parsed a number, let's see if we want this */
173                 if (errno != ERANGE && min <= number && (!max || number <= max)) {
174                         *ret = number;
175                         return 0;
176                 }
177         }
178         return -1;
179 }
180
181 int string_to_number_l(const char *s, unsigned long min, unsigned long max,
182                        unsigned long *ret)
183 {
184         int result;
185         unsigned long long number;
186
187         result = string_to_number_ll(s, min, max, &number);
188         *ret = (unsigned long)number;
189
190         return result;
191 }
192
193 int string_to_number(const char *s, unsigned int min, unsigned int max,
194                 unsigned int *ret)
195 {
196         int result;
197         unsigned long number;
198
199         result = string_to_number_l(s, min, max, &number);
200         *ret = (unsigned int)number;
201
202         return result;
203 }
204
205 /*
206  * strtonum{,l} - string to number conversion
207  *
208  * If @end is NULL, we assume the caller does not want
209  * a case like "15a", so reject it.
210  */
211 bool strtonuml(const char *s, char **end, unsigned long *value,
212                unsigned long min, unsigned long max)
213 {
214         unsigned long v;
215         char *my_end;
216
217         errno = 0;
218         v = strtoul(s, &my_end, 0);
219
220         if (my_end == s)
221                 return false;
222         if (end != NULL)
223                 *end = my_end;
224
225         if (errno != ERANGE && min <= v && (max == 0 || v <= max)) {
226                 if (value != NULL)
227                         *value = v;
228                 if (end == NULL)
229                         return *my_end == '\0';
230                 return true;
231         }
232
233         return false;
234 }
235
236 bool strtonum(const char *s, char **end, unsigned int *value,
237                   unsigned int min, unsigned int max)
238 {
239         unsigned long v;
240         bool ret;
241
242         ret = strtonuml(s, end, &v, min, max);
243         if (value != NULL)
244                 *value = v;
245         return ret;
246 }
247
248 int service_to_port(const char *name, const char *proto)
249 {
250         struct servent *service;
251
252         if ((service = getservbyname(name, proto)) != NULL)
253                 return ntohs((unsigned short) service->s_port);
254
255         return -1;
256 }
257
258 u_int16_t parse_port(const char *port, const char *proto)
259 {
260         unsigned int portnum;
261
262         if ((string_to_number(port, 0, 65535, &portnum)) != -1 ||
263             (portnum = service_to_port(port, proto)) != (unsigned)-1)
264                 return (u_int16_t)portnum;
265
266         exit_error(PARAMETER_PROBLEM,
267                    "invalid port/service `%s' specified", port);
268 }
269
270 void parse_interface(const char *arg, char *vianame, unsigned char *mask)
271 {
272         int vialen = strlen(arg);
273         unsigned int i;
274
275         memset(mask, 0, IFNAMSIZ);
276         memset(vianame, 0, IFNAMSIZ);
277
278         if (vialen + 1 > IFNAMSIZ)
279                 exit_error(PARAMETER_PROBLEM,
280                            "interface name `%s' must be shorter than IFNAMSIZ"
281                            " (%i)", arg, IFNAMSIZ-1);
282
283         strcpy(vianame, arg);
284         if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
285                 memset(mask, 0, IFNAMSIZ);
286         else if (vianame[vialen - 1] == '+') {
287                 memset(mask, 0xFF, vialen - 1);
288                 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
289                 /* Don't remove `+' here! -HW */
290         } else {
291                 /* Include nul-terminator in match */
292                 memset(mask, 0xFF, vialen + 1);
293                 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
294                 for (i = 0; vianame[i]; i++) {
295                         if (vianame[i] == ':' ||
296                             vianame[i] == '!' ||
297                             vianame[i] == '*') {
298                                 fprintf(stderr,
299                                         "Warning: weird character in interface"
300                                         " `%s' (No aliases, :, ! or *).\n",
301                                         vianame);
302                                 break;
303                         }
304                 }
305         }
306 }
307
308 #ifndef NO_SHARED_LIBS
309 static void *load_extension(const char *search_path, const char *prefix,
310     const char *name, bool is_target)
311 {
312         const char *dir = search_path, *next;
313         void *ptr = NULL;
314         struct stat sb;
315         char path[256];
316
317         do {
318                 next = strchr(dir, ':');
319                 if (next == NULL)
320                         next = dir + strlen(dir);
321                 snprintf(path, sizeof(path), "%.*s/libxt_%s.so",
322                          (unsigned int)(next - dir), dir, name);
323
324                 if (dlopen(path, RTLD_NOW) != NULL) {
325                         /* Found library.  If it didn't register itself,
326                            maybe they specified target as match. */
327                         if (is_target)
328                                 ptr = find_target(name, DONT_LOAD);
329                         else
330                                 ptr = find_match(name, DONT_LOAD, NULL);
331                 } else if (stat(path, &sb) == 0) {
332                         fprintf(stderr, "%s: %s\n", path, dlerror());
333                 }
334
335                 if (ptr != NULL)
336                         return ptr;
337
338                 snprintf(path, sizeof(path), "%.*s/%s%s.so",
339                          (unsigned int)(next - dir), dir, prefix, name);
340                 if (dlopen(path, RTLD_NOW) != NULL) {
341                         if (is_target)
342                                 ptr = find_target(name, DONT_LOAD);
343                         else
344                                 ptr = find_match(name, DONT_LOAD, NULL);
345                 } else if (stat(path, &sb) == 0) {
346                         fprintf(stderr, "%s: %s\n", path, dlerror());
347                 }
348
349                 if (ptr != NULL)
350                         return ptr;
351
352                 dir = next + 1;
353         } while (*next != '\0');
354
355         return NULL;
356 }
357 #endif
358
359 struct xtables_match *find_match(const char *name, enum xt_tryload tryload,
360                                  struct xtables_rule_match **matches)
361 {
362         struct xtables_match *ptr;
363         const char *icmp6 = "icmp6";
364
365         /* This is ugly as hell. Nonetheless, there is no way of changing
366          * this without hurting backwards compatibility */
367         if ( (strcmp(name,"icmpv6") == 0) ||
368              (strcmp(name,"ipv6-icmp") == 0) ||
369              (strcmp(name,"icmp6") == 0) )
370                 name = icmp6;
371
372         for (ptr = xtables_matches; ptr; ptr = ptr->next) {
373                 if (strcmp(name, ptr->name) == 0) {
374                         struct xtables_match *clone;
375
376                         /* First match of this type: */
377                         if (ptr->m == NULL)
378                                 break;
379
380                         /* Second and subsequent clones */
381                         clone = fw_malloc(sizeof(struct xtables_match));
382                         memcpy(clone, ptr, sizeof(struct xtables_match));
383                         clone->mflags = 0;
384                         /* This is a clone: */
385                         clone->next = clone;
386
387                         ptr = clone;
388                         break;
389                 }
390         }
391
392 #ifndef NO_SHARED_LIBS
393         if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
394                 ptr = load_extension(lib_dir, afinfo.libprefix, name, false);
395
396                 if (ptr == NULL && tryload == LOAD_MUST_SUCCEED)
397                         exit_error(PARAMETER_PROBLEM,
398                                    "Couldn't load match `%s':%s\n",
399                                    name, dlerror());
400         }
401 #else
402         if (ptr && !ptr->loaded) {
403                 if (tryload != DONT_LOAD)
404                         ptr->loaded = 1;
405                 else
406                         ptr = NULL;
407         }
408         if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
409                 exit_error(PARAMETER_PROBLEM,
410                            "Couldn't find match `%s'\n", name);
411         }
412 #endif
413
414         if (ptr && matches) {
415                 struct xtables_rule_match **i;
416                 struct xtables_rule_match *newentry;
417
418                 newentry = fw_malloc(sizeof(struct xtables_rule_match));
419
420                 for (i = matches; *i; i = &(*i)->next) {
421                         if (strcmp(name, (*i)->match->name) == 0)
422                                 (*i)->completed = 1;
423                 }
424                 newentry->match = ptr;
425                 newentry->completed = 0;
426                 newentry->next = NULL;
427                 *i = newentry;
428         }
429
430         return ptr;
431 }
432
433
434 struct xtables_target *find_target(const char *name, enum xt_tryload tryload)
435 {
436         struct xtables_target *ptr;
437
438         /* Standard target? */
439         if (strcmp(name, "") == 0
440             || strcmp(name, XTC_LABEL_ACCEPT) == 0
441             || strcmp(name, XTC_LABEL_DROP) == 0
442             || strcmp(name, XTC_LABEL_QUEUE) == 0
443             || strcmp(name, XTC_LABEL_RETURN) == 0)
444                 name = "standard";
445
446         for (ptr = xtables_targets; ptr; ptr = ptr->next) {
447                 if (strcmp(name, ptr->name) == 0)
448                         break;
449         }
450
451 #ifndef NO_SHARED_LIBS
452         if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
453                 ptr = load_extension(lib_dir, afinfo.libprefix, name, true);
454
455                 if (ptr == NULL && tryload == LOAD_MUST_SUCCEED)
456                         exit_error(PARAMETER_PROBLEM,
457                                    "Couldn't load target `%s':%s\n",
458                                    name, dlerror());
459         }
460 #else
461         if (ptr && !ptr->loaded) {
462                 if (tryload != DONT_LOAD)
463                         ptr->loaded = 1;
464                 else
465                         ptr = NULL;
466         }
467         if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
468                 exit_error(PARAMETER_PROBLEM,
469                            "Couldn't find target `%s'\n", name);
470         }
471 #endif
472
473         if (ptr)
474                 ptr->used = 1;
475
476         return ptr;
477 }
478
479 static int compatible_revision(const char *name, u_int8_t revision, int opt)
480 {
481         struct xt_get_revision rev;
482         socklen_t s = sizeof(rev);
483         int max_rev, sockfd;
484
485         sockfd = socket(afinfo.family, SOCK_RAW, IPPROTO_RAW);
486         if (sockfd < 0) {
487                 if (errno == EPERM) {
488                         /* revision 0 is always supported. */
489                         if (revision != 0)
490                                 fprintf(stderr, "Could not determine whether "
491                                                 "revision %u is supported, "
492                                                 "assuming it is.\n",
493                                         revision);
494                         return 1;
495                 }
496                 fprintf(stderr, "Could not open socket to kernel: %s\n",
497                         strerror(errno));
498                 exit(1);
499         }
500
501         load_xtables_ko(modprobe_program, 1);
502
503         strcpy(rev.name, name);
504         rev.revision = revision;
505
506         max_rev = getsockopt(sockfd, afinfo.ipproto, opt, &rev, &s);
507         if (max_rev < 0) {
508                 /* Definitely don't support this? */
509                 if (errno == ENOENT || errno == EPROTONOSUPPORT) {
510                         close(sockfd);
511                         return 0;
512                 } else if (errno == ENOPROTOOPT) {
513                         close(sockfd);
514                         /* Assume only revision 0 support (old kernel) */
515                         return (revision == 0);
516                 } else {
517                         fprintf(stderr, "getsockopt failed strangely: %s\n",
518                                 strerror(errno));
519                         exit(1);
520                 }
521         }
522         close(sockfd);
523         return 1;
524 }
525
526
527 static int compatible_match_revision(const char *name, u_int8_t revision)
528 {
529         return compatible_revision(name, revision, afinfo.so_rev_match);
530 }
531
532 static int compatible_target_revision(const char *name, u_int8_t revision)
533 {
534         return compatible_revision(name, revision, afinfo.so_rev_target);
535 }
536
537 void xtables_register_match(struct xtables_match *me)
538 {
539         struct xtables_match **i, *old;
540
541         if (strcmp(me->version, program_version) != 0) {
542                 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
543                         program_name, me->name, me->version, program_version);
544                 exit(1);
545         }
546
547         /* Revision field stole a char from name. */
548         if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
549                 fprintf(stderr, "%s: target `%s' has invalid name\n",
550                         program_name, me->name);
551                 exit(1);
552         }
553
554         if (me->family >= NPROTO) {
555                 fprintf(stderr,
556                         "%s: BUG: match %s has invalid protocol family\n",
557                         program_name, me->name);
558                 exit(1);
559         }
560
561         /* ignore not interested match */
562         if (me->family != afinfo.family && me->family != AF_UNSPEC)
563                 return;
564
565         old = find_match(me->name, DURING_LOAD, NULL);
566         if (old) {
567                 if (old->revision == me->revision &&
568                     old->family == me->family) {
569                         fprintf(stderr,
570                                 "%s: match `%s' already registered.\n",
571                                 program_name, me->name);
572                         exit(1);
573                 }
574
575                 /* Now we have two (or more) options, check compatibility. */
576                 if (compatible_match_revision(old->name, old->revision)
577                     && old->revision > me->revision)
578                         return;
579
580                 /* See if new match can be used. */
581                 if (!compatible_match_revision(me->name, me->revision))
582                         return;
583
584                 /* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
585                 if (old->revision == me->revision && me->family == AF_UNSPEC)
586                         return;
587
588                 /* Delete old one. */
589                 for (i = &xtables_matches; *i!=old; i = &(*i)->next);
590                 *i = old->next;
591         }
592
593         if (me->size != XT_ALIGN(me->size)) {
594                 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
595                         program_name, me->name, (unsigned int)me->size);
596                 exit(1);
597         }
598
599         /* Append to list. */
600         for (i = &xtables_matches; *i; i = &(*i)->next);
601         me->next = NULL;
602         *i = me;
603
604         me->m = NULL;
605         me->mflags = 0;
606 }
607
608 void xtables_register_target(struct xtables_target *me)
609 {
610         struct xtables_target *old;
611
612         if (strcmp(me->version, program_version) != 0) {
613                 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
614                         program_name, me->name, me->version, program_version);
615                 exit(1);
616         }
617
618         /* Revision field stole a char from name. */
619         if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
620                 fprintf(stderr, "%s: target `%s' has invalid name\n",
621                         program_name, me->name);
622                 exit(1);
623         }
624
625         if (me->family >= NPROTO) {
626                 fprintf(stderr,
627                         "%s: BUG: target %s has invalid protocol family\n",
628                         program_name, me->name);
629                 exit(1);
630         }
631
632         /* ignore not interested target */
633         if (me->family != afinfo.family && me->family != AF_UNSPEC)
634                 return;
635
636         old = find_target(me->name, DURING_LOAD);
637         if (old) {
638                 struct xtables_target **i;
639
640                 if (old->revision == me->revision &&
641                     old->family == me->family) {
642                         fprintf(stderr,
643                                 "%s: target `%s' already registered.\n",
644                                 program_name, me->name);
645                         exit(1);
646                 }
647
648                 /* Now we have two (or more) options, check compatibility. */
649                 if (compatible_target_revision(old->name, old->revision)
650                     && old->revision > me->revision)
651                         return;
652
653                 /* See if new target can be used. */
654                 if (!compatible_target_revision(me->name, me->revision))
655                         return;
656
657                 /* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
658                 if (old->revision == me->revision && me->family == AF_UNSPEC)
659                         return;
660
661                 /* Delete old one. */
662                 for (i = &xtables_targets; *i!=old; i = &(*i)->next);
663                 *i = old->next;
664         }
665
666         if (me->size != XT_ALIGN(me->size)) {
667                 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
668                         program_name, me->name, (unsigned int)me->size);
669                 exit(1);
670         }
671
672         /* Prepend to list. */
673         me->next = xtables_targets;
674         xtables_targets = me;
675         me->t = NULL;
676         me->tflags = 0;
677 }
678
679 void param_act(unsigned int status, const char *p1, ...)
680 {
681         const char *p2, *p3;
682         va_list args;
683         bool b;
684
685         va_start(args, p1);
686
687         switch (status) {
688         case P_ONLY_ONCE:
689                 p2 = va_arg(args, const char *);
690                 b  = va_arg(args, unsigned int);
691                 if (!b)
692                         return;
693                 exit_error(PARAMETER_PROBLEM,
694                            "%s: \"%s\" option may only be specified once",
695                            p1, p2);
696                 break;
697         case P_NO_INVERT:
698                 p2 = va_arg(args, const char *);
699                 b  = va_arg(args, unsigned int);
700                 if (!b)
701                         return;
702                 exit_error(PARAMETER_PROBLEM,
703                            "%s: \"%s\" option cannot be inverted", p1, p2);
704                 break;
705         case P_BAD_VALUE:
706                 p2 = va_arg(args, const char *);
707                 p3 = va_arg(args, const char *);
708                 exit_error(PARAMETER_PROBLEM,
709                            "%s: Bad value for \"%s\" option: \"%s\"",
710                            p1, p2, p3);
711                 break;
712         case P_ONE_ACTION:
713                 b = va_arg(args, unsigned int);
714                 if (!b)
715                         return;
716                 exit_error(PARAMETER_PROBLEM,
717                            "%s: At most one action is possible", p1);
718                 break;
719         default:
720                 exit_error(status, p1, args);
721                 break;
722         }
723
724         va_end(args);
725 }
726
727 const char *ipaddr_to_numeric(const struct in_addr *addrp)
728 {
729         static char buf[20];
730         const unsigned char *bytep = (const void *)&addrp->s_addr;
731
732         sprintf(buf, "%u.%u.%u.%u", bytep[0], bytep[1], bytep[2], bytep[3]);
733         return buf;
734 }
735
736 static const char *ipaddr_to_host(const struct in_addr *addr)
737 {
738         struct hostent *host;
739
740         host = gethostbyaddr(addr, sizeof(struct in_addr), AF_INET);
741         if (host == NULL)
742                 return NULL;
743
744         return host->h_name;
745 }
746
747 static const char *ipaddr_to_network(const struct in_addr *addr)
748 {
749         struct netent *net;
750
751         if ((net = getnetbyaddr(ntohl(addr->s_addr), AF_INET)) != NULL)
752                 return net->n_name;
753
754         return NULL;
755 }
756
757 const char *ipaddr_to_anyname(const struct in_addr *addr)
758 {
759         const char *name;
760
761         if ((name = ipaddr_to_host(addr)) != NULL ||
762             (name = ipaddr_to_network(addr)) != NULL)
763                 return name;
764
765         return ipaddr_to_numeric(addr);
766 }
767
768 const char *ipmask_to_numeric(const struct in_addr *mask)
769 {
770         static char buf[20];
771         uint32_t maskaddr, bits;
772         int i;
773
774         maskaddr = ntohl(mask->s_addr);
775
776         if (maskaddr == 0xFFFFFFFFL)
777                 /* we don't want to see "/32" */
778                 return "";
779
780         i = 32;
781         bits = 0xFFFFFFFEL;
782         while (--i >= 0 && maskaddr != bits)
783                 bits <<= 1;
784         if (i >= 0)
785                 sprintf(buf, "/%d", i);
786         else
787                 /* mask was not a decent combination of 1's and 0's */
788                 sprintf(buf, "/%s", ipaddr_to_numeric(mask));
789
790         return buf;
791 }
792
793 static struct in_addr *__numeric_to_ipaddr(const char *dotted, bool is_mask)
794 {
795         static struct in_addr addr;
796         unsigned char *addrp;
797         unsigned int onebyte;
798         char buf[20], *p, *q;
799         int i;
800
801         /* copy dotted string, because we need to modify it */
802         strncpy(buf, dotted, sizeof(buf) - 1);
803         buf[sizeof(buf) - 1] = '\0';
804         addrp = (void *)&addr.s_addr;
805
806         p = buf;
807         for (i = 0; i < 3; ++i) {
808                 if ((q = strchr(p, '.')) == NULL) {
809                         if (is_mask)
810                                 return NULL;
811
812                         /* autocomplete, this is a network address */
813                         if (!strtonum(p, NULL, &onebyte, 0, 255))
814                                 return NULL;
815
816                         addrp[i] = onebyte;
817                         while (i < 3)
818                                 addrp[++i] = 0;
819
820                         return &addr;
821                 }
822
823                 *q = '\0';
824                 if (!strtonum(p, NULL, &onebyte, 0, 255))
825                         return NULL;
826
827                 addrp[i] = onebyte;
828                 p = q + 1;
829         }
830
831         /* we have checked 3 bytes, now we check the last one */
832         if (!strtonum(p, NULL, &onebyte, 0, 255))
833                 return NULL;
834
835         addrp[3] = onebyte;
836         return &addr;
837 }
838
839 struct in_addr *numeric_to_ipaddr(const char *dotted)
840 {
841         return __numeric_to_ipaddr(dotted, false);
842 }
843
844 struct in_addr *numeric_to_ipmask(const char *dotted)
845 {
846         return __numeric_to_ipaddr(dotted, true);
847 }
848
849 static struct in_addr *network_to_ipaddr(const char *name)
850 {
851         static struct in_addr addr;
852         struct netent *net;
853
854         if ((net = getnetbyname(name)) != NULL) {
855                 if (net->n_addrtype != AF_INET)
856                         return NULL;
857                 addr.s_addr = htonl(net->n_net);
858                 return &addr;
859         }
860
861         return NULL;
862 }
863
864 static struct in_addr *host_to_ipaddr(const char *name, unsigned int *naddr)
865 {
866         struct hostent *host;
867         struct in_addr *addr;
868         unsigned int i;
869
870         *naddr = 0;
871         if ((host = gethostbyname(name)) != NULL) {
872                 if (host->h_addrtype != AF_INET ||
873                     host->h_length != sizeof(struct in_addr))
874                         return NULL;
875
876                 while (host->h_addr_list[*naddr] != NULL)
877                         ++*naddr;
878                 addr = fw_calloc(*naddr, sizeof(struct in_addr) * *naddr);
879                 for (i = 0; i < *naddr; i++)
880                         memcpy(&addr[i], host->h_addr_list[i],
881                                sizeof(struct in_addr));
882                 return addr;
883         }
884
885         return NULL;
886 }
887
888 static struct in_addr *
889 ipparse_hostnetwork(const char *name, unsigned int *naddrs)
890 {
891         struct in_addr *addrptmp, *addrp;
892
893         if ((addrptmp = numeric_to_ipaddr(name)) != NULL ||
894             (addrptmp = network_to_ipaddr(name)) != NULL) {
895                 addrp = fw_malloc(sizeof(struct in_addr));
896                 memcpy(addrp, addrptmp, sizeof(*addrp));
897                 *naddrs = 1;
898                 return addrp;
899         }
900         if ((addrptmp = host_to_ipaddr(name, naddrs)) != NULL)
901                 return addrptmp;
902
903         exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
904 }
905
906 static struct in_addr *parse_ipmask(const char *mask)
907 {
908         static struct in_addr maskaddr;
909         struct in_addr *addrp;
910         unsigned int bits;
911
912         if (mask == NULL) {
913                 /* no mask at all defaults to 32 bits */
914                 maskaddr.s_addr = 0xFFFFFFFF;
915                 return &maskaddr;
916         }
917         if ((addrp = numeric_to_ipmask(mask)) != NULL)
918                 /* dotted_to_addr already returns a network byte order addr */
919                 return addrp;
920         if (string_to_number(mask, 0, 32, &bits) == -1)
921                 exit_error(PARAMETER_PROBLEM,
922                            "invalid mask `%s' specified", mask);
923         if (bits != 0) {
924                 maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
925                 return &maskaddr;
926         }
927
928         maskaddr.s_addr = 0U;
929         return &maskaddr;
930 }
931
932 void ipparse_hostnetworkmask(const char *name, struct in_addr **addrpp,
933                              struct in_addr *maskp, unsigned int *naddrs)
934 {
935         unsigned int i, j, k, n;
936         struct in_addr *addrp;
937         char buf[256], *p;
938
939         strncpy(buf, name, sizeof(buf) - 1);
940         buf[sizeof(buf) - 1] = '\0';
941         if ((p = strrchr(buf, '/')) != NULL) {
942                 *p = '\0';
943                 addrp = parse_ipmask(p + 1);
944         } else {
945                 addrp = parse_ipmask(NULL);
946         }
947         memcpy(maskp, addrp, sizeof(*maskp));
948
949         /* if a null mask is given, the name is ignored, like in "any/0" */
950         if (maskp->s_addr == 0U)
951                 strcpy(buf, "0.0.0.0");
952
953         addrp = *addrpp = ipparse_hostnetwork(buf, naddrs);
954         n = *naddrs;
955         for (i = 0, j = 0; i < n; ++i) {
956                 addrp[j++].s_addr &= maskp->s_addr;
957                 for (k = 0; k < j - 1; ++k)
958                         if (addrp[k].s_addr == addrp[j-1].s_addr) {
959                                 --*naddrs;
960                                 --j;
961                                 break;
962                         }
963         }
964 }
965
966 const char *ip6addr_to_numeric(const struct in6_addr *addrp)
967 {
968         /* 0000:0000:0000:0000:0000:000.000.000.000
969          * 0000:0000:0000:0000:0000:0000:0000:0000 */
970         static char buf[50+1];
971         return inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
972 }
973
974 static const char *ip6addr_to_host(const struct in6_addr *addr)
975 {
976         static char hostname[NI_MAXHOST];
977         struct sockaddr_in6 saddr;
978         int err;
979
980         memset(&saddr, 0, sizeof(struct sockaddr_in6));
981         memcpy(&saddr.sin6_addr, addr, sizeof(*addr));
982         saddr.sin6_family = AF_INET6;
983
984         err = getnameinfo((const void *)&saddr, sizeof(struct sockaddr_in6),
985               hostname, sizeof(hostname) - 1, NULL, 0, 0);
986         if (err != 0) {
987 #ifdef DEBUG
988                 fprintf(stderr,"IP2Name: %s\n",gai_strerror(err));
989 #endif
990                 return NULL;
991         }
992
993 #ifdef DEBUG
994         fprintf (stderr, "\naddr2host: %s\n", hostname);
995 #endif
996         return hostname;
997 }
998
999 const char *ip6addr_to_anyname(const struct in6_addr *addr)
1000 {
1001         const char *name;
1002
1003         if ((name = ip6addr_to_host(addr)) != NULL)
1004                 return name;
1005
1006         return ip6addr_to_numeric(addr);
1007 }
1008
1009 static int ip6addr_prefix_length(const struct in6_addr *k)
1010 {
1011         unsigned int bits = 0;
1012         uint32_t a, b, c, d;
1013
1014         a = ntohl(k->s6_addr32[0]);
1015         b = ntohl(k->s6_addr32[1]);
1016         c = ntohl(k->s6_addr32[2]);
1017         d = ntohl(k->s6_addr32[3]);
1018         while (a & 0x80000000U) {
1019                 ++bits;
1020                 a <<= 1;
1021                 a  |= (b >> 31) & 1;
1022                 b <<= 1;
1023                 b  |= (c >> 31) & 1;
1024                 c <<= 1;
1025                 c  |= (d >> 31) & 1;
1026                 d <<= 1;
1027         }
1028         if (a != 0 || b != 0 || c != 0 || d != 0)
1029                 return -1;
1030         return bits;
1031 }
1032
1033 const char *ip6mask_to_numeric(const struct in6_addr *addrp)
1034 {
1035         static char buf[50+2];
1036         int l = ip6addr_prefix_length(addrp);
1037
1038         if (l == -1) {
1039                 strcpy(buf, "/");
1040                 strcat(buf, ip6addr_to_numeric(addrp));
1041                 return buf;
1042         }
1043         sprintf(buf, "/%d", l);
1044         return buf;
1045 }
1046
1047 struct in6_addr *numeric_to_ip6addr(const char *num)
1048 {
1049         static struct in6_addr ap;
1050         int err;
1051
1052         if ((err = inet_pton(AF_INET6, num, &ap)) == 1)
1053                 return &ap;
1054 #ifdef DEBUG
1055         fprintf(stderr, "\nnumeric2addr: %d\n", err);
1056 #endif
1057         return NULL;
1058 }
1059
1060 static struct in6_addr *
1061 host_to_ip6addr(const char *name, unsigned int *naddr)
1062 {
1063         static struct in6_addr *addr;
1064         struct addrinfo hints;
1065         struct addrinfo *res;
1066         int err;
1067
1068         memset(&hints, 0, sizeof(hints));
1069         hints.ai_flags    = AI_CANONNAME;
1070         hints.ai_family   = AF_INET6;
1071         hints.ai_socktype = SOCK_RAW;
1072         hints.ai_protocol = IPPROTO_IPV6;
1073         hints.ai_next     = NULL;
1074
1075         *naddr = 0;
1076         if ((err = getaddrinfo(name, NULL, &hints, &res)) != 0) {
1077 #ifdef DEBUG
1078                 fprintf(stderr,"Name2IP: %s\n",gai_strerror(err));
1079 #endif
1080                 return NULL;
1081         } else {
1082                 if (res->ai_family != AF_INET6 ||
1083                     res->ai_addrlen != sizeof(struct sockaddr_in6))
1084                         return NULL;
1085
1086 #ifdef DEBUG
1087                 fprintf(stderr, "resolved: len=%d  %s ", res->ai_addrlen,
1088                         ip6addr_to_numeric(&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr));
1089 #endif
1090                 /* Get the first element of the address-chain */
1091                 addr = fw_malloc(sizeof(struct in6_addr));
1092                 memcpy(addr, &((const struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1093                        sizeof(struct in6_addr));
1094                 freeaddrinfo(res);
1095                 *naddr = 1;
1096                 return addr;
1097         }
1098
1099         return NULL;
1100 }
1101
1102 static struct in6_addr *network_to_ip6addr(const char *name)
1103 {
1104         /*      abort();*/
1105         /* TODO: not implemented yet, but the exception breaks the
1106          *       name resolvation */
1107         return NULL;
1108 }
1109
1110 static struct in6_addr *
1111 ip6parse_hostnetwork(const char *name, unsigned int *naddrs)
1112 {
1113         struct in6_addr *addrp, *addrptmp;
1114
1115         if ((addrptmp = numeric_to_ip6addr(name)) != NULL ||
1116             (addrptmp = network_to_ip6addr(name)) != NULL) {
1117                 addrp = fw_malloc(sizeof(struct in6_addr));
1118                 memcpy(addrp, addrptmp, sizeof(*addrp));
1119                 *naddrs = 1;
1120                 return addrp;
1121         }
1122         if ((addrp = host_to_ip6addr(name, naddrs)) != NULL)
1123                 return addrp;
1124
1125         exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1126 }
1127
1128 static struct in6_addr *parse_ip6mask(char *mask)
1129 {
1130         static struct in6_addr maskaddr;
1131         struct in6_addr *addrp;
1132         unsigned int bits;
1133
1134         if (mask == NULL) {
1135                 /* no mask at all defaults to 128 bits */
1136                 memset(&maskaddr, 0xff, sizeof maskaddr);
1137                 return &maskaddr;
1138         }
1139         if ((addrp = numeric_to_ip6addr(mask)) != NULL)
1140                 return addrp;
1141         if (string_to_number(mask, 0, 128, &bits) == -1)
1142                 exit_error(PARAMETER_PROBLEM,
1143                            "invalid mask `%s' specified", mask);
1144         if (bits != 0) {
1145                 char *p = (void *)&maskaddr;
1146                 memset(p, 0xff, bits / 8);
1147                 memset(p + (bits / 8) + 1, 0, (128 - bits) / 8);
1148                 p[bits/8] = 0xff << (8 - (bits & 7));
1149                 return &maskaddr;
1150         }
1151
1152         memset(&maskaddr, 0, sizeof(maskaddr));
1153         return &maskaddr;
1154 }
1155
1156 void ip6parse_hostnetworkmask(const char *name, struct in6_addr **addrpp,
1157                               struct in6_addr *maskp, unsigned int *naddrs)
1158 {
1159         struct in6_addr *addrp;
1160         unsigned int i, j, k, n;
1161         char buf[256], *p;
1162
1163         strncpy(buf, name, sizeof(buf) - 1);
1164         buf[sizeof(buf)-1] = '\0';
1165         if ((p = strrchr(buf, '/')) != NULL) {
1166                 *p = '\0';
1167                 addrp = parse_ip6mask(p + 1);
1168         } else {
1169                 addrp = parse_ip6mask(NULL);
1170         }
1171         memcpy(maskp, addrp, sizeof(*maskp));
1172
1173         /* if a null mask is given, the name is ignored, like in "any/0" */
1174         if (memcmp(maskp, &in6addr_any, sizeof(in6addr_any)) == 0)
1175                 strcpy(buf, "::");
1176
1177         addrp = *addrpp = ip6parse_hostnetwork(buf, naddrs);
1178         n = *naddrs;
1179         for (i = 0, j = 0; i < n; ++i) {
1180                 for (k = 0; k < 4; ++k)
1181                         addrp[j].s6_addr32[k] &= maskp->s6_addr32[k];
1182                 ++j;
1183                 for (k = 0; k < j - 1; ++k)
1184                         if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
1185                                 --*naddrs;
1186                                 --j;
1187                                 break;
1188                         }
1189         }
1190 }
1191
1192 void save_string(const char *value)
1193 {
1194         static const char no_quote_chars[] = "_-0123456789"
1195                 "abcdefghijklmnopqrstuvwxyz"
1196                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1197         static const char escape_chars[] = "\"\\'";
1198         size_t length;
1199         const char *p;
1200
1201         length = strcspn(value, no_quote_chars);
1202         if (length > 0 && value[length] == 0) {
1203                 /* no quoting required */
1204                 fputs(value, stdout);
1205                 putchar(' ');
1206         } else {
1207                 /* there is at least one dangerous character in the
1208                    value, which we have to quote.  Write double quotes
1209                    around the value and escape special characters with
1210                    a backslash */
1211                 putchar('"');
1212
1213                 for (p = strpbrk(value, escape_chars); p != NULL;
1214                      p = strpbrk(value, escape_chars)) {
1215                         if (p > value)
1216                                 fwrite(value, 1, p - value, stdout);
1217                         putchar('\\');
1218                         putchar(*p);
1219                         value = p + 1;
1220                 }
1221
1222                 /* print the rest and finish the double quoted
1223                    string */
1224                 fputs(value, stdout);
1225                 printf("\" ");
1226         }
1227 }