2 * lib/utils.c Utility Functions
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
9 * Copyright (c) 2003-2006 Thomas Graf <tgraf@suug.ch>
13 * @defgroup utils Utilities
17 #include <netlink-local.h>
18 #include <netlink/netlink.h>
19 #include <netlink/utils.h>
20 #include <linux/socket.h>
27 struct nl_dump_params nl_debug_dp = {
28 .dp_type = NL_DUMP_FULL,
31 static void __init nl_debug_init(void)
35 if ((nldbg = getenv("NLDBG"))) {
36 long level = strtol(nldbg, &end, 0);
41 nl_debug_dp.dp_fd = stderr;
45 * @name Error Code Helpers
53 int __nl_error(int err, const char *file, unsigned int line, const char *func,
68 vasprintf(&user_err, fmt, args);
73 asprintf(&errbuf, "%s:%u:%s: %s (errno = %s)",
74 file, line, func, fmt ? user_err : "", strerror(err));
76 asprintf(&errbuf, "%s (errno = %s)",
77 fmt ? user_err : "", strerror(err));
86 int __nl_read_num_str_file(const char *path, int (*cb)(long, const char *))
91 fd = fopen(path, "r");
93 return nl_error(errno, "Unable to open file %s for reading",
96 while (fgets(buf, sizeof(buf), fd)) {
101 if (*buf == '#' || *buf == '\n' || *buf == '\r')
104 num = strtol(buf, &end, 0);
106 return nl_error(EINVAL, "Parsing error");
108 if (num == LONG_MIN || num == LONG_MAX)
109 return nl_error(errno, "Number of out range");
111 while (*end == ' ' || *end == '\t')
114 goodlen = strcspn(end, "#\r\n\t ");
116 return nl_error(EINVAL, "Empty string");
132 int nl_get_errno(void)
139 * Return error message for an error code
140 * @return error message
142 char *nl_geterror(void)
148 return strerror(nlerrno);
154 * Print a libnl error message
155 * @arg s error message prefix
157 * Prints the error message of the call that failed last.
159 * If s is not NULL and *s is not a null byte the argument
160 * string is printed, followed by a colon and a blank. Then
161 * the error message and a new-line.
163 void nl_perror(const char *s)
166 fprintf(stderr, "%s: %s\n", s, nl_geterror());
168 fprintf(stderr, "%s\n", nl_geterror());
174 * @name Unit Pretty-Printing
179 * Cancel down a byte counter
180 * @arg l byte counter
181 * @arg unit destination unit pointer
183 * Cancels down a byte counter until it reaches a reasonable
184 * unit. The chosen unit is assigned to \a unit.
186 * @return The cancelled down byte counter in the new unit.
188 double nl_cancel_down_bytes(unsigned long long l, char **unit)
190 if (l >= 1099511627776LL) {
192 return ((double) l) / 1099511627776LL;
193 } else if (l >= 1073741824) {
195 return ((double) l) / 1073741824;
196 } else if (l >= 1048576) {
198 return ((double) l) / 1048576;
199 } else if (l >= 1024) {
201 return ((double) l) / 1024;
209 * Cancel down a bit counter
211 * @arg unit destination unit pointer
213 * Cancels downa bit counter until it reaches a reasonable
214 * unit. The chosen unit is assigned to \a unit.
216 * @return The cancelled down bit counter in the new unit.
218 double nl_cancel_down_bits(unsigned long long l, char **unit)
220 if (l >= 1099511627776ULL) {
222 return ((double) l) / 1099511627776ULL;
223 } else if (l >= 1073741824) {
225 return ((double) l) / 1073741824;
226 } else if (l >= 1048576) {
228 return ((double) l) / 1048576;
229 } else if (l >= 1024) {
231 return ((double) l) / 1024;
240 * Cancel down a micro second value
241 * @arg l micro seconds
242 * @arg unit destination unit pointer
244 * Cancels down a microsecond counter until it reaches a
245 * reasonable unit. The chosen unit is assigned to \a unit.
247 * @return The cancelled down microsecond in the new unit
249 double nl_cancel_down_us(uint32_t l, char **unit)
253 return ((double) l) / 1000000;
254 } else if (l >= 1000) {
256 return ((double) l) / 1000;
266 * @name Generic Unit Translations
271 * Convert a character string to a size
272 * @arg str size encoded as character string
274 * Converts the specified size as character to the corresponding
277 * Supported formats are:
278 * - b,kb/k,m/mb,gb/g for bytes
279 * - bit,kbit/mbit/gbit
281 * @return The number of bytes or -1 if the string is unparseable
283 long nl_size2int(const char *str)
286 long l = strtol(str, &p, 0);
291 if (!strcasecmp(p, "kb") || !strcasecmp(p, "k"))
293 else if (!strcasecmp(p, "gb") || !strcasecmp(p, "g"))
295 else if (!strcasecmp(p, "gbit"))
296 l *= 1024*1024*1024/8;
297 else if (!strcasecmp(p, "mb") || !strcasecmp(p, "m"))
299 else if (!strcasecmp(p, "mbit"))
301 else if (!strcasecmp(p, "kbit"))
303 else if (!strcasecmp(p, "bit"))
305 else if (strcasecmp(p, "b") != 0)
313 * Convert a character string to a probability
314 * @arg str probability encoded as character string
316 * Converts the specified probability as character to the
317 * corresponding probability number.
319 * Supported formats are:
323 * @return The probability relative to NL_PROB_MIN and NL_PROB_MAX
325 long nl_prob2int(const char *str)
328 double d = strtod(str, &p);
336 if (d > 1.0f || d < 0.0f)
339 if (*p && strcmp(p, "%") != 0)
342 return rint(d * NL_PROB_MAX);
348 * @name Time Translations
353 static uint32_t user_hz = USER_HZ;
355 static uint32_t user_hz = 100;
358 static double ticks_per_usec = 1.0f;
360 /* Retrieves the configured HZ and ticks/us value in the kernel.
361 * The value is cached. Supported ways of getting it:
363 * 1) environment variable
364 * 2) /proc/net/psched and sysconf
366 * Supports the environment variables:
367 * PROC_NET_PSCHED - may point to psched file in /proc
368 * PROC_ROOT - may point to /proc fs */
369 static void __init get_psched_settings(void)
371 char name[FILENAME_MAX];
373 int got_hz = 0, got_tick = 0;
376 long hz = strtol(getenv("HZ"), NULL, 0);
378 if (LONG_MIN != hz && LONG_MAX != hz) {
385 user_hz = sysconf(_SC_CLK_TCK);
387 if (getenv("TICKS_PER_USEC")) {
388 double t = strtod(getenv("TICKS_PER_USEC"), NULL);
395 if (getenv("PROC_NET_PSCHED"))
396 snprintf(name, sizeof(name), "%s", getenv("PROC_NET_PSCHED"));
397 else if (getenv("PROC_ROOT"))
398 snprintf(name, sizeof(name), "%s/net/psched",
399 getenv("PROC_ROOT"));
401 strncpy(name, "/proc/net/psched", sizeof(name) - 1);
403 if ((fd = fopen(name, "r"))) {
404 uint32_t tick, us, nom;
405 int r = fscanf(fd, "%08x%08x%08x%*08x", &tick, &us, &nom);
407 if (4 == r && nom == 1000000 && !got_tick)
408 ticks_per_usec = (double)tick/(double)us;
416 * Return the value of HZ
425 * Convert micro seconds to ticks
426 * @arg us micro seconds
427 * @return number of ticks
429 uint32_t nl_us2ticks(uint32_t us)
431 return us * ticks_per_usec;
436 * Convert ticks to micro seconds
437 * @arg ticks number of ticks
438 * @return microseconds
440 uint32_t nl_ticks2us(uint32_t ticks)
442 return ticks / ticks_per_usec;
445 long nl_time2int(const char *str)
448 long l = strtol(str, &p, 0);
453 if (!strcasecmp(p, "min") == 0 || !strcasecmp(p, "m"))
455 else if (!strcasecmp(p, "hour") || !strcasecmp(p, "h"))
457 else if (!strcasecmp(p, "day") || !strcasecmp(p, "d"))
459 else if (strcasecmp(p, "s") != 0)
467 * Convert milliseconds to a character string
468 * @arg msec number of milliseconds
469 * @arg buf destination buffer
470 * @arg len buffer length
472 * Converts milliseconds to a character string split up in days, hours,
473 * minutes, seconds, and milliseconds and stores it in the specified
474 * destination buffer.
476 * @return The destination buffer.
478 char * nl_msec2str(uint64_t msec, char *buf, size_t len)
481 char *units[] = {"d", "h", "m", "s", "msec"};
483 #define _SPLIT(idx, unit) if ((split[idx] = msec / unit) > 0) msec %= unit
484 _SPLIT(0, 86400000); /* days */
485 _SPLIT(1, 3600000); /* hours */
486 _SPLIT(2, 60000); /* minutes */
487 _SPLIT(3, 1000); /* seconds */
493 for (i = 0; i < ARRAY_SIZE(split); i++) {
496 snprintf(t, sizeof(t), "%s%d%s",
497 strlen(buf) ? " " : "", split[i], units[i]);
498 strncat(buf, t, len - strlen(buf) - 1);
508 * @name Link Layer Protocol Translations
512 static struct trans_tbl llprotos[] = {
514 __ADD(ARPHRD_ETHER,ether)
515 __ADD(ARPHRD_EETHER,eether)
516 __ADD(ARPHRD_AX25,ax25)
517 __ADD(ARPHRD_PRONET,pronet)
518 __ADD(ARPHRD_CHAOS,chaos)
519 __ADD(ARPHRD_IEEE802,ieee802)
520 __ADD(ARPHRD_ARCNET,arcnet)
521 __ADD(ARPHRD_APPLETLK,atalk)
522 __ADD(ARPHRD_DLCI,dlci)
523 __ADD(ARPHRD_ATM,atm)
524 __ADD(ARPHRD_METRICOM,metricom)
525 __ADD(ARPHRD_IEEE1394,ieee1394)
527 __ADD(ARPHRD_EUI64,eui64)
529 __ADD(ARPHRD_INFINIBAND,infiniband)
530 __ADD(ARPHRD_SLIP,slip)
531 __ADD(ARPHRD_CSLIP,cslip)
532 __ADD(ARPHRD_SLIP6,slip6)
533 __ADD(ARPHRD_CSLIP6,cslip6)
534 __ADD(ARPHRD_RSRVD,rsrvd)
535 __ADD(ARPHRD_ADAPT,adapt)
536 __ADD(ARPHRD_ROSE,rose)
537 __ADD(ARPHRD_X25,x25)
539 __ADD(ARPHRD_HWX25,hwx25)
541 __ADD(ARPHRD_PPP,ppp)
542 __ADD(ARPHRD_HDLC,hdlc)
543 __ADD(ARPHRD_LAPB,lapb)
544 __ADD(ARPHRD_DDCMP,ddcmp)
545 __ADD(ARPHRD_RAWHDLC,rawhdlc)
546 __ADD(ARPHRD_TUNNEL,ipip)
547 __ADD(ARPHRD_TUNNEL6,tunnel6)
548 __ADD(ARPHRD_FRAD,frad)
549 __ADD(ARPHRD_SKIP,skip)
550 __ADD(ARPHRD_LOOPBACK,loopback)
551 __ADD(ARPHRD_LOCALTLK,localtlk)
552 __ADD(ARPHRD_FDDI,fddi)
553 __ADD(ARPHRD_BIF,bif)
554 __ADD(ARPHRD_SIT,sit)
555 __ADD(ARPHRD_IPDDP,ip/ddp)
556 __ADD(ARPHRD_IPGRE,gre)
557 __ADD(ARPHRD_PIMREG,pimreg)
558 __ADD(ARPHRD_HIPPI,hippi)
559 __ADD(ARPHRD_ASH,ash)
560 __ADD(ARPHRD_ECONET,econet)
561 __ADD(ARPHRD_IRDA,irda)
562 __ADD(ARPHRD_FCPP,fcpp)
563 __ADD(ARPHRD_FCAL,fcal)
564 __ADD(ARPHRD_FCPL,fcpl)
565 __ADD(ARPHRD_FCFABRIC,fcfb_0)
566 __ADD(ARPHRD_FCFABRIC+1,fcfb_1)
567 __ADD(ARPHRD_FCFABRIC+2,fcfb_2)
568 __ADD(ARPHRD_FCFABRIC+3,fcfb_3)
569 __ADD(ARPHRD_FCFABRIC+4,fcfb_4)
570 __ADD(ARPHRD_FCFABRIC+5,fcfb_5)
571 __ADD(ARPHRD_FCFABRIC+6,fcfb_6)
572 __ADD(ARPHRD_FCFABRIC+7,fcfb_7)
573 __ADD(ARPHRD_FCFABRIC+8,fcfb_8)
574 __ADD(ARPHRD_FCFABRIC+9,fcfb_9)
575 __ADD(ARPHRD_FCFABRIC+10,fcfb_10)
576 __ADD(ARPHRD_FCFABRIC+11,fcfb_11)
577 __ADD(ARPHRD_FCFABRIC+12,fcfb_12)
578 __ADD(ARPHRD_IEEE802_TR,tr)
579 __ADD(ARPHRD_IEEE80211,ieee802.11)
580 #ifdef ARPHRD_IEEE80211_PRISM
581 __ADD(ARPHRD_IEEE80211_PRISM, ieee802.11_prism)
584 __ADD(ARPHRD_VOID,void)
588 char * nl_llproto2str(int llproto, char *buf, size_t len)
590 return __type2str(llproto, buf, len, llprotos, ARRAY_SIZE(llprotos));
593 int nl_str2llproto(const char *name)
595 return __str2type(name, llprotos, ARRAY_SIZE(llprotos));
602 * @name Ethernet Protocol Translations
606 static struct trans_tbl ether_protos[] = {
607 __ADD(ETH_P_LOOP,loop)
609 __ADD(ETH_P_PUPAT,pupat)
614 __ADD(ETH_P_IEEEPUP,ieeepup)
615 __ADD(ETH_P_IEEEPUPAT,ieeepupat)
617 __ADD(ETH_P_DNA_DL,dna_dl)
618 __ADD(ETH_P_DNA_RC,dna_rc)
619 __ADD(ETH_P_DNA_RT,dna_rt)
621 __ADD(ETH_P_DIAG,diag)
622 __ADD(ETH_P_CUST,cust)
624 __ADD(ETH_P_RARP,rarp)
625 __ADD(ETH_P_ATALK,atalk)
626 __ADD(ETH_P_AARP,aarp)
628 __ADD(ETH_P_8021Q,802.1q)
631 __ADD(ETH_P_IPV6,ipv6)
633 __ADD(ETH_P_WCCP,wccp)
635 __ADD(ETH_P_PPP_DISC,ppp_disc)
636 __ADD(ETH_P_PPP_SES,ppp_ses)
637 __ADD(ETH_P_MPLS_UC,mpls_uc)
638 __ADD(ETH_P_MPLS_MC,mpls_mc)
639 __ADD(ETH_P_ATMMPOA,atmmpoa)
640 __ADD(ETH_P_ATMFATE,atmfate)
641 __ADD(ETH_P_EDP2,edp2)
642 __ADD(ETH_P_802_3,802.3)
643 __ADD(ETH_P_AX25,ax25)
645 __ADD(ETH_P_802_2,802.2)
646 __ADD(ETH_P_SNAP,snap)
647 __ADD(ETH_P_DDCMP,ddcmp)
648 __ADD(ETH_P_WAN_PPP,wan_ppp)
649 __ADD(ETH_P_PPP_MP,ppp_mp)
650 __ADD(ETH_P_LOCALTALK,localtalk)
651 __ADD(ETH_P_PPPTALK,ppptalk)
652 __ADD(ETH_P_TR_802_2,tr_802.2)
653 __ADD(ETH_P_MOBITEX,mobitex)
654 __ADD(ETH_P_CONTROL,control)
655 __ADD(ETH_P_IRDA,irda)
656 __ADD(ETH_P_ECONET,econet)
657 __ADD(ETH_P_HDLC,hdlc)
660 char *nl_ether_proto2str(int eproto, char *buf, size_t len)
662 return __type2str(eproto, buf, len, ether_protos,
663 ARRAY_SIZE(ether_protos));
666 int nl_str2ether_proto(const char *name)
668 return __str2type(name, ether_protos, ARRAY_SIZE(ether_protos));
674 * @name IP Protocol Translations
678 char *nl_ip_proto2str(int proto, char *buf, size_t len)
680 struct protoent *p = getprotobynumber(proto);
683 snprintf(buf, len, "%s", p->p_name);
687 snprintf(buf, len, "0x%x", proto);
691 int nl_str2ip_proto(const char *name)
693 struct protoent *p = getprotobyname(name);
700 l = strtoul(name, &end, 0);
701 if (l == ULONG_MAX || *end != '\0')
710 * @name Dumping Helpers
715 * Handle a new line while dumping
716 * @arg params Dumping parameters
717 * @arg line Number of lines dumped already.
719 * This function must be called before dumping any onto a
720 * new line. It will ensure proper prefixing as specified
721 * by the dumping parameters.
723 * @note This function will NOT dump any newlines itself
725 void nl_new_line(struct nl_dump_params *params, int line)
727 if (params->dp_prefix) {
729 for (i = 0; i < params->dp_prefix; i++) {
731 fprintf(params->dp_fd, " ");
732 else if (params->dp_buf)
733 strncat(params->dp_buf, " ",
735 sizeof(params->dp_buf) - 1);
739 if (params->dp_nl_cb)
740 params->dp_nl_cb(params, line);
744 * Dump a formatted character string
745 * @arg params Dumping parameters
746 * @arg fmt printf style formatting string
747 * @arg ... Arguments to formatting string
749 * Dumps a printf style formatting string to the output device
750 * as specified by the dumping parameters.
752 void nl_dump(struct nl_dump_params *params, const char *fmt, ...)
757 __dp_dump(params, fmt, args);