1 /*
2  * OS specific functions
3  * Copyright (c) 2005-2009, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #ifndef OS_H
10 #define OS_H
11 
12 #if defined(__ZEPHYR__)
13 typedef long long os_time_t;
14 #else
15 typedef long os_time_t;
16 #endif
17 
18 /**
19  * os_sleep - Sleep (sec, usec)
20  * @sec: Number of seconds to sleep
21  * @usec: Number of microseconds to sleep
22  */
23 void os_sleep(os_time_t sec, os_time_t usec);
24 
25 struct os_time {
26 	os_time_t sec;
27 	os_time_t usec;
28 };
29 
30 struct os_reltime {
31 	os_time_t sec;
32 	os_time_t usec;
33 };
34 
35 /**
36  * os_get_time - Get current time (sec, usec)
37  * @t: Pointer to buffer for the time
38  * Returns: 0 on success, -1 on failure
39  */
40 int os_get_time(struct os_time *t);
41 
42 /**
43  * os_get_reltime - Get relative time (sec, usec)
44  * @t: Pointer to buffer for the time
45  * Returns: 0 on success, -1 on failure
46  */
47 int os_get_reltime(struct os_reltime *t);
48 
49 
50 /* Helpers for handling struct os_time */
51 
os_time_before(struct os_time * a,struct os_time * b)52 static inline int os_time_before(struct os_time *a, struct os_time *b)
53 {
54 	return (a->sec < b->sec) ||
55 	       (a->sec == b->sec && a->usec < b->usec);
56 }
57 
58 
os_time_sub(struct os_time * a,struct os_time * b,struct os_time * res)59 static inline void os_time_sub(struct os_time *a, struct os_time *b,
60 			       struct os_time *res)
61 {
62 	res->sec = a->sec - b->sec;
63 	res->usec = a->usec - b->usec;
64 	if (res->usec < 0) {
65 		res->sec--;
66 		res->usec += 1000000;
67 	}
68 }
69 
70 
71 /* Helpers for handling struct os_reltime */
72 
os_reltime_before(struct os_reltime * a,struct os_reltime * b)73 static inline int os_reltime_before(struct os_reltime *a,
74 				    struct os_reltime *b)
75 {
76 	return (a->sec < b->sec) ||
77 	       (a->sec == b->sec && a->usec < b->usec);
78 }
79 
80 
os_reltime_sub(struct os_reltime * a,struct os_reltime * b,struct os_reltime * res)81 static inline void os_reltime_sub(struct os_reltime *a, struct os_reltime *b,
82 				  struct os_reltime *res)
83 {
84 	res->sec = a->sec - b->sec;
85 	res->usec = a->usec - b->usec;
86 	if (res->usec < 0) {
87 		res->sec--;
88 		res->usec += 1000000;
89 	}
90 }
91 
92 
os_reltime_age(struct os_reltime * start,struct os_reltime * age)93 static inline void os_reltime_age(struct os_reltime *start,
94 				  struct os_reltime *age)
95 {
96 	struct os_reltime now;
97 
98 	os_get_reltime(&now);
99 	os_reltime_sub(&now, start, age);
100 }
101 
102 
os_reltime_expired(struct os_reltime * now,struct os_reltime * ts,os_time_t timeout_secs)103 static inline int os_reltime_expired(struct os_reltime *now,
104 				     struct os_reltime *ts,
105 				     os_time_t timeout_secs)
106 {
107 	struct os_reltime age;
108 
109 	os_reltime_sub(now, ts, &age);
110 	return (age.sec > timeout_secs) ||
111 	       (age.sec == timeout_secs && age.usec > 0);
112 }
113 
114 
os_reltime_initialized(struct os_reltime * t)115 static inline int os_reltime_initialized(struct os_reltime *t)
116 {
117 	return t->sec != 0 || t->usec != 0;
118 }
119 
120 
121 /**
122  * os_mktime - Convert broken-down time into seconds since 1970-01-01
123  * @year: Four digit year
124  * @month: Month (1 .. 12)
125  * @day: Day of month (1 .. 31)
126  * @hour: Hour (0 .. 23)
127  * @min: Minute (0 .. 59)
128  * @sec: Second (0 .. 60)
129  * @t: Buffer for returning calendar time representation (seconds since
130  * 1970-01-01 00:00:00)
131  * Returns: 0 on success, -1 on failure
132  *
133  * Note: The result is in seconds from Epoch, i.e., in UTC, not in local time
134  * which is used by POSIX mktime().
135  */
136 int os_mktime(int year, int month, int day, int hour, int min, int sec,
137 	      os_time_t *t);
138 
139 struct os_tm {
140 	int sec; /* 0..59 or 60 for leap seconds */
141 	int min; /* 0..59 */
142 	int hour; /* 0..23 */
143 	int day; /* 1..31 */
144 	int month; /* 1..12 */
145 	int year; /* Four digit year */
146 };
147 
148 int os_gmtime(os_time_t t, struct os_tm *tm);
149 
150 /**
151  * os_daemonize - Run in the background (detach from the controlling terminal)
152  * @pid_file: File name to write the process ID to or %NULL to skip this
153  * Returns: 0 on success, -1 on failure
154  */
155 int os_daemonize(const char *pid_file);
156 
157 /**
158  * os_daemonize_terminate - Stop running in the background (remove pid file)
159  * @pid_file: File name to write the process ID to or %NULL to skip this
160  */
161 void os_daemonize_terminate(const char *pid_file);
162 
163 /**
164  * os_get_random - Get cryptographically strong pseudo random data
165  * @buf: Buffer for pseudo random data
166  * @len: Length of the buffer
167  * Returns: 0 on success, -1 on failure
168  */
169 int os_get_random(unsigned char *buf, size_t len);
170 
171 /**
172  * os_random - Get pseudo random value (not necessarily very strong)
173  * Returns: Pseudo random value
174  */
175 unsigned long os_random(void);
176 
177 /**
178  * os_rel2abs_path - Get an absolute path for a file
179  * @rel_path: Relative path to a file
180  * Returns: Absolute path for the file or %NULL on failure
181  *
182  * This function tries to convert a relative path of a file to an absolute path
183  * in order for the file to be found even if current working directory has
184  * changed. The returned value is allocated and caller is responsible for
185  * freeing it. It is acceptable to just return the same path in an allocated
186  * buffer, e.g., return strdup(rel_path). This function is only used to find
187  * configuration files when os_daemonize() may have changed the current working
188  * directory and relative path would be pointing to a different location.
189  */
190 char * os_rel2abs_path(const char *rel_path);
191 
192 /**
193  * os_program_init - Program initialization (called at start)
194  * Returns: 0 on success, -1 on failure
195  *
196  * This function is called when a programs starts. If there are any OS specific
197  * processing that is needed, it can be placed here. It is also acceptable to
198  * just return 0 if not special processing is needed.
199  */
200 int os_program_init(void);
201 
202 /**
203  * os_program_deinit - Program deinitialization (called just before exit)
204  *
205  * This function is called just before a program exists. If there are any OS
206  * specific processing, e.g., freeing resourced allocated in os_program_init(),
207  * it should be done here. It is also acceptable for this function to do
208  * nothing.
209  */
210 void os_program_deinit(void);
211 
212 /**
213  * os_setenv - Set environment variable
214  * @name: Name of the variable
215  * @value: Value to set to the variable
216  * @overwrite: Whether existing variable should be overwritten
217  * Returns: 0 on success, -1 on error
218  *
219  * This function is only used for wpa_cli action scripts. OS wrapper does not
220  * need to implement this if such functionality is not needed.
221  */
222 int os_setenv(const char *name, const char *value, int overwrite);
223 
224 /**
225  * os_unsetenv - Delete environent variable
226  * @name: Name of the variable
227  * Returns: 0 on success, -1 on error
228  *
229  * This function is only used for wpa_cli action scripts. OS wrapper does not
230  * need to implement this if such functionality is not needed.
231  */
232 int os_unsetenv(const char *name);
233 
234 /**
235  * os_readfile - Read a file to an allocated memory buffer
236  * @name: Name of the file to read
237  * @len: For returning the length of the allocated buffer
238  * Returns: Pointer to the allocated buffer or %NULL on failure
239  *
240  * This function allocates memory and reads the given file to this buffer. Both
241  * binary and text files can be read with this function. The caller is
242  * responsible for freeing the returned buffer with os_free().
243  */
244 char * os_readfile(const char *name, size_t *len);
245 
246 /**
247  * os_file_exists - Check whether the specified file exists
248  * @fname: Path and name of the file
249  * Returns: 1 if the file exists or 0 if not
250  */
251 int os_file_exists(const char *fname);
252 
253 /**
254  * os_fdatasync - Sync a file's (for a given stream) state with storage device
255  * @stream: the stream to be flushed
256  * Returns: 0 if the operation succeeded or -1 on failure
257  */
258 int os_fdatasync(FILE *stream);
259 
260 /**
261  * os_zalloc - Allocate and zero memory
262  * @size: Number of bytes to allocate
263  * Returns: Pointer to allocated and zeroed memory or %NULL on failure
264  *
265  * Caller is responsible for freeing the returned buffer with os_free().
266  */
267 void * os_zalloc(size_t size);
268 
269 /**
270  * os_calloc - Allocate and zero memory for an array
271  * @nmemb: Number of members in the array
272  * @size: Number of bytes in each member
273  * Returns: Pointer to allocated and zeroed memory or %NULL on failure
274  *
275  * This function can be used as a wrapper for os_zalloc(nmemb * size) when an
276  * allocation is used for an array. The main benefit over os_zalloc() is in
277  * having an extra check to catch integer overflows in multiplication.
278  *
279  * Caller is responsible for freeing the returned buffer with os_free().
280  */
os_calloc(size_t nmemb,size_t size)281 static inline void * os_calloc(size_t nmemb, size_t size)
282 {
283 	if (size && nmemb > (~(size_t) 0) / size)
284 		return NULL;
285 	return os_zalloc(nmemb * size);
286 }
287 
288 
289 /*
290  * The following functions are wrapper for standard ANSI C or POSIX functions.
291  * By default, they are just defined to use the standard function name and no
292  * os_*.c implementation is needed for them. This avoids extra function calls
293  * by allowing the C pre-processor take care of the function name mapping.
294  *
295  * If the target system uses a C library that does not provide these functions,
296  * build_config.h can be used to define the wrappers to use a different
297  * function name. This can be done on function-by-function basis since the
298  * defines here are only used if build_config.h does not define the os_* name.
299  * If needed, os_*.c file can be used to implement the functions that are not
300  * included in the C library on the target system. Alternatively,
301  * OS_NO_C_LIB_DEFINES can be defined to skip all defines here in which case
302  * these functions need to be implemented in os_*.c file for the target system.
303  */
304 
305 #ifdef OS_NO_C_LIB_DEFINES
306 
307 /**
308  * os_malloc - Allocate dynamic memory
309  * @size: Size of the buffer to allocate
310  * Returns: Allocated buffer or %NULL on failure
311  *
312  * Caller is responsible for freeing the returned buffer with os_free().
313  */
314 void * os_malloc(size_t size);
315 
316 /**
317  * os_realloc - Re-allocate dynamic memory
318  * @ptr: Old buffer from os_malloc() or os_realloc()
319  * @size: Size of the new buffer
320  * Returns: Allocated buffer or %NULL on failure
321  *
322  * Caller is responsible for freeing the returned buffer with os_free().
323  * If re-allocation fails, %NULL is returned and the original buffer (ptr) is
324  * not freed and caller is still responsible for freeing it.
325  */
326 void * os_realloc(void *ptr, size_t size);
327 
328 /**
329  * os_free - Free dynamic memory
330  * @ptr: Old buffer from os_malloc() or os_realloc(); can be %NULL
331  */
332 void os_free(void *ptr);
333 
334 /**
335  * os_memcpy - Copy memory area
336  * @dest: Destination
337  * @src: Source
338  * @n: Number of bytes to copy
339  * Returns: dest
340  *
341  * The memory areas src and dst must not overlap. os_memmove() can be used with
342  * overlapping memory.
343  */
344 void * os_memcpy(void *dest, const void *src, size_t n);
345 
346 /**
347  * os_memmove - Copy memory area
348  * @dest: Destination
349  * @src: Source
350  * @n: Number of bytes to copy
351  * Returns: dest
352  *
353  * The memory areas src and dst may overlap.
354  */
355 void * os_memmove(void *dest, const void *src, size_t n);
356 
357 /**
358  * os_memset - Fill memory with a constant byte
359  * @s: Memory area to be filled
360  * @c: Constant byte
361  * @n: Number of bytes started from s to fill with c
362  * Returns: s
363  */
364 void * os_memset(void *s, int c, size_t n);
365 
366 /**
367  * os_memcmp - Compare memory areas
368  * @s1: First buffer
369  * @s2: Second buffer
370  * @n: Maximum numbers of octets to compare
371  * Returns: An integer less than, equal to, or greater than zero if s1 is
372  * found to be less than, to match, or be greater than s2. Only first n
373  * characters will be compared.
374  */
375 int os_memcmp(const void *s1, const void *s2, size_t n);
376 
377 /**
378  * os_strdup - Duplicate a string
379  * @s: Source string
380  * Returns: Allocated buffer with the string copied into it or %NULL on failure
381  *
382  * Caller is responsible for freeing the returned buffer with os_free().
383  */
384 char * os_strdup(const char *s);
385 
386 /**
387  * os_strlen - Calculate the length of a string
388  * @s: '\0' terminated string
389  * Returns: Number of characters in s (not counting the '\0' terminator)
390  */
391 size_t os_strlen(const char *s);
392 
393 /**
394  * os_strcasecmp - Compare two strings ignoring case
395  * @s1: First string
396  * @s2: Second string
397  * Returns: An integer less than, equal to, or greater than zero if s1 is
398  * found to be less than, to match, or be greatred than s2
399  */
400 int os_strcasecmp(const char *s1, const char *s2);
401 
402 /**
403  * os_strncasecmp - Compare two strings ignoring case
404  * @s1: First string
405  * @s2: Second string
406  * @n: Maximum numbers of characters to compare
407  * Returns: An integer less than, equal to, or greater than zero if s1 is
408  * found to be less than, to match, or be greater than s2. Only first n
409  * characters will be compared.
410  */
411 int os_strncasecmp(const char *s1, const char *s2, size_t n);
412 
413 /**
414  * os_strchr - Locate the first occurrence of a character in string
415  * @s: String
416  * @c: Character to search for
417  * Returns: Pointer to the matched character or %NULL if not found
418  */
419 char * os_strchr(const char *s, int c);
420 
421 /**
422  * os_strrchr - Locate the last occurrence of a character in string
423  * @s: String
424  * @c: Character to search for
425  * Returns: Pointer to the matched character or %NULL if not found
426  */
427 char * os_strrchr(const char *s, int c);
428 
429 /**
430  * os_strcmp - Compare two strings
431  * @s1: First string
432  * @s2: Second string
433  * Returns: An integer less than, equal to, or greater than zero if s1 is
434  * found to be less than, to match, or be greatred than s2
435  */
436 int os_strcmp(const char *s1, const char *s2);
437 
438 /**
439  * os_strncmp - Compare two strings
440  * @s1: First string
441  * @s2: Second string
442  * @n: Maximum numbers of characters to compare
443  * Returns: An integer less than, equal to, or greater than zero if s1 is
444  * found to be less than, to match, or be greater than s2. Only first n
445  * characters will be compared.
446  */
447 int os_strncmp(const char *s1, const char *s2, size_t n);
448 
449 /**
450  * os_strstr - Locate a substring
451  * @haystack: String (haystack) to search from
452  * @needle: Needle to search from haystack
453  * Returns: Pointer to the beginning of the substring or %NULL if not found
454  */
455 char * os_strstr(const char *haystack, const char *needle);
456 
457 /**
458  * os_snprintf - Print to a memory buffer
459  * @str: Memory buffer to print into
460  * @size: Maximum length of the str buffer
461  * @format: printf format
462  * Returns: Number of characters printed (not including trailing '\0').
463  *
464  * If the output buffer is truncated, number of characters which would have
465  * been written is returned. Since some C libraries return -1 in such a case,
466  * the caller must be prepared on that value, too, to indicate truncation.
467  *
468  * Note: Some C library implementations of snprintf() may not guarantee null
469  * termination in case the output is truncated. The OS wrapper function of
470  * os_snprintf() should provide this guarantee, i.e., to null terminate the
471  * output buffer if a C library version of the function is used and if that
472  * function does not guarantee null termination.
473  *
474  * If the target system does not include snprintf(), see, e.g.,
475  * http://www.ijs.si/software/snprintf/ for an example of a portable
476  * implementation of snprintf.
477  */
478 int os_snprintf(char *str, size_t size, const char *format, ...);
479 
480 #else /* OS_NO_C_LIB_DEFINES */
481 
482 #ifdef WPA_TRACE
483 void * os_malloc(size_t size);
484 void * os_realloc(void *ptr, size_t size);
485 void os_free(void *ptr);
486 char * os_strdup(const char *s);
487 #else /* WPA_TRACE */
488 #ifndef os_malloc
489 #define os_malloc(s) malloc((s))
490 #endif
491 #ifndef os_realloc
492 #define os_realloc(p, s) realloc((p), (s))
493 #endif
494 #ifndef os_free
495 #define os_free(p) free((p))
496 #endif
497 #ifndef os_strdup
498 #ifdef _MSC_VER
499 #define os_strdup(s) _strdup(s)
500 #else
501 #define os_strdup(s) strdup(s)
502 #endif
503 #endif
504 #endif /* WPA_TRACE */
505 
506 #ifndef os_memcpy
507 #define os_memcpy(d, s, n) memcpy((d), (s), (n))
508 #endif
509 #ifndef os_memmove
510 #define os_memmove(d, s, n) memmove((d), (s), (n))
511 #endif
512 #ifndef os_memset
513 #define os_memset(s, c, n) memset(s, c, n)
514 #endif
515 #ifndef os_memcmp
516 #define os_memcmp(s1, s2, n) memcmp((s1), (s2), (n))
517 #endif
518 
519 #ifndef os_strlen
520 #define os_strlen(s) strlen(s)
521 #endif
522 #ifndef os_strcasecmp
523 #ifdef _MSC_VER
524 #define os_strcasecmp(s1, s2) _stricmp((s1), (s2))
525 #else
526 #define os_strcasecmp(s1, s2) strcasecmp((s1), (s2))
527 #endif
528 #endif
529 #ifndef os_strncasecmp
530 #ifdef _MSC_VER
531 #define os_strncasecmp(s1, s2, n) _strnicmp((s1), (s2), (n))
532 #else
533 #define os_strncasecmp(s1, s2, n) strncasecmp((s1), (s2), (n))
534 #endif
535 #endif
536 #ifndef os_strchr
537 #define os_strchr(s, c) strchr((s), (c))
538 #endif
539 #ifndef os_strcmp
540 #define os_strcmp(s1, s2) strcmp((s1), (s2))
541 #endif
542 #ifndef os_strncmp
543 #define os_strncmp(s1, s2, n) strncmp((s1), (s2), (n))
544 #endif
545 #ifndef os_strrchr
546 #define os_strrchr(s, c) strrchr((s), (c))
547 #endif
548 #ifndef os_strstr
549 #define os_strstr(h, n) strstr((h), (n))
550 #endif
551 
552 #ifndef os_snprintf
553 #ifdef _MSC_VER
554 #define os_snprintf _snprintf
555 #else
556 #define os_snprintf snprintf
557 #endif
558 #endif
559 
560 #endif /* OS_NO_C_LIB_DEFINES */
561 
562 
os_snprintf_error(size_t size,int res)563 static inline int os_snprintf_error(size_t size, int res)
564 {
565 	return res < 0 || (unsigned int) res >= size;
566 }
567 
568 
os_realloc_array(void * ptr,size_t nmemb,size_t size)569 static inline void * os_realloc_array(void *ptr, size_t nmemb, size_t size)
570 {
571 	if (size && nmemb > (~(size_t) 0) / size)
572 		return NULL;
573 	return os_realloc(ptr, nmemb * size);
574 }
575 
576 /**
577  * os_remove_in_array - Remove a member from an array by index
578  * @ptr: Pointer to the array
579  * @nmemb: Current member count of the array
580  * @size: The size per member of the array
581  * @idx: Index of the member to be removed
582  */
os_remove_in_array(void * ptr,size_t nmemb,size_t size,size_t idx)583 static inline void os_remove_in_array(void *ptr, size_t nmemb, size_t size,
584 				      size_t idx)
585 {
586 	if (idx < nmemb - 1)
587 		os_memmove(((unsigned char *) ptr) + idx * size,
588 			   ((unsigned char *) ptr) + (idx + 1) * size,
589 			   (nmemb - idx - 1) * size);
590 }
591 
592 /**
593  * os_strlcpy - Copy a string with size bound and NUL-termination
594  * @dest: Destination
595  * @src: Source
596  * @siz: Size of the target buffer
597  * Returns: Total length of the target string (length of src) (not including
598  * NUL-termination)
599  *
600  * This function matches in behavior with the strlcpy(3) function in OpenBSD.
601  */
602 size_t os_strlcpy(char *dest, const char *src, size_t siz);
603 
604 /**
605  * os_memcmp_const - Constant time memory comparison
606  * @a: First buffer to compare
607  * @b: Second buffer to compare
608  * @len: Number of octets to compare
609  * Returns: 0 if buffers are equal, non-zero if not
610  *
611  * This function is meant for comparing passwords or hash values where
612  * difference in execution time could provide external observer information
613  * about the location of the difference in the memory buffers. The return value
614  * does not behave like os_memcmp(), i.e., os_memcmp_const() cannot be used to
615  * sort items into a defined order. Unlike os_memcmp(), execution time of
616  * os_memcmp_const() does not depend on the contents of the compared memory
617  * buffers, but only on the total compared length.
618  */
619 int os_memcmp_const(const void *a, const void *b, size_t len);
620 
621 
622 /**
623  * os_memdup - Allocate duplicate of passed memory chunk
624  * @src: Source buffer to duplicate
625  * @len: Length of source buffer
626  * Returns: %NULL if allocation failed, copy of src buffer otherwise
627  *
628  * This function allocates a memory block like os_malloc() would, and
629  * copies the given source buffer into it.
630  */
631 void * os_memdup(const void *src, size_t len);
632 
633 /**
634  * os_exec - Execute an external program
635  * @program: Path to the program
636  * @arg: Command line argument string
637  * @wait_completion: Whether to wait until the program execution completes
638  * Returns: 0 on success, -1 on error
639  */
640 int os_exec(const char *program, const char *arg, int wait_completion);
641 
642 
643 #ifdef OS_REJECT_C_LIB_FUNCTIONS
644 #define malloc OS_DO_NOT_USE_malloc
645 #define realloc OS_DO_NOT_USE_realloc
646 #define free OS_DO_NOT_USE_free
647 #define memcpy OS_DO_NOT_USE_memcpy
648 #define memmove OS_DO_NOT_USE_memmove
649 #define memset OS_DO_NOT_USE_memset
650 #define memcmp OS_DO_NOT_USE_memcmp
651 #undef strdup
652 #define strdup OS_DO_NOT_USE_strdup
653 #define strlen OS_DO_NOT_USE_strlen
654 #define strcasecmp OS_DO_NOT_USE_strcasecmp
655 #define strncasecmp OS_DO_NOT_USE_strncasecmp
656 #undef strchr
657 #define strchr OS_DO_NOT_USE_strchr
658 #undef strcmp
659 #define strcmp OS_DO_NOT_USE_strcmp
660 #undef strncmp
661 #define strncmp OS_DO_NOT_USE_strncmp
662 #undef strncpy
663 #define strncpy OS_DO_NOT_USE_strncpy
664 #define strrchr OS_DO_NOT_USE_strrchr
665 #define strstr OS_DO_NOT_USE_strstr
666 #undef snprintf
667 #define snprintf OS_DO_NOT_USE_snprintf
668 
669 #define strcpy OS_DO_NOT_USE_strcpy
670 #endif /* OS_REJECT_C_LIB_FUNCTIONS */
671 
672 
673 #if defined(WPA_TRACE_BFD) && defined(CONFIG_TESTING_OPTIONS)
674 #define TEST_FAIL() testing_test_fail()
675 int testing_test_fail(void);
676 extern char wpa_trace_fail_func[256];
677 extern unsigned int wpa_trace_fail_after;
678 extern char wpa_trace_test_fail_func[256];
679 extern unsigned int wpa_trace_test_fail_after;
680 #else
681 #define TEST_FAIL() 0
682 #endif
683 
684 #endif /* OS_H */
685