Imported Upstream version 1.1.0
[platform/upstream/iotivity.git] / resource / c_common / ocrandom / src / ocrandom.c
1 //******************************************************************
2 //
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
25 //
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
31 #endif
32
33 #if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
34 #include "fcntl.h"
35 #include "unistd.h"
36 #include <stdlib.h>
37 #include <sys/time.h>
38 #include <time.h>
39 #if defined(__ANDROID__)
40 #include <ctype.h>
41 #include <linux/time.h>
42 #endif
43 #endif
44 #include "ocrandom.h"
45 #include <stdio.h>
46
47 #if !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
48 #include <uuid/uuid.h>
49 #endif
50
51 #if !defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
52 #define NANO_SEC 1000000000
53 #endif
54
55 #ifdef ARDUINO
56 #include "Arduino.h"
57
58 // ARM GCC compiler doesnt define srandom function.
59 #if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
60 #define HAVE_SRANDOM 1
61 #endif
62
63 uint8_t GetRandomBitRaw()
64 {
65     return analogRead((uint8_t)ANALOG_IN) & 0x1;
66 }
67
68 uint8_t GetRandomBitRaw2()
69 {
70     int a = 0;
71     for (;;)
72     {
73         a = GetRandomBitRaw() | (GetRandomBitRaw()<<1);
74         if (a==1)
75         {
76             return 0; // 1 to 0 transition: log a zero bit
77         }
78         if (a==2)
79         {
80             return 1;// 0 to 1 transition: log a one bit
81         }
82         // For other cases, try again.
83     }
84 }
85
86 uint8_t GetRandomBit()
87 {
88     int a = 0;
89     for (;;)
90     {
91         a = GetRandomBitRaw2() | (GetRandomBitRaw2()<<1);
92         if (a==1)
93         {
94             return 0; // 1 to 0 transition: log a zero bit
95         }
96         if (a==2)
97         {
98             return 1;// 0 to 1 transition: log a one bit
99         }
100         // For other cases, try again.
101     }
102 }
103 #endif
104
105 int8_t OCSeedRandom()
106 {
107 #if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__) || defined(__TIZEN__)
108     // Get current time to Seed.
109     uint64_t currentTime = 0;
110 #ifdef __ANDROID__
111     struct timespec getTs;
112     clock_gettime(CLOCK_MONOTONIC, &getTs);
113     currentTime = (getTs.tv_sec * (uint64_t)NANO_SEC + getTs.tv_nsec)/1000;
114 #elif  _POSIX_TIMERS > 0
115     struct timespec ts;
116     clock_gettime(CLOCK_MONOTONIC, &ts);
117     currentTime = (ts.tv_sec * (uint64_t)NANO_SEC + ts.tv_nsec)/ 1000;
118 #else
119     struct timeval tv;
120     gettimeofday(&tv, NULL);
121     currentTime = tv.tv_sec * (uint64_t)1000000 + tv.tv_usec;
122 #endif
123
124     int32_t fd = open("/dev/urandom", O_RDONLY);
125     if (fd >= 0)
126     {
127         uint32_t randomSeed = 0;
128         uint32_t totalRead = 0; //how many integers were read
129         int32_t currentRead = 0;
130         while (totalRead < sizeof(randomSeed))
131         {
132             currentRead = read(fd, (uint8_t*) &randomSeed + totalRead,
133                     sizeof(randomSeed) - totalRead);
134             if (currentRead > 0)
135             {
136                 totalRead += currentRead;
137             }
138         }
139         close(fd);
140         srand(randomSeed | currentTime);
141     }
142     else
143     {
144         // Do time based seed when problem in accessing "/dev/urandom"
145         srand(currentTime);
146     }
147
148     return 0;
149 #elif defined ARDUINO
150     uint32_t result =0;
151     uint8_t i;
152     for (i=32; i--;)
153     {
154         result += result + GetRandomBit();
155     }
156 #if HAVE_SRANDOM
157     srandom(result);
158 #else
159     srand(result);
160 #endif
161     return 0;
162 #endif
163
164 }
165
166 void OCFillRandomMem(uint8_t * location, uint16_t len)
167 {
168     if (!location)
169     {
170         return;
171     }
172     for (; len--;)
173     {
174         *location++ = OCGetRandomByte();
175     }
176 }
177
178 uint32_t OCGetRandom()
179 {
180     uint32_t result = 0;
181     OCFillRandomMem((uint8_t*) &result, 4);
182     return result;
183 }
184
185 uint8_t OCGetRandomByte(void)
186 {
187 #if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
188     return rand() & 0x00FF;
189 #elif defined ARDUINO
190 #ifdef HAVE_SRANDOM
191     return random() & 0x00FF;
192 #else
193     return rand() & 0x00FF;
194 #endif
195 #endif
196 }
197
198 uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound)
199 {
200     uint32_t base;
201     uint32_t diff;
202     uint32_t result;
203     if (firstBound > secondBound)
204     {
205         base = secondBound;
206         diff = firstBound - secondBound;
207     }
208     else if (firstBound < secondBound)
209     {
210         base = firstBound;
211         diff = secondBound - firstBound;
212     }
213     else
214     {
215         return secondBound;
216     }
217     result = ((float)OCGetRandom()/((float)(0xFFFFFFFF))*(float)diff) + (float) base;
218     return result;
219 }
220
221 #if defined(__ANDROID__)
222 uint8_t parseUuidChar(char c)
223 {
224     if (isdigit(c))
225     {
226         return c - '0';
227     }
228     else
229     {
230         return c - 'a' + 10;
231     }
232 }
233 uint8_t parseUuidPart(const char *c)
234 {
235     return (parseUuidChar(c[0])<<4) + parseUuidChar(c[1]);
236 }
237 #endif
238
239 OCRandomUuidResult OCGenerateUuid(uint8_t uuid[UUID_SIZE])
240 {
241     if (!uuid)
242     {
243         return RAND_UUID_INVALID_PARAM;
244     }
245 #if defined(__ANDROID__)
246     char uuidString[UUID_STRING_SIZE];
247     int8_t ret = OCGenerateUuidString(uuidString);
248
249     if (ret < 0)
250     {
251         return ret;
252     }
253
254     uuid[ 0] = parseUuidPart(&uuidString[0]);
255     uuid[ 1] = parseUuidPart(&uuidString[2]);
256     uuid[ 2] = parseUuidPart(&uuidString[4]);
257     uuid[ 3] = parseUuidPart(&uuidString[6]);
258
259     uuid[ 4] = parseUuidPart(&uuidString[9]);
260     uuid[ 5] = parseUuidPart(&uuidString[11]);
261
262     uuid[ 6] = parseUuidPart(&uuidString[14]);
263     uuid[ 7] = parseUuidPart(&uuidString[16]);
264
265     uuid[ 8] = parseUuidPart(&uuidString[19]);
266     uuid[ 9] = parseUuidPart(&uuidString[21]);
267
268     uuid[10] = parseUuidPart(&uuidString[24]);
269     uuid[11] = parseUuidPart(&uuidString[26]);
270     uuid[12] = parseUuidPart(&uuidString[28]);
271     uuid[13] = parseUuidPart(&uuidString[30]);
272     uuid[14] = parseUuidPart(&uuidString[32]);
273     uuid[15] = parseUuidPart(&uuidString[34]);
274
275     return RAND_UUID_OK;
276 #elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
277     // note: uuid_t is typedefed as unsigned char[16] on linux/apple
278     uuid_generate(uuid);
279     return RAND_UUID_OK;
280 #else
281     // Fallback for all platforms is filling the array with random data
282     OCFillRandomMem(uuid, UUID_SIZE);
283     return RAND_UUID_OK;
284 #endif
285 }
286
287 OCRandomUuidResult OCGenerateUuidString(char uuidString[UUID_STRING_SIZE])
288 {
289     if (!uuidString)
290     {
291         return RAND_UUID_INVALID_PARAM;
292     }
293 #if defined(__ANDROID__)
294     int32_t fd = open("/proc/sys/kernel/random/uuid", O_RDONLY);
295     if (fd > 0)
296     {
297         ssize_t readResult = read(fd, uuidString, UUID_STRING_SIZE - 1);
298         close(fd);
299         if (readResult < 0)
300         {
301             return RAND_UUID_READ_ERROR;
302         }
303         else if (readResult < UUID_STRING_SIZE - 1)
304         {
305             uuidString[0] = '\0';
306             return RAND_UUID_READ_ERROR;
307         }
308
309         uuidString[UUID_STRING_SIZE - 1] = '\0';
310         for (char* p = uuidString; *p; ++p)
311         {
312             *p = tolower(*p);
313         }
314         return RAND_UUID_OK;
315     }
316     else
317     {
318         close(fd);
319         return RAND_UUID_READ_ERROR;
320     }
321 #elif !defined(__ANDROID__) && (defined(__linux__) || defined(__APPLE__))
322     uint8_t uuid[UUID_SIZE];
323     int8_t ret = OCGenerateUuid(uuid);
324
325     if (ret != 0)
326     {
327         return ret;
328     }
329
330     uuid_unparse_lower(uuid, uuidString);
331     return RAND_UUID_OK;
332
333 #else
334     uint8_t uuid[UUID_SIZE];
335     OCGenerateUuid(uuid);
336
337     return OCConvertUuidToString(uuid, uuidString);
338 #endif
339 }
340
341 OCRandomUuidResult OCConvertUuidToString(const uint8_t uuid[UUID_SIZE],
342                                          char uuidString[UUID_STRING_SIZE])
343 {
344     if (uuid == NULL || uuidString == NULL)
345     {
346         return RAND_UUID_INVALID_PARAM;
347     }
348
349
350     int ret = snprintf(uuidString, UUID_STRING_SIZE,
351             "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
352             uuid[0], uuid[1], uuid[2], uuid[3],
353             uuid[4], uuid[5], uuid[6], uuid[7],
354             uuid[8], uuid[9], uuid[10], uuid[11],
355             uuid[12], uuid[13], uuid[14], uuid[15]
356             );
357
358     if (ret != UUID_STRING_SIZE - 1)
359     {
360         return RAND_UUID_CONVERT_ERROR;
361     }
362
363     return RAND_UUID_OK;
364 }