xref: /illumos-gate/usr/src/lib/libdladm/common/libdladm.c (revision 8c0b080c8ed055a259d8cd26b9f005211c6a9753)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 /*
26  * Copyright (c) 2015, Joyent, Inc.
27  * Copyright 2020 Peter Tribble.
28  * Copyright 2022 OmniOS Community Edition (OmniOSce) Association.
29  */
30 
31 #include <unistd.h>
32 #include <errno.h>
33 #include <ctype.h>
34 #include <fcntl.h>
35 #include <strings.h>
36 #include <dirent.h>
37 #include <stdlib.h>
38 #include <assert.h>
39 #include <stdio.h>
40 #include <stdarg.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <sys/param.h>
44 #include <sys/stat.h>
45 #include <sys/dld.h>
46 #include <sys/dld_ioc.h>
47 #include <libdladm_impl.h>
48 #include <libintl.h>
49 #include <libdlpi.h>
50 #include <libdllink.h>
51 
52 static char	dladm_rootdir[MAXPATHLEN] = "/";
53 
54 typedef struct media_type_desc {
55 	uint32_t	media_type;
56 #define	MAX_MEDIA_TYPE_STRING	32
57 	const char	media_type_str[MAX_MEDIA_TYPE_STRING];
58 } media_type_t;
59 
60 static media_type_t media_type_table[] =  {
61 	{ DL_ETHER,	"Ethernet" },
62 	{ DL_WIFI,	"WiFi" },
63 	{ DL_IB,	"Infiniband" },
64 	{ DL_IPV4,	"IPv4Tunnel" },
65 	{ DL_IPV6,	"IPv6Tunnel" },
66 	{ DL_6TO4,	"6to4Tunnel" },
67 	{ DL_CSMACD,	"CSMA/CD" },
68 	{ DL_TPB,	"TokenBus" },
69 	{ DL_TPR,	"TokenRing" },
70 	{ DL_METRO,	"MetroNet" },
71 	{ DL_HDLC,	"HDLC" },
72 	{ DL_CHAR,	"SyncCharacter" },
73 	{ DL_CTCA,	"CTCA" },
74 	{ DL_FDDI,	"FDDI" },
75 	{ DL_FC,	"FiberChannel" },
76 	{ DL_ATM,	"ATM" },
77 	{ DL_IPATM,	"ATM(ClassicIP)" },
78 	{ DL_X25,	"X.25" },
79 	{ DL_IPX25,	"X.25(ClassicIP)" },
80 	{ DL_ISDN,	"ISDN" },
81 	{ DL_HIPPI,	"HIPPI" },
82 	{ DL_100VG,	"100BaseVGEthernet" },
83 	{ DL_100VGTPR,	"100BaseVGTokenRing" },
84 	{ DL_ETH_CSMA,	"IEEE802.3" },
85 	{ DL_100BT,	"100BaseT" },
86 	{ DL_FRAME,	"FrameRelay" },
87 	{ DL_MPFRAME,	"MPFrameRelay" },
88 	{ DL_ASYNC,	"AsyncCharacter" },
89 	{ DL_IPNET,	"IPNET" },
90 	{ DL_OTHER,	"Other" }
91 };
92 #define	MEDIATYPECOUNT	(sizeof (media_type_table) / sizeof (media_type_t))
93 
94 typedef struct {
95 	uint32_t	lp_type;
96 	char		*lp_name;
97 } link_protect_t;
98 
99 static link_protect_t link_protect_types[] = {
100 	{ MPT_MACNOSPOOF, "mac-nospoof" },
101 	{ MPT_RESTRICTED, "restricted" },
102 	{ MPT_IPNOSPOOF, "ip-nospoof" },
103 	{ MPT_DHCPNOSPOOF, "dhcp-nospoof" }
104 };
105 #define	LPTYPES	(sizeof (link_protect_types) / sizeof (link_protect_t))
106 
107 dladm_status_t
108 dladm_open(dladm_handle_t *handle)
109 {
110 	int dld_fd;
111 
112 	if (handle == NULL)
113 		return (DLADM_STATUS_BADARG);
114 
115 	if ((dld_fd = open(DLD_CONTROL_DEV, O_RDWR)) < 0)
116 		return (dladm_errno2status(errno));
117 
118 	/*
119 	 * Don't open DLMGMT_DOOR now.  dlmgmtd(8) is not able to
120 	 * open the door when the dladm handle is opened because the
121 	 * door hasn't been created yet at that time.  Thus, we must
122 	 * open it on-demand in dladm_door_fd().  Move the open()
123 	 * to dladm_door_fd() for all cases.
124 	 */
125 
126 	if ((*handle = malloc(sizeof (struct dladm_handle))) == NULL) {
127 		(void) close(dld_fd);
128 		return (DLADM_STATUS_NOMEM);
129 	}
130 
131 	(*handle)->dld_fd = dld_fd;
132 	(*handle)->door_fd = -1;
133 	(*handle)->dld_kcp = NULL;
134 
135 	return (DLADM_STATUS_OK);
136 }
137 
138 void
139 dladm_close(dladm_handle_t handle)
140 {
141 	if (handle != NULL) {
142 		(void) close(handle->dld_fd);
143 		if (handle->door_fd != -1)
144 			(void) close(handle->door_fd);
145 		if (handle->dld_kcp != NULL)
146 			(void) kstat_close(handle->dld_kcp);
147 		free(handle);
148 	}
149 }
150 
151 int
152 dladm_dld_fd(dladm_handle_t handle)
153 {
154 	return (handle->dld_fd);
155 }
156 
157 kstat_ctl_t *
158 dladm_dld_kcp(dladm_handle_t handle)
159 {
160 	if (handle->dld_kcp == NULL)
161 		handle->dld_kcp = kstat_open();
162 	return (handle->dld_kcp);
163 }
164 
165 /*
166  * If DLMGMT_DOOR hasn't been opened in the handle yet, open it.
167  */
168 dladm_status_t
169 dladm_door_fd(dladm_handle_t handle, int *door_fd)
170 {
171 	int fd;
172 
173 	if (handle->door_fd == -1) {
174 		if ((fd = open(DLMGMT_DOOR, O_RDONLY)) < 0)
175 			return (dladm_errno2status(errno));
176 		handle->door_fd = fd;
177 	}
178 	*door_fd = handle->door_fd;
179 
180 	return (DLADM_STATUS_OK);
181 }
182 
183 const char *
184 dladm_status2str(dladm_status_t status, char *buf)
185 {
186 	const char	*s;
187 
188 	switch (status) {
189 	case DLADM_STATUS_OK:
190 		s = "ok";
191 		break;
192 	case DLADM_STATUS_BADARG:
193 		s = "invalid argument";
194 		break;
195 	case DLADM_STATUS_FAILED:
196 		s = "operation failed";
197 		break;
198 	case DLADM_STATUS_TOOSMALL:
199 		s = "buffer size too small";
200 		break;
201 	case DLADM_STATUS_NOTSUP:
202 		s = "operation not supported";
203 		break;
204 	case DLADM_STATUS_NOTFOUND:
205 		s = "object not found";
206 		break;
207 	case DLADM_STATUS_BADVAL:
208 		s = "invalid value";
209 		break;
210 	case DLADM_STATUS_NOMEM:
211 		s = "insufficient memory";
212 		break;
213 	case DLADM_STATUS_EXIST:
214 		s = "object already exists";
215 		break;
216 	case DLADM_STATUS_LINKINVAL:
217 		s = "invalid link";
218 		break;
219 	case DLADM_STATUS_PROPRDONLY:
220 		s = "read-only property";
221 		break;
222 	case DLADM_STATUS_BADVALCNT:
223 		s = "invalid number of values";
224 		break;
225 	case DLADM_STATUS_DBNOTFOUND:
226 		s = "database not found";
227 		break;
228 	case DLADM_STATUS_DENIED:
229 		s = "permission denied";
230 		break;
231 	case DLADM_STATUS_IOERR:
232 		s = "I/O error";
233 		break;
234 	case DLADM_STATUS_TEMPONLY:
235 		s = "change cannot be persistent";
236 		break;
237 	case DLADM_STATUS_TIMEDOUT:
238 		s = "operation timed out";
239 		break;
240 	case DLADM_STATUS_ISCONN:
241 		s = "already connected";
242 		break;
243 	case DLADM_STATUS_NOTCONN:
244 		s = "not connected";
245 		break;
246 	case DLADM_STATUS_REPOSITORYINVAL:
247 		s = "invalid configuration repository";
248 		break;
249 	case DLADM_STATUS_MACADDRINVAL:
250 		s = "invalid MAC address";
251 		break;
252 	case DLADM_STATUS_KEYINVAL:
253 		s = "invalid key";
254 		break;
255 	case DLADM_STATUS_INVALIDMACADDRLEN:
256 		s = "invalid MAC address length";
257 		break;
258 	case DLADM_STATUS_INVALIDMACADDRTYPE:
259 		s = "invalid MAC address type";
260 		break;
261 	case DLADM_STATUS_LINKBUSY:
262 		s = "link busy";
263 		break;
264 	case DLADM_STATUS_VIDINVAL:
265 		s = "invalid VLAN identifier";
266 		break;
267 	case DLADM_STATUS_TRYAGAIN:
268 		s = "try again later";
269 		break;
270 	case DLADM_STATUS_NONOTIF:
271 		s = "link notification is not supported";
272 		break;
273 	case DLADM_STATUS_BADTIMEVAL:
274 		s = "invalid time range";
275 		break;
276 	case DLADM_STATUS_INVALIDMACADDR:
277 		s = "invalid MAC address value";
278 		break;
279 	case DLADM_STATUS_INVALIDMACADDRNIC:
280 		s = "MAC address reserved for use by underlying data-link";
281 		break;
282 	case DLADM_STATUS_INVALIDMACADDRINUSE:
283 		s = "MAC address is already in use";
284 		break;
285 	case DLADM_STATUS_MACFACTORYSLOTINVALID:
286 		s = "invalid factory MAC address slot";
287 		break;
288 	case DLADM_STATUS_MACFACTORYSLOTUSED:
289 		s = "factory MAC address slot already used";
290 		break;
291 	case DLADM_STATUS_MACFACTORYSLOTALLUSED:
292 		s = "all factory MAC address slots are in use";
293 		break;
294 	case DLADM_STATUS_MACFACTORYNOTSUP:
295 		s = "factory MAC address slots not supported";
296 		break;
297 	case DLADM_STATUS_INVALIDMACPREFIX:
298 		s = "Invalid MAC address prefix value";
299 		break;
300 	case DLADM_STATUS_INVALIDMACPREFIXLEN:
301 		s = "Invalid MAC address prefix length";
302 		break;
303 	case DLADM_STATUS_BADCPUID:
304 		s = "non-existent processor ID";
305 		break;
306 	case DLADM_STATUS_CPUERR:
307 		s = "could not determine processor status";
308 		break;
309 	case DLADM_STATUS_CPUNOTONLINE:
310 		s = "processor not online";
311 		break;
312 	case DLADM_STATUS_TOOMANYELEMENTS:
313 		s = "too many elements specified";
314 		break;
315 	case DLADM_STATUS_BADRANGE:
316 		s = "invalid range";
317 		break;
318 	case DLADM_STATUS_DB_NOTFOUND:
319 		s = "database not found";
320 		break;
321 	case DLADM_STATUS_DB_PARSE_ERR:
322 		s = "database parse error";
323 		break;
324 	case DLADM_STATUS_PROP_PARSE_ERR:
325 		s = "property parse error";
326 		break;
327 	case DLADM_STATUS_ATTR_PARSE_ERR:
328 		s = "attribute parse error";
329 		break;
330 	case DLADM_STATUS_FLOW_DB_ERR:
331 		s = "flow database error";
332 		break;
333 	case DLADM_STATUS_FLOW_DB_OPEN_ERR:
334 		s = "flow database open error";
335 		break;
336 	case DLADM_STATUS_FLOW_DB_PARSE_ERR:
337 		s = "flow database parse error";
338 		break;
339 	case DLADM_STATUS_FLOWPROP_DB_PARSE_ERR:
340 		s = "flow property database parse error";
341 		break;
342 	case DLADM_STATUS_FLOW_ADD_ERR:
343 		s = "flow add error";
344 		break;
345 	case DLADM_STATUS_FLOW_WALK_ERR:
346 		s = "flow walk error";
347 		break;
348 	case DLADM_STATUS_FLOW_IDENTICAL:
349 		s = "a flow with identical attributes exists";
350 		break;
351 	case DLADM_STATUS_FLOW_INCOMPATIBLE:
352 		s = "flow(s) with incompatible attributes exists";
353 		break;
354 	case DLADM_STATUS_FLOW_EXISTS:
355 		s = "link still has flows";
356 		break;
357 	case DLADM_STATUS_PERSIST_FLOW_EXISTS:
358 		s = "persistent flow with the same name exists";
359 		break;
360 	case DLADM_STATUS_INVALID_IP:
361 		s = "invalid IP address";
362 		break;
363 	case DLADM_STATUS_INVALID_PREFIXLEN:
364 		s = "invalid IP prefix length";
365 		break;
366 	case DLADM_STATUS_INVALID_PROTOCOL:
367 		s = "invalid IP protocol";
368 		break;
369 	case DLADM_STATUS_INVALID_PORT:
370 		s = "invalid port number";
371 		break;
372 	case DLADM_STATUS_INVALID_DSF:
373 		s = "invalid dsfield";
374 		break;
375 	case DLADM_STATUS_INVALID_DSFMASK:
376 		s = "invalid dsfield mask";
377 		break;
378 	case DLADM_STATUS_INVALID_MACMARGIN:
379 		s = "MTU check failed, use lower MTU or -f option";
380 		break;
381 	case DLADM_STATUS_BADPROP:
382 		s = "invalid property";
383 		break;
384 	case DLADM_STATUS_MINMAXBW:
385 		s = "minimum value for maxbw is 1200K";
386 		break;
387 	case DLADM_STATUS_NO_HWRINGS:
388 		s = "request hw rings failed";
389 		break;
390 	case DLADM_STATUS_PERMONLY:
391 		s = "change must be persistent";
392 		break;
393 	case DLADM_STATUS_OPTMISSING:
394 		s = "optional software not installed";
395 		break;
396 	case DLADM_STATUS_IPTUNTYPE:
397 		s = "invalid IP tunnel type";
398 		break;
399 	case DLADM_STATUS_IPTUNTYPEREQD:
400 		s = "IP tunnel type required";
401 		break;
402 	case DLADM_STATUS_BADIPTUNLADDR:
403 		s = "invalid local IP tunnel address";
404 		break;
405 	case DLADM_STATUS_BADIPTUNRADDR:
406 		s = "invalid remote IP tunnel address";
407 		break;
408 	case DLADM_STATUS_ADDRINUSE:
409 		s = "address already in use";
410 		break;
411 	case DLADM_STATUS_POOLCPU:
412 		s = "pool and cpus property are mutually exclusive";
413 		break;
414 	case DLADM_STATUS_INVALID_PORT_INSTANCE:
415 		s = "invalid IB phys link";
416 		break;
417 	case DLADM_STATUS_PORT_IS_DOWN:
418 		s = "port is down";
419 		break;
420 	case DLADM_STATUS_PARTITION_EXISTS:
421 		s = "partition already exists";
422 		break;
423 	case DLADM_STATUS_PKEY_NOT_PRESENT:
424 		s = "PKEY is not present on the port";
425 		break;
426 	case DLADM_STATUS_INVALID_PKEY:
427 		s = "invalid PKEY";
428 		break;
429 	case DLADM_STATUS_NO_IB_HW_RESOURCE:
430 		s = "IB internal resource not available";
431 		break;
432 	case DLADM_STATUS_INVALID_PKEY_TBL_SIZE:
433 		s = "invalid PKEY table size";
434 		break;
435 	case DLADM_STATUS_PORT_NOPROTO:
436 		s = "local or remote port requires transport";
437 		break;
438 	case DLADM_STATUS_INVALID_MTU:
439 		s = "MTU check failed, MTU outside of device's supported range";
440 		break;
441 	case DLADM_STATUS_PERSIST_ON_TEMP:
442 		s = "can't create persistent object on top of temporary object";
443 		break;
444 	case DLADM_STATUS_BAD_ENCAP:
445 		s = "invalid encapsulation protocol";
446 		break;
447 	case DLADM_STATUS_ADDRNOTAVAIL:
448 		s = "can't assign requested address";
449 		break;
450 	default:
451 		s = "<unknown error>";
452 		break;
453 	}
454 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
455 	return (buf);
456 }
457 
458 /*
459  * Convert a unix errno to a dladm_status_t.
460  * We only convert errnos that are likely to be encountered. All others
461  * are mapped to DLADM_STATUS_FAILED.
462  */
463 dladm_status_t
464 dladm_errno2status(int err)
465 {
466 	switch (err) {
467 	case 0:
468 		return (DLADM_STATUS_OK);
469 	case EINVAL:
470 		return (DLADM_STATUS_BADARG);
471 	case EEXIST:
472 		return (DLADM_STATUS_EXIST);
473 	case ENOENT:
474 		return (DLADM_STATUS_NOTFOUND);
475 	case ENOSPC:
476 		return (DLADM_STATUS_TOOSMALL);
477 	case ENOMEM:
478 		return (DLADM_STATUS_NOMEM);
479 	case ENOTSUP:
480 		return (DLADM_STATUS_NOTSUP);
481 	case ENETDOWN:
482 		return (DLADM_STATUS_NONOTIF);
483 	case EACCES:
484 	case EPERM:
485 		return (DLADM_STATUS_DENIED);
486 	case EIO:
487 		return (DLADM_STATUS_IOERR);
488 	case EBUSY:
489 		return (DLADM_STATUS_LINKBUSY);
490 	case EAGAIN:
491 		return (DLADM_STATUS_TRYAGAIN);
492 	case ENOTEMPTY:
493 		return (DLADM_STATUS_FLOW_EXISTS);
494 	case EOPNOTSUPP:
495 		return (DLADM_STATUS_FLOW_INCOMPATIBLE);
496 	case EALREADY:
497 		return (DLADM_STATUS_FLOW_IDENTICAL);
498 	case EADDRINUSE:
499 		return (DLADM_STATUS_ADDRINUSE);
500 	case EADDRNOTAVAIL:
501 		return (DLADM_STATUS_ADDRNOTAVAIL);
502 	default:
503 		return (DLADM_STATUS_FAILED);
504 	}
505 }
506 
507 boolean_t
508 dladm_str2interval(char *oarg, uint32_t *interval)
509 {
510 	int		val;
511 	char		*endp = NULL;
512 
513 	errno = 0;
514 	val = strtol(oarg, &endp, 10);
515 	if (errno != 0 || val <= 0 || *endp != '\0')
516 		return (B_FALSE);
517 
518 	*interval = val;
519 
520 	return (B_TRUE);
521 }
522 
523 dladm_status_t
524 dladm_str2bw(char *oarg, uint64_t *bw)
525 {
526 	char		*endp = NULL;
527 	int64_t		n;
528 	int		mult = 1;
529 
530 	errno = 0;
531 	n = strtoull(oarg, &endp, 10);
532 
533 	if ((errno != 0) || (strlen(endp) > 1))
534 		return (DLADM_STATUS_BADARG);
535 
536 	if (n < 0)
537 		return (DLADM_STATUS_BADVAL);
538 
539 	switch (*endp) {
540 	case 'k':
541 	case 'K':
542 		mult = 1000;
543 		break;
544 	case 'm':
545 	case 'M':
546 	case '\0':
547 		mult = 1000000;
548 		break;
549 	case 'g':
550 	case 'G':
551 		mult = 1000000000;
552 		break;
553 	case '%':
554 		/*
555 		 * percentages not supported for now,
556 		 * see RFE 6540675
557 		 */
558 		return (DLADM_STATUS_NOTSUP);
559 	default:
560 		return (DLADM_STATUS_BADVAL);
561 	}
562 
563 	*bw = n * mult;
564 
565 	/* check for overflow */
566 	if (*bw / mult != n)
567 		return (DLADM_STATUS_BADARG);
568 
569 	return (DLADM_STATUS_OK);
570 }
571 
572 /*
573  * Convert bandwidth in bps to a string in Mbps.  For values greater
574  * than 1Mbps or 1000000, print a whole Mbps value.  For values that
575  * have fractional Mbps in whole Kbps, print the bandwidth in a manner
576  * similar to a floating point format.
577  *
578  *        bps       string
579  *          0            0
580  *        100            0
581  *       2000        0.002
582  *     431000        0.431
583  *    1000000            1
584  *    1030000        1.030
585  *  100000000          100
586  */
587 const char *
588 dladm_bw2str(int64_t bw, char *buf)
589 {
590 	int kbps, mbps;
591 
592 	kbps = (bw%1000000)/1000;
593 	mbps = bw/1000000;
594 	if (kbps != 0) {
595 		(void) snprintf(buf, DLADM_STRSIZE, "%5u.%03u", mbps, kbps);
596 	} else {
597 		(void) snprintf(buf, DLADM_STRSIZE, "%5u", mbps);
598 	}
599 
600 	return (buf);
601 }
602 
603 #define	LOCK_DB_PERMS	S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
604 
605 static int
606 i_dladm_lock_db(const char *lock_file, short type)
607 {
608 	int	lock_fd;
609 	struct	flock lock;
610 
611 	if ((lock_fd = open(lock_file, O_RDWR | O_CREAT | O_TRUNC,
612 	    LOCK_DB_PERMS)) < 0)
613 		return (-1);
614 
615 	lock.l_type = type;
616 	lock.l_whence = SEEK_SET;
617 	lock.l_start = 0;
618 	lock.l_len = 0;
619 
620 	if (fcntl(lock_fd, F_SETLKW, &lock) < 0) {
621 		int err = errno;
622 
623 		(void) close(lock_fd);
624 		(void) unlink(lock_file);
625 		errno = err;
626 		return (-1);
627 	}
628 	return (lock_fd);
629 }
630 
631 static void
632 i_dladm_unlock_db(const char *lock_file, int fd)
633 {
634 	struct flock lock;
635 
636 	if (fd < 0)
637 		return;
638 
639 	lock.l_type = F_UNLCK;
640 	lock.l_whence = SEEK_SET;
641 	lock.l_start = 0;
642 	lock.l_len = 0;
643 
644 	(void) fcntl(fd, F_SETLKW, &lock);
645 	(void) close(fd);
646 	(void) unlink(lock_file);
647 }
648 
649 /*
650  * Given a link class, returns its class string.
651  */
652 const char *
653 dladm_class2str(datalink_class_t class, char *buf)
654 {
655 	const char *s;
656 
657 	switch (class) {
658 	case DATALINK_CLASS_PHYS:
659 		s = "phys";
660 		break;
661 	case DATALINK_CLASS_VLAN:
662 		s = "vlan";
663 		break;
664 	case DATALINK_CLASS_AGGR:
665 		s = "aggr";
666 		break;
667 	case DATALINK_CLASS_VNIC:
668 		s = "vnic";
669 		break;
670 	case DATALINK_CLASS_ETHERSTUB:
671 		s = "etherstub";
672 		break;
673 	case DATALINK_CLASS_IPTUN:
674 		s = "iptun";
675 		break;
676 	case DATALINK_CLASS_SIMNET:
677 		s = "simnet";
678 		break;
679 	case DATALINK_CLASS_BRIDGE:
680 		s = "bridge";
681 		break;
682 	case DATALINK_CLASS_PART:
683 		s = "part";
684 		break;
685 	case DATALINK_CLASS_OVERLAY:
686 		s = "overlay";
687 		break;
688 	default:
689 		s = "unknown";
690 		break;
691 	}
692 
693 	(void) snprintf(buf, DLADM_STRSIZE, "%s", s);
694 	return (buf);
695 }
696 
697 /*
698  * Given a physical link media type, returns its media type string.
699  */
700 const char *
701 dladm_media2str(uint32_t media, char *buf)
702 {
703 	const char *s = "--";
704 	media_type_t *mt;
705 	int idx;
706 
707 	for (idx = 0; idx < MEDIATYPECOUNT; idx++) {
708 		mt = media_type_table + idx;
709 		if (mt->media_type == media) {
710 			s = mt->media_type_str;
711 			break;
712 		}
713 	}
714 
715 	(void) snprintf(buf, DLADM_STRSIZE, "%s", s);
716 	return (buf);
717 }
718 
719 /*
720  * Given a physical link media type string, returns its media type constant.
721  */
722 uint32_t
723 dladm_str2media(const char *buf)
724 {
725 	media_type_t *mt;
726 	int idx;
727 
728 	for (idx = 0; idx < MEDIATYPECOUNT; idx++) {
729 		mt = media_type_table + idx;
730 		if (strcasecmp(buf, mt->media_type_str) == 0)
731 			return (mt->media_type);
732 	}
733 
734 	return (DL_OTHER);
735 }
736 
737 dladm_status_t
738 i_dladm_rw_db(dladm_handle_t handle, const char *db_file, mode_t db_perms,
739     dladm_status_t (*process_db)(dladm_handle_t, void *, FILE *, FILE *),
740     void *arg, boolean_t writeop)
741 {
742 	dladm_status_t	status = DLADM_STATUS_OK;
743 	FILE		*fp, *nfp = NULL;
744 	char		lock[MAXPATHLEN];
745 	char		file[MAXPATHLEN];
746 	char		newfile[MAXPATHLEN];
747 	char		*db_basename;
748 	int		nfd, lock_fd;
749 
750 	/*
751 	 * If we are called from a boot script such as net-physical,
752 	 * it's quite likely that the root fs is still not writable.
753 	 * For this case, it's ok for the lock creation to fail since
754 	 * no one else could be accessing our configuration file.
755 	 */
756 	db_basename = strrchr(db_file, '/');
757 	if (db_basename == NULL || db_basename[1] == '\0')
758 		return (dladm_errno2status(EINVAL));
759 	db_basename++;
760 	(void) snprintf(lock, MAXPATHLEN, "/tmp/%s.lock", db_basename);
761 	if ((lock_fd = i_dladm_lock_db
762 	    (lock, (writeop ? F_WRLCK : F_RDLCK))) < 0 && errno != EROFS)
763 		return (dladm_errno2status(errno));
764 
765 	(void) snprintf(file, MAXPATHLEN, "%s/%s", dladm_rootdir, db_file);
766 	if ((fp = fopen(file, (writeop ? "r+" : "r"))) == NULL) {
767 		int	err = errno;
768 
769 		i_dladm_unlock_db(lock, lock_fd);
770 		if (err == ENOENT)
771 			return (DLADM_STATUS_DBNOTFOUND);
772 
773 		return (dladm_errno2status(err));
774 	}
775 
776 	if (writeop) {
777 		(void) snprintf(newfile, MAXPATHLEN, "%s/%s.new",
778 		    dladm_rootdir, db_file);
779 		if ((nfd = open(newfile, O_WRONLY | O_CREAT | O_TRUNC,
780 		    db_perms)) < 0) {
781 			(void) fclose(fp);
782 			i_dladm_unlock_db(lock, lock_fd);
783 			return (dladm_errno2status(errno));
784 		}
785 
786 		if ((nfp = fdopen(nfd, "w")) == NULL) {
787 			(void) close(nfd);
788 			(void) fclose(fp);
789 			(void) unlink(newfile);
790 			i_dladm_unlock_db(lock, lock_fd);
791 			return (dladm_errno2status(errno));
792 		}
793 	}
794 	status = (*process_db)(handle, arg, fp, nfp);
795 	if (!writeop || status != DLADM_STATUS_OK)
796 		goto done;
797 
798 	/* Set permissions on file to db_perms */
799 	if (fchmod(nfd, db_perms) < 0) {
800 		status = dladm_errno2status(errno);
801 		goto done;
802 	}
803 
804 	/*
805 	 * Configuration files need to be owned by the 'dladm' user and
806 	 * 'netadm' group.
807 	 */
808 	if (fchown(nfd, UID_DLADM, GID_NETADM) < 0) {
809 		status = dladm_errno2status(errno);
810 		goto done;
811 	}
812 
813 	if (fflush(nfp) == EOF) {
814 		status = dladm_errno2status(errno);
815 		goto done;
816 	}
817 	(void) fclose(fp);
818 	(void) fclose(nfp);
819 
820 	if (rename(newfile, file) < 0) {
821 		(void) unlink(newfile);
822 		i_dladm_unlock_db(lock, lock_fd);
823 		return (dladm_errno2status(errno));
824 	}
825 
826 	i_dladm_unlock_db(lock, lock_fd);
827 	return (DLADM_STATUS_OK);
828 
829 done:
830 	if (nfp != NULL) {
831 		(void) fclose(nfp);
832 		if (status != DLADM_STATUS_OK)
833 			(void) unlink(newfile);
834 	}
835 	(void) fclose(fp);
836 	i_dladm_unlock_db(lock, lock_fd);
837 	return (status);
838 }
839 
840 dladm_status_t
841 dladm_set_rootdir(const char *rootdir)
842 {
843 	DIR	*dp;
844 
845 	if (rootdir == NULL || *rootdir != '/' ||
846 	    (dp = opendir(rootdir)) == NULL)
847 		return (DLADM_STATUS_BADARG);
848 
849 	(void) strncpy(dladm_rootdir, rootdir, MAXPATHLEN);
850 	(void) closedir(dp);
851 	return (DLADM_STATUS_OK);
852 }
853 
854 boolean_t
855 dladm_valid_linkname(const char *link)
856 {
857 	size_t		len = strlen(link);
858 	const char	*cp;
859 	int		nd = 0;
860 
861 	if (len >= MAXLINKNAMELEN)
862 		return (B_FALSE);
863 
864 	/* Link name cannot start with a digit */
865 	if (isdigit(link[0]))
866 		return (B_FALSE);
867 	/* Link name must end with a number without leading zeroes */
868 	cp = link + len - 1;
869 	while (isdigit(*cp)) {
870 		cp--;
871 		nd++;
872 	}
873 	if (nd == 0 || (nd > 1 && *(cp + 1) == '0'))
874 		return (B_FALSE);
875 
876 	/*
877 	 * The legal characters in a link name are:
878 	 * alphanumeric (a-z,  A-Z,  0-9), underscore ('_'), and '.'.
879 	 */
880 	for (cp = link; *cp != '\0'; cp++) {
881 		if ((isalnum(*cp) == 0) && (*cp != '_') && (*cp != '.'))
882 			return (B_FALSE);
883 	}
884 
885 	return (B_TRUE);
886 }
887 
888 /*
889  * Convert priority string to a value.
890  */
891 dladm_status_t
892 dladm_str2pri(char *token, mac_priority_level_t *pri)
893 {
894 	if (strlen(token) == strlen("low") &&
895 	    strncasecmp(token, "low", strlen("low")) == 0) {
896 		*pri = MPL_LOW;
897 	} else if (strlen(token) == strlen("medium") &&
898 	    strncasecmp(token, "medium", strlen("medium")) == 0) {
899 		*pri = MPL_MEDIUM;
900 	} else if (strlen(token) == strlen("high") &&
901 	    strncasecmp(token, "high", strlen("high")) == 0) {
902 		*pri = MPL_HIGH;
903 	} else {
904 		return (DLADM_STATUS_BADVAL);
905 	}
906 	return (DLADM_STATUS_OK);
907 }
908 
909 /*
910  * Convert priority value to a string.
911  */
912 const char *
913 dladm_pri2str(mac_priority_level_t pri, char *buf)
914 {
915 	const char	*s;
916 
917 	switch (pri) {
918 	case MPL_LOW:
919 		s = "low";
920 		break;
921 	case MPL_MEDIUM:
922 		s = "medium";
923 		break;
924 	case MPL_HIGH:
925 		s = "high";
926 		break;
927 	default:
928 		s = "--";
929 		break;
930 	}
931 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
932 	return (buf);
933 }
934 
935 /*
936  * Convert protect string to a value.
937  */
938 dladm_status_t
939 dladm_str2protect(char *token, uint32_t *ptype)
940 {
941 	link_protect_t	*lp;
942 	int		i;
943 
944 	for (i = 0; i < LPTYPES; i++) {
945 		lp = &link_protect_types[i];
946 		if (strcmp(token, lp->lp_name) == 0) {
947 			*ptype = lp->lp_type;
948 			return (DLADM_STATUS_OK);
949 		}
950 	}
951 	return (DLADM_STATUS_BADVAL);
952 }
953 
954 /*
955  * Convert protect value to a string.
956  */
957 const char *
958 dladm_protect2str(uint32_t ptype, char *buf)
959 {
960 	const char	*s = "--";
961 	link_protect_t	*lp;
962 	int		i;
963 
964 	for (i = 0; i < LPTYPES; i++) {
965 		lp = &link_protect_types[i];
966 		if (lp->lp_type == ptype) {
967 			s = lp->lp_name;
968 			break;
969 		}
970 	}
971 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
972 	return (buf);
973 }
974 
975 /*
976  * Convert an IPv4 address to/from a string.
977  */
978 const char *
979 dladm_ipv4addr2str(void *addr, char *buf)
980 {
981 	if (inet_ntop(AF_INET, addr, buf, INET_ADDRSTRLEN) == NULL)
982 		buf[0] = '\0';
983 
984 	return (buf);
985 }
986 
987 dladm_status_t
988 dladm_str2ipv4addr(char *token, void *addr)
989 {
990 	return (inet_pton(AF_INET, token, addr) == 1 ?
991 	    DLADM_STATUS_OK : DLADM_STATUS_INVALID_IP);
992 }
993 
994 const char *
995 dladm_ipv6addr2str(void *addr, char *buf)
996 {
997 	if (inet_ntop(AF_INET6, addr, buf, INET6_ADDRSTRLEN) == NULL)
998 		buf[0] = '\0';
999 
1000 	return (buf);
1001 }
1002 
1003 dladm_status_t
1004 dladm_str2ipv6addr(char *token, void *addr)
1005 {
1006 	return (inet_pton(AF_INET6, token, addr) == 1 ?
1007 	    DLADM_STATUS_OK : DLADM_STATUS_INVALID_IP);
1008 }
1009 
1010 /*
1011  * Find the set bits in a mask.
1012  * This is used for expanding a bitmask into individual sub-masks
1013  * which can be used for further processing.
1014  */
1015 void
1016 dladm_find_setbits32(uint32_t mask, uint32_t *list, uint32_t *cnt)
1017 {
1018 	int	i, c = 0;
1019 
1020 	for (i = 0; i < 32; i++) {
1021 		if (((1 << i) & mask) != 0)
1022 			list[c++] = 1 << i;
1023 	}
1024 	*cnt = c;
1025 }
1026 
1027 void
1028 dladm_free_args(dladm_arg_list_t *list)
1029 {
1030 	if (list != NULL) {
1031 		free(list->al_buf);
1032 		free(list);
1033 	}
1034 }
1035 
1036 dladm_status_t
1037 dladm_parse_args(char *str, dladm_arg_list_t **listp, boolean_t novalues)
1038 {
1039 	dladm_arg_list_t	*list;
1040 	dladm_arg_info_t	*aip;
1041 	char			*buf, *curr;
1042 	int			len, i;
1043 
1044 	if (str == NULL)
1045 		return (DLADM_STATUS_BADVAL);
1046 
1047 	if (str[0] == '\0')
1048 		return (DLADM_STATUS_OK);
1049 
1050 	list = malloc(sizeof (dladm_arg_list_t));
1051 	if (list == NULL)
1052 		return (dladm_errno2status(errno));
1053 
1054 	list->al_count = 0;
1055 	list->al_buf = buf = strdup(str);
1056 	if (buf == NULL)
1057 		return (dladm_errno2status(errno));
1058 
1059 	curr = buf;
1060 	len = strlen(buf);
1061 	aip = NULL;
1062 	for (i = 0; i < len; i++) {
1063 		char		c = buf[i];
1064 		boolean_t	match = (c == '=' || c == ',');
1065 
1066 		if (!match && i != len - 1)
1067 			continue;
1068 
1069 		if (match) {
1070 			buf[i] = '\0';
1071 			if (*curr == '\0')
1072 				goto fail;
1073 		}
1074 
1075 		if (aip != NULL && c != '=') {
1076 			if (aip->ai_count > DLADM_MAX_ARG_VALS)
1077 				goto fail;
1078 
1079 			if (novalues)
1080 				goto fail;
1081 
1082 			aip->ai_val[aip->ai_count] = curr;
1083 			aip->ai_count++;
1084 		} else {
1085 			if (list->al_count > DLADM_MAX_ARG_VALS)
1086 				goto fail;
1087 
1088 			aip = &list->al_info[list->al_count];
1089 			aip->ai_name = curr;
1090 			aip->ai_count = 0;
1091 			list->al_count++;
1092 			if (c == ',')
1093 				aip = NULL;
1094 		}
1095 		curr = buf + i + 1;
1096 	}
1097 
1098 	*listp = list;
1099 	return (DLADM_STATUS_OK);
1100 
1101 fail:
1102 	dladm_free_args(list);
1103 	return (DLADM_STATUS_FAILED);
1104 }
1105 
1106 /*
1107  * mac_propval_range_t functions.  Currently implemented for only
1108  * ranges of uint32_t elements, but can be expanded as required.
1109  */
1110 /*
1111  * Convert an array of strings (which can be ranges or individual
1112  * elements) into a single mac_propval_range_t structure which
1113  * is allocated here but should be freed by the caller.
1114  */
1115 dladm_status_t
1116 dladm_strs2range(char **prop_val, uint_t val_cnt, mac_propval_type_t type,
1117     mac_propval_range_t **range)
1118 {
1119 	int			i;
1120 	char			*endp;
1121 	mac_propval_range_t	*rangep;
1122 	dladm_status_t		status = DLADM_STATUS_OK;
1123 
1124 	switch (type) {
1125 	case MAC_PROPVAL_UINT32: {
1126 		mac_propval_uint32_range_t	*ur;
1127 
1128 		/* Allocate range structure */
1129 		rangep = malloc(sizeof (mac_propval_range_t) +
1130 		    (val_cnt-1)*(sizeof (mac_propval_uint32_range_t)));
1131 		if (rangep == NULL)
1132 			return (DLADM_STATUS_NOMEM);
1133 
1134 		rangep->mpr_count = 0;
1135 		ur = &rangep->mpr_range_uint32[0];
1136 		for (i = 0; i < val_cnt; i++, ur++) {
1137 			errno = 0;
1138 			if (strchr(prop_val[i], '-') == NULL) {
1139 				/* single element */
1140 				ur->mpur_min = ur->mpur_max =
1141 				    strtol(prop_val[i], &endp, 10);
1142 				if ((endp != NULL) && (*endp != '\0')) {
1143 					return (DLADM_STATUS_BADRANGE);
1144 				}
1145 			} else {
1146 				/* range of elements */
1147 				ur->mpur_min = strtol(prop_val[i], &endp, 10);
1148 				if (*endp++ != '-')
1149 					return (DLADM_STATUS_BADRANGE);
1150 				ur->mpur_max = strtol(endp, &endp, 10);
1151 				if ((endp != NULL && *endp != '\0') ||
1152 				    ur->mpur_max < ur->mpur_min)
1153 					return (DLADM_STATUS_BADRANGE);
1154 			}
1155 			rangep->mpr_count++;
1156 		}
1157 		break;
1158 	}
1159 	default:
1160 		return (DLADM_STATUS_BADVAL);
1161 	}
1162 
1163 	rangep->mpr_type = type;
1164 	*range = rangep;
1165 
1166 	return (status);
1167 }
1168 
1169 /*
1170  * Convert a mac_propval_range_t structure into an array of elements.
1171  */
1172 dladm_status_t
1173 dladm_range2list(const mac_propval_range_t *rangep, void *elem, uint_t *nelem)
1174 {
1175 	int		i, j, k;
1176 	dladm_status_t	status = DLADM_STATUS_OK;
1177 
1178 	switch (rangep->mpr_type) {
1179 	case MAC_PROPVAL_UINT32: {
1180 		const mac_propval_uint32_range_t	*ur;
1181 		uint32_t				*elem32 = elem;
1182 
1183 		k = 0;
1184 		ur = &rangep->mpr_range_uint32[0];
1185 		for (i = 0; i < rangep->mpr_count; i++, ur++) {
1186 			for (j = 0; j <= ur->mpur_max - ur->mpur_min; j++) {
1187 				elem32[k++] = ur->mpur_min + j;
1188 				if (k > *nelem) {
1189 					status = DLADM_STATUS_TOOMANYELEMENTS;
1190 					break;
1191 				}
1192 			}
1193 		}
1194 		*nelem = k;
1195 		break;
1196 	}
1197 	default:
1198 		status = DLADM_STATUS_BADVAL;
1199 		break;
1200 	}
1201 	return (status);
1202 }
1203 
1204 /*
1205  * Convert a mac_propval_range_t structure into an array of strings
1206  * of single elements or ranges.
1207  */
1208 int
1209 dladm_range2strs(const mac_propval_range_t *rangep, char **prop_val)
1210 {
1211 	int	i;
1212 
1213 	switch (rangep->mpr_type) {
1214 	case MAC_PROPVAL_UINT32: {
1215 		const mac_propval_uint32_range_t	*ur;
1216 
1217 		/* Write ranges and individual elements */
1218 		ur = &rangep->mpr_range_uint32[0];
1219 		for (i = 0; i < rangep->mpr_count; i++, ur++) {
1220 			if (ur->mpur_min == ur->mpur_max) {
1221 				/* single element */
1222 				(void) snprintf(prop_val[i], DLADM_PROP_VAL_MAX,
1223 				    "%u", ur->mpur_min);
1224 			} else {
1225 				/* range of elements */
1226 				(void) snprintf(prop_val[i], DLADM_PROP_VAL_MAX,
1227 				    "%u-%u", ur->mpur_min, ur->mpur_max);
1228 			}
1229 		}
1230 		return (0);
1231 	}
1232 	case MAC_PROPVAL_STR: {
1233 		const mac_propval_str_range_t	*str;
1234 		size_t				coff, len;
1235 
1236 		coff = 0;
1237 		str = &rangep->u.mpr_str;
1238 		for (i = 0; i < rangep->mpr_count; i++) {
1239 			len = strlen(&str->mpur_data[coff]);
1240 			(void) strlcpy(prop_val[i], &str->mpur_data[coff],
1241 			    DLADM_PROP_VAL_MAX);
1242 			coff += len + 1;
1243 		}
1244 		return (0);
1245 	}
1246 	default:
1247 		break;
1248 	}
1249 	return (EINVAL);
1250 }
1251 
1252 static int
1253 uint32cmp(const void *a, const void *b)
1254 {
1255 	return (*(uint32_t *)a - *(uint32_t *)b);
1256 }
1257 
1258 /*
1259  * Sort and convert an array of elements into a single
1260  * mac_propval_range_t structure which is allocated here but
1261  * should be freed by the caller.
1262  */
1263 dladm_status_t
1264 dladm_list2range(void *elem, uint_t nelem, mac_propval_type_t type,
1265     mac_propval_range_t **range)
1266 {
1267 	int			i;
1268 	uint_t			nr = 0;
1269 	mac_propval_range_t	*rangep;
1270 	dladm_status_t		status = DLADM_STATUS_OK;
1271 
1272 	switch (type) {
1273 	case MAC_PROPVAL_UINT32: {
1274 		mac_propval_uint32_range_t	*ur;
1275 		uint32_t			*elem32 = elem;
1276 		uint32_t			*sort32;
1277 
1278 		/* Allocate range structure */
1279 		rangep = malloc(sizeof (mac_propval_range_t) +
1280 		    (nelem-1)*(sizeof (mac_propval_uint32_range_t)));
1281 		if (rangep == NULL)
1282 			return (DLADM_STATUS_NOMEM);
1283 
1284 		/* Allocate array for sorting */
1285 		sort32 = malloc(nelem * sizeof (uint32_t));
1286 		if (sort32 == NULL) {
1287 			free(rangep);
1288 			return (DLADM_STATUS_NOMEM);
1289 		}
1290 
1291 		/* Copy and sort list */
1292 		for (i = 0; i < nelem; i++)
1293 			sort32[i] =  elem32[i];
1294 		if (nelem > 1)
1295 			qsort(sort32, nelem, sizeof (uint32_t), uint32cmp);
1296 
1297 		/* Convert list to ranges */
1298 		ur = &rangep->mpr_range_uint32[0];
1299 		ur->mpur_min = ur->mpur_max = sort32[0];
1300 		for (i = 1; i < nelem; i++) {
1301 			if (sort32[i]-sort32[i-1] == 1) {
1302 				/* part of current range */
1303 				ur->mpur_max = sort32[i];
1304 			} else {
1305 				/* start a new range */
1306 				nr++; ur++;
1307 				ur->mpur_min = ur->mpur_max = sort32[i];
1308 			}
1309 		}
1310 		free(sort32);
1311 		break;
1312 	}
1313 	default:
1314 		return (DLADM_STATUS_BADRANGE);
1315 	}
1316 
1317 	rangep->mpr_type = type;
1318 	rangep->mpr_count = nr + 1;
1319 	*range = rangep;
1320 
1321 	return (status);
1322 }
1323 
1324 void
1325 dladm_errlist_init(dladm_errlist_t *erl)
1326 {
1327 	bzero(erl, sizeof (dladm_errlist_t));
1328 }
1329 
1330 void
1331 dladm_errlist_reset(dladm_errlist_t *erl)
1332 {
1333 	uint_t i;
1334 
1335 	for (i = 0; i < erl->el_count; i++)
1336 		free(erl->el_errs[i]);
1337 	free(erl->el_errs);
1338 	dladm_errlist_init(erl);
1339 }
1340 
1341 uint_t
1342 dladm_errlist_count(dladm_errlist_t *erl)
1343 {
1344 	return (erl->el_count);
1345 }
1346 
1347 dladm_status_t
1348 dladm_errlist_append(dladm_errlist_t *erl, const char *fmt, ...)
1349 {
1350 	int ret;
1351 	va_list ap;
1352 	char *m = NULL;
1353 
1354 	if (erl->el_count == erl->el_alloc) {
1355 		int alloc;
1356 		void *addr;
1357 		if (erl->el_alloc == 0) {
1358 			assert(erl->el_errs == NULL);
1359 			alloc = 32;
1360 		} else {
1361 			alloc = erl->el_alloc + 32;
1362 		}
1363 		addr = realloc(erl->el_errs, sizeof (char *) * alloc);
1364 		if (addr == NULL)
1365 			return (DLADM_STATUS_NOMEM);
1366 
1367 		erl->el_errs = addr;
1368 		erl->el_alloc = alloc;
1369 	}
1370 
1371 	va_start(ap, fmt);
1372 	ret = vasprintf(&m, fmt, ap);
1373 	va_end(ap);
1374 	if (ret == -1)
1375 		return (dladm_errno2status(errno));
1376 	erl->el_errs[erl->el_count] = m;
1377 	erl->el_count++;
1378 	return (DLADM_STATUS_OK);
1379 }
1380