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