xref: /netbsd-src/sys/kern/kern_uuid.c (revision a536ee5124e62c9a0051a252f7833dc8f50f44c9)
1 /*	$NetBSD: kern_uuid.c,v 1.18 2011/11/19 22:51:25 tls Exp $	*/
2 
3 /*
4  * Copyright (c) 2002 Marcel Moolenaar
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: /repoman/r/ncvs/src/sys/kern/kern_uuid.c,v 1.7 2004/01/12 13:34:11 rse Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 __KERNEL_RCSID(0, "$NetBSD: kern_uuid.c,v 1.18 2011/11/19 22:51:25 tls Exp $");
33 
34 #include <sys/param.h>
35 #include <sys/endian.h>
36 #include <sys/kernel.h>
37 #include <sys/mutex.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/uuid.h>
41 
42 /* NetBSD */
43 #include <sys/proc.h>
44 #include <sys/mount.h>
45 #include <sys/syscallargs.h>
46 #include <sys/uio.h>
47 #include <sys/cprng.h>
48 
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_types.h>
52 
53 /*
54  * See also:
55  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
56  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
57  *
58  * Note that the generator state is itself an UUID, but the time and clock
59  * sequence fields are written in the native byte order.
60  */
61 
62 CTASSERT(sizeof(struct uuid) == 16);
63 
64 /* We use an alternative, more convenient representation in the generator. */
65 struct uuid_private {
66 	union {
67 		uint64_t	ll;		/* internal. */
68 		struct {
69 			uint32_t	low;
70 			uint16_t	mid;
71 			uint16_t	hi;
72 		} x;
73 	} time;
74 	uint16_t	seq;			/* Big-endian. */
75 	uint16_t	node[UUID_NODE_LEN>>1];
76 };
77 
78 CTASSERT(sizeof(struct uuid_private) == 16);
79 
80 static struct uuid_private uuid_last;
81 
82 /* "UUID generator mutex lock" */
83 static kmutex_t uuid_mutex;
84 
85 void
86 uuid_init(void)
87 {
88 
89 	mutex_init(&uuid_mutex, MUTEX_DEFAULT, IPL_NONE);
90 }
91 
92 /*
93  * Return the first MAC address we encounter or, if none was found,
94  * construct a sufficiently random multicast address. We don't try
95  * to return the same MAC address as previously returned. We always
96  * generate a new multicast address if no MAC address exists in the
97  * system.
98  * It would be nice to know if 'ifnet' or any of its sub-structures
99  * has been changed in any way. If not, we could simply skip the
100  * scan and safely return the MAC address we returned before.
101  */
102 static void
103 uuid_node(uint16_t *node)
104 {
105 	struct ifnet *ifp;
106 	struct ifaddr *ifa;
107 	struct sockaddr_dl *sdl;
108 	int i, s;
109 
110 	s = splnet();
111 	KERNEL_LOCK(1, NULL);
112 	IFNET_FOREACH(ifp) {
113 		/* Walk the address list */
114 		IFADDR_FOREACH(ifa, ifp) {
115 			sdl = (struct sockaddr_dl*)ifa->ifa_addr;
116 			if (sdl != NULL && sdl->sdl_family == AF_LINK &&
117 			    sdl->sdl_type == IFT_ETHER) {
118 				/* Got a MAC address. */
119 				memcpy(node, CLLADDR(sdl), UUID_NODE_LEN);
120 				KERNEL_UNLOCK_ONE(NULL);
121 				splx(s);
122 				return;
123 			}
124 		}
125 	}
126 	KERNEL_UNLOCK_ONE(NULL);
127 	splx(s);
128 
129 	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
130 		node[i] = (uint16_t)cprng_fast32();
131 	*((uint8_t*)node) |= 0x01;
132 }
133 
134 /*
135  * Get the current time as a 60 bit count of 100-nanosecond intervals
136  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
137  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
138  * Gregorian reform to the Christian calendar.
139  */
140 static uint64_t
141 uuid_time(void)
142 {
143 	struct timespec tsp;
144 	uint64_t xtime = 0x01B21DD213814000LL;
145 
146 	nanotime(&tsp);
147 	xtime += (uint64_t)tsp.tv_sec * 10000000LL;
148 	xtime += (uint64_t)(tsp.tv_nsec / 100);
149 	return (xtime & ((1LL << 60) - 1LL));
150 }
151 
152 /*
153  * Internal routine to actually generate the UUID.
154  */
155 static void
156 uuid_generate(struct uuid_private *uuid, uint64_t *timep, int count)
157 {
158 	uint64_t xtime;
159 
160 	mutex_enter(&uuid_mutex);
161 
162 	uuid_node(uuid->node);
163 	xtime = uuid_time();
164 	*timep = xtime;
165 
166 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid->node[0] ||
167 	    uuid_last.node[1] != uuid->node[1] ||
168 	    uuid_last.node[2] != uuid->node[2])
169 		uuid->seq = (uint16_t)cprng_fast32() & 0x3fff;
170 	else if (uuid_last.time.ll >= xtime)
171 		uuid->seq = (uuid_last.seq + 1) & 0x3fff;
172 	else
173 		uuid->seq = uuid_last.seq;
174 
175 	uuid_last = *uuid;
176 	uuid_last.time.ll = (xtime + count - 1) & ((1LL << 60) - 1LL);
177 
178 	mutex_exit(&uuid_mutex);
179 }
180 
181 static int
182 kern_uuidgen(struct uuid *store, int count, bool to_user)
183 {
184 	struct uuid_private uuid;
185 	uint64_t xtime;
186 	int error = 0, i;
187 
188 	KASSERT(count >= 1);
189 
190 	/* Generate the base UUID. */
191 	uuid_generate(&uuid, &xtime, count);
192 
193 	/* Set sequence and variant and deal with byte order. */
194 	uuid.seq = htobe16(uuid.seq | 0x8000);
195 
196 	for (i = 0; i < count; xtime++, i++) {
197 		/* Set time and version (=1) and deal with byte order. */
198 		uuid.time.x.low = (uint32_t)xtime;
199 		uuid.time.x.mid = (uint16_t)(xtime >> 32);
200 		uuid.time.x.hi = ((uint16_t)(xtime >> 48) & 0xfff) | (1 << 12);
201 		if (to_user) {
202 			error = copyout(&uuid, store + i, sizeof(uuid));
203 			if (error != 0)
204 				break;
205 		} else {
206 			memcpy(store + i, &uuid, sizeof(uuid));
207 		}
208 	}
209 
210 	return error;
211 }
212 
213 int
214 sys_uuidgen(struct lwp *l, const struct sys_uuidgen_args *uap, register_t *retval)
215 {
216 	/*
217 	 * Limit the number of UUIDs that can be created at the same time
218 	 * to some arbitrary number. This isn't really necessary, but I
219 	 * like to have some sort of upper-bound that's less than 2G :-)
220 	 * XXX needs to be tunable.
221 	 */
222 	if (SCARG(uap,count) < 1 || SCARG(uap,count) > 2048)
223 		return (EINVAL);
224 
225 	return kern_uuidgen(SCARG(uap, store), SCARG(uap,count), true);
226 }
227 
228 int
229 uuidgen(struct uuid *store, int count)
230 {
231 	return kern_uuidgen(store,count, false);
232 }
233 
234 int
235 uuid_snprintf(char *buf, size_t sz, const struct uuid *uuid)
236 {
237 	const struct uuid_private *id;
238 	int cnt;
239 
240 	id = (const struct uuid_private *)uuid;
241 	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
242 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
243 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
244 	return (cnt);
245 }
246 
247 int
248 uuid_printf(const struct uuid *uuid)
249 {
250 	char buf[UUID_STR_LEN];
251 
252 	(void) uuid_snprintf(buf, sizeof(buf), uuid);
253 	printf("%s", buf);
254 	return (0);
255 }
256 
257 /*
258  * Encode/Decode UUID into octet-stream.
259  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
260  *
261  * 0                   1                   2                   3
262  *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
263  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
264  *  |                          time_low                             |
265  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
266  *  |       time_mid                |         time_hi_and_version   |
267  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
268  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
269  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
270  *  |                         node (2-5)                            |
271  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
272  */
273 
274 void
275 uuid_enc_le(void *buf, const struct uuid *uuid)
276 {
277 	uint8_t *p = buf;
278 	int i;
279 
280 	le32enc(p, uuid->time_low);
281 	le16enc(p + 4, uuid->time_mid);
282 	le16enc(p + 6, uuid->time_hi_and_version);
283 	p[8] = uuid->clock_seq_hi_and_reserved;
284 	p[9] = uuid->clock_seq_low;
285 	for (i = 0; i < _UUID_NODE_LEN; i++)
286 		p[10 + i] = uuid->node[i];
287 }
288 
289 void
290 uuid_dec_le(void const *buf, struct uuid *uuid)
291 {
292 	const uint8_t *p = buf;
293 	int i;
294 
295 	uuid->time_low = le32dec(p);
296 	uuid->time_mid = le16dec(p + 4);
297 	uuid->time_hi_and_version = le16dec(p + 6);
298 	uuid->clock_seq_hi_and_reserved = p[8];
299 	uuid->clock_seq_low = p[9];
300 	for (i = 0; i < _UUID_NODE_LEN; i++)
301 		uuid->node[i] = p[10 + i];
302 }
303 
304 void
305 uuid_enc_be(void *buf, const struct uuid *uuid)
306 {
307 	uint8_t *p = buf;
308 	int i;
309 
310 	be32enc(p, uuid->time_low);
311 	be16enc(p + 4, uuid->time_mid);
312 	be16enc(p + 6, uuid->time_hi_and_version);
313 	p[8] = uuid->clock_seq_hi_and_reserved;
314 	p[9] = uuid->clock_seq_low;
315 	for (i = 0; i < _UUID_NODE_LEN; i++)
316 		p[10 + i] = uuid->node[i];
317 }
318 
319 void
320 uuid_dec_be(void const *buf, struct uuid *uuid)
321 {
322 	const uint8_t *p = buf;
323 	int i;
324 
325 	uuid->time_low = be32dec(p);
326 	uuid->time_mid = be16dec(p + 4);
327 	uuid->time_hi_and_version = be16dec(p + 6);
328 	uuid->clock_seq_hi_and_reserved = p[8];
329 	uuid->clock_seq_low = p[9];
330 	for (i = 0; i < _UUID_NODE_LEN; i++)
331 		uuid->node[i] = p[10 + i];
332 }
333