]> rtime.felk.cvut.cz Git - lisovros/iproute2_canprio.git/blob - lib/utils.c
ip: abbreviation of network-prefix is no longer possible with ip route
[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  * 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 int get_addr_1(inet_prefix *addr, const char *name, int family)
248 {
249         memset(addr, 0, sizeof(*addr));
250
251         if (strcmp(name, "default") == 0 ||
252             strcmp(name, "all") == 0 ||
253             strcmp(name, "any") == 0) {
254                 if (family == AF_DECnet)
255                         return -1;
256                 addr->family = family;
257                 addr->bytelen = (family == AF_INET6 ? 16 : 4);
258                 addr->bitlen = -1;
259                 return 0;
260         }
261
262         if (strchr(name, ':')) {
263                 addr->family = AF_INET6;
264                 if (family != AF_UNSPEC && family != AF_INET6)
265                         return -1;
266                 if (inet_pton(AF_INET6, name, addr->data) <= 0)
267                         return -1;
268                 addr->bytelen = 16;
269                 addr->bitlen = -1;
270                 return 0;
271         }
272
273         if (family == AF_DECnet) {
274                 struct dn_naddr dna;
275                 addr->family = AF_DECnet;
276                 if (dnet_pton(AF_DECnet, name, &dna) <= 0)
277                         return -1;
278                 memcpy(addr->data, dna.a_addr, 2);
279                 addr->bytelen = 2;
280                 addr->bitlen = -1;
281                 return 0;
282         }
283
284         addr->family = AF_INET;
285         if (family != AF_UNSPEC && family != AF_INET)
286                 return -1;
287         if (inet_aton(name, addr->data) <= 0)
288                 return -1;
289         addr->bytelen = 4;
290         addr->bitlen = -1;
291         return 0;
292 }
293
294 int get_prefix_1(inet_prefix *dst, char *arg, int family)
295 {
296         int err;
297         unsigned plen;
298         char *slash;
299
300         memset(dst, 0, sizeof(*dst));
301
302         if (strcmp(arg, "default") == 0 ||
303             strcmp(arg, "any") == 0 ||
304             strcmp(arg, "all") == 0) {
305                 if (family == AF_DECnet)
306                         return -1;
307                 dst->family = family;
308                 dst->bytelen = 0;
309                 dst->bitlen = 0;
310                 return 0;
311         }
312
313         slash = strchr(arg, '/');
314         if (slash)
315                 *slash = 0;
316
317         err = get_addr_1(dst, arg, family);
318         if (err == 0) {
319                 switch(dst->family) {
320                         case AF_INET6:
321                                 dst->bitlen = 128;
322                                 break;
323                         case AF_DECnet:
324                                 dst->bitlen = 16;
325                                 break;
326                         default:
327                         case AF_INET:
328                                 dst->bitlen = 32;
329                 }
330                 if (slash) {
331                         if (get_netmask(&plen, slash+1, 0)
332                                         || plen > dst->bitlen) {
333                                 err = -1;
334                                 goto done;
335                         }
336                         dst->flags |= PREFIXLEN_SPECIFIED;
337                         dst->bitlen = plen;
338                 }
339         }
340 done:
341         if (slash)
342                 *slash = '/';
343         return err;
344 }
345
346 int get_addr(inet_prefix *dst, const char *arg, int family)
347 {
348         if (family == AF_PACKET) {
349                 fprintf(stderr, "Error: \"%s\" may be inet address, but it is not allowed in this context.\n", arg);
350                 exit(1);
351         }
352         if (get_addr_1(dst, arg, family)) {
353                 fprintf(stderr, "Error: an inet address is expected rather than \"%s\".\n", arg);
354                 exit(1);
355         }
356         return 0;
357 }
358
359 int get_prefix(inet_prefix *dst, char *arg, int family)
360 {
361         if (family == AF_PACKET) {
362                 fprintf(stderr, "Error: \"%s\" may be inet prefix, but it is not allowed in this context.\n", arg);
363                 exit(1);
364         }
365         if (get_prefix_1(dst, arg, family)) {
366                 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", arg);
367                 exit(1);
368         }
369         return 0;
370 }
371
372 __u32 get_addr32(const char *name)
373 {
374         inet_prefix addr;
375         if (get_addr_1(&addr, name, AF_INET)) {
376                 fprintf(stderr, "Error: an IP address is expected rather than \"%s\"\n", name);
377                 exit(1);
378         }
379         return addr.data[0];
380 }
381
382 void incomplete_command(void)
383 {
384         fprintf(stderr, "Command line is not complete. Try option \"help\"\n");
385         exit(-1);
386 }
387
388 void missarg(const char *key)
389 {
390         fprintf(stderr, "Error: argument \"%s\" is required\n", key);
391         exit(-1);
392 }
393
394 void invarg(const char *msg, const char *arg)
395 {
396         fprintf(stderr, "Error: argument \"%s\" is wrong: %s\n", arg, msg);
397         exit(-1);
398 }
399
400 void duparg(const char *key, const char *arg)
401 {
402         fprintf(stderr, "Error: duplicate \"%s\": \"%s\" is the second value.\n", key, arg);
403         exit(-1);
404 }
405
406 void duparg2(const char *key, const char *arg)
407 {
408         fprintf(stderr, "Error: either \"%s\" is duplicate, or \"%s\" is a garbage.\n", key, arg);
409         exit(-1);
410 }
411
412 int matches(const char *cmd, const char *pattern)
413 {
414         int len = strlen(cmd);
415         if (len > strlen(pattern))
416                 return -1;
417         return memcmp(pattern, cmd, len);
418 }
419
420 int inet_addr_match(const inet_prefix *a, const inet_prefix *b, int bits)
421 {
422         const __u32 *a1 = a->data;
423         const __u32 *a2 = b->data;
424         int words = bits >> 0x05;
425
426         bits &= 0x1f;
427
428         if (words)
429                 if (memcmp(a1, a2, words << 2))
430                         return -1;
431
432         if (bits) {
433                 __u32 w1, w2;
434                 __u32 mask;
435
436                 w1 = a1[words];
437                 w2 = a2[words];
438
439                 mask = htonl((0xffffffff) << (0x20 - bits));
440
441                 if ((w1 ^ w2) & mask)
442                         return 1;
443         }
444
445         return 0;
446 }
447
448 int __iproute2_hz_internal;
449
450 int __get_hz(void)
451 {
452         char name[1024];
453         int hz = 0;
454         FILE *fp;
455
456         if (getenv("HZ"))
457                 return atoi(getenv("HZ")) ? : HZ;
458
459         if (getenv("PROC_NET_PSCHED")) {
460                 snprintf(name, sizeof(name)-1, "%s", getenv("PROC_NET_PSCHED"));
461         } else if (getenv("PROC_ROOT")) {
462                 snprintf(name, sizeof(name)-1, "%s/net/psched", getenv("PROC_ROOT"));
463         } else {
464                 strcpy(name, "/proc/net/psched");
465         }
466         fp = fopen(name, "r");
467
468         if (fp) {
469                 unsigned nom, denom;
470                 if (fscanf(fp, "%*08x%*08x%08x%08x", &nom, &denom) == 2)
471                         if (nom == 1000000)
472                                 hz = denom;
473                 fclose(fp);
474         }
475         if (hz)
476                 return hz;
477         return HZ;
478 }
479
480 int __iproute2_user_hz_internal;
481
482 int __get_user_hz(void)
483 {
484         return sysconf(_SC_CLK_TCK);
485 }
486
487 const char *rt_addr_n2a(int af, int len, const void *addr, char *buf, int buflen)
488 {
489         switch (af) {
490         case AF_INET:
491         case AF_INET6:
492                 return inet_ntop(af, addr, buf, buflen);
493         case AF_IPX:
494                 return ipx_ntop(af, addr, buf, buflen);
495         case AF_DECnet:
496         {
497                 struct dn_naddr dna = { 2, { 0, 0, }};
498                 memcpy(dna.a_addr, addr, 2);
499                 return dnet_ntop(af, &dna, buf, buflen);
500         }
501         default:
502                 return "???";
503         }
504 }
505
506 #ifdef RESOLVE_HOSTNAMES
507 struct namerec
508 {
509         struct namerec *next;
510         const char *name;
511         inet_prefix addr;
512 };
513
514 #define NHASH 257
515 static struct namerec *nht[NHASH];
516
517 static const char *resolve_address(const void *addr, int len, int af)
518 {
519         struct namerec *n;
520         struct hostent *h_ent;
521         unsigned hash;
522         static int notfirst;
523
524
525         if (af == AF_INET6 && ((__u32*)addr)[0] == 0 &&
526             ((__u32*)addr)[1] == 0 && ((__u32*)addr)[2] == htonl(0xffff)) {
527                 af = AF_INET;
528                 addr += 12;
529                 len = 4;
530         }
531
532         hash = *(__u32 *)(addr + len - 4) % NHASH;
533
534         for (n = nht[hash]; n; n = n->next) {
535                 if (n->addr.family == af &&
536                     n->addr.bytelen == len &&
537                     memcmp(n->addr.data, addr, len) == 0)
538                         return n->name;
539         }
540         if ((n = malloc(sizeof(*n))) == NULL)
541                 return NULL;
542         n->addr.family = af;
543         n->addr.bytelen = len;
544         n->name = NULL;
545         memcpy(n->addr.data, addr, len);
546         n->next = nht[hash];
547         nht[hash] = n;
548         if (++notfirst == 1)
549                 sethostent(1);
550         fflush(stdout);
551
552         if ((h_ent = gethostbyaddr(addr, len, af)) != NULL)
553                 n->name = strdup(h_ent->h_name);
554
555         /* Even if we fail, "negative" entry is remembered. */
556         return n->name;
557 }
558 #endif
559
560
561 const char *format_host(int af, int len, const void *addr,
562                         char *buf, int buflen)
563 {
564 #ifdef RESOLVE_HOSTNAMES
565         if (resolve_hosts) {
566                 const char *n;
567
568                 if (len <= 0) {
569                         switch (af) {
570                         case AF_INET:
571                                 len = 4;
572                                 break;
573                         case AF_INET6:
574                                 len = 16;
575                                 break;
576                         case AF_IPX:
577                                 len = 10;
578                                 break;
579 #ifdef AF_DECnet
580                         /* I see no reasons why gethostbyname
581                            may not work for DECnet */
582                         case AF_DECnet:
583                                 len = 2;
584                                 break;
585 #endif
586                         default: ;
587                         }
588                 }
589                 if (len > 0 &&
590                     (n = resolve_address(addr, len, af)) != NULL)
591                         return n;
592         }
593 #endif
594         return rt_addr_n2a(af, len, addr, buf, buflen);
595 }
596
597
598 char *hexstring_n2a(const __u8 *str, int len, char *buf, int blen)
599 {
600         char *ptr = buf;
601         int i;
602
603         for (i=0; i<len; i++) {
604                 if (blen < 3)
605                         break;
606                 sprintf(ptr, "%02x", str[i]);
607                 ptr += 2;
608                 blen -= 2;
609                 if (i != len-1 && blen > 1) {
610                         *ptr++ = ':';
611                         blen--;
612                 }
613         }
614         return buf;
615 }
616
617 __u8* hexstring_a2n(const char *str, __u8 *buf, int blen)
618 {
619         int cnt = 0;
620
621         for (;;) {
622                 unsigned acc;
623                 char ch;
624
625                 acc = 0;
626
627                 while ((ch = *str) != ':' && ch != 0) {
628                         if (ch >= '0' && ch <= '9')
629                                 ch -= '0';
630                         else if (ch >= 'a' && ch <= 'f')
631                                 ch -= 'a'-10;
632                         else if (ch >= 'A' && ch <= 'F')
633                                 ch -= 'A'-10;
634                         else
635                                 return NULL;
636                         acc = (acc<<4) + ch;
637                         str++;
638                 }
639
640                 if (acc > 255)
641                         return NULL;
642                 if (cnt < blen) {
643                         buf[cnt] = acc;
644                         cnt++;
645                 }
646                 if (ch == 0)
647                         break;
648                 ++str;
649         }
650         if (cnt < blen)
651                 memset(buf+cnt, 0, blen-cnt);
652         return buf;
653 }
654
655 int print_timestamp(FILE *fp)
656 {
657         struct timeval tv;
658         char *tstr;
659
660         memset(&tv, 0, sizeof(tv));
661         gettimeofday(&tv, NULL);
662
663         tstr = asctime(localtime(&tv.tv_sec));
664         tstr[strlen(tstr)-1] = 0;
665         fprintf(fp, "Timestamp: %s %lu usec\n", tstr, tv.tv_usec);
666         return 0;
667 }
668
669 int cmdlineno;
670
671 /* Like glibc getline but handle continuation lines and comments */
672 ssize_t getcmdline(char **linep, size_t *lenp, FILE *in)
673 {
674         ssize_t cc;
675         char *cp;
676
677         if ((cc = getline(linep, lenp, in)) < 0)
678                 return cc;      /* eof or error */
679         ++cmdlineno;
680
681         cp = strchr(*linep, '#');
682         if (cp)
683                 *cp = '\0';
684
685         while ((cp = strstr(*linep, "\\\n")) != NULL) {
686                 char *line1 = NULL;
687                 size_t len1 = 0;
688                 size_t cc1;
689
690                 if ((cc1 = getline(&line1, &len1, in)) < 0) {
691                         fprintf(stderr, "Missing continuation line\n");
692                         return cc1;
693                 }
694
695                 ++cmdlineno;
696                 *cp = 0;
697
698                 cp = strchr(line1, '#');
699                 if (cp)
700                         *cp = '\0';
701
702                 *lenp = strlen(*linep) + strlen(line1) + 1;
703                 *linep = realloc(*linep, *lenp);
704                 if (!*linep) {
705                         fprintf(stderr, "Out of memory\n");
706                         *lenp = 0;
707                         return -1;
708                 }
709                 cc += cc1 - 2;
710                 strcat(*linep, line1);
711                 free(line1);
712         }
713         return cc;
714 }
715
716 /* split command line into argument vector */
717 int makeargs(char *line, char *argv[], int maxargs)
718 {
719         static const char ws[] = " \t\r\n";
720         char *cp;
721         int argc = 0;
722
723         for (cp = strtok(line, ws); cp; cp = strtok(NULL, ws)) {
724                 if (argc >= (maxargs - 1)) {
725                         fprintf(stderr, "Too many arguments to command\n");
726                         exit(1);
727                 }
728                 argv[argc++] = cp;
729         }
730         argv[argc] = NULL;
731
732         return argc;
733 }