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