This commit was generated by cvs2svn to compensate for changes in r786,
[libnl.git] / lib / utils.c
1 /*
2  * lib/utils.c          Utility Functions
3  *
4  *      This library is free software; you can redistribute it and/or
5  *      modify it under the terms of the GNU Lesser General Public
6  *      License as published by the Free Software Foundation version 2.1
7  *      of the License.
8  *
9  * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
10  */
11
12 /**
13  * @defgroup utils Utilities
14  * @{
15  */
16
17 #include <netlink-local.h>
18 #include <netlink/netlink.h>
19 #include <netlink/utils.h>
20 #include <linux/socket.h>
21
22 /**
23  * Debug level
24  */
25 int nl_debug = 0;
26
27 /**
28  * @name Error Code Helpers
29  * @{
30  */
31
32 static char *errbuf;
33 static int nlerrno;
34
35 /** @cond SKIP */
36 int __nl_error(int err, const char *file, unsigned int line, const char *func,
37                const char *fmt, ...)
38 {
39         char *user_err;
40         va_list args;
41
42         if (errbuf) {
43                 free(errbuf);
44                 errbuf = NULL;
45         }
46
47         nlerrno = err;
48
49         if (fmt) {
50                 va_start(args, fmt);
51                 vasprintf(&user_err, fmt, args);
52                 va_end(args);
53         }
54
55 #ifdef VERBOSE_ERRORS
56         asprintf(&errbuf, "%s:%u:%s: %s (errno = %s)",
57                  file, line, func, fmt ? user_err : "", strerror(err));
58 #else
59         asprintf(&errbuf, "%s (errno = %s)",
60                  fmt ? user_err : "", strerror(err));
61 #endif
62
63         if (fmt)
64                 free(user_err);
65
66         return -err;
67 }
68
69 int nl_get_errno(void)
70 {
71         return nlerrno;
72 }
73
74 /** @endcond */
75
76 /**
77  * Return error message for an error code
78  * @return error message
79  */
80 char *nl_geterror(void)
81 {
82         if (errbuf)
83                 return errbuf;
84
85         if (nlerrno)
86                 return strerror(nlerrno);
87
88         return "Sucess\n";
89 }
90
91 /** @} */
92
93 /**
94  * @name Unit Pretty-Printing
95  * @{
96  */
97
98 /**
99  * Cancel down a byte counter
100  * @arg l               byte counter
101  * @arg unit            destination unit pointer
102  *
103  * Cancels down a byte counter until it reaches a reasonable
104  * unit. The chosen unit is assigned to \a unit.
105  * 
106  * @return The cancelled down byte counter in the new unit.
107  */
108 double nl_cancel_down_bytes(unsigned long long l, char **unit)
109 {
110         if (l >= 1099511627776LL) {
111                 *unit = "TiB";
112                 return ((double) l) / 1099511627776LL;
113         } else if (l >= 1073741824) {
114                 *unit = "GiB";
115                 return ((double) l) / 1073741824;
116         } else if (l >= 1048576) {
117                 *unit = "MiB";
118                 return ((double) l) / 1048576;
119         } else if (l >= 1024) {
120                 *unit = "KiB";
121                 return ((double) l) / 1024;
122         } else {
123                 *unit = "B";
124                 return (double) l;
125         }
126 }
127
128 /**
129  * Cancel down a bit counter
130  * @arg l               bit counter
131  * @arg unit            destination unit pointer
132  *
133  * Cancels downa bit counter until it reaches a reasonable
134  * unit. The chosen unit is assigned to \a unit.
135  *
136  * @return The cancelled down bit counter in the new unit.
137  */
138 double nl_cancel_down_bits(unsigned long long l, char **unit)
139 {
140         if (l >= 1099511627776ULL) {
141                 *unit = "Tbit";
142                 return ((double) l) / 1099511627776ULL;
143         } else if (l >= 1073741824) {
144                 *unit = "Gbit";
145                 return ((double) l) / 1073741824;
146         } else if (l >= 1048576) {
147                 *unit = "Mbit";
148                 return ((double) l) / 1048576;
149         } else if (l >= 1024) {
150                 *unit = "Kbit";
151                 return ((double) l) / 1024;
152         } else {
153                 *unit = "bit";
154                 return (double) l;
155         }
156                 
157 }
158
159 /**
160  * Cancel down a micro second value
161  * @arg l               micro seconds
162  * @arg unit            destination unit pointer
163  *
164  * Cancels down a microsecond counter until it reaches a
165  * reasonable unit. The chosen unit is assigned to \a unit.
166  *
167  * @return The cancelled down microsecond in the new unit
168  */
169 double nl_cancel_down_us(uint32_t l, char **unit)
170 {
171         if (l >= 1000000) {
172                 *unit = "s";
173                 return ((double) l) / 1000000;
174         } else if (l >= 1000) {
175                 *unit = "ms";
176                 return ((double) l) / 1000;
177         } else {
178                 *unit = "us";
179                 return (double) l;
180         }
181 }
182
183 /** @} */
184
185 /**
186  * @name Generic Unit Translations
187  * @{
188  */
189
190 /**
191  * Convert a character string to a size
192  * @arg str             size encoded as character string
193  *
194  * Converts the specified size as character to the corresponding
195  * number of bytes.
196  *
197  * Supported formats are:
198  *  - b,kb/k,m/mb,gb/g for bytes
199  *  - bit,kbit/mbit/gbit
200  *
201  * @return The number of bytes or -1 if the string is unparseable
202  */
203 long nl_size2int(const char *str)
204 {
205         char *p;
206         long l = strtol(str, &p, 0);
207         if (p == str)
208                 return -1;
209
210         if (*p) {
211                 if (!strcasecmp(p, "kb") || !strcasecmp(p, "k"))
212                         l *= 1024;
213                 else if (!strcasecmp(p, "gb") || !strcasecmp(p, "g"))
214                         l *= 1024*1024*1024;
215                 else if (!strcasecmp(p, "gbit"))
216                         l *= 1024*1024*1024/8;
217                 else if (!strcasecmp(p, "mb") || !strcasecmp(p, "m"))
218                         l *= 1024*1024;
219                 else if (!strcasecmp(p, "mbit"))
220                         l *= 1024*1024/8;
221                 else if (!strcasecmp(p, "kbit"))
222                         l *= 1024/8;
223                 else if (!strcasecmp(p, "bit"))
224                         l /= 8;
225                 else if (strcasecmp(p, "b") != 0)
226                         return -1;
227         }
228
229         return l;
230 }
231
232 /**
233  * Convert a character string to a probability
234  * @arg str             probability encoded as character string
235  *
236  * Converts the specified probability as character to the
237  * corresponding probability number.
238  *
239  * Supported formats are:
240  *  - 0.0-1.0
241  *  - 0%-100%
242  *
243  * @return The probability relative to NL_PROB_MIN and NL_PROB_MAX
244  */
245 long nl_prob2int(const char *str)
246 {
247         char *p;
248         double d = strtod(str, &p);
249
250         if (p == str)
251                 return -1;
252
253         if (d > 1.0)
254                 d /= 100.0f;
255
256         if (d > 1.0f || d < 0.0f)
257                 return -1;
258
259         if (*p && strcmp(p, "%") != 0)
260                 return -1;
261
262         return rint(d * NL_PROB_MAX);
263 }
264
265 /** @} */
266
267 /**
268  * @name Time Translations
269  * @{
270  */
271
272 #ifdef USER_HZ
273 static uint32_t user_hz = USER_HZ;
274 #else
275 static uint32_t user_hz = 100;
276 #endif
277
278 static double ticks_per_usec = 1.0f;
279
280 /* Retrieves the configured HZ and ticks/us value in the kernel.
281  * The value is cached. Supported ways of getting it:
282  *
283  * 1) environment variable
284  * 2) /proc/net/psched and sysconf
285  *
286  * Supports the environment variables:
287  *   PROC_NET_PSCHED  - may point to psched file in /proc
288  *   PROC_ROOT        - may point to /proc fs */ 
289 static void __init get_psched_settings(void)
290 {
291         char name[FILENAME_MAX];
292         FILE *fd;
293         int got_hz = 0, got_tick = 0;
294
295         if (getenv("HZ")) {
296                 long hz = strtol(getenv("HZ"), NULL, 0);
297
298                 if (LONG_MIN != hz && LONG_MAX != hz) {
299                         user_hz = hz;
300                         got_hz = 1;
301                 }
302         }
303
304         if (!got_hz)
305                 user_hz = sysconf(_SC_CLK_TCK);
306
307         if (getenv("TICKS_PER_USEC")) {
308                 double t = strtod(getenv("TICKS_PER_USEC"), NULL);
309
310                 ticks_per_usec = t;
311                 got_tick = 1;
312         }
313                 
314
315         if (getenv("PROC_NET_PSCHED"))
316                 snprintf(name, sizeof(name), "%s", getenv("PROC_NET_PSCHED"));
317         else if (getenv("PROC_ROOT"))
318                 snprintf(name, sizeof(name), "%s/net/psched",
319                          getenv("PROC_ROOT"));
320         else
321                 strncpy(name, "/proc/net/psched", sizeof(name) - 1);
322
323         if ((fd = fopen(name, "r"))) {
324                 uint32_t tick, us, nom;
325                 int r = fscanf(fd, "%08x%08x%08x%*08x", &tick, &us, &nom);
326
327                 if (4 == r && nom == 1000000 && !got_tick)
328                         ticks_per_usec = (double)tick/(double)us;
329                         
330                 fclose(fd);
331         }
332 }
333
334
335 /**
336  * Return the value of HZ
337  */
338 int nl_get_hz(void)
339 {
340         return user_hz;
341 }
342
343
344 /**
345  * Convert micro seconds to ticks
346  * @arg us              micro seconds
347  * @return number of ticks
348  */
349 uint32_t nl_us2ticks(uint32_t us)
350 {
351         return us * ticks_per_usec;
352 }
353
354
355 /**
356  * Convert ticks to micro seconds
357  * @arg ticks           number of ticks
358  * @return microseconds
359  */
360 uint32_t nl_ticks2us(uint32_t ticks)
361 {
362         return ticks / ticks_per_usec;
363 }
364
365 long nl_time2int(const char *str)
366 {
367         char *p;
368         long l = strtol(str, &p, 0);
369         if (p == str)
370                 return -1;
371
372         if (*p) {
373                 if (!strcasecmp(p, "min") == 0 || !strcasecmp(p, "m"))
374                         l *= 60;
375                 else if (!strcasecmp(p, "hour") || !strcasecmp(p, "h"))
376                         l *= 60*60;
377                 else if (!strcasecmp(p, "day") || !strcasecmp(p, "d"))
378                         l *= 60*60*24;
379                 else if (strcasecmp(p, "s") != 0)
380                         return -1;
381         }
382
383         return l;
384 }
385
386 /**
387  * Convert milliseconds to a character string
388  * @arg msec            number of milliseconds
389  * @arg buf             destination buffer
390  * @arg len             buffer length
391  *
392  * Converts milliseconds to a character string split up in days, hours,
393  * minutes, seconds, and milliseconds and stores it in the specified
394  * destination buffer.
395  *
396  * @return The destination buffer.
397  */
398 char * nl_msec2str(uint64_t msec, char *buf, size_t len)
399 {
400         int i, split[5];
401         char *units[] = {"d", "h", "m", "s", "msec"};
402
403 #define _SPLIT(idx, unit) if ((split[idx] = msec / unit) > 0) msec %= unit
404         _SPLIT(0, 86400000);    /* days */
405         _SPLIT(1, 3600000);     /* hours */
406         _SPLIT(2, 60000);       /* minutes */
407         _SPLIT(3, 1000);        /* seconds */
408 #undef  _SPLIT
409         split[4] = msec;
410
411         memset(buf, 0, len);
412
413         for (i = 0; i < ARRAY_SIZE(split); i++) {
414                 if (split[i] > 0) {
415                         char t[64];
416                         snprintf(t, sizeof(t), "%s%d%s",
417                                  strlen(buf) ? " " : "", split[i], units[i]);
418                         strncat(buf, t, len - strlen(buf) - 1);
419                 }
420         }
421
422         return buf;
423 }
424
425 /** @} */
426
427 /**
428  * @name Link Layer Protocol Translations
429  * @{
430  */
431
432 static struct trans_tbl llprotos[] = {
433         {0, "generic"},
434         __ADD(ARPHRD_ETHER,ether)
435         __ADD(ARPHRD_EETHER,eether)
436         __ADD(ARPHRD_AX25,ax25)
437         __ADD(ARPHRD_PRONET,pronet)
438         __ADD(ARPHRD_CHAOS,chaos)
439         __ADD(ARPHRD_IEEE802,ieee802)
440         __ADD(ARPHRD_ARCNET,arcnet)
441         __ADD(ARPHRD_APPLETLK,atalk)
442         __ADD(ARPHRD_DLCI,dlci)
443         __ADD(ARPHRD_ATM,atm)
444         __ADD(ARPHRD_METRICOM,metricom)
445         __ADD(ARPHRD_IEEE1394,ieee1394)
446 #ifdef ARPHRD_EUI64
447         __ADD(ARPHRD_EUI64,eui64)
448 #endif
449         __ADD(ARPHRD_INFINIBAND,infiniband)
450         __ADD(ARPHRD_SLIP,slip)
451         __ADD(ARPHRD_CSLIP,cslip)
452         __ADD(ARPHRD_SLIP6,slip6)
453         __ADD(ARPHRD_CSLIP6,cslip6)
454         __ADD(ARPHRD_RSRVD,rsrvd)
455         __ADD(ARPHRD_ADAPT,adapt)
456         __ADD(ARPHRD_ROSE,rose)
457         __ADD(ARPHRD_X25,x25)
458 #ifdef ARPHRD_HWX25
459         __ADD(ARPHRD_HWX25,hwx25)
460 #endif
461         __ADD(ARPHRD_PPP,ppp)
462         __ADD(ARPHRD_HDLC,hdlc)
463         __ADD(ARPHRD_LAPB,lapb)
464         __ADD(ARPHRD_DDCMP,ddcmp)
465         __ADD(ARPHRD_RAWHDLC,rawhdlc)
466         __ADD(ARPHRD_TUNNEL,ipip)
467         __ADD(ARPHRD_TUNNEL6,tunnel6)
468         __ADD(ARPHRD_FRAD,frad)
469         __ADD(ARPHRD_SKIP,skip)
470         __ADD(ARPHRD_LOOPBACK,loopback)
471         __ADD(ARPHRD_LOCALTLK,localtlk)
472         __ADD(ARPHRD_FDDI,fddi)
473         __ADD(ARPHRD_BIF,bif)
474         __ADD(ARPHRD_SIT,sit)
475         __ADD(ARPHRD_IPDDP,ip/ddp)
476         __ADD(ARPHRD_IPGRE,gre)
477         __ADD(ARPHRD_PIMREG,pimreg)
478         __ADD(ARPHRD_HIPPI,hippi)
479         __ADD(ARPHRD_ASH,ash)
480         __ADD(ARPHRD_ECONET,econet)
481         __ADD(ARPHRD_IRDA,irda)
482         __ADD(ARPHRD_FCPP,fcpp)
483         __ADD(ARPHRD_FCAL,fcal)
484         __ADD(ARPHRD_FCPL,fcpl)
485         __ADD(ARPHRD_FCFABRIC,fcfb_0)
486         __ADD(ARPHRD_FCFABRIC+1,fcfb_1)
487         __ADD(ARPHRD_FCFABRIC+2,fcfb_2)
488         __ADD(ARPHRD_FCFABRIC+3,fcfb_3)
489         __ADD(ARPHRD_FCFABRIC+4,fcfb_4)
490         __ADD(ARPHRD_FCFABRIC+5,fcfb_5)
491         __ADD(ARPHRD_FCFABRIC+6,fcfb_6)
492         __ADD(ARPHRD_FCFABRIC+7,fcfb_7)
493         __ADD(ARPHRD_FCFABRIC+8,fcfb_8)
494         __ADD(ARPHRD_FCFABRIC+9,fcfb_9)
495         __ADD(ARPHRD_FCFABRIC+10,fcfb_10)
496         __ADD(ARPHRD_FCFABRIC+11,fcfb_11)
497         __ADD(ARPHRD_FCFABRIC+12,fcfb_12)
498         __ADD(ARPHRD_IEEE802_TR,tr)
499         __ADD(ARPHRD_IEEE80211,ieee802.11)
500 #ifdef ARPHRD_IEEE80211_PRISM
501         __ADD(ARPHRD_IEEE80211_PRISM, ieee802.11_prism)
502 #endif
503 #ifdef ARPHRD_VOID
504         __ADD(ARPHRD_VOID,void)
505 #endif
506 };
507
508 /**
509  * Convert a link layer protocol to a character string (Reentrant).
510  * @arg llproto         link layer protocol
511  * @arg buf             destination buffer
512  * @arg len             buffer length
513  *
514  * Converts a link layer protocol to a character string and stores
515  * it in the specified destination buffer.
516  *
517  * @return The destination buffer or the type encoded in hexidecimal
518  *         form if no match was found.
519  */
520 char * nl_llproto2str(int llproto, char *buf, size_t len)
521 {
522         return __type2str(llproto, buf, len, llprotos, ARRAY_SIZE(llprotos));
523 }
524
525 /**
526  * Convert a character string to a link layer protocol
527  * @arg name            name of link layer protocol
528  *
529  * Converts the provided character string specifying a link layer
530  * protocl to the corresponding numeric value.
531  *
532  * @return link layer protocol or a negative value if none was found.
533  */
534 int nl_str2llproto(const char *name)
535 {
536         return __str2type(name, llprotos, ARRAY_SIZE(llprotos));
537 }
538
539 /** @} */
540
541
542 /**
543  * @name Ethernet Protocol Translations
544  * @{
545  */
546
547 static struct trans_tbl ether_protos[] = {
548         __ADD(ETH_P_LOOP,loop)
549         __ADD(ETH_P_PUP,pup)
550         __ADD(ETH_P_PUPAT,pupat)
551         __ADD(ETH_P_IP,ip)
552         __ADD(ETH_P_X25,x25)
553         __ADD(ETH_P_ARP,arp)
554         __ADD(ETH_P_BPQ,bpq)
555         __ADD(ETH_P_IEEEPUP,ieeepup)
556         __ADD(ETH_P_IEEEPUPAT,ieeepupat)
557         __ADD(ETH_P_DEC,dec)
558         __ADD(ETH_P_DNA_DL,dna_dl)
559         __ADD(ETH_P_DNA_RC,dna_rc)
560         __ADD(ETH_P_DNA_RT,dna_rt)
561         __ADD(ETH_P_LAT,lat)
562         __ADD(ETH_P_DIAG,diag)
563         __ADD(ETH_P_CUST,cust)
564         __ADD(ETH_P_SCA,sca)
565         __ADD(ETH_P_RARP,rarp)
566         __ADD(ETH_P_ATALK,atalk)
567         __ADD(ETH_P_AARP,aarp)
568 #ifdef ETH_P_8021Q
569         __ADD(ETH_P_8021Q,802.1q)
570 #endif
571         __ADD(ETH_P_IPX,ipx)
572         __ADD(ETH_P_IPV6,ipv6)
573 #ifdef ETH_P_WCCP
574         __ADD(ETH_P_WCCP,wccp)
575 #endif
576         __ADD(ETH_P_PPP_DISC,ppp_disc)
577         __ADD(ETH_P_PPP_SES,ppp_ses)
578         __ADD(ETH_P_MPLS_UC,mpls_uc)
579         __ADD(ETH_P_MPLS_MC,mpls_mc)
580         __ADD(ETH_P_ATMMPOA,atmmpoa)
581         __ADD(ETH_P_ATMFATE,atmfate)
582         __ADD(ETH_P_EDP2,edp2)
583         __ADD(ETH_P_802_3,802.3)
584         __ADD(ETH_P_AX25,ax25)
585         __ADD(ETH_P_ALL,all)
586         __ADD(ETH_P_802_2,802.2)
587         __ADD(ETH_P_SNAP,snap)
588         __ADD(ETH_P_DDCMP,ddcmp)
589         __ADD(ETH_P_WAN_PPP,wan_ppp)
590         __ADD(ETH_P_PPP_MP,ppp_mp)
591         __ADD(ETH_P_LOCALTALK,localtalk)
592         __ADD(ETH_P_PPPTALK,ppptalk)
593         __ADD(ETH_P_TR_802_2,tr_802.2)
594         __ADD(ETH_P_MOBITEX,mobitex)
595         __ADD(ETH_P_CONTROL,control)
596         __ADD(ETH_P_IRDA,irda)
597         __ADD(ETH_P_ECONET,econet)
598         __ADD(ETH_P_HDLC,hdlc)
599 };
600
601 /**
602  * Convert a ethernet protocol to a character string (Reentrant).
603  * @arg eproto          ethernet protocol
604  * @arg buf             destination buffer
605  * @arg len             buffer length
606  *
607  * Converts a ethernet protocol to a character string and stores
608  * it in the specified destination buffer.
609  *
610  * @return The destination buffer or the type encoded in hexidecimal
611  *         form if no match was found.
612  */
613 char *nl_ether_proto2str(int eproto, char *buf, size_t len)
614 {
615         return __type2str(eproto, buf, len, ether_protos,
616                             ARRAY_SIZE(ether_protos));
617 }
618
619 /**
620  * Convert a character string to a ethernet protocol
621  * @arg name            name of ethernet protocol
622  *
623  * Converts the provided character string specifying a ethernet
624  * protocl to the corresponding numeric value.
625  *
626  * @return ethernet protocol or a negative value if none was found.
627  */
628 int nl_str2ether_proto(const char *name)
629 {
630         return __str2type(name, ether_protos, ARRAY_SIZE(ether_protos));
631 }
632
633 /** @} */
634
635 /** @} */