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.
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.
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]
23 * Copyright (c) 2020, Georgy Yakovlev. All rights reserved.
39 static void usage(void);
44 (void) fprintf(stderr,
45 "usage: zgenhostid [-fh] [-o path] [value]\n\n"
46 " -f\t\t force hostid file write\n"
47 " -h\t\t print this usage and exit\n"
48 " -o <filename>\t write hostid to this file\n\n"
49 "If hostid file is not present, store a hostid in it.\n"
50 "The optional value must be an 8-digit hex number between"
52 "If no value is provided, a random one will"
54 "The value must be unique among your systems.\n");
60 main(int argc, char **argv)
62 /* default file path, can be optionally set by user */
63 char path[PATH_MAX] = "/etc/hostid";
64 /* holds converted user input or lrand48() generated value */
65 unsigned long input_i = 0;
70 while ((opt = getopt_long(argc, argv, "fo:h?", 0, 0)) != -1) {
76 pathlen = snprintf(path, sizeof (path), "%s", optarg);
77 if (pathlen >= sizeof (path)) {
78 fprintf(stderr, "%s\n", strerror(EOVERFLOW));
80 } else if (pathlen < 1) {
81 fprintf(stderr, "%s\n", strerror(EINVAL));
91 char *in_s = argv[optind];
93 /* increment pointer by 2 if string is 0x prefixed */
94 if (strncasecmp("0x", in_s, 2) == 0) {
98 /* need to be exactly 8 characters */
99 const char *hex = "0123456789abcdefABCDEF";
100 if (strlen(in_s) != 8 || strspn(in_s, hex) != 8) {
101 fprintf(stderr, "%s\n", strerror(ERANGE));
105 input_i = strtoul(in_s, NULL, 16);
111 if (input_i < 0x1 || input_i > UINT32_MAX) {
112 fprintf(stderr, "%s\n", strerror(ERANGE));
118 if (force_fwrite == 0 && stat(path, &fstat) == 0 &&
119 S_ISREG(fstat.st_mode)) {
120 fprintf(stderr, "%s: %s\n", path, strerror(EEXIST));
125 * generate if not provided by user
126 * also handle unlikely zero return from lrand48()
128 while (input_i == 0) {
129 srand48(getpid() ^ time(NULL));
133 FILE *fp = fopen(path, "wb");
140 * we need just 4 bytes in native endianess
141 * not using sethostid() because it may be missing or just a stub
143 uint32_t hostid = input_i;
144 int written = fwrite(&hostid, 1, 4, fp);