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