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