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