xref: /dflybsd-src/sys/kern/kern_uuid.c (revision 92b817bb6b0d8e22d601698e9d3864697def6575)
1 /*-
2  * Copyright (c) 2002 Marcel Moolenaar
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/kern/kern_uuid.c,v 1.13 2007/04/23 12:53:00 pjd Exp $
27  * $DragonFly: src/sys/kern/kern_uuid.c,v 1.4 2007/06/19 06:07:57 dillon Exp $
28  */
29 
30 #include <sys/param.h>
31 #include <sys/endian.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/kern_syscall.h>
36 #include <sys/random.h>
37 #include <sys/sbuf.h>
38 #include <sys/socket.h>
39 #include <sys/sysproto.h>
40 #include <sys/uuid.h>
41 #include <sys/gpt.h>
42 #include <net/if_var.h>
43 
44 /*
45  * See also:
46  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
47  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
48  *
49  * Note that the generator state is itself an UUID, but the time and clock
50  * sequence fields are written in the native byte order.
51  */
52 
53 /* We use an alternative, more convenient representation in the generator. */
54 struct uuid_private {
55 	union {
56 		uint64_t	ll;		/* internal. */
57 		struct {
58 			uint32_t	low;
59 			uint16_t	mid;
60 			uint16_t	hi;
61 		} x;
62 	} time;
63 	uint16_t	seq;			/* Big-endian. */
64 	uint16_t	node[UUID_NODE_LEN>>1];
65 };
66 
67 static struct uuid_private uuid_last;
68 
69 static struct lock uuid_lock;
70 
71 static
72 void
73 uuid_lock_init(void *arg __unused)
74 {
75 	lockinit(&uuid_lock, "uuid", 0, 0);
76 }
77 SYSINIT(uuid_lock, SI_BOOT1_POST, SI_ORDER_ANY, uuid_lock_init, NULL);
78 
79 /*
80  * Ask the network subsystem for a real MAC address from any of the
81  * system interfaces.  If we can't find one, generate a random multicast
82  * MAC address.
83  */
84 static void
85 uuid_node(uint16_t *node)
86 {
87 	if (if_getanyethermac(node, UUID_NODE_LEN) != 0)
88 		read_random(node, UUID_NODE_LEN);
89 	*((uint8_t*)node) |= 0x01;
90 }
91 
92 /*
93  * Get the current time as a 60 bit count of 100-nanosecond intervals
94  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
95  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
96  * Gregorian reform to the Christian calendar.
97  */
98 static uint64_t
99 uuid_time(void)
100 {
101 	struct timespec ts;
102 	uint64_t time = 0x01B21DD213814000LL;
103 
104 	nanotime(&ts);
105 	time += ts.tv_sec * 10000000LL;		/* 100 ns increments */
106 	time += ts.tv_nsec / 100;		/* 100 ns increments */
107 	return (time & ((1LL << 60) - 1LL));	/* limit to 60 bits */
108 }
109 
110 struct uuid *
111 kern_uuidgen(struct uuid *store, size_t count)
112 {
113 	struct uuid_private uuid;
114 	uint64_t time;
115 	size_t n;
116 
117 	lockmgr(&uuid_lock, LK_EXCLUSIVE | LK_RETRY);
118 
119 	uuid_node(uuid.node);
120 	time = uuid_time();
121 
122 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid.node[0] ||
123 	    uuid_last.node[1] != uuid.node[1] ||
124 	    uuid_last.node[2] != uuid.node[2]) {
125 		read_random(&uuid.seq, sizeof(uuid.seq));
126 		uuid.seq &= 0x3fff;
127 	} else if (uuid_last.time.ll >= time) {
128 		uuid.seq = (uuid_last.seq + 1) & 0x3fff;
129 	} else {
130 		uuid.seq = uuid_last.seq;
131 	}
132 
133 	uuid_last = uuid;
134 	uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
135 
136 	lockmgr(&uuid_lock, LK_RELEASE);
137 
138 	/* Set sequence and variant and deal with byte order. */
139 	uuid.seq = htobe16(uuid.seq | 0x8000);
140 
141 	for (n = 0; n < count; n++) {
142 		/* Set time and version (=1). */
143 		uuid.time.x.low = (uint32_t)time;
144 		uuid.time.x.mid = (uint16_t)(time >> 32);
145 		uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
146 		store[n] = *(struct uuid *)&uuid;
147 		time++;
148 	}
149 
150 	return (store);
151 }
152 
153 /*
154  * uuidgen(struct uuid *store, int count)
155  *
156  * Generate an array of new UUIDs
157  *
158  * MPALMOSTSAFE
159  */
160 int
161 sys_uuidgen(struct uuidgen_args *uap)
162 {
163 	struct uuid *store;
164 	size_t count;
165 	int error;
166 
167 	/*
168 	 * Limit the number of UUIDs that can be created at the same time
169 	 * to some arbitrary number. This isn't really necessary, but I
170 	 * like to have some sort of upper-bound that's less than 2G :-)
171 	 * XXX probably needs to be tunable.
172 	 */
173 	if (uap->count < 1 || uap->count > 2048)
174 		return (EINVAL);
175 
176 	count = uap->count;
177 	store = kmalloc(count * sizeof(struct uuid), M_TEMP, M_WAITOK);
178 	get_mplock();
179 	kern_uuidgen(store, count);
180 	rel_mplock();
181 	error = copyout(store, uap->store, count * sizeof(struct uuid));
182 	kfree(store, M_TEMP);
183 	return (error);
184 }
185 
186 int
187 snprintf_uuid(char *buf, size_t sz, struct uuid *uuid)
188 {
189 	struct uuid_private *id;
190 	int cnt;
191 
192 	id = (struct uuid_private *)uuid;
193 	cnt = ksnprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
194 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
195 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
196 	return (cnt);
197 }
198 
199 int
200 printf_uuid(struct uuid *uuid)
201 {
202 	char buf[38];
203 
204 	snprintf_uuid(buf, sizeof(buf), uuid);
205 	return (kprintf("%s", buf));
206 }
207 
208 int
209 sbuf_printf_uuid(struct sbuf *sb, struct uuid *uuid)
210 {
211 	char buf[38];
212 
213 	snprintf_uuid(buf, sizeof(buf), uuid);
214 	return (sbuf_printf(sb, "%s", buf));
215 }
216 
217 /*
218  * Test functions
219  */
220 
221 /* A macro used to improve the readability of uuid_compare(). */
222 #define DIFF_RETURN(a, b, field)	do {			\
223 	if ((a)->field != (b)->field)				\
224 		return (((a)->field < (b)->field) ? -1 : 1);	\
225 } while (0)
226 
227 /*
228  * kuuid_compare() - compare two UUIDs.
229  * See also:
230  *	http://www.opengroup.org/onlinepubs/009629399/uuid_compare.htm
231  *
232  * NOTE: Either UUID can be NULL, meaning a nil UUID. nil UUIDs are smaller
233  *	 than any non-nil UUID.
234  */
235 int
236 kuuid_compare(const struct uuid *a, const struct uuid *b)
237 {
238 	int	res;
239 
240 	/* Deal with NULL or equal pointers. */
241 	if (a == b)
242 		return (0);
243 	if (a == NULL)
244 		return ((kuuid_is_nil(b)) ? 0 : -1);
245 	if (b == NULL)
246 		return ((kuuid_is_nil(a)) ? 0 : 1);
247 
248 	/* We have to compare the hard way. */
249 	DIFF_RETURN(a, b, time_low);
250 	DIFF_RETURN(a, b, time_mid);
251 	DIFF_RETURN(a, b, time_hi_and_version);
252 	DIFF_RETURN(a, b, clock_seq_hi_and_reserved);
253 	DIFF_RETURN(a, b, clock_seq_low);
254 
255 	res = bcmp(a->node, b->node, sizeof(a->node));
256 	if (res)
257 		return ((res < 0) ? -1 : 1);
258 	return (0);
259 }
260 
261 #undef DIFF_RETURN
262 
263 int
264 kuuid_is_nil(const struct uuid *uuid)
265 {
266 	int i;
267 
268 	for (i = 0; i < sizeof(*uuid); i += sizeof(int)) {
269 		if (*(const int *)((const char *)uuid + i) != 0)
270 			return(0);
271 	}
272 	return(1);
273 }
274 
275 int
276 kuuid_is_ccd(const struct uuid *uuid)
277 {
278 	static struct uuid ccd_uuid = GPT_ENT_TYPE_DRAGONFLY_CCD;
279 	return(kuuid_compare(uuid, &ccd_uuid) == 0);
280 }
281 
282 int
283 kuuid_is_vinum(const struct uuid *uuid)
284 {
285 	static struct uuid vinum_uuid = GPT_ENT_TYPE_DRAGONFLY_VINUM;
286 	return(kuuid_compare(uuid, &vinum_uuid) == 0);
287 }
288 
289 /*
290  * Encode/Decode UUID into byte-stream.
291  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
292  *
293  * 0                   1                   2                   3
294  *   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
295  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
296  *  |                          time_low                             |
297  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
298  *  |       time_mid                |         time_hi_and_version   |
299  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
300  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
301  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
302  *  |                         node (2-5)                            |
303  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
304  */
305 
306 void
307 le_uuid_enc(void *buf, struct uuid const *uuid)
308 {
309 	u_char *p;
310 	int i;
311 
312 	p = buf;
313 	le32enc(p, uuid->time_low);
314 	le16enc(p + 4, uuid->time_mid);
315 	le16enc(p + 6, uuid->time_hi_and_version);
316 	p[8] = uuid->clock_seq_hi_and_reserved;
317 	p[9] = uuid->clock_seq_low;
318 	for (i = 0; i < _UUID_NODE_LEN; i++)
319 		p[10 + i] = uuid->node[i];
320 }
321 
322 void
323 le_uuid_dec(void const *buf, struct uuid *uuid)
324 {
325 	u_char const *p;
326 	int i;
327 
328 	p = buf;
329 	uuid->time_low = le32dec(p);
330 	uuid->time_mid = le16dec(p + 4);
331 	uuid->time_hi_and_version = le16dec(p + 6);
332 	uuid->clock_seq_hi_and_reserved = p[8];
333 	uuid->clock_seq_low = p[9];
334 	for (i = 0; i < _UUID_NODE_LEN; i++)
335 		uuid->node[i] = p[10 + i];
336 }
337 
338 void
339 be_uuid_enc(void *buf, struct uuid const *uuid)
340 {
341 	u_char *p;
342 	int i;
343 
344 	p = buf;
345 	be32enc(p, uuid->time_low);
346 	be16enc(p + 4, uuid->time_mid);
347 	be16enc(p + 6, uuid->time_hi_and_version);
348 	p[8] = uuid->clock_seq_hi_and_reserved;
349 	p[9] = uuid->clock_seq_low;
350 	for (i = 0; i < _UUID_NODE_LEN; i++)
351 		p[10 + i] = uuid->node[i];
352 }
353 
354 void
355 be_uuid_dec(void const *buf, struct uuid *uuid)
356 {
357 	u_char const *p;
358 	int i;
359 
360 	p = buf;
361 	uuid->time_low = be32dec(p);
362 	uuid->time_mid = le16dec(p + 4);
363 	uuid->time_hi_and_version = be16dec(p + 6);
364 	uuid->clock_seq_hi_and_reserved = p[8];
365 	uuid->clock_seq_low = p[9];
366 	for (i = 0; i < _UUID_NODE_LEN; i++)
367 		uuid->node[i] = p[10 + i];
368 }
369 
370 int
371 parse_uuid(const char *str, struct uuid *uuid)
372 {
373 	u_int c[11];
374 	int n;
375 
376 	/* An empty string represents a nil UUID. */
377 	if (*str == '\0') {
378 		bzero(uuid, sizeof(*uuid));
379 		return (0);
380 	}
381 
382 	/* The UUID string representation has a fixed length. */
383 	if (strlen(str) != 36)
384 		return (EINVAL);
385 
386 	/*
387 	 * We only work with "new" UUIDs. New UUIDs have the form:
388 	 *      01234567-89ab-cdef-0123-456789abcdef
389 	 * The so called "old" UUIDs, which we don't support, have the form:
390 	 *      0123456789ab.cd.ef.01.23.45.67.89.ab
391 	 */
392 	if (str[8] != '-')
393 		return (EINVAL);
394 
395 	n = ksscanf(str, "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", c + 0, c + 1,
396 	    c + 2, c + 3, c + 4, c + 5, c + 6, c + 7, c + 8, c + 9, c + 10);
397 	/* Make sure we have all conversions. */
398 	if (n != 11)
399 		return (EINVAL);
400 
401 	/* Successful scan. Build the UUID. */
402 	uuid->time_low = c[0];
403 	uuid->time_mid = c[1];
404 	uuid->time_hi_and_version = c[2];
405 	uuid->clock_seq_hi_and_reserved = c[3];
406 	uuid->clock_seq_low = c[4];
407 	for (n = 0; n < 6; n++)
408 		uuid->node[n] = c[n + 5];
409 
410 	/* Check semantics... */
411 	return (((c[3] & 0x80) != 0x00 &&		/* variant 0? */
412 	    (c[3] & 0xc0) != 0x80 &&			/* variant 1? */
413 	    (c[3] & 0xe0) != 0xc0) ? EINVAL : 0);	/* variant 2? */
414 }
415