libnl  3.3.0
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-2012 Thomas Graf <tgraf@suug.ch>
10  */
11 
12 /**
13  * @ingroup core
14  * @defgroup utils Utilities
15  *
16  * Collection of helper functions
17  *
18  * @{
19  *
20  * Header
21  * ------
22  * ~~~~{.c}
23  * #include <netlink/utils.h>
24  * ~~~~
25  */
26 
27 #include <netlink-private/netlink.h>
28 #include <netlink-private/utils.h>
29 #include <netlink/netlink.h>
30 #include <netlink/utils.h>
31 #include <linux/socket.h>
32 #include <stdlib.h> /* exit() */
33 #ifdef HAVE_STRERROR_L
34 #include <locale.h>
35 #endif
36 
37 /**
38  * Global variable indicating the desired level of debugging output.
39  *
40  * Level | Messages Printed
41  * ----- | ---------------------------------------------------------
42  * 0 | Debugging output disabled
43  * 1 | Warnings, important events and notifications
44  * 2 | More or less important debugging messages
45  * 3 | Repetitive events causing a flood of debugging messages
46  * 4 | Even less important messages
47  *
48  * If available, the variable will be initialized to the value of the
49  * environment variable `NLDBG`. The default value is 0 (disabled).
50  *
51  * For more information, see section @core_doc{_debugging, Debugging}.
52  */
53 int nl_debug = 0;
54 
55 /** @cond SKIP */
56 #ifdef NL_DEBUG
57 struct nl_dump_params nl_debug_dp = {
59 };
60 
61 static void __init nl_debug_init(void)
62 {
63  char *nldbg, *end;
64 
65  if ((nldbg = getenv("NLDBG"))) {
66  long level = strtol(nldbg, &end, 0);
67  if (nldbg != end)
68  nl_debug = level;
69  }
70 
71  nl_debug_dp.dp_fd = stderr;
72 }
73 #endif
74 
75 int __nl_read_num_str_file(const char *path, int (*cb)(long, const char *))
76 {
77  FILE *fd;
78  char buf[128];
79 
80  fd = fopen(path, "re");
81  if (fd == NULL)
82  return -nl_syserr2nlerr(errno);
83 
84  while (fgets(buf, sizeof(buf), fd)) {
85  int goodlen, err;
86  long num;
87  char *end;
88 
89  if (*buf == '#' || *buf == '\n' || *buf == '\r')
90  continue;
91 
92  num = strtol(buf, &end, 0);
93  if (end == buf) {
94  fclose(fd);
95  return -NLE_INVAL;
96  }
97 
98  if (num == LONG_MIN || num == LONG_MAX) {
99  fclose(fd);
100  return -NLE_RANGE;
101  }
102 
103  while (*end == ' ' || *end == '\t')
104  end++;
105 
106  goodlen = strcspn(end, "#\r\n\t ");
107  if (goodlen == 0) {
108  fclose(fd);
109  return -NLE_INVAL;
110  }
111 
112  end[goodlen] = '\0';
113 
114  err = cb(num, end);
115  if (err < 0) {
116  fclose(fd);
117  return err;
118  }
119  }
120 
121  fclose(fd);
122 
123  return 0;
124 }
125 
126 const char *nl_strerror_l(int err)
127 {
128  const char *buf;
129 #ifdef HAVE_STRERROR_L
130  int errno_save = errno;
131  locale_t loc = newlocale(LC_MESSAGES_MASK, "", (locale_t)0);
132 
133  if (loc == (locale_t)0) {
134  if (errno == ENOENT)
135  loc = newlocale(LC_MESSAGES_MASK,
136  "POSIX", (locale_t)0);
137  }
138  if (loc != (locale_t)0) {
139  buf = strerror_l(err, loc);
140  freelocale(loc);
141  } else {
142  buf = "newlocale() failed";
143  }
144 
145  errno = errno_save;
146 #else
147  buf = strerror(err);
148 #endif
149  return buf;
150 }
151 /** @endcond */
152 
153 /**
154  * @name Pretty Printing of Numbers
155  * @{
156  */
157 
158 /**
159  * Cancel down a byte counter
160  * @arg l byte counter
161  * @arg unit destination unit pointer
162  *
163  * Cancels down a byte counter until it reaches a reasonable
164  * unit. The chosen unit is assigned to \a unit.
165  * This function assume 1024 bytes in one kilobyte
166  *
167  * @return The cancelled down byte counter in the new unit.
168  */
169 double nl_cancel_down_bytes(unsigned long long l, char **unit)
170 {
171  if (l >= 1099511627776LL) {
172  *unit = "TiB";
173  return ((double) l) / 1099511627776LL;
174  } else if (l >= 1073741824) {
175  *unit = "GiB";
176  return ((double) l) / 1073741824;
177  } else if (l >= 1048576) {
178  *unit = "MiB";
179  return ((double) l) / 1048576;
180  } else if (l >= 1024) {
181  *unit = "KiB";
182  return ((double) l) / 1024;
183  } else {
184  *unit = "B";
185  return (double) l;
186  }
187 }
188 
189 /**
190  * Cancel down a bit counter
191  * @arg l bit counter
192  * @arg unit destination unit pointer
193  *
194  * Cancels down bit counter until it reaches a reasonable
195  * unit. The chosen unit is assigned to \a unit.
196  * This function assume 1000 bits in one kilobit
197  *
198  * @return The cancelled down bit counter in the new unit.
199  */
200 double nl_cancel_down_bits(unsigned long long l, char **unit)
201 {
202  if (l >= 1000000000000ULL) {
203  *unit = "Tbit";
204  return ((double) l) / 1000000000000ULL;
205  }
206 
207  if (l >= 1000000000) {
208  *unit = "Gbit";
209  return ((double) l) / 1000000000;
210  }
211 
212  if (l >= 1000000) {
213  *unit = "Mbit";
214  return ((double) l) / 1000000;
215  }
216 
217  if (l >= 1000) {
218  *unit = "Kbit";
219  return ((double) l) / 1000;
220  }
221 
222  *unit = "bit";
223  return (double) l;
224 }
225 
226 int nl_rate2str(unsigned long long rate, int type, char *buf, size_t len)
227 {
228  char *unit;
229  double frac;
230 
231  switch (type) {
232  case NL_BYTE_RATE:
233  frac = nl_cancel_down_bytes(rate, &unit);
234  break;
235 
236  case NL_BIT_RATE:
237  frac = nl_cancel_down_bits(rate, &unit);
238  break;
239 
240  default:
241  BUG();
242  }
243 
244  return snprintf(buf, len, "%.2f%s/s", frac, unit);
245 }
246 
247 /**
248  * Cancel down a micro second value
249  * @arg l micro seconds
250  * @arg unit destination unit pointer
251  *
252  * Cancels down a microsecond counter until it reaches a
253  * reasonable unit. The chosen unit is assigned to \a unit.
254  *
255  * @return The cancelled down microsecond in the new unit
256  */
257 double nl_cancel_down_us(uint32_t l, char **unit)
258 {
259  if (l >= 1000000) {
260  *unit = "s";
261  return ((double) l) / 1000000;
262  } else if (l >= 1000) {
263  *unit = "ms";
264  return ((double) l) / 1000;
265  } else {
266  *unit = "us";
267  return (double) l;
268  }
269 }
270 
271 /** @} */
272 
273 /**
274  * @name Generic Unit Translations
275  * @{
276  */
277 
278 /**
279  * Convert a character string to a size
280  * @arg str size encoded as character string
281  *
282  * Converts the specified size as character to the corresponding
283  * number of bytes.
284  *
285  * Supported formats are:
286  * - b,kb/k,m/mb,gb/g for bytes
287  * - bit,kbit/mbit/gbit
288  *
289  * This function assume 1000 bits in one kilobit and
290  * 1024 bytes in one kilobyte
291  *
292  * @return The number of bytes or -1 if the string is unparseable
293  */
294 long nl_size2int(const char *str)
295 {
296  char *p;
297  long l = strtol(str, &p, 0);
298  if (p == str)
299  return -NLE_INVAL;
300 
301  if (*p) {
302  if (!strcasecmp(p, "kb") || !strcasecmp(p, "k"))
303  l *= 1024;
304  else if (!strcasecmp(p, "gb") || !strcasecmp(p, "g"))
305  l *= 1024*1024*1024;
306  else if (!strcasecmp(p, "gbit"))
307  l *= 1000000000L/8;
308  else if (!strcasecmp(p, "mb") || !strcasecmp(p, "m"))
309  l *= 1024*1024;
310  else if (!strcasecmp(p, "mbit"))
311  l *= 1000000/8;
312  else if (!strcasecmp(p, "kbit"))
313  l *= 1000/8;
314  else if (!strcasecmp(p, "bit"))
315  l /= 8;
316  else if (strcasecmp(p, "b") != 0)
317  return -NLE_INVAL;
318  }
319 
320  return l;
321 }
322 
323 static const struct {
324  double limit;
325  const char *unit;
326 } size_units[] = {
327  { 1024. * 1024. * 1024. * 1024. * 1024., "EiB" },
328  { 1024. * 1024. * 1024. * 1024., "TiB" },
329  { 1024. * 1024. * 1024., "GiB" },
330  { 1024. * 1024., "MiB" },
331  { 1024., "KiB" },
332  { 0., "B" },
333 };
334 
335 /**
336  * Convert a size toa character string
337  * @arg size Size in number of bytes
338  * @arg buf Buffer to write character string to
339  * @arg len Size of buf
340  *
341  * This function converts a value in bytes to a human readable representation
342  * of it. The function uses IEC prefixes:
343  *
344  * @code
345  * 1024 bytes => 1 KiB
346  * 1048576 bytes => 1 MiB
347  * @endcode
348  *
349  * The highest prefix is used which ensures a result of >= 1.0, the result
350  * is provided as floating point number with a maximum precision of 2 digits:
351  * @code
352  * 965176 bytes => 942.55 KiB
353  * @endcode
354  *
355  * @return pointer to buf
356  */
357 char *nl_size2str(const size_t size, char *buf, const size_t len)
358 {
359  size_t i;
360 
361  if (size == 0) {
362  snprintf(buf, len, "0B");
363  return buf;
364  }
365 
366  for (i = 0; i < ARRAY_SIZE(size_units); i++) {
367  if (size >= size_units[i].limit) {
368  snprintf(buf, len, "%.2g%s",
369  (double) size / size_units[i].limit,
370  size_units[i].unit);
371  return buf;
372  }
373  }
374 
375  BUG();
376 }
377 
378 /**
379  * Convert a character string to a probability
380  * @arg str probability encoded as character string
381  *
382  * Converts the specified probability as character to the
383  * corresponding probability number.
384  *
385  * Supported formats are:
386  * - 0.0-1.0
387  * - 0%-100%
388  *
389  * @return The probability relative to NL_PROB_MIN and NL_PROB_MAX
390  */
391 long nl_prob2int(const char *str)
392 {
393  char *p;
394  double d = strtod(str, &p);
395 
396  if (p == str)
397  return -NLE_INVAL;
398 
399  if (d > 1.0)
400  d /= 100.0f;
401 
402  if (d > 1.0f || d < 0.0f)
403  return -NLE_RANGE;
404 
405  if (*p && strcmp(p, "%") != 0)
406  return -NLE_INVAL;
407 
408  return (long) (((d * NL_PROB_MAX) + 0.5));
409 }
410 
411 /** @} */
412 
413 /**
414  * @name Time Translations
415  * @{
416  */
417 
418 #ifndef USER_HZ
419 #define USER_HZ 100
420 #endif
421 
422 static uint32_t user_hz = USER_HZ;
423 static uint32_t psched_hz = USER_HZ;
424 
425 static double ticks_per_usec = 1.0f;
426 
427 /* Retrieves the configured HZ and ticks/us value in the kernel.
428  * The value is cached. Supported ways of getting it:
429  *
430  * 1) environment variable
431  * 2) /proc/net/psched and sysconf
432  *
433  * Supports the environment variables:
434  * PROC_NET_PSCHED - may point to psched file in /proc
435  * PROC_ROOT - may point to /proc fs */
436 static void get_psched_settings(void)
437 {
438  char name[FILENAME_MAX];
439  FILE *fd;
440  int got_hz = 0;
441  static volatile int initialized = 0;
442  const char *ev;
443  NL_LOCK(mutex);
444 
445  if (initialized == 1)
446  return;
447 
448  nl_lock(&mutex);
449 
450  if (initialized == 1)
451  return;
452 
453  if ((ev = getenv("HZ"))) {
454  long hz = strtol(ev, NULL, 0);
455 
456  if (LONG_MIN != hz && LONG_MAX != hz) {
457  user_hz = hz;
458  got_hz = 1;
459  }
460  }
461 
462  if (!got_hz)
463  user_hz = sysconf(_SC_CLK_TCK);
464 
465  psched_hz = user_hz;
466 
467  if ((ev = getenv("TICKS_PER_USEC"))) {
468  double t = strtod(ev, NULL);
469  ticks_per_usec = t;
470  }
471  else {
472  if ((ev = getenv("PROC_NET_PSCHED")))
473  snprintf(name, sizeof(name), "%s", ev);
474  else if ((ev = getenv("PROC_ROOT")))
475  snprintf(name, sizeof(name), "%s/net/psched", ev);
476  else
477  strncpy(name, "/proc/net/psched", sizeof(name) - 1);
478 
479  if ((fd = fopen(name, "re"))) {
480  unsigned int ns_per_usec, ns_per_tick, nom, denom;
481 
482  if (fscanf(fd, "%08x %08x %08x %08x",
483  &ns_per_usec, &ns_per_tick, &nom, &denom) != 4) {
484  NL_DBG(1, "Fatal error: can not read psched settings from \"%s\". " \
485  "Try to set TICKS_PER_USEC, PROC_NET_PSCHED or PROC_ROOT " \
486  "environment variables\n", name);
487  exit(1);
488  }
489 
490  ticks_per_usec = (double) ns_per_usec /
491  (double) ns_per_tick;
492 
493  if (nom == 1000000)
494  psched_hz = denom;
495 
496  fclose(fd);
497  }
498  }
499  initialized = 1;
500 
501  nl_unlock(&mutex);
502 }
503 
504 
505 /**
506  * Return the value of HZ
507  */
508 int nl_get_user_hz(void)
509 {
510  get_psched_settings();
511  return user_hz;
512 }
513 
514 /**
515  * Return the value of packet scheduler HZ
516  */
518 {
519  get_psched_settings();
520  return psched_hz;
521 }
522 
523 /**
524  * Convert micro seconds to ticks
525  * @arg us micro seconds
526  * @return number of ticks
527  */
528 uint32_t nl_us2ticks(uint32_t us)
529 {
530  get_psched_settings();
531  return us * ticks_per_usec;
532 }
533 
534 
535 /**
536  * Convert ticks to micro seconds
537  * @arg ticks number of ticks
538  * @return microseconds
539  */
540 uint32_t nl_ticks2us(uint32_t ticks)
541 {
542  get_psched_settings();
543  return ticks / ticks_per_usec;
544 }
545 
546 int nl_str2msec(const char *str, uint64_t *result)
547 {
548  uint64_t total = 0, l;
549  int plen;
550  char *p;
551 
552  do {
553  l = strtoul(str, &p, 0);
554  if (p == str)
555  return -NLE_INVAL;
556  else if (*p) {
557  plen = strcspn(p, " \t");
558 
559  if (!plen)
560  total += l;
561  else if (!strncasecmp(p, "sec", plen))
562  total += (l * 1000);
563  else if (!strncasecmp(p, "min", plen))
564  total += (l * 1000*60);
565  else if (!strncasecmp(p, "hour", plen))
566  total += (l * 1000*60*60);
567  else if (!strncasecmp(p, "day", plen))
568  total += (l * 1000*60*60*24);
569  else
570  return -NLE_INVAL;
571 
572  str = p + plen;
573  } else
574  total += l;
575  } while (*str && *p);
576 
577  *result = total;
578 
579  return 0;
580 }
581 
582 /**
583  * Convert milliseconds to a character string
584  * @arg msec number of milliseconds
585  * @arg buf destination buffer
586  * @arg len buffer length
587  *
588  * Converts milliseconds to a character string split up in days, hours,
589  * minutes, seconds, and milliseconds and stores it in the specified
590  * destination buffer.
591  *
592  * @return The destination buffer.
593  */
594 char * nl_msec2str(uint64_t msec, char *buf, size_t len)
595 {
596  uint64_t split[5];
597  size_t i;
598  static const char *units[5] = {"d", "h", "m", "s", "msec"};
599  char * const buf_orig = buf;
600 
601  if (msec == 0) {
602  snprintf(buf, len, "0msec");
603  return buf_orig;
604  }
605 
606 #define _SPLIT(idx, unit) if ((split[idx] = msec / unit)) msec %= unit
607  _SPLIT(0, 86400000); /* days */
608  _SPLIT(1, 3600000); /* hours */
609  _SPLIT(2, 60000); /* minutes */
610  _SPLIT(3, 1000); /* seconds */
611 #undef _SPLIT
612  split[4] = msec;
613 
614  for (i = 0; i < ARRAY_SIZE(split) && len; i++) {
615  int l;
616  if (split[i] == 0)
617  continue;
618  l = snprintf(buf, len, "%s%" PRIu64 "%s",
619  (buf==buf_orig) ? "" : " ", split[i], units[i]);
620  buf += l;
621  len -= l;
622  }
623 
624  return buf_orig;
625 }
626 
627 /** @} */
628 
629 /**
630  * @name Netlink Family Translations
631  * @{
632  */
633 
634 static const struct trans_tbl nlfamilies[] = {
635  __ADD(NETLINK_ROUTE,route),
636  __ADD(NETLINK_USERSOCK,usersock),
637  __ADD(NETLINK_FIREWALL,firewall),
638  __ADD(NETLINK_INET_DIAG,inetdiag),
639  __ADD(NETLINK_NFLOG,nflog),
640  __ADD(NETLINK_XFRM,xfrm),
641  __ADD(NETLINK_SELINUX,selinux),
642  __ADD(NETLINK_ISCSI,iscsi),
643  __ADD(NETLINK_AUDIT,audit),
644  __ADD(NETLINK_FIB_LOOKUP,fib_lookup),
645  __ADD(NETLINK_CONNECTOR,connector),
646  __ADD(NETLINK_NETFILTER,netfilter),
647  __ADD(NETLINK_IP6_FW,ip6_fw),
648  __ADD(NETLINK_DNRTMSG,dnrtmsg),
649  __ADD(NETLINK_KOBJECT_UEVENT,kobject_uevent),
650  __ADD(NETLINK_GENERIC,generic),
651  __ADD(NETLINK_SCSITRANSPORT,scsitransport),
652  __ADD(NETLINK_ECRYPTFS,ecryptfs),
653  __ADD(NETLINK_RDMA,rdma),
654  __ADD(NETLINK_CRYPTO,crypto),
655 };
656 
657 char * nl_nlfamily2str(int family, char *buf, size_t size)
658 {
659  return __type2str(family, buf, size, nlfamilies,
660  ARRAY_SIZE(nlfamilies));
661 }
662 
663 int nl_str2nlfamily(const char *name)
664 {
665  return __str2type(name, nlfamilies, ARRAY_SIZE(nlfamilies));
666 }
667 
668 /**
669  * @}
670  */
671 
672 /**
673  * @name Link Layer Protocol Translations
674  * @{
675  */
676 
677 static const struct trans_tbl llprotos[] = {
678  {0, "generic"},
679  __ADD(ARPHRD_NETROM,netrom),
680  __ADD(ARPHRD_ETHER,ether),
681  __ADD(ARPHRD_EETHER,eether),
682  __ADD(ARPHRD_AX25,ax25),
683  __ADD(ARPHRD_PRONET,pronet),
684  __ADD(ARPHRD_CHAOS,chaos),
685  __ADD(ARPHRD_IEEE802,ieee802),
686  __ADD(ARPHRD_ARCNET,arcnet),
687  __ADD(ARPHRD_APPLETLK,atalk),
688  __ADD(ARPHRD_DLCI,dlci),
689  __ADD(ARPHRD_ATM,atm),
690  __ADD(ARPHRD_METRICOM,metricom),
691  __ADD(ARPHRD_IEEE1394,ieee1394),
692  __ADD(ARPHRD_EUI64,eui64),
693  __ADD(ARPHRD_INFINIBAND,infiniband),
694  __ADD(ARPHRD_SLIP,slip),
695  __ADD(ARPHRD_CSLIP,cslip),
696  __ADD(ARPHRD_SLIP6,slip6),
697  __ADD(ARPHRD_CSLIP6,cslip6),
698  __ADD(ARPHRD_RSRVD,rsrvd),
699  __ADD(ARPHRD_ADAPT,adapt),
700  __ADD(ARPHRD_ROSE,rose),
701  __ADD(ARPHRD_X25,x25),
702  __ADD(ARPHRD_HWX25,hwx25),
703  __ADD(ARPHRD_CAN,can),
704  __ADD(ARPHRD_PPP,ppp),
705  __ADD(ARPHRD_CISCO,cisco),
706  __ADD(ARPHRD_HDLC,hdlc),
707  __ADD(ARPHRD_LAPB,lapb),
708  __ADD(ARPHRD_DDCMP,ddcmp),
709  __ADD(ARPHRD_RAWHDLC,rawhdlc),
710  __ADD(ARPHRD_TUNNEL,ipip),
711  __ADD(ARPHRD_TUNNEL6,tunnel6),
712  __ADD(ARPHRD_FRAD,frad),
713  __ADD(ARPHRD_SKIP,skip),
714  __ADD(ARPHRD_LOOPBACK,loopback),
715  __ADD(ARPHRD_LOCALTLK,localtlk),
716  __ADD(ARPHRD_FDDI,fddi),
717  __ADD(ARPHRD_BIF,bif),
718  __ADD(ARPHRD_SIT,sit),
719  __ADD(ARPHRD_IPDDP,ip/ddp),
720  __ADD(ARPHRD_IPGRE,gre),
721  __ADD(ARPHRD_PIMREG,pimreg),
722  __ADD(ARPHRD_HIPPI,hippi),
723  __ADD(ARPHRD_ASH,ash),
724  __ADD(ARPHRD_ECONET,econet),
725  __ADD(ARPHRD_IRDA,irda),
726  __ADD(ARPHRD_FCPP,fcpp),
727  __ADD(ARPHRD_FCAL,fcal),
728  __ADD(ARPHRD_FCPL,fcpl),
729  __ADD(ARPHRD_FCFABRIC,fcfb_0),
730  __ADD(ARPHRD_FCFABRIC+1,fcfb_1),
731  __ADD(ARPHRD_FCFABRIC+2,fcfb_2),
732  __ADD(ARPHRD_FCFABRIC+3,fcfb_3),
733  __ADD(ARPHRD_FCFABRIC+4,fcfb_4),
734  __ADD(ARPHRD_FCFABRIC+5,fcfb_5),
735  __ADD(ARPHRD_FCFABRIC+6,fcfb_6),
736  __ADD(ARPHRD_FCFABRIC+7,fcfb_7),
737  __ADD(ARPHRD_FCFABRIC+8,fcfb_8),
738  __ADD(ARPHRD_FCFABRIC+9,fcfb_9),
739  __ADD(ARPHRD_FCFABRIC+10,fcfb_10),
740  __ADD(ARPHRD_FCFABRIC+11,fcfb_11),
741  __ADD(ARPHRD_FCFABRIC+12,fcfb_12),
742  __ADD(ARPHRD_IEEE802_TR,tr),
743  __ADD(ARPHRD_IEEE80211,ieee802.11),
744  __ADD(ARPHRD_IEEE80211_PRISM,ieee802.11_prism),
745  __ADD(ARPHRD_IEEE80211_RADIOTAP,ieee802.11_radiotap),
746  __ADD(ARPHRD_IEEE802154,ieee802.15.4),
747  __ADD(ARPHRD_IEEE802154_MONITOR,ieee802.15.4_monitor),
748  __ADD(ARPHRD_PHONET,phonet),
749  __ADD(ARPHRD_PHONET_PIPE,phonet_pipe),
750  __ADD(ARPHRD_CAIF,caif),
751  __ADD(ARPHRD_IP6GRE,ip6gre),
752  __ADD(ARPHRD_NETLINK,netlink),
753  __ADD(ARPHRD_6LOWPAN,6lowpan),
754  __ADD(ARPHRD_VOID,void),
755  __ADD(ARPHRD_NONE,nohdr),
756 };
757 
758 char * nl_llproto2str(int llproto, char *buf, size_t len)
759 {
760  return __type2str(llproto, buf, len, llprotos, ARRAY_SIZE(llprotos));
761 }
762 
763 int nl_str2llproto(const char *name)
764 {
765  return __str2type(name, llprotos, ARRAY_SIZE(llprotos));
766 }
767 
768 /** @} */
769 
770 
771 /**
772  * @name Ethernet Protocol Translations
773  * @{
774  */
775 
776 static const struct trans_tbl ether_protos[] = {
777  __ADD(ETH_P_LOOP,loop),
778  __ADD(ETH_P_PUP,pup),
779  __ADD(ETH_P_PUPAT,pupat),
780  __ADD(ETH_P_IP,ip),
781  __ADD(ETH_P_X25,x25),
782  __ADD(ETH_P_ARP,arp),
783  __ADD(ETH_P_BPQ,bpq),
784  __ADD(ETH_P_IEEEPUP,ieeepup),
785  __ADD(ETH_P_IEEEPUPAT,ieeepupat),
786  __ADD(ETH_P_DEC,dec),
787  __ADD(ETH_P_DNA_DL,dna_dl),
788  __ADD(ETH_P_DNA_RC,dna_rc),
789  __ADD(ETH_P_DNA_RT,dna_rt),
790  __ADD(ETH_P_LAT,lat),
791  __ADD(ETH_P_DIAG,diag),
792  __ADD(ETH_P_CUST,cust),
793  __ADD(ETH_P_SCA,sca),
794  __ADD(ETH_P_TEB,teb),
795  __ADD(ETH_P_RARP,rarp),
796  __ADD(ETH_P_ATALK,atalk),
797  __ADD(ETH_P_AARP,aarp),
798 #ifdef ETH_P_8021Q
799  __ADD(ETH_P_8021Q,802.1q),
800 #endif
801  __ADD(ETH_P_IPX,ipx),
802  __ADD(ETH_P_IPV6,ipv6),
803  __ADD(ETH_P_PAUSE,pause),
804  __ADD(ETH_P_SLOW,slow),
805 #ifdef ETH_P_WCCP
806  __ADD(ETH_P_WCCP,wccp),
807 #endif
808  __ADD(ETH_P_PPP_DISC,ppp_disc),
809  __ADD(ETH_P_PPP_SES,ppp_ses),
810  __ADD(ETH_P_MPLS_UC,mpls_uc),
811  __ADD(ETH_P_MPLS_MC,mpls_mc),
812  __ADD(ETH_P_ATMMPOA,atmmpoa),
813  __ADD(ETH_P_LINK_CTL,link_ctl),
814  __ADD(ETH_P_ATMFATE,atmfate),
815  __ADD(ETH_P_PAE,pae),
816  __ADD(ETH_P_AOE,aoe),
817  __ADD(ETH_P_TIPC,tipc),
818  __ADD(ETH_P_1588,ieee1588),
819  __ADD(ETH_P_FCOE,fcoe),
820  __ADD(ETH_P_FIP,fip),
821  __ADD(ETH_P_EDSA,edsa),
822  __ADD(ETH_P_EDP2,edp2),
823  __ADD(ETH_P_802_3,802.3),
824  __ADD(ETH_P_AX25,ax25),
825  __ADD(ETH_P_ALL,all),
826  __ADD(ETH_P_802_2,802.2),
827  __ADD(ETH_P_SNAP,snap),
828  __ADD(ETH_P_DDCMP,ddcmp),
829  __ADD(ETH_P_WAN_PPP,wan_ppp),
830  __ADD(ETH_P_PPP_MP,ppp_mp),
831  __ADD(ETH_P_LOCALTALK,localtalk),
832  __ADD(ETH_P_CAN,can),
833  __ADD(ETH_P_PPPTALK,ppptalk),
834  __ADD(ETH_P_TR_802_2,tr_802.2),
835  __ADD(ETH_P_MOBITEX,mobitex),
836  __ADD(ETH_P_CONTROL,control),
837  __ADD(ETH_P_IRDA,irda),
838  __ADD(ETH_P_ECONET,econet),
839  __ADD(ETH_P_HDLC,hdlc),
840  __ADD(ETH_P_ARCNET,arcnet),
841  __ADD(ETH_P_DSA,dsa),
842  __ADD(ETH_P_TRAILER,trailer),
843  __ADD(ETH_P_PHONET,phonet),
844  __ADD(ETH_P_IEEE802154,ieee802154),
845  __ADD(ETH_P_CAIF,caif),
846 };
847 
848 char *nl_ether_proto2str(int eproto, char *buf, size_t len)
849 {
850  return __type2str(eproto, buf, len, ether_protos,
851  ARRAY_SIZE(ether_protos));
852 }
853 
854 int nl_str2ether_proto(const char *name)
855 {
856  return __str2type(name, ether_protos, ARRAY_SIZE(ether_protos));
857 }
858 
859 /** @} */
860 
861 /**
862  * @name IP Protocol Translations
863  * @{
864  */
865 
866 char *nl_ip_proto2str(int proto, char *buf, size_t len)
867 {
868  struct protoent *p = getprotobynumber(proto);
869 
870  if (p) {
871  snprintf(buf, len, "%s", p->p_name);
872  return buf;
873  }
874 
875  snprintf(buf, len, "0x%x", proto);
876  return buf;
877 }
878 
879 int nl_str2ip_proto(const char *name)
880 {
881  struct protoent *p = getprotobyname(name);
882  unsigned long l;
883  char *end;
884 
885  if (p)
886  return p->p_proto;
887 
888  l = strtoul(name, &end, 0);
889  if (l == ULONG_MAX || *end != '\0')
890  return -NLE_OBJ_NOTFOUND;
891 
892  return (int) l;
893 }
894 
895 /** @} */
896 
897 /**
898  * @name Dumping Helpers
899  * @{
900  */
901 
902 /**
903  * Handle a new line while dumping
904  * @arg params Dumping parameters
905  *
906  * This function must be called before dumping any onto a
907  * new line. It will ensure proper prefixing as specified
908  * by the dumping parameters.
909  *
910  * @note This function will NOT dump any newlines itself
911  */
912 void nl_new_line(struct nl_dump_params *params)
913 {
914  params->dp_line++;
915 
916  if (params->dp_prefix) {
917  int i;
918  for (i = 0; i < params->dp_prefix; i++) {
919  if (params->dp_fd)
920  fprintf(params->dp_fd, " ");
921  else if (params->dp_buf)
922  strncat(params->dp_buf, " ",
923  params->dp_buflen -
924  strlen(params->dp_buf) - 1);
925  }
926  }
927 
928  if (params->dp_nl_cb)
929  params->dp_nl_cb(params, params->dp_line);
930 }
931 
932 static void dump_one(struct nl_dump_params *parms, const char *fmt,
933  va_list args)
934 {
935  if (parms->dp_fd)
936  vfprintf(parms->dp_fd, fmt, args);
937  else if (parms->dp_buf || parms->dp_cb) {
938  char *buf = NULL;
939  if (vasprintf(&buf, fmt, args) >= 0) {
940  if (parms->dp_cb)
941  parms->dp_cb(parms, buf);
942  else
943  strncat(parms->dp_buf, buf,
944  parms->dp_buflen -
945  strlen(parms->dp_buf) - 1);
946  free(buf);
947  }
948  }
949 }
950 
951 
952 /**
953  * Dump a formatted character string
954  * @arg params Dumping parameters
955  * @arg fmt printf style formatting string
956  * @arg ... Arguments to formatting string
957  *
958  * Dumps a printf style formatting string to the output device
959  * as specified by the dumping parameters.
960  */
961 void nl_dump(struct nl_dump_params *params, const char *fmt, ...)
962 {
963  va_list args;
964 
965  va_start(args, fmt);
966  dump_one(params, fmt, args);
967  va_end(args);
968 }
969 
970 void nl_dump_line(struct nl_dump_params *parms, const char *fmt, ...)
971 {
972  va_list args;
973 
974  nl_new_line(parms);
975 
976  va_start(args, fmt);
977  dump_one(parms, fmt, args);
978  va_end(args);
979 }
980 
981 
982 /** @} */
983 
984 /** @cond SKIP */
985 
986 int __trans_list_add(int i, const char *a, struct nl_list_head *head)
987 {
988  struct trans_list *tl;
989 
990  tl = calloc(1, sizeof(*tl));
991  if (!tl)
992  return -NLE_NOMEM;
993 
994  tl->i = i;
995  tl->a = strdup(a);
996 
997  nl_list_add_tail(&tl->list, head);
998 
999  return 0;
1000 }
1001 
1002 void __trans_list_clear(struct nl_list_head *head)
1003 {
1004  struct trans_list *tl, *next;
1005 
1006  nl_list_for_each_entry_safe(tl, next, head, list) {
1007  free(tl->a);
1008  free(tl);
1009  }
1010 
1011  nl_init_list_head(head);
1012 }
1013 
1014 char *__type2str(int type, char *buf, size_t len,
1015  const struct trans_tbl *tbl, size_t tbl_len)
1016 {
1017  size_t i;
1018  for (i = 0; i < tbl_len; i++) {
1019  if (tbl[i].i == type) {
1020  snprintf(buf, len, "%s", tbl[i].a);
1021  return buf;
1022  }
1023  }
1024 
1025  snprintf(buf, len, "0x%x", type);
1026  return buf;
1027 }
1028 
1029 char *__list_type2str(int type, char *buf, size_t len,
1030  struct nl_list_head *head)
1031 {
1032  struct trans_list *tl;
1033 
1034  nl_list_for_each_entry(tl, head, list) {
1035  if (tl->i == type) {
1036  snprintf(buf, len, "%s", tl->a);
1037  return buf;
1038  }
1039  }
1040 
1041  snprintf(buf, len, "0x%x", type);
1042  return buf;
1043 }
1044 
1045 char *__flags2str(int flags, char *buf, size_t len,
1046  const struct trans_tbl *tbl, size_t tbl_len)
1047 {
1048  size_t i;
1049  int tmp = flags;
1050 
1051  memset(buf, 0, len);
1052 
1053  for (i = 0; i < tbl_len; i++) {
1054  if (tbl[i].i & tmp) {
1055  tmp &= ~tbl[i].i;
1056  strncat(buf, tbl[i].a, len - strlen(buf) - 1);
1057  if ((tmp & flags))
1058  strncat(buf, ",", len - strlen(buf) - 1);
1059  }
1060  }
1061 
1062  return buf;
1063 }
1064 
1065 int __str2type(const char *buf, const struct trans_tbl *tbl, size_t tbl_len)
1066 {
1067  unsigned long l;
1068  char *end;
1069  size_t i;
1070 
1071  if (*buf == '\0')
1072  return -NLE_INVAL;
1073 
1074  for (i = 0; i < tbl_len; i++)
1075  if (!strcasecmp(tbl[i].a, buf))
1076  return tbl[i].i;
1077 
1078  l = strtoul(buf, &end, 0);
1079  if (l == ULONG_MAX || *end != '\0')
1080  return -NLE_OBJ_NOTFOUND;
1081 
1082  return (int) l;
1083 }
1084 
1085 int __list_str2type(const char *buf, struct nl_list_head *head)
1086 {
1087  struct trans_list *tl;
1088  unsigned long l;
1089  char *end;
1090 
1091  if (*buf == '\0')
1092  return -NLE_INVAL;
1093 
1094  nl_list_for_each_entry(tl, head, list) {
1095  if (!strcasecmp(tl->a, buf))
1096  return tl->i;
1097  }
1098 
1099  l = strtoul(buf, &end, 0);
1100  if (l == ULONG_MAX || *end != '\0')
1101  return -NLE_OBJ_NOTFOUND;
1102 
1103  return (int) l;
1104 }
1105 
1106 int __str2flags(const char *buf, const struct trans_tbl *tbl, size_t tbl_len)
1107 {
1108  int flags = 0;
1109  size_t i;
1110  size_t len; /* ptrdiff_t ? */
1111  char *p = (char *) buf, *t;
1112 
1113  for (;;) {
1114  if (*p == ' ')
1115  p++;
1116 
1117  t = strchr(p, ',');
1118  len = t ? t - p : strlen(p);
1119  for (i = 0; i < tbl_len; i++)
1120  if (len == strlen(tbl[i].a) &&
1121  !strncasecmp(tbl[i].a, p, len))
1122  flags |= tbl[i].i;
1123 
1124  if (!t)
1125  return flags;
1126 
1127  p = ++t;
1128  }
1129 
1130  return 0;
1131 }
1132 
1133 void dump_from_ops(struct nl_object *obj, struct nl_dump_params *params)
1134 {
1135  int type = params->dp_type;
1136 
1137  if (type < 0 || type > NL_DUMP_MAX)
1138  BUG();
1139 
1140  params->dp_line = 0;
1141 
1142  if (params->dp_dump_msgtype) {
1143 #if 0
1144  /* XXX */
1145  char buf[64];
1146 
1147  dp_dump_line(params, 0, "%s ",
1148  nl_cache_mngt_type2name(obj->ce_ops,
1149  obj->ce_ops->co_protocol,
1150  obj->ce_msgtype,
1151  buf, sizeof(buf)));
1152 #endif
1153  params->dp_pre_dump = 1;
1154  }
1155 
1156  if (obj->ce_ops->oo_dump[type])
1157  obj->ce_ops->oo_dump[type](obj, params);
1158 }
1159 
1160 /**
1161  * Check for library capabilities
1162  *
1163  * @arg capability capability identifier
1164  *
1165  * Check whether the loaded libnl library supports a certain capability.
1166  * This is useful so that applications can workaround known issues of
1167  * libnl that are fixed in newer library versions, without
1168  * having a hard dependency on the new version. It is also useful, for
1169  * capabilities that cannot easily be detected using autoconf tests.
1170  * The capabilities are integer constants with name NL_CAPABILITY_*.
1171  *
1172  * As this function is intended to detect capabilities at runtime,
1173  * you might not want to depend during compile time on the NL_CAPABILITY_*
1174  * names. Instead you can use their numeric values which are guaranteed not to
1175  * change meaning.
1176  *
1177  * @return non zero if libnl supports a certain capability, 0 otherwise.
1178  **/
1179 int nl_has_capability (int capability)
1180 {
1181  static const uint8_t caps[ ( NL_CAPABILITY_MAX + 7 ) / 8 ] = {
1182 #define _NL_ASSERT(expr) ( 0 * sizeof(struct { unsigned int x: ( (!!(expr)) ? 1 : -1 ); }) )
1183 #define _NL_SETV(i, r, v) \
1184  ( _NL_ASSERT( (v) == 0 || (i) * 8 + (r) == (v) - 1 ) + \
1185  ( (v) == 0 ? 0 : (1 << (r)) ) )
1186 #define _NL_SET(i, v0, v1, v2, v3, v4, v5, v6, v7) \
1187  [(i)] = ( \
1188  _NL_SETV((i), 0, (v0)) | _NL_SETV((i), 4, (v4)) | \
1189  _NL_SETV((i), 1, (v1)) | _NL_SETV((i), 5, (v5)) | \
1190  _NL_SETV((i), 2, (v2)) | _NL_SETV((i), 6, (v6)) | \
1191  _NL_SETV((i), 3, (v3)) | _NL_SETV((i), 7, (v7)) )
1192  _NL_SET(0,
1194  NL_CAPABILITY_ROUTE_LINK_VETH_GET_PEER_OWN_REFERENCE,
1195  NL_CAPABILITY_ROUTE_LINK_CLS_ADD_ACT_OWN_REFERENCE,
1196  NL_CAPABILITY_NL_CONNECT_RETRY_GENERATE_PORT_ON_ADDRINUSE,
1197  NL_CAPABILITY_ROUTE_LINK_GET_KERNEL_FAIL_OPNOTSUPP,
1198  NL_CAPABILITY_ROUTE_ADDR_COMPARE_CACHEINFO,
1199  NL_CAPABILITY_VERSION_3_2_26,
1200  NL_CAPABILITY_NL_RECV_FAIL_TRUNC_NO_PEEK),
1201  _NL_SET(1,
1202  NL_CAPABILITY_LINK_BUILD_CHANGE_REQUEST_SET_CHANGE,
1203  NL_CAPABILITY_RTNL_NEIGH_GET_FILTER_AF_UNSPEC_FIX,
1204  NL_CAPABILITY_VERSION_3_2_27,
1205  NL_CAPABILITY_RTNL_LINK_VLAN_PROTOCOL_SERIALZE,
1206  NL_CAPABILITY_RTNL_LINK_PARSE_GRE_REMOTE,
1207  NL_CAPABILITY_RTNL_LINK_VLAN_INGRESS_MAP_CLEAR,
1208  NL_CAPABILITY_RTNL_LINK_VXLAN_IO_COMPARE,
1209  NL_CAPABILITY_NL_OBJECT_DIFF64),
1210  _NL_SET (2,
1211  NL_CAPABILITY_XFRM_SA_KEY_SIZE,
1212  NL_CAPABILITY_RTNL_ADDR_PEER_FIX,
1213  NL_CAPABILITY_VERSION_3_2_28,
1214  NL_CAPABILITY_RTNL_ADDR_PEER_ID_FIX,
1215  NL_CAPABILITY_NL_ADDR_FILL_SOCKADDR,
1216  NL_CAPABILITY_XFRM_SEC_CTX_LEN,
1217  NL_CAPABILITY_LINK_BUILD_ADD_REQUEST_SET_CHANGE,
1218  NL_CAPABILITY_NL_RECVMSGS_PEEK_BY_DEFAULT),
1219  _NL_SET (3,
1220  NL_CAPABILITY_VERSION_3_2_29,
1221  NL_CAPABILITY_XFRM_SP_SEC_CTX_LEN,
1222  NL_CAPABILITY_VERSION_3_3_0,
1223  0,
1224  0,
1225  0,
1226  0,
1227  0),
1228  /* IMPORTANT: these capability numbers are intended to be universal and stable
1229  * for libnl3. Don't allocate new numbers on your own that differ from upstream
1230  * libnl3.
1231  *
1232  * Instead register a capability number upstream too. We will take patches
1233  * for that. We especially take patches to register a capability number that is
1234  * only implemented in your fork of libnl3.
1235  *
1236  * If you really don't want that, use capabilities in the range 0x7000 to 0x7FFF.
1237  * (NL_CAPABILITY_IS_USER_RESERVED). Upstream libnl3 will not register conflicting
1238  * capabilities in that range.
1239  *
1240  * Obviously, only backport capability numbers to libnl versions that actually
1241  * implement that capability as well. */
1242 #undef _NL_SET
1243 #undef _NL_SETV
1244 #undef _NL_ASSERT
1245  };
1246 
1247  if (capability <= 0 || capability > NL_CAPABILITY_MAX)
1248  return 0;
1249  capability--;
1250  return (caps[capability / 8] & (1 << (capability % 8))) != 0;
1251 }
1252 
1253 /** @endcond */
1254 
1255 /** @} */
int nl_get_user_hz(void)
Return the value of HZ.
Definition: utils.c:508
void nl_new_line(struct nl_dump_params *params)
Handle a new line while dumping.
Definition: utils.c:912
char * dp_buf
Alternatively the output may be redirected into a buffer.
Definition: types.h:88
FILE * dp_fd
File descriptor the dumping output should go to.
Definition: types.h:83
void(* dp_cb)(struct nl_dump_params *, char *)
A callback invoked for output.
Definition: types.h:63
long nl_size2int(const char *str)
Convert a character string to a size.
Definition: utils.c:294
double nl_cancel_down_bits(unsigned long long l, char **unit)
Cancel down a bit counter.
Definition: utils.c:200
enum nl_dump_type dp_type
Specifies the type of dump that is requested.
Definition: types.h:38
char * nl_msec2str(uint64_t msec, char *buf, size_t len)
Convert milliseconds to a character string.
Definition: utils.c:594
#define NL_PROB_MAX
Upper probability limit nl_dump_type.
Definition: utils.h:37
Dump all attributes but no statistics.
Definition: types.h:23
char * nl_size2str(const size_t size, char *buf, const size_t len)
Convert a size toa character string.
Definition: utils.c:357
void(* dp_nl_cb)(struct nl_dump_params *, int)
A callback invoked for every new line, can be used to customize the indentation.
Definition: types.h:73
rtnl_route_build_msg() no longer guesses the route scope if explicitly set to RT_SCOPE_NOWHERE.
Definition: utils.h:90
double nl_cancel_down_bytes(unsigned long long l, char **unit)
Cancel down a byte counter.
Definition: utils.c:169
int dp_pre_dump
PRIVATE Set if a dump was performed prior to the actual dump handler.
Definition: types.h:99
double nl_cancel_down_us(uint32_t l, char **unit)
Cancel down a micro second value.
Definition: utils.c:257
int nl_get_psched_hz(void)
Return the value of packet scheduler HZ.
Definition: utils.c:517
uint32_t nl_ticks2us(uint32_t ticks)
Convert ticks to micro seconds.
Definition: utils.c:540
long nl_prob2int(const char *str)
Convert a character string to a probability.
Definition: utils.c:391
int dp_prefix
Specifies the number of whitespaces to be put in front of every new line (indentation).
Definition: types.h:44
uint32_t nl_us2ticks(uint32_t us)
Convert micro seconds to ticks.
Definition: utils.c:528
Dumping parameters.
Definition: types.h:33
size_t dp_buflen
Length of the buffer dp_buf.
Definition: types.h:93
void nl_dump(struct nl_dump_params *params, const char *fmt,...)
Dump a formatted character string.
Definition: utils.c:961
int nl_debug
Global variable indicating the desired level of debugging output.
Definition: utils.c:53
int dp_dump_msgtype
Causes each element to be prefixed with the message type.
Definition: types.h:54