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