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