1 // SPDX-License-Identifier: CDDL-1.0 2 /* 3 * CDDL HEADER START 4 * 5 * The contents of this file are subject to the terms of the 6 * Common Development and Distribution License (the "License"). 7 * You may not use this file except in compliance with the License. 8 * 9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 10 * or https://opensource.org/licenses/CDDL-1.0. 11 * See the License for the specific language governing permissions 12 * and limitations under the License. 13 * 14 * When distributing Covered Code, include this CDDL HEADER in each 15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 16 * If applicable, add the following below this CDDL HEADER, with the 17 * fields enclosed by brackets "[]" replaced with your own identifying 18 * information: Portions Copyright [yyyy] [name of copyright owner] 19 * 20 * CDDL HEADER END 21 */ 22 /* 23 * Copyright (c) 2017, Lawrence Livermore National Security, LLC. 24 */ 25 26 #include <fcntl.h> 27 #include <stdlib.h> 28 #include <stdio.h> 29 #include <sys/types.h> 30 #include <sys/stat.h> 31 #include <sys/systeminfo.h> 32 33 static unsigned long 34 get_spl_hostid(void) 35 { 36 FILE *f; 37 unsigned long hostid; 38 char *env; 39 40 /* 41 * Allow the hostid to be subverted for testing. 42 */ 43 env = getenv("ZFS_HOSTID"); 44 if (env) 45 return (strtoull(env, NULL, 0)); 46 47 f = fopen("/proc/sys/kernel/spl/hostid", "re"); 48 if (!f) 49 return (0); 50 51 if (fscanf(f, "%lx", &hostid) != 1) 52 hostid = 0; 53 54 fclose(f); 55 56 return (hostid); 57 } 58 59 unsigned long 60 get_system_hostid(void) 61 { 62 unsigned long hostid = get_spl_hostid(); 63 uint32_t system_hostid; 64 65 /* 66 * We do not use gethostid(3) because it can return a bogus ID, 67 * depending on the libc and /etc/hostid presence, 68 * and the kernel and userspace must agree. 69 * See comments above hostid_read() in the SPL. 70 */ 71 if (hostid == 0) { 72 int fd = open("/etc/hostid", O_RDONLY | O_CLOEXEC); 73 if (fd >= 0) { 74 if (read(fd, &system_hostid, sizeof (system_hostid)) 75 != sizeof (system_hostid)) 76 hostid = 0; 77 else 78 hostid = system_hostid; 79 (void) close(fd); 80 } 81 } 82 83 return (hostid & HOSTID_MASK); 84 } 85