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