xref: /netbsd-src/sys/kern/kern_uuid.c (revision ce099b40997c43048fb78bd578195f81d2456523)
1 /*	$NetBSD: kern_uuid.c,v 1.14 2008/04/19 18:21:38 plunky Exp $	*/
2 
3 /*
4  * Copyright (c) 2002 Marcel Moolenaar
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: /repoman/r/ncvs/src/sys/kern/kern_uuid.c,v 1.7 2004/01/12 13:34:11 rse Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 __KERNEL_RCSID(0, "$NetBSD: kern_uuid.c,v 1.14 2008/04/19 18:21:38 plunky Exp $");
33 
34 #include <sys/param.h>
35 #include <sys/endian.h>
36 #include <sys/kernel.h>
37 #include <sys/mutex.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/uuid.h>
41 
42 /* NetBSD */
43 #include <sys/proc.h>
44 #include <sys/mount.h>
45 #include <sys/syscallargs.h>
46 #include <sys/uio.h>
47 
48 #include <net/if.h>
49 #include <net/if_dl.h>
50 #include <net/if_types.h>
51 
52 /*
53  * See also:
54  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
55  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
56  *
57  * Note that the generator state is itself an UUID, but the time and clock
58  * sequence fields are written in the native byte order.
59  */
60 
61 /* XXX Do we have a similar ASSERT()? */
62 #define CTASSERT(x)
63 
64 CTASSERT(sizeof(struct uuid) == 16);
65 
66 /* We use an alternative, more convenient representation in the generator. */
67 struct uuid_private {
68 	union {
69 		uint64_t	ll;		/* internal. */
70 		struct {
71 			uint32_t	low;
72 			uint16_t	mid;
73 			uint16_t	hi;
74 		} x;
75 	} time;
76 	uint16_t	seq;			/* Big-endian. */
77 	uint16_t	node[UUID_NODE_LEN>>1];
78 };
79 
80 CTASSERT(sizeof(struct uuid_private) == 16);
81 
82 static struct uuid_private uuid_last;
83 
84 /* "UUID generator mutex lock" */
85 static kmutex_t uuid_mutex;
86 
87 void
88 uuid_init(void)
89 {
90 
91 	mutex_init(&uuid_mutex, MUTEX_DEFAULT, IPL_NONE);
92 }
93 
94 /*
95  * Return the first MAC address we encounter or, if none was found,
96  * construct a sufficiently random multicast address. We don't try
97  * to return the same MAC address as previously returned. We always
98  * generate a new multicast address if no MAC address exists in the
99  * system.
100  * It would be nice to know if 'ifnet' or any of its sub-structures
101  * has been changed in any way. If not, we could simply skip the
102  * scan and safely return the MAC address we returned before.
103  */
104 static void
105 uuid_node(uint16_t *node)
106 {
107 	struct ifnet *ifp;
108 	struct ifaddr *ifa;
109 	struct sockaddr_dl *sdl;
110 	int i, s;
111 
112 	s = splnet();
113 	KERNEL_LOCK(1, NULL);
114 	IFNET_FOREACH(ifp) {
115 		/* Walk the address list */
116 		IFADDR_FOREACH(ifa, ifp) {
117 			sdl = (struct sockaddr_dl*)ifa->ifa_addr;
118 			if (sdl != NULL && sdl->sdl_family == AF_LINK &&
119 			    sdl->sdl_type == IFT_ETHER) {
120 				/* Got a MAC address. */
121 				memcpy(node, CLLADDR(sdl), UUID_NODE_LEN);
122 				KERNEL_UNLOCK_ONE(NULL);
123 				splx(s);
124 				return;
125 			}
126 		}
127 	}
128 	KERNEL_UNLOCK_ONE(NULL);
129 	splx(s);
130 
131 	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
132 		node[i] = (uint16_t)arc4random();
133 	*((uint8_t*)node) |= 0x01;
134 }
135 
136 /*
137  * Get the current time as a 60 bit count of 100-nanosecond intervals
138  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
139  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
140  * Gregorian reform to the Christian calendar.
141  */
142 /*
143  * At present, NetBSD has no timespec source, only timeval sources.  So,
144  * we use timeval.
145  */
146 static uint64_t
147 uuid_time(void)
148 {
149 	struct timeval tv;
150 	uint64_t xtime = 0x01B21DD213814000LL;
151 
152 	microtime(&tv);
153 	xtime += (uint64_t)tv.tv_sec * 10000000LL;
154 	xtime += (uint64_t)(10 * tv.tv_usec);
155 	return (xtime & ((1LL << 60) - 1LL));
156 }
157 
158 /*
159  * Internal routine to actually generate the UUID.
160  */
161 static void
162 uuid_generate(struct uuid_private *uuid, uint64_t *timep, int count)
163 {
164 	uint64_t xtime;
165 
166 	mutex_enter(&uuid_mutex);
167 
168 	uuid_node(uuid->node);
169 	xtime = uuid_time();
170 	*timep = xtime;
171 
172 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid->node[0] ||
173 	    uuid_last.node[1] != uuid->node[1] ||
174 	    uuid_last.node[2] != uuid->node[2])
175 		uuid->seq = (uint16_t)arc4random() & 0x3fff;
176 	else if (uuid_last.time.ll >= xtime)
177 		uuid->seq = (uuid_last.seq + 1) & 0x3fff;
178 	else
179 		uuid->seq = uuid_last.seq;
180 
181 	uuid_last = *uuid;
182 	uuid_last.time.ll = (xtime + count - 1) & ((1LL << 60) - 1LL);
183 
184 	mutex_exit(&uuid_mutex);
185 }
186 
187 int
188 sys_uuidgen(struct lwp *l, const struct sys_uuidgen_args *uap, register_t *retval)
189 {
190 	struct uuid_private uuid;
191 	uint64_t xtime;
192 	int error;
193 	int i;
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 needs to be tunable.
200 	 */
201 	if (SCARG(uap,count) < 1 || SCARG(uap,count) > 2048)
202 		return (EINVAL);
203 
204 	/* XXX: pre-validate accessibility to the whole of the UUID store? */
205 
206 	/* Generate the base UUID. */
207 	uuid_generate(&uuid, &xtime, SCARG(uap, count));
208 
209 	/* Set sequence and variant and deal with byte order. */
210 	uuid.seq = htobe16(uuid.seq | 0x8000);
211 
212 	/* XXX: this should copyout larger chunks at a time. */
213 	for (i = 0; i < SCARG(uap, count); xtime++, i++) {
214 		/* Set time and version (=1) and deal with byte order. */
215 		uuid.time.x.low = (uint32_t)xtime;
216 		uuid.time.x.mid = (uint16_t)(xtime >> 32);
217 		uuid.time.x.hi = ((uint16_t)(xtime >> 48) & 0xfff) | (1 << 12);
218 		error = copyout(&uuid, SCARG(uap,store) + i, sizeof(uuid));
219 		if (error != 0)
220 			return error;
221 	}
222 
223 	return 0;
224 }
225 
226 int
227 uuid_snprintf(char *buf, size_t sz, const struct uuid *uuid)
228 {
229 	const struct uuid_private *id;
230 	int cnt;
231 
232 	id = (const struct uuid_private *)uuid;
233 	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
234 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
235 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
236 	return (cnt);
237 }
238 
239 int
240 uuid_printf(const struct uuid *uuid)
241 {
242 	char buf[UUID_STR_LEN];
243 
244 	(void) uuid_snprintf(buf, sizeof(buf), uuid);
245 	printf("%s", buf);
246 	return (0);
247 }
248 
249 /*
250  * Encode/Decode UUID into octet-stream.
251  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
252  *
253  * 0                   1                   2                   3
254  *   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
255  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
256  *  |                          time_low                             |
257  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
258  *  |       time_mid                |         time_hi_and_version   |
259  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
260  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
261  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
262  *  |                         node (2-5)                            |
263  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
264  */
265 
266 void
267 uuid_enc_le(void *buf, const struct uuid *uuid)
268 {
269 	uint8_t *p = buf;
270 	int i;
271 
272 	le32enc(p, uuid->time_low);
273 	le16enc(p + 4, uuid->time_mid);
274 	le16enc(p + 6, uuid->time_hi_and_version);
275 	p[8] = uuid->clock_seq_hi_and_reserved;
276 	p[9] = uuid->clock_seq_low;
277 	for (i = 0; i < _UUID_NODE_LEN; i++)
278 		p[10 + i] = uuid->node[i];
279 }
280 
281 void
282 uuid_dec_le(void const *buf, struct uuid *uuid)
283 {
284 	const uint8_t *p = buf;
285 	int i;
286 
287 	uuid->time_low = le32dec(p);
288 	uuid->time_mid = le16dec(p + 4);
289 	uuid->time_hi_and_version = le16dec(p + 6);
290 	uuid->clock_seq_hi_and_reserved = p[8];
291 	uuid->clock_seq_low = p[9];
292 	for (i = 0; i < _UUID_NODE_LEN; i++)
293 		uuid->node[i] = p[10 + i];
294 }
295 
296 void
297 uuid_enc_be(void *buf, const struct uuid *uuid)
298 {
299 	uint8_t *p = buf;
300 	int i;
301 
302 	be32enc(p, uuid->time_low);
303 	be16enc(p + 4, uuid->time_mid);
304 	be16enc(p + 6, uuid->time_hi_and_version);
305 	p[8] = uuid->clock_seq_hi_and_reserved;
306 	p[9] = uuid->clock_seq_low;
307 	for (i = 0; i < _UUID_NODE_LEN; i++)
308 		p[10 + i] = uuid->node[i];
309 }
310 
311 void
312 uuid_dec_be(void const *buf, struct uuid *uuid)
313 {
314 	const uint8_t *p = buf;
315 	int i;
316 
317 	uuid->time_low = be32dec(p);
318 	uuid->time_mid = be16dec(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