kern_uuid.c revision 185571
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
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/kern/kern_uuid.c 185571 2008-12-02 21:37:28Z bz $");
29
30#include <sys/param.h>
31#include <sys/endian.h>
32#include <sys/kernel.h>
33#include <sys/lock.h>
34#include <sys/mutex.h>
35#include <sys/sbuf.h>
36#include <sys/socket.h>
37#include <sys/sysproto.h>
38#include <sys/systm.h>
39#include <sys/uuid.h>
40#include <sys/vimage.h>
41
42#include <net/if.h>
43#include <net/if_dl.h>
44#include <net/if_types.h>
45#include <net/vnet.h>
46
47/*
48 * See also:
49 *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
50 *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
51 *
52 * Note that the generator state is itself an UUID, but the time and clock
53 * sequence fields are written in the native byte order.
54 */
55
56CTASSERT(sizeof(struct uuid) == 16);
57
58/* We use an alternative, more convenient representation in the generator. */
59struct uuid_private {
60	union {
61		uint64_t	ll;		/* internal. */
62		struct {
63			uint32_t	low;
64			uint16_t	mid;
65			uint16_t	hi;
66		} x;
67	} time;
68	uint16_t	seq;			/* Big-endian. */
69	uint16_t	node[UUID_NODE_LEN>>1];
70};
71
72CTASSERT(sizeof(struct uuid_private) == 16);
73
74static struct uuid_private uuid_last;
75
76static struct mtx uuid_mutex;
77MTX_SYSINIT(uuid_lock, &uuid_mutex, "UUID generator mutex lock", MTX_DEF);
78
79/*
80 * Return the first MAC address we encounter or, if none was found,
81 * construct a sufficiently random multicast address. We don't try
82 * to return the same MAC address as previously returned. We always
83 * generate a new multicast address if no MAC address exists in the
84 * system.
85 * It would be nice to know if 'ifnet' or any of its sub-structures
86 * has been changed in any way. If not, we could simply skip the
87 * scan and safely return the MAC address we returned before.
88 */
89static void
90uuid_node(uint16_t *node)
91{
92	INIT_VNET_NET(curvnet);
93	struct ifnet *ifp;
94	struct ifaddr *ifa;
95	struct sockaddr_dl *sdl;
96	int i;
97
98	IFNET_RLOCK();
99	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
100		/* Walk the address list */
101		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
102			sdl = (struct sockaddr_dl*)ifa->ifa_addr;
103			if (sdl != NULL && sdl->sdl_family == AF_LINK &&
104			    sdl->sdl_type == IFT_ETHER) {
105				/* Got a MAC address. */
106				bcopy(LLADDR(sdl), node, UUID_NODE_LEN);
107				IFNET_RUNLOCK();
108				return;
109			}
110		}
111	}
112	IFNET_RUNLOCK();
113
114	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
115		node[i] = (uint16_t)arc4random();
116	*((uint8_t*)node) |= 0x01;
117}
118
119/*
120 * Get the current time as a 60 bit count of 100-nanosecond intervals
121 * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
122 * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
123 * Gregorian reform to the Christian calendar.
124 */
125static uint64_t
126uuid_time(void)
127{
128	struct bintime bt;
129	uint64_t time = 0x01B21DD213814000LL;
130
131	bintime(&bt);
132	time += (uint64_t)bt.sec * 10000000LL;
133	time += (10000000LL * (uint32_t)(bt.frac >> 32)) >> 32;
134	return (time & ((1LL << 60) - 1LL));
135}
136
137struct uuid *
138kern_uuidgen(struct uuid *store, size_t count)
139{
140	struct uuid_private uuid;
141	uint64_t time;
142	size_t n;
143
144	mtx_lock(&uuid_mutex);
145
146	uuid_node(uuid.node);
147	time = uuid_time();
148
149	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid.node[0] ||
150	    uuid_last.node[1] != uuid.node[1] ||
151	    uuid_last.node[2] != uuid.node[2])
152		uuid.seq = (uint16_t)arc4random() & 0x3fff;
153	else if (uuid_last.time.ll >= time)
154		uuid.seq = (uuid_last.seq + 1) & 0x3fff;
155	else
156		uuid.seq = uuid_last.seq;
157
158	uuid_last = uuid;
159	uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
160
161	mtx_unlock(&uuid_mutex);
162
163	/* Set sequence and variant and deal with byte order. */
164	uuid.seq = htobe16(uuid.seq | 0x8000);
165
166	for (n = 0; n < count; n++) {
167		/* Set time and version (=1). */
168		uuid.time.x.low = (uint32_t)time;
169		uuid.time.x.mid = (uint16_t)(time >> 32);
170		uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
171		store[n] = *(struct uuid *)&uuid;
172		time++;
173	}
174
175	return (store);
176}
177
178#ifndef _SYS_SYSPROTO_H_
179struct uuidgen_args {
180	struct uuid *store;
181	int	count;
182};
183#endif
184int
185uuidgen(struct thread *td, struct uuidgen_args *uap)
186{
187	struct uuid *store;
188	size_t count;
189	int error;
190
191	/*
192	 * Limit the number of UUIDs that can be created at the same time
193	 * to some arbitrary number. This isn't really necessary, but I
194	 * like to have some sort of upper-bound that's less than 2G :-)
195	 * XXX probably needs to be tunable.
196	 */
197	if (uap->count < 1 || uap->count > 2048)
198		return (EINVAL);
199
200	count = uap->count;
201	store = malloc(count * sizeof(struct uuid), M_TEMP, M_WAITOK);
202	kern_uuidgen(store, count);
203	error = copyout(store, uap->store, count * sizeof(struct uuid));
204	free(store, M_TEMP);
205	return (error);
206}
207
208int
209snprintf_uuid(char *buf, size_t sz, struct uuid *uuid)
210{
211	struct uuid_private *id;
212	int cnt;
213
214	id = (struct uuid_private *)uuid;
215	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
216	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
217	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
218	return (cnt);
219}
220
221int
222printf_uuid(struct uuid *uuid)
223{
224	char buf[38];
225
226	snprintf_uuid(buf, sizeof(buf), uuid);
227	return (printf("%s", buf));
228}
229
230int
231sbuf_printf_uuid(struct sbuf *sb, struct uuid *uuid)
232{
233	char buf[38];
234
235	snprintf_uuid(buf, sizeof(buf), uuid);
236	return (sbuf_printf(sb, "%s", buf));
237}
238
239/*
240 * Encode/Decode UUID into byte-stream.
241 *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
242 *
243 * 0                   1                   2                   3
244 *   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
245 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
246 *  |                          time_low                             |
247 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
248 *  |       time_mid                |         time_hi_and_version   |
249 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
250 *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
251 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
252 *  |                         node (2-5)                            |
253 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
254 */
255
256void
257le_uuid_enc(void *buf, struct uuid const *uuid)
258{
259	u_char *p;
260	int i;
261
262	p = buf;
263	le32enc(p, uuid->time_low);
264	le16enc(p + 4, uuid->time_mid);
265	le16enc(p + 6, uuid->time_hi_and_version);
266	p[8] = uuid->clock_seq_hi_and_reserved;
267	p[9] = uuid->clock_seq_low;
268	for (i = 0; i < _UUID_NODE_LEN; i++)
269		p[10 + i] = uuid->node[i];
270}
271
272void
273le_uuid_dec(void const *buf, struct uuid *uuid)
274{
275	u_char const *p;
276	int i;
277
278	p = buf;
279	uuid->time_low = le32dec(p);
280	uuid->time_mid = le16dec(p + 4);
281	uuid->time_hi_and_version = le16dec(p + 6);
282	uuid->clock_seq_hi_and_reserved = p[8];
283	uuid->clock_seq_low = p[9];
284	for (i = 0; i < _UUID_NODE_LEN; i++)
285		uuid->node[i] = p[10 + i];
286}
287
288void
289be_uuid_enc(void *buf, struct uuid const *uuid)
290{
291	u_char *p;
292	int i;
293
294	p = buf;
295	be32enc(p, uuid->time_low);
296	be16enc(p + 4, uuid->time_mid);
297	be16enc(p + 6, uuid->time_hi_and_version);
298	p[8] = uuid->clock_seq_hi_and_reserved;
299	p[9] = uuid->clock_seq_low;
300	for (i = 0; i < _UUID_NODE_LEN; i++)
301		p[10 + i] = uuid->node[i];
302}
303
304void
305be_uuid_dec(void const *buf, struct uuid *uuid)
306{
307	u_char const *p;
308	int i;
309
310	p = buf;
311	uuid->time_low = be32dec(p);
312	uuid->time_mid = le16dec(p + 4);
313	uuid->time_hi_and_version = be16dec(p + 6);
314	uuid->clock_seq_hi_and_reserved = p[8];
315	uuid->clock_seq_low = p[9];
316	for (i = 0; i < _UUID_NODE_LEN; i++)
317		uuid->node[i] = p[10 + i];
318}
319
320int
321parse_uuid(const char *str, struct uuid *uuid)
322{
323	u_int c[11];
324	int n;
325
326	/* An empty string represents a nil UUID. */
327	if (*str == '\0') {
328		bzero(uuid, sizeof(*uuid));
329		return (0);
330	}
331
332	/* The UUID string representation has a fixed length. */
333	if (strlen(str) != 36)
334		return (EINVAL);
335
336	/*
337	 * We only work with "new" UUIDs. New UUIDs have the form:
338	 *      01234567-89ab-cdef-0123-456789abcdef
339	 * The so called "old" UUIDs, which we don't support, have the form:
340	 *      0123456789ab.cd.ef.01.23.45.67.89.ab
341	 */
342	if (str[8] != '-')
343		return (EINVAL);
344
345	n = sscanf(str, "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", c + 0, c + 1,
346	    c + 2, c + 3, c + 4, c + 5, c + 6, c + 7, c + 8, c + 9, c + 10);
347	/* Make sure we have all conversions. */
348	if (n != 11)
349		return (EINVAL);
350
351	/* Successful scan. Build the UUID. */
352	uuid->time_low = c[0];
353	uuid->time_mid = c[1];
354	uuid->time_hi_and_version = c[2];
355	uuid->clock_seq_hi_and_reserved = c[3];
356	uuid->clock_seq_low = c[4];
357	for (n = 0; n < 6; n++)
358		uuid->node[n] = c[n + 5];
359
360	/* Check semantics... */
361	return (((c[3] & 0x80) != 0x00 &&		/* variant 0? */
362	    (c[3] & 0xc0) != 0x80 &&			/* variant 1? */
363	    (c[3] & 0xe0) != 0xc0) ? EINVAL : 0);	/* variant 2? */
364}
365