Whamcloud - gitweb
LU-6081 user: use random() instead of /dev/urandom
[fs/lustre-release.git] / lustre / utils / liblustreapi_util.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * (C) Copyright (c) 2015, Cray Inc, all rights reserved.
7  *
8  * All rights reserved. This program and the accompanying materials
9  * are made available under the terms of the GNU Lesser General Public License
10  * LGPL version 2.1 or (at your discretion) any later version.
11  * LGPL version 2.1 accompanies this distribution, and is available at
12  * http://www.gnu.org/licenses/lgpl-2.1.html
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * LGPL HEADER END
20  */
21 /*
22  * lustre/utils/liblustreapi_util.c
23  *
24  * Misc LGPL-licenced utility functions for liblustreapi.
25  *
26  * Author: Frank Zago <fzago@cray.com>
27  */
28
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdbool.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <sys/syscall.h>
37
38 /*
39  * Indicate whether the liblustreapi_init() constructor below has run or not.
40  *
41  * This can be used by external programs to ensure if the initialization
42  * mechanism has actually worked.
43  */
44 bool liblustreapi_initialized;
45
46
47 /*
48  * Initializes the library
49  */
50 static __attribute__ ((constructor)) void liblustreapi_init(void)
51 {
52         unsigned int    seed;
53         struct timeval  tv;
54         int             fd;
55
56         /* Initializes the random number generator (random()). Get
57          * data from different places in case one of them fails. This
58          * is enough to get reasonably random numbers, but is not
59          * strong enough to be used for cryptography. */
60         seed = syscall(SYS_gettid);
61
62         if (gettimeofday(&tv, NULL) == 0) {
63                 seed ^= tv.tv_sec;
64                 seed ^= tv.tv_usec;
65         }
66
67         fd = open("/dev/urandom", O_RDONLY | O_NOFOLLOW);
68         if (fd >= 0) {
69                 unsigned int rnumber;
70
71                 (void)read(fd, &rnumber, sizeof(rnumber));
72                 seed ^= rnumber;
73                 close(fd);
74         }
75
76         srandom(seed);
77         liblustreapi_initialized = true;
78 }