]> git.ipfire.org Git - people/ms/strongswan.git/blame - src/libstrongswan/utils/utils.h
enumerator: Enumerate glob(3) matches using gl_pathc
[people/ms/strongswan.git] / src / libstrongswan / utils / utils.h
CommitLineData
552cc11b 1/*
766141bc 2 * Copyright (C) 2008-2014 Tobias Brunner
552cc11b
MW
3 * Copyright (C) 2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
552cc11b
MW
15 */
16
17/**
bca34c37
TB
18 * @defgroup utils_i utils
19 * @{ @ingroup utils
552cc11b
MW
20 */
21
22#ifndef UTILS_H_
23#define UTILS_H_
24
25#include <sys/types.h>
26#include <stdlib.h>
27#include <stddef.h>
3f310c0d 28#include <sys/time.h>
0be12e35 29#include <string.h>
552cc11b 30
922ee2c5
MW
31#ifdef WIN32
32# include "windows.h"
33#else
34# define _GNU_SOURCE
35# include <arpa/inet.h>
36# include <sys/socket.h>
37# include <netdb.h>
38# include <netinet/in.h>
266ee0a1 39# include <sched.h>
922ee2c5
MW
40#endif
41
eab241fb
AS
42/**
43 * strongSwan program return codes
44 */
45#define SS_RC_LIBSTRONGSWAN_INTEGRITY 64
46#define SS_RC_DAEMON_INTEGRITY 65
3646c8a1 47#define SS_RC_INITIALIZATION_FAILED 66
eab241fb 48
5d8306de
AS
49#define SS_RC_FIRST SS_RC_LIBSTRONGSWAN_INTEGRITY
50#define SS_RC_LAST SS_RC_INITIALIZATION_FAILED
51
552cc11b
MW
52/**
53 * Number of bits in a byte
54 */
55#define BITS_PER_BYTE 8
56
57/**
58 * Default length for various auxiliary text buffers
59 */
60#define BUF_LEN 512
61
62/**
a2a28d90 63 * General purpose boolean type.
552cc11b 64 */
a2a28d90
TB
65#ifdef HAVE_STDBOOL_H
66# include <stdbool.h>
67#else
68# ifndef HAVE__BOOL
69# define _Bool signed char
70# endif /* HAVE__BOOL */
71# define bool _Bool
72# define false 0
73# define true 1
74# define __bool_true_false_are_defined 1
75#endif /* HAVE_STDBOOL_H */
76#ifndef FALSE
77# define FALSE false
78#endif /* FALSE */
79#ifndef TRUE
80# define TRUE true
81#endif /* TRUE */
82
9ee8b3b4
MW
83#include "enum.h"
84#include "utils/strerror.h"
85
a43f1e56
MW
86/**
87 * Directory separator character in paths on this platform
88 */
89#ifdef WIN32
90# define DIRECTORY_SEPARATOR "\\"
91#else
92# define DIRECTORY_SEPARATOR "/"
93#endif
94
87a79e6a
MW
95/**
96 * Initialize utility functions
97 */
98void utils_init();
99
100/**
101 * Deinitialize utility functions
102 */
103void utils_deinit();
104
a2a28d90
TB
105/**
106 * Helper function that compares two strings for equality
107 */
108static inline bool streq(const char *x, const char *y)
109{
110 return strcmp(x, y) == 0;
111}
552cc11b
MW
112
113/**
985dcab1 114 * Helper function that compares two strings for equality, length limited
552cc11b 115 */
985dcab1
TB
116static inline bool strneq(const char *x, const char *y, size_t len)
117{
118 return strncmp(x, y, len) == 0;
119}
552cc11b 120
f460facd
TB
121/**
122 * Helper function that checks if a string starts with a given prefix
123 */
124static inline bool strpfx(const char *x, const char *prefix)
125{
126 return strneq(x, prefix, strlen(prefix));
127}
128
63176bbc 129/**
a2a28d90 130 * Helper function that compares two strings for equality ignoring case
63176bbc 131 */
a2a28d90
TB
132static inline bool strcaseeq(const char *x, const char *y)
133{
134 return strcasecmp(x, y) == 0;
135}
63176bbc 136
7a3e0a63 137/**
985dcab1 138 * Helper function that compares two strings for equality ignoring case, length limited
7a3e0a63 139 */
985dcab1
TB
140static inline bool strncaseeq(const char *x, const char *y, size_t len)
141{
142 return strncasecmp(x, y, len) == 0;
143}
7a3e0a63 144
32a145fd
TB
145/**
146 * Helper function that checks if a string starts with a given prefix
147 */
148static inline bool strcasepfx(const char *x, const char *prefix)
149{
150 return strncaseeq(x, prefix, strlen(prefix));
151}
152
1038d9fe
MW
153/**
154 * NULL-safe strdup variant
155 */
753ca22f
TB
156static inline char *strdupnull(const char *s)
157{
158 return s ? strdup(s) : NULL;
159}
1038d9fe 160
552cc11b 161/**
985dcab1 162 * Helper function that compares two binary blobs for equality
552cc11b 163 */
985dcab1
TB
164static inline bool memeq(const void *x, const void *y, size_t len)
165{
166 return memcmp(x, y, len) == 0;
167}
552cc11b 168
6d4654b9
TB
169/**
170 * Calling memcpy() with NULL pointers, even with n == 0, results in undefined
171 * behavior according to the C standard. This version is guaranteed to not
172 * access the pointers if n is 0.
173 */
174static inline void *memcpy_noop(void *dst, const void *src, size_t n)
175{
176 return n ? memcpy(dst, src, n) : dst;
177}
178#define memcpy(d,s,n) memcpy_noop(d,s,n)
179
180/**
181 * Calling memmove() with NULL pointers, even with n == 0, results in undefined
182 * behavior according to the C standard. This version is guaranteed to not
183 * access the pointers if n is 0.
184 */
185static inline void *memmove_noop(void *dst, const void *src, size_t n)
186{
187 return n ? memmove(dst, src, n) : dst;
188}
189#define memmove(d,s,n) memmove_noop(d,s,n)
190
191/**
192 * Calling memset() with a NULL pointer, even with n == 0, results in undefined
193 * behavior according to the C standard. This version is guaranteed to not
194 * access the pointer if n is 0.
195 */
196static inline void *memset_noop(void *s, int c, size_t n)
197{
198 return n ? memset(s, c, n) : s;
199}
200#define memset(s,c,n) memset_noop(s,c,n)
201
552cc11b
MW
202/**
203 * Macro gives back larger of two values.
204 */
e822fc57
TB
205#define max(x,y) ({ \
206 typeof(x) _x = (x); \
207 typeof(y) _y = (y); \
208 _x > _y ? _x : _y; })
209
552cc11b
MW
210/**
211 * Macro gives back smaller of two values.
212 */
e822fc57
TB
213#define min(x,y) ({ \
214 typeof(x) _x = (x); \
215 typeof(y) _y = (y); \
216 _x < _y ? _x : _y; })
552cc11b
MW
217
218/**
219 * Call destructor of an object, if object != NULL
220 */
221#define DESTROY_IF(obj) if (obj) (obj)->destroy(obj)
222
223/**
224 * Call offset destructor of an object, if object != NULL
225 */
226#define DESTROY_OFFSET_IF(obj, offset) if (obj) obj->destroy_offset(obj, offset);
227
228/**
229 * Call function destructor of an object, if object != NULL
230 */
231#define DESTROY_FUNCTION_IF(obj, fn) if (obj) obj->destroy_function(obj, fn);
232
233/**
234 * Debug macro to follow control flow
235 */
236#define POS printf("%s, line %d\n", __FILE__, __LINE__)
237
74eed73a
MW
238/**
239 * Object allocation/initialization macro, using designated initializer.
240 */
2e1f4a46
MW
241#define INIT(this, ...) { (this) = malloc(sizeof(*(this))); \
242 *(this) = (typeof(*(this))){ __VA_ARGS__ }; }
74eed73a 243
1a1ff9d1
MW
244/**
245 * Method declaration/definition macro, providing private and public interface.
246 *
247 * Defines a method name with this as first parameter and a return value ret,
248 * and an alias for this method with a _ prefix, having the this argument
249 * safely casted to the public interface iface.
250 * _name is provided a function pointer, but will get optimized out by GCC.
251 */
252#define METHOD(iface, name, ret, this, ...) \
23d2bf84
MW
253 static ret name(union {iface *_public; this;} \
254 __attribute__((transparent_union)), ##__VA_ARGS__); \
d185b6ac 255 static typeof(name) *_##name = (typeof(name)*)name; \
23d2bf84
MW
256 static ret name(this, ##__VA_ARGS__)
257
258/**
259 * Same as METHOD(), but is defined for two public interfaces.
260 */
261#define METHOD2(iface1, iface2, name, ret, this, ...) \
262 static ret name(union {iface1 *_public1; iface2 *_public2; this;} \
263 __attribute__((transparent_union)), ##__VA_ARGS__); \
d185b6ac 264 static typeof(name) *_##name = (typeof(name)*)name; \
1a1ff9d1
MW
265 static ret name(this, ##__VA_ARGS__)
266
9e932513
MW
267/**
268 * Callback declaration/definition macro, allowing casted first parameter.
269 *
270 * This is very similar to METHOD, but instead of casting the first parameter
271 * to a public interface, it uses a void*. This allows type safe definition
272 * of a callback function, while using the real type for the first parameter.
273 */
274#define CALLBACK(name, ret, param1, ...) \
275 static ret _cb_##name(union {void *_generic; param1;} \
276 __attribute__((transparent_union)), ##__VA_ARGS__); \
277 static typeof(_cb_##name) *name = (typeof(_cb_##name)*)_cb_##name; \
278 static ret _cb_##name(param1, ##__VA_ARGS__)
279
e79dbda3
TB
280/**
281 * This macro allows counting the number of arguments passed to a macro.
282 * Combined with the VA_ARGS_DISPATCH() macro this can be used to implement
283 * macro overloading based on the number of arguments.
284 * 0 to 10 arguments are currently supported.
285 */
286#define VA_ARGS_NUM(...) _VA_ARGS_NUM(0,##__VA_ARGS__,10,9,8,7,6,5,4,3,2,1,0)
287#define _VA_ARGS_NUM(_0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,NUM,...) NUM
288
289/**
290 * This macro can be used to dispatch a macro call based on the number of given
291 * arguments, for instance:
292 *
293 * @code
294 * #define MY_MACRO(...) VA_ARGS_DISPATCH(MY_MACRO, __VA_ARGS__)(__VA_ARGS__)
295 * #define MY_MACRO1(arg) one_arg(arg)
296 * #define MY_MACRO2(arg1,arg2) two_args(arg1,arg2)
297 * @endcode
298 *
299 * MY_MACRO() can now be called with either one or two arguments, which will
300 * resolve to one_arg(arg) or two_args(arg1,arg2), respectively.
301 */
302#define VA_ARGS_DISPATCH(func, ...) _VA_ARGS_DISPATCH(func, VA_ARGS_NUM(__VA_ARGS__))
303#define _VA_ARGS_DISPATCH(func, num) __VA_ARGS_DISPATCH(func, num)
304#define __VA_ARGS_DISPATCH(func, num) func ## num
305
7ba89ccd
MW
306/**
307 * Architecture independent bitfield definition helpers (at least with GCC).
308 *
309 * Defines a bitfield with a type t and a fixed size of bitfield members, e.g.:
310 * BITFIELD2(u_int8_t,
311 * low: 4,
312 * high: 4,
313 * ) flags;
314 * The member defined first placed at bit 0.
315 */
316#if BYTE_ORDER == LITTLE_ENDIAN
317#define BITFIELD2(t, a, b,...) struct { t a; t b; __VA_ARGS__}
318#define BITFIELD3(t, a, b, c,...) struct { t a; t b; t c; __VA_ARGS__}
319#define BITFIELD4(t, a, b, c, d,...) struct { t a; t b; t c; t d; __VA_ARGS__}
320#define BITFIELD5(t, a, b, c, d, e,...) struct { t a; t b; t c; t d; t e; __VA_ARGS__}
321#elif BYTE_ORDER == BIG_ENDIAN
322#define BITFIELD2(t, a, b,...) struct { t b; t a; __VA_ARGS__}
323#define BITFIELD3(t, a, b, c,...) struct { t c; t b; t a; __VA_ARGS__}
324#define BITFIELD4(t, a, b, c, d,...) struct { t d; t c; t b; t a; __VA_ARGS__}
325#define BITFIELD5(t, a, b, c, d, e,...) struct { t e; t d; t c; t b; t a; __VA_ARGS__}
326#endif
327
552cc11b
MW
328/**
329 * Macro to allocate a sized type.
330 */
331#define malloc_thing(thing) ((thing*)malloc(sizeof(thing)))
332
fca4d3ee
MW
333/**
334 * Get the number of elements in an array
335 */
336#define countof(array) (sizeof(array)/sizeof(array[0]))
337
479f2950
MW
338/**
339 * Ignore result of functions tagged with warn_unused_result attributes
340 */
d0230850 341#define ignore_result(call) { if(call){}; }
479f2950 342
552cc11b
MW
343/**
344 * Assign a function as a class method
345 */
346#define ASSIGN(method, function) (method = (typeof(method))function)
347
348/**
349 * time_t not defined
350 */
351#define UNDEFINED_TIME 0
352
9f0327e6
AS
353/**
354 * Maximum time since epoch causing wrap-around on Jan 19 03:14:07 UTC 2038
355 */
356#define TIME_32_BIT_SIGNED_MAX 0x7fffffff
357
cc396286
TB
358/**
359 * define some missing fixed width int types on OpenSolaris.
360 * TODO: since the uintXX_t types are defined by the C99 standard we should
361 * probably use those anyway
362 */
922ee2c5 363#if defined __sun || defined WIN32
cc396286
TB
364 #include <stdint.h>
365 typedef uint8_t u_int8_t;
366 typedef uint16_t u_int16_t;
367 typedef uint32_t u_int32_t;
368 typedef uint64_t u_int64_t;
369#endif
370
552cc11b
MW
371typedef enum status_t status_t;
372
373/**
374 * Return values of function calls.
375 */
376enum status_t {
377 /**
378 * Call succeeded.
379 */
380 SUCCESS,
7daf5226 381
552cc11b
MW
382 /**
383 * Call failed.
384 */
385 FAILED,
7daf5226 386
552cc11b
MW
387 /**
388 * Out of resources.
389 */
390 OUT_OF_RES,
7daf5226 391
552cc11b
MW
392 /**
393 * The suggested operation is already done
394 */
395 ALREADY_DONE,
7daf5226 396
552cc11b
MW
397 /**
398 * Not supported.
399 */
400 NOT_SUPPORTED,
7daf5226 401
552cc11b
MW
402 /**
403 * One of the arguments is invalid.
404 */
405 INVALID_ARG,
7daf5226 406
552cc11b
MW
407 /**
408 * Something could not be found.
409 */
410 NOT_FOUND,
7daf5226 411
552cc11b
MW
412 /**
413 * Error while parsing.
414 */
415 PARSE_ERROR,
7daf5226 416
552cc11b
MW
417 /**
418 * Error while verifying.
419 */
420 VERIFY_ERROR,
7daf5226 421
552cc11b
MW
422 /**
423 * Object in invalid state.
424 */
425 INVALID_STATE,
7daf5226 426
552cc11b
MW
427 /**
428 * Destroy object which called method belongs to.
429 */
430 DESTROY_ME,
7daf5226 431
552cc11b
MW
432 /**
433 * Another call to the method is required.
434 */
435 NEED_MORE,
436};
437
438/**
439 * enum_names for type status_t.
440 */
441extern enum_name_t *status_names;
442
4d174272
MW
443typedef enum tty_escape_t tty_escape_t;
444
445/**
446 * Excape codes for tty colors
447 */
448enum tty_escape_t {
449 /** text properties */
450 TTY_RESET,
451 TTY_BOLD,
452 TTY_UNDERLINE,
453 TTY_BLINKING,
454
455 /** foreground colors */
456 TTY_FG_BLACK,
457 TTY_FG_RED,
458 TTY_FG_GREEN,
459 TTY_FG_YELLOW,
460 TTY_FG_BLUE,
461 TTY_FG_MAGENTA,
462 TTY_FG_CYAN,
463 TTY_FG_WHITE,
464 TTY_FG_DEF,
465
466 /** background colors */
467 TTY_BG_BLACK,
468 TTY_BG_RED,
469 TTY_BG_GREEN,
470 TTY_BG_YELLOW,
471 TTY_BG_BLUE,
472 TTY_BG_MAGENTA,
473 TTY_BG_CYAN,
474 TTY_BG_WHITE,
475 TTY_BG_DEF,
476};
477
478/**
479 * Get the escape string for a given TTY color, empty string on non-tty fd
480 */
481char* tty_escape_get(int fd, tty_escape_t escape);
482
552cc11b
MW
483/**
484 * deprecated pluto style return value:
485 * error message, NULL for success
486 */
487typedef const char *err_t;
488
489/**
490 * Handle struct timeval like an own type.
491 */
492typedef struct timeval timeval_t;
493
494/**
495 * Handle struct timespec like an own type.
496 */
497typedef struct timespec timespec_t;
498
499/**
500 * Handle struct chunk_t like an own type.
501 */
502typedef struct sockaddr sockaddr_t;
503
552cc11b
MW
504/**
505 * Same as memcpy, but XORs src into dst instead of copy
506 */
507void memxor(u_int8_t dest[], u_int8_t src[], size_t n);
508
ed678b52
MW
509/**
510 * Safely overwrite n bytes of memory at ptr with zero, non-inlining variant.
511 */
512void memwipe_noinline(void *ptr, size_t n);
513
514/**
515 * Safely overwrite n bytes of memory at ptr with zero, inlining variant.
516 */
517static inline void memwipe_inline(void *ptr, size_t n)
518{
519 volatile char *c = (volatile char*)ptr;
d45b242b 520 size_t m, i;
ed678b52
MW
521
522 /* byte wise until long aligned */
d45b242b 523 for (i = 0; (uintptr_t)&c[i] % sizeof(long) && i < n; i++)
ed678b52
MW
524 {
525 c[i] = 0;
526 }
d45b242b
MW
527 /* word wise */
528 if (n >= sizeof(long))
ed678b52 529 {
d45b242b
MW
530 for (m = n - sizeof(long); i <= m; i += sizeof(long))
531 {
532 *(volatile long*)&c[i] = 0;
533 }
ed678b52
MW
534 }
535 /* byte wise of the rest */
536 for (; i < n; i++)
537 {
538 c[i] = 0;
539 }
540}
541
542/**
543 * Safely overwrite n bytes of memory at ptr with zero, auto-inlining variant.
544 */
545static inline void memwipe(void *ptr, size_t n)
546{
c480b5f4
TB
547 if (!ptr)
548 {
549 return;
550 }
ed678b52
MW
551 if (__builtin_constant_p(n))
552 {
553 memwipe_inline(ptr, n);
554 }
555 else
556 {
557 memwipe_noinline(ptr, n);
558 }
559}
560
81736d7d
TB
561/**
562 * A variant of strstr with the characteristics of memchr, where haystack is not
563 * a null-terminated string but simply a memory area of length n.
564 */
565void *memstr(const void *haystack, const char *needle, size_t n);
566
2ed241ae
TB
567/**
568 * Replacement for memrchr(3) if it is not provided by the C library.
569 *
570 * @param s start of the memory area to search
571 * @param c character to search
572 * @param n length of memory area to search
573 * @return pointer to the found character or NULL
574 */
575void *utils_memrchr(const void *s, int c, size_t n);
576
577#ifndef HAVE_MEMRCHR
578#define memrchr(s,c,n) utils_memrchr(s,c,n)
579#endif
580
d543d9ca
TB
581/**
582 * Translates the characters in the given string, searching for characters
583 * in 'from' and mapping them to characters in 'to'.
584 * The two characters sets 'from' and 'to' must contain the same number of
585 * characters.
586 */
587char *translate(char *str, const char *from, const char *to);
588
ccb6758e 589/**
4ab38d98 590 * Replaces all occurrences of search in the given string with replace.
ccb6758e
TB
591 *
592 * Allocates memory only if anything is replaced in the string. The original
593 * string is also returned if any of the arguments are invalid (e.g. if search
594 * is empty or any of them are NULL).
595 *
596 * @param str original string
597 * @param search string to search for and replace
4ab38d98 598 * @param replace string to replace found occurrences with
ccb6758e
TB
599 * @return allocated string, if anything got replaced, str otherwise
600 */
601char *strreplace(const char *str, const char *search, const char *replace);
602
66c0801d
MW
603/**
604 * Portable function to wait for SIGINT/SIGTERM (or equivalent).
605 */
606void wait_sigint();
607
766141bc
TB
608/**
609 * Like dirname(3) returns the directory part of the given null-terminated
610 * pathname, up to but not including the final '/' (or '.' if no '/' is found).
611 * Trailing '/' are not counted as part of the pathname.
612 *
613 * The difference is that it does this in a thread-safe manner (i.e. it does not
614 * use static buffers) and does not modify the original path.
615 *
616 * @param path original pathname
617 * @return allocated directory component
618 */
619char *path_dirname(const char *path);
620
621/**
622 * Like basename(3) returns the filename part of the given null-terminated path,
623 * i.e. the part following the final '/' (or '.' if path is empty or NULL).
624 * Trailing '/' are not counted as part of the pathname.
625 *
626 * The difference is that it does this in a thread-safe manner (i.e. it does not
627 * use static buffers) and does not modify the original path.
628 *
629 * @param path original pathname
630 * @return allocated filename component
631 */
632char *path_basename(const char *path);
633
67b3bcd1
MW
634/**
635 * Check if a given path is absolute.
636 *
637 * @param path path to check
638 * @return TRUE if absolute, FALSE if relative
639 */
640bool path_absolute(const char *path);
641
6c20579a 642/**
7daf5226 643 * Creates a directory and all required parent directories.
6c20579a 644 *
3f310c0d 645 * @param path path to the new directory
7daf5226 646 * @param mode permissions of the new directory/directories
6c20579a
TB
647 * @return TRUE on success
648 */
649bool mkdir_p(const char *path, mode_t mode);
650
9a8fdc15
TB
651#ifndef HAVE_CLOSEFROM
652/**
653 * Close open file descriptors greater than or equal to lowfd.
654 *
4ab38d98 655 * @param lowfd start closing file descriptors from here
9a8fdc15
TB
656 */
657void closefrom(int lowfd);
658#endif
659
3f310c0d
MW
660/**
661 * Get a timestamp from a monotonic time source.
662 *
663 * While the time()/gettimeofday() functions are affected by leap seconds
664 * and system time changes, this function returns ever increasing monotonic
665 * time stamps.
666 *
667 * @param tv timeval struct receiving monotonic timestamps, or NULL
668 * @return monotonic timestamp in seconds
669 */
670time_t time_monotonic(timeval_t *tv);
671
eecd41e3
TB
672/**
673 * Add the given number of milliseconds to the given timeval struct
674 *
675 * @param tv timeval struct to modify
676 * @param ms number of milliseconds
677 */
678static inline void timeval_add_ms(timeval_t *tv, u_int ms)
679{
680 tv->tv_usec += ms * 1000;
819c02db 681 while (tv->tv_usec >= 1000000 /* 1s */)
eecd41e3
TB
682 {
683 tv->tv_usec -= 1000000;
684 tv->tv_sec++;
685 }
686}
687
081ae2eb
MW
688/**
689 * returns null
690 */
691void *return_null();
692
233b853d
MW
693/**
694 * No-Operation function
695 */
696void nop();
697
da17b016
MW
698/**
699 * returns TRUE
700 */
701bool return_true();
702
703/**
704 * returns FALSE
705 */
706bool return_false();
707
502edf42
MW
708/**
709 * returns FAILED
710 */
711status_t return_failed();
712
4755ab50
MW
713/**
714 * returns SUCCESS
715 */
716status_t return_success();
717
0be12e35
MW
718/**
719 * Write a 16-bit host order value in network order to an unaligned address.
720 *
721 * @param host host order 16-bit value
722 * @param network unaligned address to write network order value to
723 */
724static inline void htoun16(void *network, u_int16_t host)
725{
dbee988e
MW
726 char *unaligned = (char*)network;
727
0be12e35 728 host = htons(host);
dbee988e 729 memcpy(unaligned, &host, sizeof(host));
0be12e35
MW
730}
731
732/**
733 * Write a 32-bit host order value in network order to an unaligned address.
734 *
735 * @param host host order 32-bit value
736 * @param network unaligned address to write network order value to
737 */
738static inline void htoun32(void *network, u_int32_t host)
739{
dbee988e
MW
740 char *unaligned = (char*)network;
741
0be12e35 742 host = htonl(host);
dbee988e 743 memcpy((char*)unaligned, &host, sizeof(host));
0be12e35
MW
744}
745
fbeb9454
AS
746/**
747 * Write a 64-bit host order value in network order to an unaligned address.
748 *
a91462df 749 * @param host host order 64-bit value
fbeb9454
AS
750 * @param network unaligned address to write network order value to
751 */
752static inline void htoun64(void *network, u_int64_t host)
753{
754 char *unaligned = (char*)network;
f4e25e60
MW
755
756#ifdef be64toh
757 host = htobe64(host);
758 memcpy((char*)unaligned, &host, sizeof(host));
759#else
fbeb9454
AS
760 u_int32_t high_part, low_part;
761
762 high_part = host >> 32;
763 high_part = htonl(high_part);
764 low_part = host & 0xFFFFFFFFLL;
765 low_part = htonl(low_part);
766
767 memcpy(unaligned, &high_part, sizeof(high_part));
768 unaligned += sizeof(high_part);
769 memcpy(unaligned, &low_part, sizeof(low_part));
f4e25e60 770#endif
fbeb9454
AS
771}
772
0be12e35
MW
773/**
774 * Read a 16-bit value in network order from an unaligned address to host order.
775 *
776 * @param network unaligned address to read network order value from
777 * @return host order value
778 */
779static inline u_int16_t untoh16(void *network)
780{
dbee988e 781 char *unaligned = (char*)network;
0be12e35
MW
782 u_int16_t tmp;
783
dbee988e 784 memcpy(&tmp, unaligned, sizeof(tmp));
0be12e35
MW
785 return ntohs(tmp);
786}
787
788/**
789 * Read a 32-bit value in network order from an unaligned address to host order.
790 *
791 * @param network unaligned address to read network order value from
792 * @return host order value
793 */
794static inline u_int32_t untoh32(void *network)
795{
dbee988e 796 char *unaligned = (char*)network;
0be12e35
MW
797 u_int32_t tmp;
798
dbee988e 799 memcpy(&tmp, unaligned, sizeof(tmp));
f8f4f31a 800 return ntohl(tmp);
0be12e35
MW
801}
802
fbeb9454
AS
803/**
804 * Read a 64-bit value in network order from an unaligned address to host order.
805 *
806 * @param network unaligned address to read network order value from
807 * @return host order value
808 */
809static inline u_int64_t untoh64(void *network)
810{
811 char *unaligned = (char*)network;
f4e25e60
MW
812
813#ifdef be64toh
814 u_int64_t tmp;
815
816 memcpy(&tmp, unaligned, sizeof(tmp));
817 return be64toh(tmp);
818#else
fbeb9454
AS
819 u_int32_t high_part, low_part;
820
821 memcpy(&high_part, unaligned, sizeof(high_part));
822 unaligned += sizeof(high_part);
823 memcpy(&low_part, unaligned, sizeof(low_part));
824
825 high_part = ntohl(high_part);
826 low_part = ntohl(low_part);
827
828 return (((u_int64_t)high_part) << 32) + low_part;
f4e25e60 829#endif
fbeb9454
AS
830}
831
84044f9c 832/**
812ae898 833 * Get the padding required to make size a multiple of alignment
84044f9c 834 */
812ae898 835static inline size_t pad_len(size_t size, size_t alignment)
84044f9c 836{
812ae898 837 size_t remainder;
84044f9c 838
812ae898
TB
839 remainder = size % alignment;
840 return remainder ? alignment - remainder : 0;
841}
842
843/**
844 * Round up size to be multiple of alignment
845 */
846static inline size_t round_up(size_t size, size_t alignment)
847{
848 return size + pad_len(size, alignment);
84044f9c
MW
849}
850
851/**
812ae898 852 * Round down size to be a multiple of alignment
84044f9c 853 */
812ae898 854static inline size_t round_down(size_t size, size_t alignment)
84044f9c 855{
812ae898 856 return size - (size % alignment);
84044f9c
MW
857}
858
552cc11b
MW
859/**
860 * Special type to count references
861 */
4d04e2c6 862typedef u_int refcount_t;
efd0fe21 863
a0c2370e
TB
864/* use __atomic* built-ins with GCC 4.7 and newer */
865#ifdef __GNUC__
866# if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 6))
867# define HAVE_GCC_ATOMIC_OPERATIONS
868# endif
869#endif
870
efd0fe21
MW
871#ifdef HAVE_GCC_ATOMIC_OPERATIONS
872
0f603d42
TB
873#define ref_get(ref) __atomic_add_fetch(ref, 1, __ATOMIC_RELAXED)
874/* The relaxed memory model works fine for increments as these (usually) don't
875 * change the state of refcounted objects. But here we have to ensure that we
876 * free the right stuff if ref counted objects are mutable. So we have to sync
877 * with other threads that call ref_put(). It would be sufficient to use
878 * __ATOMIC_RELEASE here and then call __atomic_thread_fence() with
879 * __ATOMIC_ACQUIRE if we reach 0, but since we don't have control over the use
880 * of ref_put() we have to make sure. */
881#define ref_put(ref) (!__atomic_sub_fetch(ref, 1, __ATOMIC_ACQ_REL))
882#define ref_cur(ref) __atomic_load_n(ref, __ATOMIC_RELAXED)
883
884#define _cas_impl(ptr, oldval, newval) ({ typeof(oldval) _old = oldval; \
885 __atomic_compare_exchange_n(ptr, &_old, newval, FALSE, \
886 __ATOMIC_SEQ_CST, __ATOMIC_RELAXED); })
887#define cas_bool(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
888#define cas_ptr(ptr, oldval, newval) _cas_impl(ptr, oldval, newval)
889
890#elif defined(HAVE_GCC_SYNC_OPERATIONS)
891
3160b92a 892#define ref_get(ref) __sync_add_and_fetch(ref, 1)
efd0fe21 893#define ref_put(ref) (!__sync_sub_and_fetch(ref, 1))
efedd0d2 894#define ref_cur(ref) __sync_fetch_and_add(ref, 0)
efd0fe21 895
5317dd68
TB
896#define cas_bool(ptr, oldval, newval) \
897 (__sync_bool_compare_and_swap(ptr, oldval, newval))
898#define cas_ptr(ptr, oldval, newval) \
899 (__sync_bool_compare_and_swap(ptr, oldval, newval))
900
0f603d42 901#else /* !HAVE_GCC_ATOMIC_OPERATIONS && !HAVE_GCC_SYNC_OPERATIONS */
efd0fe21 902
552cc11b
MW
903/**
904 * Get a new reference.
905 *
efedd0d2 906 * Increments the reference counter atomically.
552cc11b
MW
907 *
908 * @param ref pointer to ref counter
3160b92a 909 * @return new value of ref
552cc11b 910 */
3160b92a 911refcount_t ref_get(refcount_t *ref);
552cc11b
MW
912
913/**
914 * Put back a unused reference.
915 *
efedd0d2 916 * Decrements the reference counter atomically and
552cc11b
MW
917 * says if more references available.
918 *
919 * @param ref pointer to ref counter
920 * @return TRUE if no more references counted
921 */
922bool ref_put(refcount_t *ref);
923
efedd0d2
TB
924/**
925 * Get the current value of the reference counter.
926 *
927 * @param ref pointer to ref counter
928 * @return current value of ref
929 */
930refcount_t ref_cur(refcount_t *ref);
931
5317dd68
TB
932/**
933 * Atomically replace value of ptr with newval if it currently equals oldval.
934 *
935 * @param ptr pointer to variable
936 * @param oldval old value of the variable
937 * @param newval new value set if possible
938 * @return TRUE if value equaled oldval and newval was written
939 */
940bool cas_bool(bool *ptr, bool oldval, bool newval);
941
942/**
943 * Atomically replace value of ptr with newval if it currently equals oldval.
944 *
945 * @param ptr pointer to variable
946 * @param oldval old value of the variable
947 * @param newval new value set if possible
948 * @return TRUE if value equaled oldval and newval was written
949 */
950bool cas_ptr(void **ptr, void *oldval, void *newval);
951
efd0fe21
MW
952#endif /* HAVE_GCC_ATOMIC_OPERATIONS */
953
2077d996
MW
954#ifndef HAVE_FMEMOPEN
955# ifdef HAVE_FUNOPEN
9df621d2
MW
956# define HAVE_FMEMOPEN
957# define HAVE_FMEMOPEN_FALLBACK
5ac29360 958# include <stdio.h>
2077d996
MW
959/**
960 * fmemopen(3) fallback using BSD funopen.
961 *
962 * We could also provide one using fopencookie(), but should we have it we
963 * most likely have fmemopen().
964 *
965 * fseek() is currently not supported.
966 */
967FILE *fmemopen(void *buf, size_t size, const char *mode);
968# endif /* FUNOPEN */
969#endif /* FMEMOPEN */
970
552cc11b 971/**
d25ce370 972 * printf hook for time_t.
552cc11b 973 *
7daf5226 974 * Arguments are:
323f9f99 975 * time_t* time, bool utc
552cc11b 976 */
1b40b74d 977int time_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 978 const void *const *args);
552cc11b
MW
979
980/**
d25ce370 981 * printf hook for time_t deltas.
552cc11b 982 *
7daf5226 983 * Arguments are:
323f9f99 984 * time_t* begin, time_t* end
552cc11b 985 */
1b40b74d 986int time_delta_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 987 const void *const *args);
552cc11b
MW
988
989/**
d25ce370 990 * printf hook for memory areas.
552cc11b 991 *
7daf5226 992 * Arguments are:
817ab8a8 993 * u_char *ptr, u_int len
552cc11b 994 */
1b40b74d 995int mem_printf_hook(printf_hook_data_t *data, printf_hook_spec_t *spec,
d25ce370 996 const void *const *args);
552cc11b 997
1490ff4d 998#endif /** UTILS_H_ @}*/