Checkign in new iproute2
[iproute2.git] / lib / utils.c
1 /*
2  * utils.c
3  *
4  *              This program is free software; you can redistribute it and/or
5  *              modify it under the terms of the GNU General Public License
6  *              as published by the Free Software Foundation; either version
7  *              2 of the License, or (at your option) any later version.
8  *
9  * Authors:     Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10  *
11  *
12  * Changes:
13  *
14  * Rani Assaf <rani@magic.metawire.com> 980929: resolve addresses
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <syslog.h>
21 #include <fcntl.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <string.h>
25 #include <netdb.h>
26 #include <arpa/inet.h>
27 #include <resolv.h>
28 #include <asm/types.h>
29 #include <linux/pkt_sched.h>
30 #include <time.h>
31 #include <sys/time.h>
32
33
34 #include "utils.h"
35
36 int get_integer(int *val, const char *arg, int base)
37 {
38         long res;
39         char *ptr;
40
41         if (!arg || !*arg)
42                 return -1;
43         res = strtol(arg, &ptr, base);
44         if (!ptr || ptr == arg || *ptr || res > INT_MAX || res < INT_MIN)
45                 return -1;
46         *val = res;
47         return 0;
48 }
49
50 int mask2bits(__u32 netmask)
51 {
52         unsigned bits = 0;
53         __u32 mask = ntohl(netmask);
54         __u32 host = ~mask;
55
56         /* a valid netmask must be 2^n - 1 */
57         if ((host & (host + 1)) != 0)
58                 return -1;
59
60         for (; mask; mask <<= 1)
61                 ++bits;
62         return bits;
63 }
64
65 static int get_netmask(unsigned *val, const char *arg, int base)
66 {
67         inet_prefix addr;
68
69         if (!get_unsigned(val, arg, base))
70                 return 0;
71
72         /* try coverting dotted quad to CIDR */
73         if (!get_addr_1(&addr, arg, AF_INET) && addr.family == AF_INET) {
74                 int b = mask2bits(addr.data[0]);
75                 
76                 if (b >= 0) {
77                         *val = b;
78                         return 0;
79                 }
80         }
81
82         return -1;
83 }
84
85 int get_unsigned(unsigned *val, const char *arg, int base)
86 {
87         unsigned long res;
88         char *ptr;
89
90         if (!arg || !*arg)
91                 return -1;
92         res = strtoul(arg, &ptr, base);
93         if (!ptr || ptr == arg || *ptr || res > UINT_MAX)
94                 return -1;
95         *val = res;
96         return 0;
97 }
98
99 /*
100  * get_jiffies is "translated" from a similar routine "get_time" in
101  * tc_util.c.  we don't use the exact same routine because tc passes
102  * microseconds to the kernel and the callers of get_jiffies want 
103  * to pass jiffies, and have a different assumption for the units of
104  * a "raw" number.
105  */
106
107 int get_jiffies(unsigned *jiffies, const char *arg, int base, int *raw)
108 {
109         double t;
110         unsigned long res;
111         char *p;
112
113         if (strchr(arg,'.') != NULL) {
114                 t = strtod(arg,&p);
115                 if (t < 0.0)
116                         return -1;
117         }
118         else {
119                 res = strtoul(arg,&p,base);
120                 if (res > UINT_MAX)
121                         return -1;
122                 t = (double)res;
123         }
124         if (p == arg)
125                 return -1;
126
127         if (__iproute2_hz_internal == 0)
128                 __iproute2_hz_internal = __get_hz();
129         
130         *raw = 1;
131
132         if (*p) {
133                 *raw = 0;
134                 if (strcasecmp(p, "s") == 0 || strcasecmp(p, "sec")==0 ||
135                     strcasecmp(p, "secs")==0)
136                         t *= __iproute2_hz_internal;
137                 else if (strcasecmp(p, "ms") == 0 || strcasecmp(p, "msec")==0 ||
138                          strcasecmp(p, "msecs") == 0)
139                         t *= __iproute2_hz_internal/1000.0;
140                 else if (strcasecmp(p, "us") == 0 || strcasecmp(p, "usec")==0 ||
141                          strcasecmp(p, "usecs") == 0)
142                         t *= __iproute2_hz_internal/1000000.0;
143                 else if (strcasecmp(p, "ns") == 0 || strcasecmp(p, "nsec")==0 ||
144                          strcasecmp(p, "nsecs") == 0)
145                         t *= __iproute2_hz_internal/1000000000.0;
146                 else if (strcasecmp(p, "j") == 0 || strcasecmp(p, "hz") == 0 ||
147                          strcasecmp(p,"jiffies") == 0)
148                         t *= 1.0; /* allow suffix, do nothing */
149                 else
150                         return -1;
151         }
152
153         /* emulate ceil() without having to bring-in -lm and always be >= 1 */
154
155         *jiffies = t;
156         if (*jiffies < t)
157                 *jiffies += 1;
158         
159         return 0;
160
161 }
162
163 int get_u64(__u64 *val, const char *arg, int base)
164 {
165         unsigned long long res;
166         char *ptr;
167
168         if (!arg || !*arg)
169                 return -1;
170         res = strtoull(arg, &ptr, base);
171         if (!ptr || ptr == arg || *ptr || res == 0xFFFFFFFFULL)
172                 return -1;
173         *val = res;
174         return 0;
175 }
176
177 int get_u32(__u32 *val, const char *arg, int base)
178 {
179         unsigned long res;
180         char *ptr;
181
182         if (!arg || !*arg)
183                 return -1;
184         res = strtoul(arg, &ptr, base);
185         if (!ptr || ptr == arg || *ptr || res > 0xFFFFFFFFUL)
186                 return -1;
187         *val = res;
188         return 0;
189 }
190
191 int get_u16(__u16 *val, const char *arg, int base)
192 {
193         unsigned long res;
194         char *ptr;
195
196         if (!arg || !*arg)
197                 return -1;
198         res = strtoul(arg, &ptr, base);
199         if (!ptr || ptr == arg || *ptr || res > 0xFFFF)
200                 return -1;
201         *val = res;
202         return 0;
203 }
204
205 int get_u8(__u8 *val, const char *arg, int base)
206 {
207         unsigned long res;
208         char *ptr;
209
210         if (!arg || !*arg)
211                 return -1;
212         res = strtoul(arg, &ptr, base);
213         if (!ptr || ptr == arg || *ptr || res > 0xFF)
214                 return -1;
215         *val = res;
216         return 0;
217 }
218
219 int get_s16(__s16 *val, const char *arg, int base)
220 {
221         long res;
222         char *ptr;
223
224         if (!arg || !*arg)
225                 return -1;
226         res = strtol(arg, &ptr, base);
227         if (!ptr || ptr == arg || *ptr || res > 0x7FFF || res < -0x8000)
228                 return -1;
229         *val = res;
230         return 0;
231 }
232
233 int get_s8(__s8 *val, const char *arg, int base)
234 {
235         long res;
236         char *ptr;
237
238         if (!arg || !*arg)
239                 return -1;
240         res = strtol(arg, &ptr, base);
241         if (!ptr || ptr == arg || *ptr || res > 0x7F || res < -0x80)
242                 return -1;
243         *val = res;
244         return 0;
245 }
246
247 /* This uses a non-standard parsing (ie not inet_aton, or inet_pton)
248  * because of legacy choice to parse 10.8 as 10.8.0.0 not 10.0.0.8
249  */
250 static int get_addr_ipv4(__u8 *ap, const char *cp)
251 {
252         int i;
253
254         for (i = 0; i < 4; i++) {
255                 unsigned long n;
256                 char *endp;
257                 
258                 n = strtoul(cp, &endp, 0);
259                 if (n > 255)
260                         return -1;      /* bogus network value */
261
262                 if (endp == cp) /* no digits */
263                         return -1;
264
265                 ap[i] = n;
266
267                 if (*endp == '\0')
268                         break;
269
270                 if (i == 3 || *endp != '.')
271                         return -1;      /* extra characters */
272                 cp = endp + 1;
273         }
274
275         return 1;
276 }
277
278 int get_addr_1(inet_prefix *addr, const char *name, int family)
279 {
280         memset(addr, 0, sizeof(*addr));
281
282         if (strcmp(name, "default") == 0 ||
283             strcmp(name, "all") == 0 ||
284             strcmp(name, "any") == 0) {
285                 if (family == AF_DECnet)
286                         return -1;
287                 addr->family = family;
288                 addr->bytelen = (family == AF_INET6 ? 16 : 4);
289                 addr->bitlen = -1;
290                 return 0;
291         }
292
293         if (strchr(name, ':')) {
294                 addr->family = AF_INET6;
295                 if (family != AF_UNSPEC && family != AF_INET6)
296                         return -1;
297                 if (inet_pton(AF_INET6, name, addr->data) <= 0)
298                         return -1;
299                 addr->bytelen = 16;
300                 addr->bitlen = -1;
301                 return 0;
302         }
303
304         if (family == AF_DECnet) {
305                 struct dn_naddr dna;
306                 addr->family = AF_DECnet;
307                 if (dnet_pton(AF_DECnet, name, &dna) <= 0)
308                         return -1;
309                 memcpy(addr->data, dna.a_addr, 2);
310                 addr->bytelen = 2;
311                 addr->bitlen = -1;
312                 return 0;
313         }
314
315         addr->family = AF_INET;
316         if (family != AF_UNSPEC && family != AF_INET)
317                 return -1;
318
319         if (get_addr_ipv4((__u8 *)addr->data, name) <= 0)
320                 return -1;
321
322         addr->bytelen = 4;
323         addr->bitlen = -1;
324         return 0;
325 }
326
327 int get_prefix_1(inet_prefix *dst, char *arg, int family)
328 {
329         int err;
330         unsigned plen;
331         char *slash;
332
333         memset(dst, 0, sizeof(*dst));
334
335         if (strcmp(arg, "default") == 0 ||
336             strcmp(arg, "any") == 0 ||
337             strcmp(arg, "all") == 0) {
338                 if (family == AF_DECnet)
339                         return -1;
340                 dst->family = family;
341                 dst->bytelen = 0;
342                 dst->bitlen = 0;
343                 return 0;
344         }
345
346         slash = strchr(arg, '/');
347         if (slash)
348                 *slash = 0;
349
350         err = get_addr_1(dst, arg, family);
351         if (err == 0) {
352                 switch(dst->family) {
353                         case AF_INET6:
354                                 dst->bitlen = 128;
355                                 break;
356                         case AF_DECnet:
357                                 dst->bitlen = 16;
358                                 break;
359                         default:
360                         case AF_INET:
361                                 dst->bitlen = 32;
362                 }
363                 if (slash) {
364                         if (get_netmask(&plen, slash+1, 0)
365                                         || plen > dst->bitlen) {
366                                 err = -1;
367                                 goto done;
368                         }
369                         dst->flags |= PREFIXLEN_SPECIFIED;
370                         dst->bitlen = plen;
371                 }
372         }
373 done:
374         if (slash)
375                 *slash = '/';
376         return err;
377 }
378
379 int get_addr(inet_prefix *dst, const char *arg, int family)
380 {
381         if (family == AF_PACKET) {
382                 fprintf(stderr, "Error: \"%s\" may be inet address, but it is not allowed in this context.\n", arg);
383                 exit(1);
384         }
385         if (get_addr_1(dst, arg, family)) {
386                 fprintf(stderr, "Error: an inet address is expected rather than \"%s\".\n", arg);
387                 exit(1);
388         }
389         return 0;
390 }
391
392 int get_prefix(inet_prefix *dst, char *arg, int family)
393 {
394         if (family == AF_PACKET) {
395                 fprintf(stderr, "Error: \"%s\" may be inet prefix, but it is not allowed in this context.\n", arg);
396                 exit(1);
397         }
398         if (get_prefix_1(dst, arg, family)) {
399                 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", arg);
400                 exit(1);
401         }
402         return 0;
403 }
404
405 __u32 get_addr32(const char *name)
406 {
407         inet_prefix addr;
408         if (get_addr_1(&addr, name, AF_INET)) {
409                 fprintf(stderr, "Error: an IP address is expected rather than \"%s\"\n", name);
410                 exit(1);
411         }
412         return addr.data[0];
413 }
414
415 void incomplete_command(void)
416 {
417         fprintf(stderr, "Command line is not complete. Try option \"help\"\n");
418         exit(-1);
419 }
420
421 void missarg(const char *key)
422 {
423         fprintf(stderr, "Error: argument \"%s\" is required\n", key);
424         exit(-1);
425 }
426
427 void invarg(const char *msg, const char *arg)
428 {
429         fprintf(stderr, "Error: argument \"%s\" is wrong: %s\n", arg, msg);
430         exit(-1);
431 }
432
433 void duparg(const char *key, const char *arg)
434 {
435         fprintf(stderr, "Error: duplicate \"%s\": \"%s\" is the second value.\n", key, arg);
436         exit(-1);
437 }
438
439 void duparg2(const char *key, const char *arg)
440 {
441         fprintf(stderr, "Error: either \"%s\" is duplicate, or \"%s\" is a garbage.\n", key, arg);
442         exit(-1);
443 }
444
445 int matches(const char *cmd, const char *pattern)
446 {
447         int len = strlen(cmd);
448         if (len > strlen(pattern))
449                 return -1;
450         return memcmp(pattern, cmd, len);
451 }
452
453 int inet_addr_match(const inet_prefix *a, const inet_prefix *b, int bits)
454 {
455         const __u32 *a1 = a->data;
456         const __u32 *a2 = b->data;
457         int words = bits >> 0x05;
458
459         bits &= 0x1f;
460
461         if (words)
462                 if (memcmp(a1, a2, words << 2))
463                         return -1;
464
465         if (bits) {
466                 __u32 w1, w2;
467                 __u32 mask;
468
469                 w1 = a1[words];
470                 w2 = a2[words];
471
472                 mask = htonl((0xffffffff) << (0x20 - bits));
473
474                 if ((w1 ^ w2) & mask)
475                         return 1;
476         }
477
478         return 0;
479 }
480
481 int __iproute2_hz_internal;
482
483 int __get_hz(void)
484 {
485         char name[1024];
486         int hz = 0;
487         FILE *fp;
488
489         if (getenv("HZ"))
490                 return atoi(getenv("HZ")) ? : HZ;
491
492         if (getenv("PROC_NET_PSCHED")) {
493                 snprintf(name, sizeof(name)-1, "%s", getenv("PROC_NET_PSCHED"));
494         } else if (getenv("PROC_ROOT")) {
495                 snprintf(name, sizeof(name)-1, "%s/net/psched", getenv("PROC_ROOT"));
496         } else {
497                 strcpy(name, "/proc/net/psched");
498         }
499         fp = fopen(name, "r");
500
501         if (fp) {
502                 unsigned nom, denom;
503                 if (fscanf(fp, "%*08x%*08x%08x%08x", &nom, &denom) == 2)
504                         if (nom == 1000000)
505                                 hz = denom;
506                 fclose(fp);
507         }
508         if (hz)
509                 return hz;
510         return HZ;
511 }
512
513 int __iproute2_user_hz_internal;
514
515 int __get_user_hz(void)
516 {
517         return sysconf(_SC_CLK_TCK);
518 }
519
520 const char *rt_addr_n2a(int af, int len, const void *addr, char *buf, int buflen)
521 {
522         switch (af) {
523         case AF_INET:
524         case AF_INET6:
525                 return inet_ntop(af, addr, buf, buflen);
526         case AF_IPX:
527                 return ipx_ntop(af, addr, buf, buflen);
528         case AF_DECnet:
529         {
530                 struct dn_naddr dna = { 2, { 0, 0, }};
531                 memcpy(dna.a_addr, addr, 2);
532                 return dnet_ntop(af, &dna, buf, buflen);
533         }
534         default:
535                 return "???";
536         }
537 }
538
539 #ifdef RESOLVE_HOSTNAMES
540 struct namerec
541 {
542         struct namerec *next;
543         const char *name;
544         inet_prefix addr;
545 };
546
547 #define NHASH 257
548 static struct namerec *nht[NHASH];
549
550 static const char *resolve_address(const void *addr, int len, int af)
551 {
552         struct namerec *n;
553         struct hostent *h_ent;
554         unsigned hash;
555         static int notfirst;
556
557
558         if (af == AF_INET6 && ((__u32*)addr)[0] == 0 &&
559             ((__u32*)addr)[1] == 0 && ((__u32*)addr)[2] == htonl(0xffff)) {
560                 af = AF_INET;
561                 addr += 12;
562                 len = 4;
563         }
564
565         hash = *(__u32 *)(addr + len - 4) % NHASH;
566
567         for (n = nht[hash]; n; n = n->next) {
568                 if (n->addr.family == af &&
569                     n->addr.bytelen == len &&
570                     memcmp(n->addr.data, addr, len) == 0)
571                         return n->name;
572         }
573         if ((n = malloc(sizeof(*n))) == NULL)
574                 return NULL;
575         n->addr.family = af;
576         n->addr.bytelen = len;
577         n->name = NULL;
578         memcpy(n->addr.data, addr, len);
579         n->next = nht[hash];
580         nht[hash] = n;
581         if (++notfirst == 1)
582                 sethostent(1);
583         fflush(stdout);
584
585         if ((h_ent = gethostbyaddr(addr, len, af)) != NULL)
586                 n->name = strdup(h_ent->h_name);
587
588         /* Even if we fail, "negative" entry is remembered. */
589         return n->name;
590 }
591 #endif
592
593
594 const char *format_host(int af, int len, const void *addr,
595                         char *buf, int buflen)
596 {
597 #ifdef RESOLVE_HOSTNAMES
598         if (resolve_hosts) {
599                 const char *n;
600
601                 if (len <= 0) {
602                         switch (af) {
603                         case AF_INET:
604                                 len = 4;
605                                 break;
606                         case AF_INET6:
607                                 len = 16;
608                                 break;
609                         case AF_IPX:
610                                 len = 10;
611                                 break;
612 #ifdef AF_DECnet
613                         /* I see no reasons why gethostbyname
614                            may not work for DECnet */
615                         case AF_DECnet:
616                                 len = 2;
617                                 break;
618 #endif
619                         default: ;
620                         }
621                 }
622                 if (len > 0 &&
623                     (n = resolve_address(addr, len, af)) != NULL)
624                         return n;
625         }
626 #endif
627         return rt_addr_n2a(af, len, addr, buf, buflen);
628 }
629
630
631 char *hexstring_n2a(const __u8 *str, int len, char *buf, int blen)
632 {
633         char *ptr = buf;
634         int i;
635
636         for (i=0; i<len; i++) {
637                 if (blen < 3)
638                         break;
639                 sprintf(ptr, "%02x", str[i]);
640                 ptr += 2;
641                 blen -= 2;
642                 if (i != len-1 && blen > 1) {
643                         *ptr++ = ':';
644                         blen--;
645                 }
646         }
647         return buf;
648 }
649
650 __u8* hexstring_a2n(const char *str, __u8 *buf, int blen)
651 {
652         int cnt = 0;
653
654         for (;;) {
655                 unsigned acc;
656                 char ch;
657
658                 acc = 0;
659
660                 while ((ch = *str) != ':' && ch != 0) {
661                         if (ch >= '0' && ch <= '9')
662                                 ch -= '0';
663                         else if (ch >= 'a' && ch <= 'f')
664                                 ch -= 'a'-10;
665                         else if (ch >= 'A' && ch <= 'F')
666                                 ch -= 'A'-10;
667                         else
668                                 return NULL;
669                         acc = (acc<<4) + ch;
670                         str++;
671                 }
672
673                 if (acc > 255)
674                         return NULL;
675                 if (cnt < blen) {
676                         buf[cnt] = acc;
677                         cnt++;
678                 }
679                 if (ch == 0)
680                         break;
681                 ++str;
682         }
683         if (cnt < blen)
684                 memset(buf+cnt, 0, blen-cnt);
685         return buf;
686 }
687
688 int print_timestamp(FILE *fp)
689 {
690         struct timeval tv;
691         char *tstr;
692
693         memset(&tv, 0, sizeof(tv));
694         gettimeofday(&tv, NULL);
695
696         tstr = asctime(localtime(&tv.tv_sec));
697         tstr[strlen(tstr)-1] = 0;
698         fprintf(fp, "Timestamp: %s %lu usec\n", tstr, tv.tv_usec);
699         return 0;
700 }
701
702 int cmdlineno;
703
704 /* Like glibc getline but handle continuation lines and comments */
705 ssize_t getcmdline(char **linep, size_t *lenp, FILE *in)
706 {
707         ssize_t cc;
708         char *cp;
709
710         if ((cc = getline(linep, lenp, in)) < 0)
711                 return cc;      /* eof or error */
712         ++cmdlineno;
713
714         cp = strchr(*linep, '#');
715         if (cp)
716                 *cp = '\0';
717
718         while ((cp = strstr(*linep, "\\\n")) != NULL) {
719                 char *line1 = NULL;
720                 size_t len1 = 0;
721                 size_t cc1;
722
723                 if ((cc1 = getline(&line1, &len1, in)) < 0) {
724                         fprintf(stderr, "Missing continuation line\n");
725                         return cc1;
726                 }
727
728                 ++cmdlineno;
729                 *cp = 0;
730
731                 cp = strchr(line1, '#');
732                 if (cp)
733                         *cp = '\0';
734
735                 *lenp = strlen(*linep) + strlen(line1) + 1;
736                 *linep = realloc(*linep, *lenp);
737                 if (!*linep) {
738                         fprintf(stderr, "Out of memory\n");
739                         *lenp = 0;
740                         return -1;
741                 }
742                 cc += cc1 - 2;
743                 strcat(*linep, line1);
744                 free(line1);
745         }
746         return cc;
747 }
748
749 /* split command line into argument vector */
750 int makeargs(char *line, char *argv[], int maxargs)
751 {
752         static const char ws[] = " \t\r\n";
753         char *cp;
754         int argc = 0;
755
756         for (cp = strtok(line, ws); cp; cp = strtok(NULL, ws)) {
757                 if (argc >= (maxargs - 1)) {
758                         fprintf(stderr, "Too many arguments to command\n");
759                         exit(1);
760                 }
761                 argv[argc++] = cp;
762         }
763         argv[argc] = NULL;
764
765         return argc;
766 }