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