xref: /freebsd/sys/kern/kern_uuid.c (revision a03411e84728e9b267056fd31c7d1d9d1dc1b01e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 
29 #include <sys/param.h>
30 #include <sys/endian.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/mutex.h>
34 #include <sys/sbuf.h>
35 #include <sys/socket.h>
36 #include <sys/sysproto.h>
37 #include <sys/systm.h>
38 #include <sys/jail.h>
39 #include <sys/uuid.h>
40 
41 #include <net/if.h>
42 #include <net/if_dl.h>
43 #include <net/if_types.h>
44 #include <net/vnet.h>
45 
46 /*
47  * See also:
48  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
49  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
50  *
51  * Note that the generator state is itself an UUID, but the time and clock
52  * sequence fields are written in the native byte order.
53  */
54 
55 CTASSERT(sizeof(struct uuid) == 16);
56 
57 /* We use an alternative, more convenient representation in the generator. */
58 struct uuid_private {
59 	union {
60 		uint64_t	ll;	/* internal, for uuid_last only */
61 		struct {
62 			uint32_t	low;
63 			uint16_t	mid;
64 			uint16_t	hi;
65 		} x;
66 	} time;
67 	uint16_t	seq;			/* Big-endian. */
68 	uint16_t	node[UUID_NODE_LEN>>1];
69 };
70 
71 CTASSERT(sizeof(struct uuid_private) == 16);
72 
73 struct uuid_macaddr {
74 	uint16_t	state;
75 #define	UUID_ETHER_EMPTY	0
76 #define	UUID_ETHER_RANDOM	1
77 #define	UUID_ETHER_UNIQUE	2
78 	uint16_t	node[UUID_NODE_LEN>>1];
79 };
80 
81 static struct uuid_private uuid_last;
82 
83 #define UUID_NETHER	4
84 static struct uuid_macaddr uuid_ether[UUID_NETHER];
85 
86 static struct mtx uuid_mutex;
87 MTX_SYSINIT(uuid_lock, &uuid_mutex, "UUID generator mutex lock", MTX_DEF);
88 
89 /*
90  * Return the first MAC address added in the array. If it's empty, then
91  * construct a sufficiently random multicast MAC address first. Any
92  * addresses added later will bump the random MAC address up tp the next
93  * index.
94  */
95 static void
96 uuid_node(uint16_t *node)
97 {
98 	int i;
99 
100 	if (uuid_ether[0].state == UUID_ETHER_EMPTY) {
101 		for (i = 0; i < (UUID_NODE_LEN>>1); i++)
102 			uuid_ether[0].node[i] = (uint16_t)arc4random();
103 		*((uint8_t*)uuid_ether[0].node) |= 0x01;
104 		uuid_ether[0].state = UUID_ETHER_RANDOM;
105 	}
106 	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
107 		node[i] = uuid_ether[0].node[i];
108 }
109 
110 /*
111  * Get the current time as a 60 bit count of 100-nanosecond intervals
112  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
113  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
114  * Gregorian reform to the Christian calendar.
115  */
116 static uint64_t
117 uuid_time(void)
118 {
119 	struct bintime bt;
120 	uint64_t time = 0x01B21DD213814000LL;
121 
122 	bintime(&bt);
123 	time += (uint64_t)bt.sec * 10000000LL;
124 	time += (10000000LL * (uint32_t)(bt.frac >> 32)) >> 32;
125 	return (time & ((1LL << 60) - 1LL));
126 }
127 
128 struct uuid *
129 kern_uuidgen(struct uuid *store, size_t count)
130 {
131 	struct uuid_private uuid;
132 	uint64_t time;
133 	size_t n;
134 
135 	mtx_lock(&uuid_mutex);
136 
137 	uuid_node(uuid.node);
138 	time = uuid_time();
139 
140 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid.node[0] ||
141 	    uuid_last.node[1] != uuid.node[1] ||
142 	    uuid_last.node[2] != uuid.node[2])
143 		uuid.seq = (uint16_t)arc4random() & 0x3fff;
144 	else if (uuid_last.time.ll >= time)
145 		uuid.seq = (uuid_last.seq + 1) & 0x3fff;
146 	else
147 		uuid.seq = uuid_last.seq;
148 
149 	uuid_last = uuid;
150 	uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
151 
152 	mtx_unlock(&uuid_mutex);
153 
154 	/* Set sequence and variant and deal with byte order. */
155 	uuid.seq = htobe16(uuid.seq | 0x8000);
156 
157 	for (n = 0; n < count; n++) {
158 		/* Set time and version (=1). */
159 		uuid.time.x.low = (uint32_t)time;
160 		uuid.time.x.mid = (uint16_t)(time >> 32);
161 		uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
162 		store[n] = *(struct uuid *)&uuid;
163 		time++;
164 	}
165 
166 	return (store);
167 }
168 
169 #ifndef _SYS_SYSPROTO_H_
170 struct uuidgen_args {
171 	struct uuid *store;
172 	int	count;
173 };
174 #endif
175 int
176 sys_uuidgen(struct thread *td, struct uuidgen_args *uap)
177 {
178 	struct uuid *store;
179 	size_t count;
180 	int error;
181 
182 	/*
183 	 * Limit the number of UUIDs that can be created at the same time
184 	 * to some arbitrary number. This isn't really necessary, but I
185 	 * like to have some sort of upper-bound that's less than 2G :-)
186 	 * XXX probably needs to be tunable.
187 	 */
188 	if (uap->count < 1 || uap->count > 2048)
189 		return (EINVAL);
190 
191 	count = uap->count;
192 	store = malloc(count * sizeof(struct uuid), M_TEMP, M_WAITOK);
193 	kern_uuidgen(store, count);
194 	error = copyout(store, uap->store, count * sizeof(struct uuid));
195 	free(store, M_TEMP);
196 	return (error);
197 }
198 
199 int
200 uuid_ether_add(const uint8_t *addr)
201 {
202 	int i, sum;
203 
204 	/*
205 	 * Validate input. No multicast (flag 0x1), no locally administered
206 	 * (flag 0x2) and no 'all-zeroes' addresses.
207 	 */
208 	if (addr[0] & 0x03)
209 		return (EINVAL);
210 	sum = 0;
211 	for (i = 0; i < UUID_NODE_LEN; i++)
212 		sum += addr[i];
213 	if (sum == 0)
214 		return (EINVAL);
215 
216 	mtx_lock(&uuid_mutex);
217 
218 	/* Make sure the MAC isn't known already and that there's space. */
219 	i = 0;
220 	while (i < UUID_NETHER && uuid_ether[i].state == UUID_ETHER_UNIQUE) {
221 		if (!bcmp(addr, uuid_ether[i].node, UUID_NODE_LEN)) {
222 			mtx_unlock(&uuid_mutex);
223 			return (EEXIST);
224 		}
225 		i++;
226 	}
227 	if (i == UUID_NETHER) {
228 		mtx_unlock(&uuid_mutex);
229 		return (ENOSPC);
230 	}
231 
232 	/* Insert MAC at index, moving the non-empty entry if possible. */
233 	if (uuid_ether[i].state == UUID_ETHER_RANDOM && i < UUID_NETHER - 1)
234 		uuid_ether[i + 1] = uuid_ether[i];
235 	uuid_ether[i].state = UUID_ETHER_UNIQUE;
236 	bcopy(addr, uuid_ether[i].node, UUID_NODE_LEN);
237 	mtx_unlock(&uuid_mutex);
238 	return (0);
239 }
240 
241 int
242 uuid_ether_del(const uint8_t *addr)
243 {
244 	int i;
245 
246 	mtx_lock(&uuid_mutex);
247 	i = 0;
248 	while (i < UUID_NETHER && uuid_ether[i].state == UUID_ETHER_UNIQUE &&
249 	    bcmp(addr, uuid_ether[i].node, UUID_NODE_LEN))
250 		i++;
251 	if (i == UUID_NETHER || uuid_ether[i].state != UUID_ETHER_UNIQUE) {
252 		mtx_unlock(&uuid_mutex);
253 		return (ENOENT);
254 	}
255 
256 	/* Remove it by shifting higher index entries down. */
257 	while (i < UUID_NETHER - 1 && uuid_ether[i].state != UUID_ETHER_EMPTY) {
258 		uuid_ether[i] = uuid_ether[i + 1];
259 		i++;
260 	}
261 	if (uuid_ether[i].state != UUID_ETHER_EMPTY) {
262 		uuid_ether[i].state = UUID_ETHER_EMPTY;
263 		bzero(uuid_ether[i].node, UUID_NODE_LEN);
264 	}
265 	mtx_unlock(&uuid_mutex);
266 	return (0);
267 }
268 
269 int
270 snprintf_uuid(char *buf, size_t sz, struct uuid *uuid)
271 {
272 	struct uuid_private *id;
273 	int cnt;
274 
275 	id = (struct uuid_private *)uuid;
276 	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
277 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
278 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
279 	return (cnt);
280 }
281 
282 int
283 printf_uuid(struct uuid *uuid)
284 {
285 	char buf[38];
286 
287 	snprintf_uuid(buf, sizeof(buf), uuid);
288 	return (printf("%s", buf));
289 }
290 
291 int
292 sbuf_printf_uuid(struct sbuf *sb, struct uuid *uuid)
293 {
294 	char buf[38];
295 
296 	snprintf_uuid(buf, sizeof(buf), uuid);
297 	return (sbuf_cat(sb, buf));
298 }
299 
300 /*
301  * Encode/Decode UUID into byte-stream.
302  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
303  *
304  * 0                   1                   2                   3
305  *   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
306  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
307  *  |                          time_low                             |
308  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
309  *  |       time_mid                |         time_hi_and_version   |
310  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
311  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
312  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
313  *  |                         node (2-5)                            |
314  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
315  */
316 
317 void
318 le_uuid_enc(void *buf, struct uuid const *uuid)
319 {
320 	u_char *p;
321 	int i;
322 
323 	p = buf;
324 	le32enc(p, uuid->time_low);
325 	le16enc(p + 4, uuid->time_mid);
326 	le16enc(p + 6, uuid->time_hi_and_version);
327 	p[8] = uuid->clock_seq_hi_and_reserved;
328 	p[9] = uuid->clock_seq_low;
329 	for (i = 0; i < _UUID_NODE_LEN; i++)
330 		p[10 + i] = uuid->node[i];
331 }
332 
333 void
334 le_uuid_dec(void const *buf, struct uuid *uuid)
335 {
336 	u_char const *p;
337 	int i;
338 
339 	p = buf;
340 	uuid->time_low = le32dec(p);
341 	uuid->time_mid = le16dec(p + 4);
342 	uuid->time_hi_and_version = le16dec(p + 6);
343 	uuid->clock_seq_hi_and_reserved = p[8];
344 	uuid->clock_seq_low = p[9];
345 	for (i = 0; i < _UUID_NODE_LEN; i++)
346 		uuid->node[i] = p[10 + i];
347 }
348 
349 void
350 be_uuid_enc(void *buf, struct uuid const *uuid)
351 {
352 	u_char *p;
353 	int i;
354 
355 	p = buf;
356 	be32enc(p, uuid->time_low);
357 	be16enc(p + 4, uuid->time_mid);
358 	be16enc(p + 6, uuid->time_hi_and_version);
359 	p[8] = uuid->clock_seq_hi_and_reserved;
360 	p[9] = uuid->clock_seq_low;
361 	for (i = 0; i < _UUID_NODE_LEN; i++)
362 		p[10 + i] = uuid->node[i];
363 }
364 
365 void
366 be_uuid_dec(void const *buf, struct uuid *uuid)
367 {
368 	u_char const *p;
369 	int i;
370 
371 	p = buf;
372 	uuid->time_low = be32dec(p);
373 	uuid->time_mid = be16dec(p + 4);
374 	uuid->time_hi_and_version = be16dec(p + 6);
375 	uuid->clock_seq_hi_and_reserved = p[8];
376 	uuid->clock_seq_low = p[9];
377 	for (i = 0; i < _UUID_NODE_LEN; i++)
378 		uuid->node[i] = p[10 + i];
379 }
380 
381 int
382 validate_uuid(const char *str, size_t size, struct uuid *uuid, int flags)
383 {
384 	u_int c[11];
385 	int n;
386 
387 	if (size == 0 || *str == '\0') {
388 		/* An empty string may represent a nil UUID. */
389 		if ((flags & VUUIDF_EMPTYOK) != 0) {
390 			if (uuid != NULL)
391 				bzero(uuid, sizeof(*uuid));
392 			return (0);
393 		}
394 
395 		return (EINVAL);
396 	}
397 
398 	/* The UUID string representation has a fixed length. */
399 	if (size != 36)
400 		return (EINVAL);
401 
402 	/*
403 	 * We only work with "new" UUIDs. New UUIDs have the form:
404 	 *      01234567-89ab-cdef-0123-456789abcdef
405 	 * The so called "old" UUIDs, which we don't support, have the form:
406 	 *      0123456789ab.cd.ef.01.23.45.67.89.ab
407 	 */
408 	if (str[8] != '-')
409 		return (EINVAL);
410 
411 	/* Now check the format. */
412 	n = sscanf(str, "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", c + 0, c + 1,
413 	    c + 2, c + 3, c + 4, c + 5, c + 6, c + 7, c + 8, c + 9, c + 10);
414 	/* Make sure we have all conversions. */
415 	if (n != 11)
416 		return (EINVAL);
417 
418 	/* Successful scan. Build the UUID if requested. */
419 	if (uuid != NULL) {
420 		uuid->time_low = c[0];
421 		uuid->time_mid = c[1];
422 		uuid->time_hi_and_version = c[2];
423 		uuid->clock_seq_hi_and_reserved = c[3];
424 		uuid->clock_seq_low = c[4];
425 		for (n = 0; n < 6; n++)
426 			uuid->node[n] = c[n + 5];
427 	}
428 
429 	if ((flags & VUUIDF_CHECKSEMANTICS) == 0)
430 		return (0);
431 
432 	return (((c[3] & 0x80) != 0x00 &&		/* variant 0? */
433 	    (c[3] & 0xc0) != 0x80 &&			/* variant 1? */
434 	    (c[3] & 0xe0) != 0xc0) ? EINVAL : 0);	/* variant 2? */
435 }
436 
437 #define	VUUIDF_PARSEFLAGS	(VUUIDF_EMPTYOK | VUUIDF_CHECKSEMANTICS)
438 
439 int
440 parse_uuid(const char *str, struct uuid *uuid)
441 {
442 
443 	return (validate_uuid(str, strlen(str), uuid, VUUIDF_PARSEFLAGS));
444 }
445 
446 int
447 uuidcmp(const struct uuid *uuid1, const struct uuid *uuid2)
448 {
449 
450 	return (memcmp(uuid1, uuid2, sizeof(struct uuid)));
451 }
452