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