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