Bring uuidgen(3) into libc and implement the uuidgen() system call.
[dragonfly.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  * $FreeBSD: src/sys/kern/kern_uuid.c,v 1.13 2007/04/23 12:53:00 pjd Exp $
27  * $DragonFly: src/sys/kern/kern_uuid.c,v 1.2 2007/06/16 19:57:10 dillon Exp $
28  */
29
30 #include <sys/param.h>
31 #include <sys/endian.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/kern_syscall.h>
36 #include <sys/random.h>
37 #include <sys/sbuf.h>
38 #include <sys/socket.h>
39 #include <sys/sysproto.h>
40 #include <sys/uuid.h>
41 #include <net/if_var.h>
42
43 /*
44  * See also:
45  *      http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
46  *      http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
47  *
48  * Note that the generator state is itself an UUID, but the time and clock
49  * sequence fields are written in the native byte order.
50  */
51
52 /* We use an alternative, more convenient representation in the generator. */
53 struct uuid_private {
54         union {
55                 uint64_t        ll;             /* internal. */
56                 struct {
57                         uint32_t        low;
58                         uint16_t        mid;
59                         uint16_t        hi;
60                 } x;
61         } time;
62         uint16_t        seq;                    /* Big-endian. */
63         uint16_t        node[UUID_NODE_LEN>>1];
64 };
65
66 static struct uuid_private uuid_last;
67
68 static struct lock uuid_lock;
69
70 static
71 void
72 uuid_lock_init(void *arg __unused)
73 {
74         lockinit(&uuid_lock, "uuid", 0, 0);
75 }
76 SYSINIT(uuid_lock, SI_BOOT1_POST, SI_ORDER_ANY, uuid_lock_init, NULL);
77
78 /*
79  * Ask the network subsystem for a real MAC address from any of the
80  * system interfaces.  If we can't find one, generate a random multicast
81  * MAC address.
82  */
83 static void
84 uuid_node(uint16_t *node)
85 {
86         if (if_getanyethermac(node, UUID_NODE_LEN) != 0)
87                 read_random(node, UUID_NODE_LEN);
88         *((uint8_t*)node) |= 0x01;
89 }
90
91 /*
92  * Get the current time as a 60 bit count of 100-nanosecond intervals
93  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
94  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
95  * Gregorian reform to the Christian calendar.
96  */
97 static uint64_t
98 uuid_time(void)
99 {
100         struct timespec ts;
101         uint64_t time = 0x01B21DD213814000LL;
102
103         nanotime(&ts);
104         time += ts.tv_sec * 10000000LL;         /* 100 ns increments */
105         time += ts.tv_nsec / 100;               /* 100 ns increments */
106         return (time & ((1LL << 60) - 1LL));    /* limit to 60 bits */
107 }
108
109 struct uuid *
110 kern_uuidgen(struct uuid *store, size_t count)
111 {
112         struct uuid_private uuid;
113         uint64_t time;
114         size_t n;
115
116         lockmgr(&uuid_lock, LK_EXCLUSIVE | LK_RETRY);
117
118         uuid_node(uuid.node);
119         time = uuid_time();
120
121         if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid.node[0] ||
122             uuid_last.node[1] != uuid.node[1] ||
123             uuid_last.node[2] != uuid.node[2]) {
124                 read_random(&uuid.seq, sizeof(uuid.seq));
125                 uuid.seq &= 0x3fff;
126         } else if (uuid_last.time.ll >= time) {
127                 uuid.seq = (uuid_last.seq + 1) & 0x3fff;
128         } else {
129                 uuid.seq = uuid_last.seq;
130         }
131
132         uuid_last = uuid;
133         uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
134
135         lockmgr(&uuid_lock, LK_RELEASE);
136
137         /* Set sequence and variant and deal with byte order. */
138         uuid.seq = htobe16(uuid.seq | 0x8000);
139
140         for (n = 0; n < count; n++) {
141                 /* Set time and version (=1). */
142                 uuid.time.x.low = (uint32_t)time;
143                 uuid.time.x.mid = (uint16_t)(time >> 32);
144                 uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
145                 store[n] = *(struct uuid *)&uuid;
146                 time++;
147         }
148
149         return (store);
150 }
151
152 /*
153  * uuidgen(struct uuid *store, int count)
154  *
155  * Generate an array of new UUIDs
156  */
157 int
158 sys_uuidgen(struct uuidgen_args *uap)
159 {
160         struct uuid *store;
161         size_t count;
162         int error;
163
164         /*
165          * Limit the number of UUIDs that can be created at the same time
166          * to some arbitrary number. This isn't really necessary, but I
167          * like to have some sort of upper-bound that's less than 2G :-)
168          * XXX probably needs to be tunable.
169          */
170         if (uap->count < 1 || uap->count > 2048)
171                 return (EINVAL);
172
173         count = uap->count;
174         store = kmalloc(count * sizeof(struct uuid), M_TEMP, M_WAITOK);
175         kern_uuidgen(store, count);
176         error = copyout(store, uap->store, count * sizeof(struct uuid));
177         kfree(store, M_TEMP);
178         return (error);
179 }
180
181 int
182 snprintf_uuid(char *buf, size_t sz, struct uuid *uuid)
183 {
184         struct uuid_private *id;
185         int cnt;
186
187         id = (struct uuid_private *)uuid;
188         cnt = ksnprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
189             id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
190             be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
191         return (cnt);
192 }
193
194 int
195 printf_uuid(struct uuid *uuid)
196 {
197         char buf[38];
198
199         snprintf_uuid(buf, sizeof(buf), uuid);
200         return (kprintf("%s", buf));
201 }
202
203 int
204 sbuf_printf_uuid(struct sbuf *sb, struct uuid *uuid)
205 {
206         char buf[38];
207
208         snprintf_uuid(buf, sizeof(buf), uuid);
209         return (sbuf_printf(sb, "%s", buf));
210 }
211
212 /*
213  * Encode/Decode UUID into byte-stream.
214  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
215  *
216  * 0                   1                   2                   3
217  *   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
218  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
219  *  |                          time_low                             |
220  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
221  *  |       time_mid                |         time_hi_and_version   |
222  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
223  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
224  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
225  *  |                         node (2-5)                            |
226  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
227  */
228
229 void
230 le_uuid_enc(void *buf, struct uuid const *uuid)
231 {
232         u_char *p;
233         int i;
234
235         p = buf;
236         le32enc(p, uuid->time_low);
237         le16enc(p + 4, uuid->time_mid);
238         le16enc(p + 6, uuid->time_hi_and_version);
239         p[8] = uuid->clock_seq_hi_and_reserved;
240         p[9] = uuid->clock_seq_low;
241         for (i = 0; i < _UUID_NODE_LEN; i++)
242                 p[10 + i] = uuid->node[i];
243 }
244
245 void
246 le_uuid_dec(void const *buf, struct uuid *uuid)
247 {
248         u_char const *p;
249         int i;
250
251         p = buf;
252         uuid->time_low = le32dec(p);
253         uuid->time_mid = le16dec(p + 4);
254         uuid->time_hi_and_version = le16dec(p + 6);
255         uuid->clock_seq_hi_and_reserved = p[8];
256         uuid->clock_seq_low = p[9];
257         for (i = 0; i < _UUID_NODE_LEN; i++)
258                 uuid->node[i] = p[10 + i];
259 }
260
261 void
262 be_uuid_enc(void *buf, struct uuid const *uuid)
263 {
264         u_char *p;
265         int i;
266
267         p = buf;
268         be32enc(p, uuid->time_low);
269         be16enc(p + 4, uuid->time_mid);
270         be16enc(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 be_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 = be32dec(p);
285         uuid->time_mid = le16dec(p + 4);
286         uuid->time_hi_and_version = be16dec(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 int
294 parse_uuid(const char *str, struct uuid *uuid)
295 {
296         u_int c[11];
297         int n;
298
299         /* An empty string represents a nil UUID. */
300         if (*str == '\0') {
301                 bzero(uuid, sizeof(*uuid));
302                 return (0);
303         }
304
305         /* The UUID string representation has a fixed length. */
306         if (strlen(str) != 36)
307                 return (EINVAL);
308
309         /*
310          * We only work with "new" UUIDs. New UUIDs have the form:
311          *      01234567-89ab-cdef-0123-456789abcdef
312          * The so called "old" UUIDs, which we don't support, have the form:
313          *      0123456789ab.cd.ef.01.23.45.67.89.ab
314          */
315         if (str[8] != '-')
316                 return (EINVAL);
317
318         n = ksscanf(str, "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", c + 0, c + 1,
319             c + 2, c + 3, c + 4, c + 5, c + 6, c + 7, c + 8, c + 9, c + 10);
320         /* Make sure we have all conversions. */
321         if (n != 11)
322                 return (EINVAL);
323
324         /* Successful scan. Build the UUID. */
325         uuid->time_low = c[0];
326         uuid->time_mid = c[1];
327         uuid->time_hi_and_version = c[2];
328         uuid->clock_seq_hi_and_reserved = c[3];
329         uuid->clock_seq_low = c[4];
330         for (n = 0; n < 6; n++)
331                 uuid->node[n] = c[n + 5];
332
333         /* Check semantics... */
334         return (((c[3] & 0x80) != 0x00 &&               /* variant 0? */
335             (c[3] & 0xc0) != 0x80 &&                    /* variant 1? */
336             (c[3] & 0xe0) != 0xc0) ? EINVAL : 0);       /* variant 2? */
337 }