xref: /netbsd-src/sys/kern/kern_uuid.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: kern_uuid.c,v 1.3 2004/09/12 23:17:37 thorpej 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.3 2004/09/12 23:17:37 thorpej Exp $");
33 
34 #include <sys/param.h>
35 #include <sys/endian.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.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/sa.h>
45 #include <sys/mount.h>
46 #include <sys/syscallargs.h>
47 #include <sys/uio.h>
48 
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/if_types.h>
52 
53 /*
54  * See also:
55  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
56  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
57  *
58  * Note that the generator state is itself an UUID, but the time and clock
59  * sequence fields are written in the native byte order.
60  */
61 
62 /* XXX Do we have a similar ASSERT()? */
63 #define CTASSERT(x)
64 
65 CTASSERT(sizeof(struct uuid) == 16);
66 
67 /* We use an alternative, more convenient representation in the generator. */
68 struct uuid_private {
69 	union {
70 		uint64_t	ll;		/* internal. */
71 		struct {
72 			uint32_t	low;
73 			uint16_t	mid;
74 			uint16_t	hi;
75 		} x;
76 	} time;
77 	uint16_t	seq;			/* Big-endian. */
78 	uint16_t	node[UUID_NODE_LEN>>1];
79 };
80 
81 CTASSERT(sizeof(struct uuid_private) == 16);
82 
83 static struct uuid_private uuid_last;
84 
85 /* "UUID generator mutex lock" */
86 static struct simplelock uuid_mutex = SIMPLELOCK_INITIALIZER;
87 
88 /*
89  * Return the first MAC address we encounter or, if none was found,
90  * construct a sufficiently random multicast address. We don't try
91  * to return the same MAC address as previously returned. We always
92  * generate a new multicast address if no MAC address exists in the
93  * system.
94  * It would be nice to know if 'ifnet' or any of its sub-structures
95  * has been changed in any way. If not, we could simply skip the
96  * scan and safely return the MAC address we returned before.
97  */
98 static void
99 uuid_node(uint16_t *node)
100 {
101 	struct ifnet *ifp;
102 	struct ifaddr *ifa;
103 	struct sockaddr_dl *sdl;
104 	int i, s;
105 
106 	s = splnet();
107 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
108 		/* Walk the address list */
109 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
110 			sdl = (struct sockaddr_dl*)ifa->ifa_addr;
111 			if (sdl != NULL && sdl->sdl_family == AF_LINK &&
112 			    sdl->sdl_type == IFT_ETHER) {
113 				/* Got a MAC address. */
114 				memcpy(node, LLADDR(sdl), UUID_NODE_LEN);
115 				splx(s);
116 				return;
117 			}
118 		}
119 	}
120 	splx(s);
121 
122 	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
123 		node[i] = (uint16_t)arc4random();
124 	*((uint8_t*)node) |= 0x01;
125 }
126 
127 /*
128  * Get the current time as a 60 bit count of 100-nanosecond intervals
129  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
130  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
131  * Gregorian reform to the Christian calendar.
132  */
133 /*
134  * At present, NetBSD has no timespec source, only timeval sources.  So,
135  * we use timeval.
136  */
137 static uint64_t
138 uuid_time(void)
139 {
140 	struct timeval tv;
141 	uint64_t time = 0x01B21DD213814000LL;
142 
143 	microtime(&tv);
144 	time += (uint64_t)tv.tv_sec * 10000000LL;
145 	time += (uint64_t)(10 * tv.tv_usec);
146 	return (time & ((1LL << 60) - 1LL));
147 }
148 
149 /*
150  * Internal routine to actually generate the UUID.
151  */
152 static void
153 uuid_generate(struct uuid_private *uuid, uint64_t *timep, int count)
154 {
155 	uint64_t time;
156 
157 	simple_lock(&uuid_mutex);
158 
159 	uuid_node(uuid->node);
160 	time = uuid_time();
161 	*timep = time;
162 
163 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid->node[0] ||
164 	    uuid_last.node[1] != uuid->node[1] ||
165 	    uuid_last.node[2] != uuid->node[2])
166 		uuid->seq = (uint16_t)arc4random() & 0x3fff;
167 	else if (uuid_last.time.ll >= time)
168 		uuid->seq = (uuid_last.seq + 1) & 0x3fff;
169 	else
170 		uuid->seq = uuid_last.seq;
171 
172 	uuid_last = *uuid;
173 	uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
174 
175 	simple_unlock(&uuid_mutex);
176 }
177 
178 int
179 sys_uuidgen(struct lwp *l, void *v, register_t *retval)
180 {
181 	struct sys_uuidgen_args *uap = v;
182 	struct uuid_private uuid;
183 	uint64_t time;
184 	int error;
185 
186 	/*
187 	 * Limit the number of UUIDs that can be created at the same time
188 	 * to some arbitrary number. This isn't really necessary, but I
189 	 * like to have some sort of upper-bound that's less than 2G :-)
190 	 * XXX needs to be tunable.
191 	 */
192 	if (SCARG(uap,count) < 1 || SCARG(uap,count) > 2048)
193 		return (EINVAL);
194 
195 	/* XXX: pre-validate accessibility to the whole of the UUID store? */
196 
197 	/* Generate the base UUID. */
198 	uuid_generate(&uuid, &time, SCARG(uap, count));
199 
200 	/* Set sequence and variant and deal with byte order. */
201 	uuid.seq = htobe16(uuid.seq | 0x8000);
202 
203 	/* XXX: this should copyout larger chunks at a time. */
204 	do {
205 		/* Set time and version (=1) and deal with byte order. */
206 		uuid.time.x.low = (uint32_t)time;
207 		uuid.time.x.mid = (uint16_t)(time >> 32);
208 		uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
209 		error = copyout(&uuid, SCARG(uap,store), sizeof(uuid));
210 		SCARG(uap, store)++;
211 		SCARG(uap, count)--;
212 		time++;
213 	} while (SCARG(uap, count) > 0 && error == 0);
214 
215 	return (error);
216 }
217 
218 int
219 uuid_snprintf(char *buf, size_t sz, const struct uuid *uuid)
220 {
221 	const struct uuid_private *id;
222 	int cnt;
223 
224 	id = (const struct uuid_private *)uuid;
225 	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
226 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
227 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
228 	return (cnt);
229 }
230 
231 int
232 uuid_printf(const struct uuid *uuid)
233 {
234 	char buf[UUID_STR_LEN];
235 
236 	(void) uuid_snprintf(buf, sizeof(buf), uuid);
237 	printf("%s", buf);
238 	return (0);
239 }
240 
241 /*
242  * Encode/Decode UUID into octet-stream.
243  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
244  *
245  * 0                   1                   2                   3
246  *   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
247  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
248  *  |                          time_low                             |
249  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
250  *  |       time_mid                |         time_hi_and_version   |
251  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
252  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
253  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
254  *  |                         node (2-5)                            |
255  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
256  */
257 
258 void
259 uuid_enc_le(void *buf, const struct uuid *uuid)
260 {
261 	uint8_t *p = buf;
262 	int i;
263 
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 
273 void
274 uuid_dec_le(void const *buf, struct uuid *uuid)
275 {
276 	const uint8_t *p = buf;
277 	int i;
278 
279 	uuid->time_low = le32dec(p);
280 	uuid->time_mid = le16dec(p + 4);
281 	uuid->time_hi_and_version = le16dec(p + 6);
282 	uuid->clock_seq_hi_and_reserved = p[8];
283 	uuid->clock_seq_low = p[9];
284 	for (i = 0; i < _UUID_NODE_LEN; i++)
285 		uuid->node[i] = p[10 + i];
286 }
287 
288 void
289 uuid_enc_be(void *buf, const struct uuid *uuid)
290 {
291 	uint8_t *p = buf;
292 	int i;
293 
294 	be32enc(p, uuid->time_low);
295 	be16enc(p + 4, uuid->time_mid);
296 	be16enc(p + 6, uuid->time_hi_and_version);
297 	p[8] = uuid->clock_seq_hi_and_reserved;
298 	p[9] = uuid->clock_seq_low;
299 	for (i = 0; i < _UUID_NODE_LEN; i++)
300 		p[10 + i] = uuid->node[i];
301 }
302 
303 void
304 uuid_dec_be(void const *buf, struct uuid *uuid)
305 {
306 	const uint8_t *p = buf;
307 	int i;
308 
309 	uuid->time_low = be32dec(p);
310 	uuid->time_mid = le16dec(p + 4);
311 	uuid->time_hi_and_version = be16dec(p + 6);
312 	uuid->clock_seq_hi_and_reserved = p[8];
313 	uuid->clock_seq_low = p[9];
314 	for (i = 0; i < _UUID_NODE_LEN; i++)
315 		uuid->node[i] = p[10 + i];
316 }
317