xref: /titanic_44/usr/src/lib/libdladm/common/libdladm.c (revision 965eec0d6b2b8d25b75f15294008c17159bf852b)
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 #include <unistd.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <fcntl.h>
29 #include <strings.h>
30 #include <dirent.h>
31 #include <stdlib.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <sys/param.h>
35 #include <sys/stat.h>
36 #include <sys/dld.h>
37 #include <sys/dld_ioc.h>
38 #include <libdladm_impl.h>
39 #include <libintl.h>
40 #include <libdlpi.h>
41 
42 static char	dladm_rootdir[MAXPATHLEN] = "/";
43 
44 typedef struct media_type_desc {
45 	uint32_t	media_type;
46 #define	MAX_MEDIA_TYPE_STRING	32
47 	const char	media_type_str[MAX_MEDIA_TYPE_STRING];
48 } media_type_t;
49 
50 static media_type_t media_type_table[] =  {
51 	{ DL_ETHER,	"Ethernet" },
52 	{ DL_WIFI,	"WiFi" },
53 	{ DL_IB,	"Infiniband" },
54 	{ DL_IPV4,	"IPv4Tunnel" },
55 	{ DL_IPV6,	"IPv6Tunnel" },
56 	{ DL_6TO4,	"6to4Tunnel" },
57 	{ DL_CSMACD,	"CSMA/CD" },
58 	{ DL_TPB,	"TokenBus" },
59 	{ DL_TPR,	"TokenRing" },
60 	{ DL_METRO,	"MetroNet" },
61 	{ DL_HDLC,	"HDLC" },
62 	{ DL_CHAR,	"SyncCharacter" },
63 	{ DL_CTCA,	"CTCA" },
64 	{ DL_FDDI, 	"FDDI" },
65 	{ DL_FC, 	"FiberChannel" },
66 	{ DL_ATM, 	"ATM" },
67 	{ DL_IPATM, 	"ATM(ClassicIP)" },
68 	{ DL_X25, 	"X.25" },
69 	{ DL_IPX25, 	"X.25(ClassicIP)" },
70 	{ DL_ISDN, 	"ISDN" },
71 	{ DL_HIPPI, 	"HIPPI" },
72 	{ DL_100VG, 	"100BaseVGEthernet" },
73 	{ DL_100VGTPR, 	"100BaseVGTokenRing" },
74 	{ DL_ETH_CSMA, 	"IEEE802.3" },
75 	{ DL_100BT, 	"100BaseT" },
76 	{ DL_FRAME, 	"FrameRelay" },
77 	{ DL_MPFRAME, 	"MPFrameRelay" },
78 	{ DL_ASYNC, 	"AsyncCharacter" },
79 	{ DL_IPNET, 	"IPNET" },
80 	{ DL_OTHER, 	"Other" }
81 };
82 #define	MEDIATYPECOUNT	(sizeof (media_type_table) / sizeof (media_type_t))
83 
84 typedef struct {
85 	uint32_t	lp_type;
86 	char		*lp_name;
87 } link_protect_t;
88 
89 static link_protect_t link_protect_types[] = {
90 	{ MPT_MACNOSPOOF, "mac-nospoof" },
91 	{ MPT_RESTRICTED, "restricted" },
92 	{ MPT_IPNOSPOOF, "ip-nospoof" },
93 	{ MPT_DHCPNOSPOOF, "dhcp-nospoof" }
94 };
95 #define	LPTYPES	(sizeof (link_protect_types) / sizeof (link_protect_t))
96 
97 dladm_status_t
98 dladm_open(dladm_handle_t *handle)
99 {
100 	int dld_fd;
101 
102 	if (handle == NULL)
103 		return (DLADM_STATUS_BADARG);
104 
105 	if ((dld_fd = open(DLD_CONTROL_DEV, O_RDWR)) < 0)
106 		return (dladm_errno2status(errno));
107 
108 	/*
109 	 * Don't open DLMGMT_DOOR now.  dlmgmtd(1M) is not able to
110 	 * open the door when the dladm handle is opened because the
111 	 * door hasn't been created yet at that time.  Thus, we must
112 	 * open it on-demand in dladm_door_fd().  Move the open()
113 	 * to dladm_door_fd() for all cases.
114 	 */
115 
116 	if ((*handle = malloc(sizeof (struct dladm_handle))) == NULL) {
117 		(void) close(dld_fd);
118 		return (DLADM_STATUS_NOMEM);
119 	}
120 
121 	(*handle)->dld_fd = dld_fd;
122 	(*handle)->door_fd = -1;
123 
124 	return (DLADM_STATUS_OK);
125 }
126 
127 void
128 dladm_close(dladm_handle_t handle)
129 {
130 	if (handle != NULL) {
131 		(void) close(handle->dld_fd);
132 		if (handle->door_fd != -1)
133 			(void) close(handle->door_fd);
134 		free(handle);
135 	}
136 }
137 
138 int
139 dladm_dld_fd(dladm_handle_t handle)
140 {
141 	return (handle->dld_fd);
142 }
143 
144 /*
145  * If DLMGMT_DOOR hasn't been opened in the handle yet, open it.
146  */
147 dladm_status_t
148 dladm_door_fd(dladm_handle_t handle, int *door_fd)
149 {
150 	int fd;
151 
152 	if (handle->door_fd == -1) {
153 		if ((fd = open(DLMGMT_DOOR, O_RDONLY)) < 0)
154 			return (dladm_errno2status(errno));
155 		handle->door_fd = fd;
156 	}
157 	*door_fd = handle->door_fd;
158 
159 	return (DLADM_STATUS_OK);
160 }
161 
162 const char *
163 dladm_status2str(dladm_status_t status, char *buf)
164 {
165 	const char	*s;
166 
167 	switch (status) {
168 	case DLADM_STATUS_OK:
169 		s = "ok";
170 		break;
171 	case DLADM_STATUS_BADARG:
172 		s = "invalid argument";
173 		break;
174 	case DLADM_STATUS_FAILED:
175 		s = "operation failed";
176 		break;
177 	case DLADM_STATUS_TOOSMALL:
178 		s = "buffer size too small";
179 		break;
180 	case DLADM_STATUS_NOTSUP:
181 		s = "operation not supported";
182 		break;
183 	case DLADM_STATUS_NOTFOUND:
184 		s = "object not found";
185 		break;
186 	case DLADM_STATUS_BADVAL:
187 		s = "invalid value";
188 		break;
189 	case DLADM_STATUS_NOMEM:
190 		s = "insufficient memory";
191 		break;
192 	case DLADM_STATUS_EXIST:
193 		s = "object already exists";
194 		break;
195 	case DLADM_STATUS_LINKINVAL:
196 		s = "invalid link";
197 		break;
198 	case DLADM_STATUS_PROPRDONLY:
199 		s = "read-only property";
200 		break;
201 	case DLADM_STATUS_BADVALCNT:
202 		s = "invalid number of values";
203 		break;
204 	case DLADM_STATUS_DBNOTFOUND:
205 		s = "database not found";
206 		break;
207 	case DLADM_STATUS_DENIED:
208 		s = "permission denied";
209 		break;
210 	case DLADM_STATUS_IOERR:
211 		s = "I/O error";
212 		break;
213 	case DLADM_STATUS_TEMPONLY:
214 		s = "change cannot be persistent";
215 		break;
216 	case DLADM_STATUS_TIMEDOUT:
217 		s = "operation timed out";
218 		break;
219 	case DLADM_STATUS_ISCONN:
220 		s = "already connected";
221 		break;
222 	case DLADM_STATUS_NOTCONN:
223 		s = "not connected";
224 		break;
225 	case DLADM_STATUS_REPOSITORYINVAL:
226 		s = "invalid configuration repository";
227 		break;
228 	case DLADM_STATUS_MACADDRINVAL:
229 		s = "invalid MAC address";
230 		break;
231 	case DLADM_STATUS_KEYINVAL:
232 		s = "invalid key";
233 		break;
234 	case DLADM_STATUS_INVALIDMACADDRLEN:
235 		s = "invalid MAC address length";
236 		break;
237 	case DLADM_STATUS_INVALIDMACADDRTYPE:
238 		s = "invalid MAC address type";
239 		break;
240 	case DLADM_STATUS_LINKBUSY:
241 		s = "link busy";
242 		break;
243 	case DLADM_STATUS_VIDINVAL:
244 		s = "invalid VLAN identifier";
245 		break;
246 	case DLADM_STATUS_TRYAGAIN:
247 		s = "try again later";
248 		break;
249 	case DLADM_STATUS_NONOTIF:
250 		s = "link notification is not supported";
251 		break;
252 	case DLADM_STATUS_BADTIMEVAL:
253 		s = "invalid time range";
254 		break;
255 	case DLADM_STATUS_INVALIDMACADDR:
256 		s = "invalid MAC address value";
257 		break;
258 	case DLADM_STATUS_INVALIDMACADDRNIC:
259 		s = "MAC address reserved for use by underlying data-link";
260 		break;
261 	case DLADM_STATUS_INVALIDMACADDRINUSE:
262 		s = "MAC address is already in use";
263 		break;
264 	case DLADM_STATUS_MACFACTORYSLOTINVALID:
265 		s = "invalid factory MAC address slot";
266 		break;
267 	case DLADM_STATUS_MACFACTORYSLOTUSED:
268 		s = "factory MAC address slot already used";
269 		break;
270 	case DLADM_STATUS_MACFACTORYSLOTALLUSED:
271 		s = "all factory MAC address slots are in use";
272 		break;
273 	case DLADM_STATUS_MACFACTORYNOTSUP:
274 		s = "factory MAC address slots not supported";
275 		break;
276 	case DLADM_STATUS_INVALIDMACPREFIX:
277 		s = "Invalid MAC address prefix value";
278 		break;
279 	case DLADM_STATUS_INVALIDMACPREFIXLEN:
280 		s = "Invalid MAC address prefix length";
281 		break;
282 	case DLADM_STATUS_CPUMAX:
283 		s = "non-existent processor ID";
284 		break;
285 	case DLADM_STATUS_CPUERR:
286 		s = "could not determine processor status";
287 		break;
288 	case DLADM_STATUS_CPUNOTONLINE:
289 		s = "processor not online";
290 		break;
291 	case DLADM_STATUS_DB_NOTFOUND:
292 		s = "database not found";
293 		break;
294 	case DLADM_STATUS_DB_PARSE_ERR:
295 		s = "database parse error";
296 		break;
297 	case DLADM_STATUS_PROP_PARSE_ERR:
298 		s = "property parse error";
299 		break;
300 	case DLADM_STATUS_ATTR_PARSE_ERR:
301 		s = "attribute parse error";
302 		break;
303 	case DLADM_STATUS_FLOW_DB_ERR:
304 		s = "flow database error";
305 		break;
306 	case DLADM_STATUS_FLOW_DB_OPEN_ERR:
307 		s = "flow database open error";
308 		break;
309 	case DLADM_STATUS_FLOW_DB_PARSE_ERR:
310 		s = "flow database parse error";
311 		break;
312 	case DLADM_STATUS_FLOWPROP_DB_PARSE_ERR:
313 		s = "flow property database parse error";
314 		break;
315 	case DLADM_STATUS_FLOW_ADD_ERR:
316 		s = "flow add error";
317 		break;
318 	case DLADM_STATUS_FLOW_WALK_ERR:
319 		s = "flow walk error";
320 		break;
321 	case DLADM_STATUS_FLOW_IDENTICAL:
322 		s = "a flow with identical attributes exists";
323 		break;
324 	case DLADM_STATUS_FLOW_INCOMPATIBLE:
325 		s = "flow(s) with incompatible attributes exists";
326 		break;
327 	case DLADM_STATUS_FLOW_EXISTS:
328 		s = "link still has flows";
329 		break;
330 	case DLADM_STATUS_PERSIST_FLOW_EXISTS:
331 		s = "persistent flow with the same name exists";
332 		break;
333 	case DLADM_STATUS_INVALID_IP:
334 		s = "invalid IP address";
335 		break;
336 	case DLADM_STATUS_INVALID_PREFIXLEN:
337 		s = "invalid IP prefix length";
338 		break;
339 	case DLADM_STATUS_INVALID_PROTOCOL:
340 		s = "invalid IP protocol";
341 		break;
342 	case DLADM_STATUS_INVALID_PORT:
343 		s = "invalid port number";
344 		break;
345 	case DLADM_STATUS_INVALID_DSF:
346 		s = "invalid dsfield";
347 		break;
348 	case DLADM_STATUS_INVALID_DSFMASK:
349 		s = "invalid dsfield mask";
350 		break;
351 	case DLADM_STATUS_INVALID_MACMARGIN:
352 		s = "MTU check failed, use lower MTU or -f option";
353 		break;
354 	case DLADM_STATUS_BADPROP:
355 		s = "invalid property";
356 		break;
357 	case DLADM_STATUS_MINMAXBW:
358 		s = "minimum value for maxbw is 1.2M";
359 		break;
360 	case DLADM_STATUS_NO_HWRINGS:
361 		s = "request hw rings failed";
362 		break;
363 	case DLADM_STATUS_PERMONLY:
364 		s = "change must be persistent";
365 		break;
366 	case DLADM_STATUS_OPTMISSING:
367 		s = "optional software not installed";
368 		break;
369 	case DLADM_STATUS_IPTUNTYPE:
370 		s = "invalid IP tunnel type";
371 		break;
372 	case DLADM_STATUS_IPTUNTYPEREQD:
373 		s = "IP tunnel type required";
374 		break;
375 	case DLADM_STATUS_BADIPTUNLADDR:
376 		s = "invalid local IP tunnel address";
377 		break;
378 	case DLADM_STATUS_BADIPTUNRADDR:
379 		s = "invalid remote IP tunnel address";
380 		break;
381 	case DLADM_STATUS_ADDRINUSE:
382 		s = "address already in use";
383 		break;
384 	case DLADM_STATUS_POOLCPU:
385 		s = "pool and cpus property are mutually exclusive";
386 		break;
387 	case DLADM_STATUS_INVALID_PORT_INSTANCE:
388 		s = "invalid IB phys link";
389 		break;
390 	case DLADM_STATUS_PORT_IS_DOWN:
391 		s = "port is down";
392 		break;
393 	case DLADM_STATUS_PARTITION_EXISTS:
394 		s = "partition already exists";
395 		break;
396 	case DLADM_STATUS_PKEY_NOT_PRESENT:
397 		s = "PKEY is not present on the port";
398 		break;
399 	case DLADM_STATUS_INVALID_PKEY:
400 		s = "invalid PKEY";
401 		break;
402 	case DLADM_STATUS_NO_IB_HW_RESOURCE:
403 		s = "IB internal resource not available";
404 		break;
405 	case DLADM_STATUS_INVALID_PKEY_TBL_SIZE:
406 		s = "invalid PKEY table size";
407 		break;
408 	default:
409 		s = "<unknown error>";
410 		break;
411 	}
412 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
413 	return (buf);
414 }
415 
416 /*
417  * Convert a unix errno to a dladm_status_t.
418  * We only convert errnos that are likely to be encountered. All others
419  * are mapped to DLADM_STATUS_FAILED.
420  */
421 dladm_status_t
422 dladm_errno2status(int err)
423 {
424 	switch (err) {
425 	case 0:
426 		return (DLADM_STATUS_OK);
427 	case EINVAL:
428 		return (DLADM_STATUS_BADARG);
429 	case EEXIST:
430 		return (DLADM_STATUS_EXIST);
431 	case ENOENT:
432 		return (DLADM_STATUS_NOTFOUND);
433 	case ENOSPC:
434 		return (DLADM_STATUS_TOOSMALL);
435 	case ENOMEM:
436 		return (DLADM_STATUS_NOMEM);
437 	case ENOTSUP:
438 		return (DLADM_STATUS_NOTSUP);
439 	case ENETDOWN:
440 		return (DLADM_STATUS_NONOTIF);
441 	case EACCES:
442 	case EPERM:
443 		return (DLADM_STATUS_DENIED);
444 	case EIO:
445 		return (DLADM_STATUS_IOERR);
446 	case EBUSY:
447 		return (DLADM_STATUS_LINKBUSY);
448 	case EAGAIN:
449 		return (DLADM_STATUS_TRYAGAIN);
450 	case ENOTEMPTY:
451 		return (DLADM_STATUS_FLOW_EXISTS);
452 	case EOPNOTSUPP:
453 		return (DLADM_STATUS_FLOW_INCOMPATIBLE);
454 	case EALREADY:
455 		return (DLADM_STATUS_FLOW_IDENTICAL);
456 	case EADDRINUSE:
457 		return (DLADM_STATUS_ADDRINUSE);
458 	default:
459 		return (DLADM_STATUS_FAILED);
460 	}
461 }
462 
463 boolean_t
464 dladm_str2interval(char *oarg, uint32_t *interval)
465 {
466 	int		val;
467 	char		*endp = NULL;
468 
469 	errno = 0;
470 	val = strtol(oarg, &endp, 10);
471 	if (errno != 0 || val <= 0 || *endp != '\0')
472 		return (B_FALSE);
473 
474 	*interval = val;
475 
476 	return (B_TRUE);
477 }
478 
479 dladm_status_t
480 dladm_str2bw(char *oarg, uint64_t *bw)
481 {
482 	char		*endp = NULL;
483 	int64_t		n;
484 	int		mult = 1;
485 
486 	n = strtoull(oarg, &endp, 10);
487 
488 	if ((errno != 0) || (strlen(endp) > 1))
489 		return (DLADM_STATUS_BADARG);
490 
491 	if (n < 0)
492 		return (DLADM_STATUS_BADVAL);
493 
494 	switch (*endp) {
495 	case 'k':
496 	case 'K':
497 		mult = 1000;
498 		break;
499 	case 'm':
500 	case 'M':
501 	case '\0':
502 		mult = 1000000;
503 		break;
504 	case 'g':
505 	case 'G':
506 		mult = 1000000000;
507 		break;
508 	case '%':
509 		/*
510 		 * percentages not supported for now,
511 		 * see RFE 6540675
512 		 */
513 		return (DLADM_STATUS_NOTSUP);
514 	default:
515 		return (DLADM_STATUS_BADVAL);
516 	}
517 
518 	*bw = n * mult;
519 
520 	/* check for overflow */
521 	if (*bw / mult != n)
522 		return (DLADM_STATUS_BADARG);
523 
524 	return (DLADM_STATUS_OK);
525 }
526 
527 /*
528  * Convert bandwidth in bps to a string in mpbs.  For values greater
529  * than 1mbps or 1000000, print a whole mbps value.  For values that
530  * have fractional Mbps in whole Kbps , print the bandwidth in a manner
531  * simlilar to a floating point format.
532  *
533  *        bps       string
534  *          0            0
535  *        100            0
536  *       2000        0.002
537  *     431000        0.431
538  *    1000000            1
539  *    1030000        1.030
540  *  100000000          100
541  */
542 const char *
543 dladm_bw2str(int64_t bw, char *buf)
544 {
545 	int kbps, mbps;
546 
547 	kbps = (bw%1000000)/1000;
548 	mbps = bw/1000000;
549 	if (kbps != 0) {
550 		if (mbps == 0)
551 			(void) snprintf(buf, DLADM_STRSIZE, "0.%03u", kbps);
552 		else
553 			(void) snprintf(buf, DLADM_STRSIZE, "%5u.%03u", mbps,
554 			    kbps);
555 	} else {
556 		(void) snprintf(buf, DLADM_STRSIZE, "%5u", mbps);
557 	}
558 
559 	return (buf);
560 }
561 
562 #define	LOCK_DB_PERMS	S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
563 
564 static int
565 i_dladm_lock_db(const char *lock_file, short type)
566 {
567 	int	lock_fd;
568 	struct	flock lock;
569 
570 	if ((lock_fd = open(lock_file, O_RDWR | O_CREAT | O_TRUNC,
571 	    LOCK_DB_PERMS)) < 0)
572 		return (-1);
573 
574 	lock.l_type = type;
575 	lock.l_whence = SEEK_SET;
576 	lock.l_start = 0;
577 	lock.l_len = 0;
578 
579 	if (fcntl(lock_fd, F_SETLKW, &lock) < 0) {
580 		int err = errno;
581 
582 		(void) close(lock_fd);
583 		(void) unlink(lock_file);
584 		errno = err;
585 		return (-1);
586 	}
587 	return (lock_fd);
588 }
589 
590 static void
591 i_dladm_unlock_db(const char *lock_file, int fd)
592 {
593 	struct flock lock;
594 
595 	if (fd < 0)
596 		return;
597 
598 	lock.l_type = F_UNLCK;
599 	lock.l_whence = SEEK_SET;
600 	lock.l_start = 0;
601 	lock.l_len = 0;
602 
603 	(void) fcntl(fd, F_SETLKW, &lock);
604 	(void) close(fd);
605 	(void) unlink(lock_file);
606 }
607 
608 /*
609  * Given a link class, returns its class string.
610  */
611 const char *
612 dladm_class2str(datalink_class_t class, char *buf)
613 {
614 	const char *s;
615 
616 	switch (class) {
617 	case DATALINK_CLASS_PHYS:
618 		s = "phys";
619 		break;
620 	case DATALINK_CLASS_VLAN:
621 		s = "vlan";
622 		break;
623 	case DATALINK_CLASS_AGGR:
624 		s = "aggr";
625 		break;
626 	case DATALINK_CLASS_VNIC:
627 		s = "vnic";
628 		break;
629 	case DATALINK_CLASS_ETHERSTUB:
630 		s = "etherstub";
631 		break;
632 	case DATALINK_CLASS_IPTUN:
633 		s = "iptun";
634 		break;
635 	case DATALINK_CLASS_SIMNET:
636 		s = "simnet";
637 		break;
638 	case DATALINK_CLASS_BRIDGE:
639 		s = "bridge";
640 		break;
641 	case DATALINK_CLASS_PART:
642 		s = "part";
643 		break;
644 	default:
645 		s = "unknown";
646 		break;
647 	}
648 
649 	(void) snprintf(buf, DLADM_STRSIZE, "%s", s);
650 	return (buf);
651 }
652 
653 /*
654  * Given a physical link media type, returns its media type string.
655  */
656 const char *
657 dladm_media2str(uint32_t media, char *buf)
658 {
659 	const char *s = "--";
660 	media_type_t *mt;
661 	int idx;
662 
663 	for (idx = 0; idx < MEDIATYPECOUNT; idx++) {
664 		mt = media_type_table + idx;
665 		if (mt->media_type == media) {
666 			s = mt->media_type_str;
667 			break;
668 		}
669 	}
670 
671 	(void) snprintf(buf, DLADM_STRSIZE, "%s", s);
672 	return (buf);
673 }
674 
675 /*
676  * Given a physical link media type string, returns its media type constant.
677  */
678 uint32_t
679 dladm_str2media(const char *buf)
680 {
681 	media_type_t *mt;
682 	int idx;
683 
684 	for (idx = 0; idx < MEDIATYPECOUNT; idx++) {
685 		mt = media_type_table + idx;
686 		if (strcasecmp(buf, mt->media_type_str) == 0)
687 			return (mt->media_type);
688 	}
689 
690 	return (DL_OTHER);
691 }
692 
693 dladm_status_t
694 i_dladm_rw_db(dladm_handle_t handle, const char *db_file, mode_t db_perms,
695     dladm_status_t (*process_db)(dladm_handle_t, void *, FILE *, FILE *),
696     void *arg, boolean_t writeop)
697 {
698 	dladm_status_t	status = DLADM_STATUS_OK;
699 	FILE		*fp, *nfp = NULL;
700 	char		lock[MAXPATHLEN];
701 	char		file[MAXPATHLEN];
702 	char		newfile[MAXPATHLEN];
703 	char		*db_basename;
704 	int		nfd, lock_fd;
705 
706 	/*
707 	 * If we are called from a boot script such as net-physical,
708 	 * it's quite likely that the root fs is still not writable.
709 	 * For this case, it's ok for the lock creation to fail since
710 	 * no one else could be accessing our configuration file.
711 	 */
712 	db_basename = strrchr(db_file, '/');
713 	if (db_basename == NULL || db_basename[1] == '\0')
714 		return (dladm_errno2status(EINVAL));
715 	db_basename++;
716 	(void) snprintf(lock, MAXPATHLEN, "/tmp/%s.lock", db_basename);
717 	if ((lock_fd = i_dladm_lock_db
718 	    (lock, (writeop ? F_WRLCK : F_RDLCK))) < 0 && errno != EROFS)
719 		return (dladm_errno2status(errno));
720 
721 	(void) snprintf(file, MAXPATHLEN, "%s/%s", dladm_rootdir, db_file);
722 	if ((fp = fopen(file, (writeop ? "r+" : "r"))) == NULL) {
723 		int	err = errno;
724 
725 		i_dladm_unlock_db(lock, lock_fd);
726 		if (err == ENOENT)
727 			return (DLADM_STATUS_DBNOTFOUND);
728 
729 		return (dladm_errno2status(err));
730 	}
731 
732 	if (writeop) {
733 		(void) snprintf(newfile, MAXPATHLEN, "%s/%s.new",
734 		    dladm_rootdir, db_file);
735 		if ((nfd = open(newfile, O_WRONLY | O_CREAT | O_TRUNC,
736 		    db_perms)) < 0) {
737 			(void) fclose(fp);
738 			i_dladm_unlock_db(lock, lock_fd);
739 			return (dladm_errno2status(errno));
740 		}
741 
742 		if ((nfp = fdopen(nfd, "w")) == NULL) {
743 			(void) close(nfd);
744 			(void) fclose(fp);
745 			(void) unlink(newfile);
746 			i_dladm_unlock_db(lock, lock_fd);
747 			return (dladm_errno2status(errno));
748 		}
749 	}
750 	status = (*process_db)(handle, arg, fp, nfp);
751 	if (!writeop || status != DLADM_STATUS_OK)
752 		goto done;
753 
754 	/* Set permissions on file to db_perms */
755 	if (fchmod(nfd, db_perms) < 0) {
756 		status = dladm_errno2status(errno);
757 		goto done;
758 	}
759 
760 	/*
761 	 * Configuration files need to be owned by the 'dladm' user and
762 	 * 'netadm' group.
763 	 */
764 	if (fchown(nfd, UID_DLADM, GID_NETADM) < 0) {
765 		status = dladm_errno2status(errno);
766 		goto done;
767 	}
768 
769 	if (fflush(nfp) == EOF) {
770 		status = dladm_errno2status(errno);
771 		goto done;
772 	}
773 	(void) fclose(fp);
774 	(void) fclose(nfp);
775 
776 	if (rename(newfile, file) < 0) {
777 		(void) unlink(newfile);
778 		i_dladm_unlock_db(lock, lock_fd);
779 		return (dladm_errno2status(errno));
780 	}
781 
782 	i_dladm_unlock_db(lock, lock_fd);
783 	return (DLADM_STATUS_OK);
784 
785 done:
786 	if (nfp != NULL) {
787 		(void) fclose(nfp);
788 		if (status != DLADM_STATUS_OK)
789 			(void) unlink(newfile);
790 	}
791 	(void) fclose(fp);
792 	i_dladm_unlock_db(lock, lock_fd);
793 	return (status);
794 }
795 
796 dladm_status_t
797 dladm_set_rootdir(const char *rootdir)
798 {
799 	DIR	*dp;
800 
801 	if (rootdir == NULL || *rootdir != '/' ||
802 	    (dp = opendir(rootdir)) == NULL)
803 		return (DLADM_STATUS_BADARG);
804 
805 	(void) strncpy(dladm_rootdir, rootdir, MAXPATHLEN);
806 	(void) closedir(dp);
807 	return (DLADM_STATUS_OK);
808 }
809 
810 boolean_t
811 dladm_valid_linkname(const char *link)
812 {
813 	size_t		len = strlen(link);
814 	const char	*cp;
815 
816 	if (len >= MAXLINKNAMELEN)
817 		return (B_FALSE);
818 
819 	/*
820 	 * The link name cannot start with a digit and must end with a digit.
821 	 */
822 	if ((isdigit(link[0]) != 0) || (isdigit(link[len - 1]) == 0))
823 		return (B_FALSE);
824 
825 	/*
826 	 * The legal characters in a link name are:
827 	 * alphanumeric (a-z,  A-Z,  0-9), underscore ('_'), and '.'.
828 	 */
829 	for (cp = link; *cp != '\0'; cp++) {
830 		if ((isalnum(*cp) == 0) && (*cp != '_') && (*cp != '.'))
831 			return (B_FALSE);
832 	}
833 
834 	return (B_TRUE);
835 }
836 
837 /*
838  * Convert priority string to a value.
839  */
840 dladm_status_t
841 dladm_str2pri(char *token, mac_priority_level_t *pri)
842 {
843 	if (strlen(token) == strlen("low") &&
844 	    strncasecmp(token, "low", strlen("low")) == 0) {
845 		*pri = MPL_LOW;
846 	} else if (strlen(token) == strlen("medium") &&
847 	    strncasecmp(token, "medium", strlen("medium")) == 0) {
848 		*pri = MPL_MEDIUM;
849 	} else if (strlen(token) == strlen("high") &&
850 	    strncasecmp(token, "high", strlen("high")) == 0) {
851 		*pri = MPL_HIGH;
852 	} else {
853 		return (DLADM_STATUS_BADVAL);
854 	}
855 	return (DLADM_STATUS_OK);
856 }
857 
858 /*
859  * Convert priority value to a string.
860  */
861 const char *
862 dladm_pri2str(mac_priority_level_t pri, char *buf)
863 {
864 	const char	*s;
865 
866 	switch (pri) {
867 	case MPL_LOW:
868 		s = "low";
869 		break;
870 	case MPL_MEDIUM:
871 		s = "medium";
872 		break;
873 	case MPL_HIGH:
874 		s = "high";
875 		break;
876 	default:
877 		s = "--";
878 		break;
879 	}
880 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
881 	return (buf);
882 }
883 
884 /*
885  * Convert protect string to a value.
886  */
887 dladm_status_t
888 dladm_str2protect(char *token, uint32_t *ptype)
889 {
890 	link_protect_t	*lp;
891 	int		i;
892 
893 	for (i = 0; i < LPTYPES; i++) {
894 		lp = &link_protect_types[i];
895 		if (strcmp(token, lp->lp_name) == 0) {
896 			*ptype = lp->lp_type;
897 			return (DLADM_STATUS_OK);
898 		}
899 	}
900 	return (DLADM_STATUS_BADVAL);
901 }
902 
903 /*
904  * Convert protect value to a string.
905  */
906 const char *
907 dladm_protect2str(uint32_t ptype, char *buf)
908 {
909 	const char	*s = "--";
910 	link_protect_t	*lp;
911 	int		i;
912 
913 	for (i = 0; i < LPTYPES; i++) {
914 		lp = &link_protect_types[i];
915 		if (lp->lp_type == ptype) {
916 			s = lp->lp_name;
917 			break;
918 		}
919 	}
920 	(void) snprintf(buf, DLADM_STRSIZE, "%s", dgettext(TEXT_DOMAIN, s));
921 	return (buf);
922 }
923 
924 /*
925  * Convert an IPv4 address to/from a string.
926  */
927 const char *
928 dladm_ipv4addr2str(void *addr, char *buf)
929 {
930 	if (inet_ntop(AF_INET, addr, buf, INET_ADDRSTRLEN) == NULL)
931 		buf[0] = '\0';
932 
933 	return (buf);
934 }
935 
936 dladm_status_t
937 dladm_str2ipv4addr(char *token, void *addr)
938 {
939 	return (inet_pton(AF_INET, token, addr) == 1 ?
940 	    DLADM_STATUS_OK : DLADM_STATUS_INVALID_IP);
941 }
942 
943 const char *
944 dladm_ipv6addr2str(void *addr, char *buf)
945 {
946 	if (inet_ntop(AF_INET6, addr, buf, INET6_ADDRSTRLEN) == NULL)
947 		buf[0] = '\0';
948 
949 	return (buf);
950 }
951 
952 dladm_status_t
953 dladm_str2ipv6addr(char *token, void *addr)
954 {
955 	return (inet_pton(AF_INET6, token, addr) == 1 ?
956 	    DLADM_STATUS_OK : DLADM_STATUS_INVALID_IP);
957 }
958 
959 /*
960  * Find the set bits in a mask.
961  * This is used for expanding a bitmask into individual sub-masks
962  * which can be used for further processing.
963  */
964 void
965 dladm_find_setbits32(uint32_t mask, uint32_t *list, uint32_t *cnt)
966 {
967 	int	i, c = 0;
968 
969 	for (i = 0; i < 32; i++) {
970 		if (((1 << i) & mask) != 0)
971 			list[c++] = 1 << i;
972 	}
973 	*cnt = c;
974 }
975 
976 void
977 dladm_free_args(dladm_arg_list_t *list)
978 {
979 	if (list != NULL) {
980 		free(list->al_buf);
981 		free(list);
982 	}
983 }
984 
985 dladm_status_t
986 dladm_parse_args(char *str, dladm_arg_list_t **listp, boolean_t novalues)
987 {
988 	dladm_arg_list_t	*list;
989 	dladm_arg_info_t	*aip;
990 	char			*buf, *curr;
991 	int			len, i;
992 
993 	if (str == NULL)
994 		return (DLADM_STATUS_BADVAL);
995 
996 	if (str[0] == '\0')
997 		return (DLADM_STATUS_OK);
998 
999 	list = malloc(sizeof (dladm_arg_list_t));
1000 	if (list == NULL)
1001 		return (dladm_errno2status(errno));
1002 
1003 	list->al_count = 0;
1004 	list->al_buf = buf = strdup(str);
1005 	if (buf == NULL)
1006 		return (dladm_errno2status(errno));
1007 
1008 	curr = buf;
1009 	len = strlen(buf);
1010 	aip = NULL;
1011 	for (i = 0; i < len; i++) {
1012 		char		c = buf[i];
1013 		boolean_t	match = (c == '=' || c == ',');
1014 
1015 		if (!match && i != len - 1)
1016 			continue;
1017 
1018 		if (match) {
1019 			buf[i] = '\0';
1020 			if (*curr == '\0')
1021 				goto fail;
1022 		}
1023 
1024 		if (aip != NULL && c != '=') {
1025 			if (aip->ai_count > DLADM_MAX_ARG_VALS)
1026 				goto fail;
1027 
1028 			if (novalues)
1029 				goto fail;
1030 
1031 			aip->ai_val[aip->ai_count] = curr;
1032 			aip->ai_count++;
1033 		} else {
1034 			if (list->al_count > DLADM_MAX_ARG_VALS)
1035 				goto fail;
1036 
1037 			aip = &list->al_info[list->al_count];
1038 			aip->ai_name = curr;
1039 			aip->ai_count = 0;
1040 			list->al_count++;
1041 			if (c == ',')
1042 				aip = NULL;
1043 		}
1044 		curr = buf + i + 1;
1045 	}
1046 
1047 	*listp = list;
1048 	return (DLADM_STATUS_OK);
1049 
1050 fail:
1051 	dladm_free_args(list);
1052 	return (DLADM_STATUS_FAILED);
1053 }
1054