Consolidate #include <sys/time.h> so libbb.h does it.
[oweals/busybox.git] / e2fsprogs / uuid / gen_uuid.c
1 /*
2  * gen_uuid.c --- generate a DCE-compatible uuid
3  *
4  * Copyright (C) 1996, 1997, 1998, 1999 Theodore Ts'o.
5  *
6  * %Begin-Header%
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  * 1. Redistributions of source code must retain the above copyright
11  *    notice, and the entire permission notice in its entirety,
12  *    including the disclaimer of warranties.
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  * 3. The name of the author may not be used to endorse or promote
17  *    products derived from this software without specific prior
18  *    written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
21  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
23  * WHICH ARE HEREBY DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
30  * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH
31  * DAMAGE.
32  * %End-Header%
33  */
34
35 #include <unistd.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <fcntl.h>
39 #include <errno.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <sys/file.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 #include <sys/ioctl.h>
45 #endif
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_SOCKIO_H
48 #include <sys/sockio.h>
49 #endif
50 #ifdef HAVE_NET_IF_H
51 #include <net/if.h>
52 #endif
53 #ifdef HAVE_NETINET_IN_H
54 #include <netinet/in.h>
55 #endif
56 #ifdef HAVE_NET_IF_DL_H
57 #include <net/if_dl.h>
58 #endif
59
60 #include "uuidP.h"
61
62 #ifdef HAVE_SRANDOM
63 #define srand(x)        srandom(x)
64 #define rand()          random()
65 #endif
66
67 static int get_random_fd(void)
68 {
69         struct timeval  tv;
70         static int      fd = -2;
71         int             i;
72
73         if (fd == -2) {
74                 gettimeofday(&tv, 0);
75                 fd = open("/dev/urandom", O_RDONLY);
76                 if (fd == -1)
77                         fd = open("/dev/random", O_RDONLY | O_NONBLOCK);
78                 srand((getpid() << 16) ^ getuid() ^ tv.tv_sec ^ tv.tv_usec);
79         }
80         /* Crank the random number generator a few times */
81         gettimeofday(&tv, 0);
82         for (i = (tv.tv_sec ^ tv.tv_usec) & 0x1F; i > 0; i--)
83                 rand();
84         return fd;
85 }
86
87
88 /*
89  * Generate a series of random bytes.  Use /dev/urandom if possible,
90  * and if not, use srandom/random.
91  */
92 static void get_random_bytes(void *buf, int nbytes)
93 {
94         int i, n = nbytes, fd = get_random_fd();
95         int lose_counter = 0;
96         unsigned char *cp = (unsigned char *) buf;
97
98         if (fd >= 0) {
99                 while (n > 0) {
100                         i = read(fd, cp, n);
101                         if (i <= 0) {
102                                 if (lose_counter++ > 16)
103                                         break;
104                                 continue;
105                         }
106                         n -= i;
107                         cp += i;
108                         lose_counter = 0;
109                 }
110         }
111
112         /*
113          * We do this all the time, but this is the only source of
114          * randomness if /dev/random/urandom is out to lunch.
115          */
116         for (cp = buf, i = 0; i < nbytes; i++)
117                 *cp++ ^= (rand() >> 7) & 0xFF;
118         return;
119 }
120
121 /*
122  * Get the ethernet hardware address, if we can find it...
123  */
124 static int get_node_id(unsigned char *node_id)
125 {
126 #ifdef HAVE_NET_IF_H
127         int             sd;
128         struct ifreq    ifr, *ifrp;
129         struct ifconf   ifc;
130         char buf[1024];
131         int             n, i;
132         unsigned char   *a;
133 #ifdef HAVE_NET_IF_DL_H
134         struct sockaddr_dl *sdlp;
135 #endif
136
137 /*
138  * BSD 4.4 defines the size of an ifreq to be
139  * max(sizeof(ifreq), sizeof(ifreq.ifr_name)+ifreq.ifr_addr.sa_len
140  * However, under earlier systems, sa_len isn't present, so the size is
141  * just sizeof(struct ifreq)
142  */
143 #ifdef HAVE_SA_LEN
144 #ifndef max
145 #define max(a,b) ((a) > (b) ? (a) : (b))
146 #endif
147 #define ifreq_size(i) max(sizeof(struct ifreq),\
148      sizeof((i).ifr_name)+(i).ifr_addr.sa_len)
149 #else
150 #define ifreq_size(i) sizeof(struct ifreq)
151 #endif /* HAVE_SA_LEN*/
152
153         sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
154         if (sd < 0) {
155                 return -1;
156         }
157         memset(buf, 0, sizeof(buf));
158         ifc.ifc_len = sizeof(buf);
159         ifc.ifc_buf = buf;
160         if (ioctl (sd, SIOCGIFCONF, (char *)&ifc) < 0) {
161                 close(sd);
162                 return -1;
163         }
164         n = ifc.ifc_len;
165         for (i = 0; i < n; i+= ifreq_size(*ifrp) ) {
166                 ifrp = (struct ifreq *)((char *) ifc.ifc_buf+i);
167                 strncpy(ifr.ifr_name, ifrp->ifr_name, IFNAMSIZ);
168 #ifdef SIOCGIFHWADDR
169                 if (ioctl(sd, SIOCGIFHWADDR, &ifr) < 0)
170                         continue;
171                 a = (unsigned char *) &ifr.ifr_hwaddr.sa_data;
172 #else
173 #ifdef SIOCGENADDR
174                 if (ioctl(sd, SIOCGENADDR, &ifr) < 0)
175                         continue;
176                 a = (unsigned char *) ifr.ifr_enaddr;
177 #else
178 #ifdef HAVE_NET_IF_DL_H
179                 sdlp = (struct sockaddr_dl *) &ifrp->ifr_addr;
180                 if ((sdlp->sdl_family != AF_LINK) || (sdlp->sdl_alen != 6))
181                         continue;
182                 a = (unsigned char *) &sdlp->sdl_data[sdlp->sdl_nlen];
183 #else
184                 /*
185                  * XXX we don't have a way of getting the hardware
186                  * address
187                  */
188                 close(sd);
189                 return 0;
190 #endif /* HAVE_NET_IF_DL_H */
191 #endif /* SIOCGENADDR */
192 #endif /* SIOCGIFHWADDR */
193                 if (!a[0] && !a[1] && !a[2] && !a[3] && !a[4] && !a[5])
194                         continue;
195                 if (node_id) {
196                         memcpy(node_id, a, 6);
197                         close(sd);
198                         return 1;
199                 }
200         }
201         close(sd);
202 #endif
203         return 0;
204 }
205
206 /* Assume that the gettimeofday() has microsecond granularity */
207 #define MAX_ADJUSTMENT 10
208
209 static int get_clock(uint32_t *clock_high, uint32_t *clock_low, uint16_t *ret_clock_seq)
210 {
211         static int                      adjustment = 0;
212         static struct timeval           last = {0, 0};
213         static uint16_t                 clock_seq;
214         struct timeval                  tv;
215         unsigned long long              clock_reg;
216
217 try_again:
218         gettimeofday(&tv, 0);
219         if ((last.tv_sec == 0) && (last.tv_usec == 0)) {
220                 get_random_bytes(&clock_seq, sizeof(clock_seq));
221                 clock_seq &= 0x3FFF;
222                 last = tv;
223                 last.tv_sec--;
224         }
225         if ((tv.tv_sec < last.tv_sec) ||
226             ((tv.tv_sec == last.tv_sec) &&
227              (tv.tv_usec < last.tv_usec))) {
228                 clock_seq = (clock_seq+1) & 0x3FFF;
229                 adjustment = 0;
230                 last = tv;
231         } else if ((tv.tv_sec == last.tv_sec) &&
232             (tv.tv_usec == last.tv_usec)) {
233                 if (adjustment >= MAX_ADJUSTMENT)
234                         goto try_again;
235                 adjustment++;
236         } else {
237                 adjustment = 0;
238                 last = tv;
239         }
240
241         clock_reg = tv.tv_usec*10 + adjustment;
242         clock_reg += ((unsigned long long) tv.tv_sec)*10000000;
243         clock_reg += (((unsigned long long) 0x01B21DD2) << 32) + 0x13814000;
244
245         *clock_high = clock_reg >> 32;
246         *clock_low = clock_reg;
247         *ret_clock_seq = clock_seq;
248         return 0;
249 }
250
251 void uuid_generate_time(uuid_t out)
252 {
253         static unsigned char node_id[6];
254         static int has_init = 0;
255         struct uuid uu;
256         uint32_t        clock_mid;
257
258         if (!has_init) {
259                 if (get_node_id(node_id) <= 0) {
260                         get_random_bytes(node_id, 6);
261                         /*
262                          * Set multicast bit, to prevent conflicts
263                          * with IEEE 802 addresses obtained from
264                          * network cards
265                          */
266                         node_id[0] |= 0x01;
267                 }
268                 has_init = 1;
269         }
270         get_clock(&clock_mid, &uu.time_low, &uu.clock_seq);
271         uu.clock_seq |= 0x8000;
272         uu.time_mid = (uint16_t) clock_mid;
273         uu.time_hi_and_version = ((clock_mid >> 16) & 0x0FFF) | 0x1000;
274         memcpy(uu.node, node_id, 6);
275         uuid_pack(&uu, out);
276 }
277
278 void uuid_generate_random(uuid_t out)
279 {
280         uuid_t  buf;
281         struct uuid uu;
282
283         get_random_bytes(buf, sizeof(buf));
284         uuid_unpack(buf, &uu);
285
286         uu.clock_seq = (uu.clock_seq & 0x3FFF) | 0x8000;
287         uu.time_hi_and_version = (uu.time_hi_and_version & 0x0FFF) | 0x4000;
288         uuid_pack(&uu, out);
289 }
290
291 /*
292  * This is the generic front-end to uuid_generate_random and
293  * uuid_generate_time.  It uses uuid_generate_random only if
294  * /dev/urandom is available, since otherwise we won't have
295  * high-quality randomness.
296  */
297 void uuid_generate(uuid_t out)
298 {
299         if (get_random_fd() >= 0)
300                 uuid_generate_random(out);
301         else
302                 uuid_generate_time(out);
303 }