Merge "Modified logic to process each VSIE of all vendors." into tizen
[platform/upstream/connman.git] / src / util.c
1 /*
2  *
3  *  Connection Manager
4  *
5  *  Copyright (C) 2014  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 #include <inttypes.h>
30 #include <stdint.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <stdlib.h>
34
35 #include "connman.h"
36
37 #define URANDOM "/dev/urandom"
38
39 int f = -1;
40
41 int __connman_util_get_random(uint64_t *val)
42 {
43         int r = 0;
44
45         if (!val)
46                 return -EINVAL;
47
48         if (read(f, val, sizeof(uint64_t)) < 0) {
49                 r = -errno;
50                 connman_warn_once("Could not read from "URANDOM);
51                 *val = random();
52         }
53
54         return r;
55 }
56
57 int __connman_util_init(void)
58 {
59         int r = 0;
60
61         if (f > 0)
62                 return 0;
63
64         f = open(URANDOM, O_RDONLY);
65         if (f < 0) {
66                 r = -errno;
67                 connman_warn("Could not open "URANDOM);
68                 srandom(time(NULL));
69         } else {
70                 uint64_t val;
71
72                 r = __connman_util_get_random(&val);
73                 if (r < 0)
74                         srandom(time(NULL));
75                 else
76                         srandom(val);
77         }
78
79         return r;
80 }
81
82 void __connman_util_cleanup(void)
83 {
84         if (f > 0)
85                 close(f);
86
87         f = -1;
88 }