xref: /freebsd/contrib/ntp/libntp/lib_strbuf.c (revision f5f40dd63bc7acbb5312b26ac1ea1103c12352a6)
1 /*
2  * lib_strbuf.c - init_lib() and library string storage
3  */
4 #ifdef HAVE_CONFIG_H
5 #include <config.h>
6 #endif
7 
8 #include <isc/mutex.h>
9 #include <isc/net.h>
10 #include <isc/result.h>
11 
12 #include "ntp_fp.h"
13 #include "ntp_stdlib.h"
14 #include "lib_strbuf.h"
15 
16 #define LIB_NUMBUF	10
17 
18 /*
19  * Storage declarations
20  */
21 static char		lib_stringbuf_storage[LIB_NUMBUF][LIB_BUFLENGTH];
22 static char *		lib_stringbuf[LIB_NUMBUF];
23 int			lib_inited;
24 static isc_mutex_t	lib_mutex;
25 int			ipv4_works;
26 int			ipv6_works;
27 int			debug;
28 
29 /*
30  * initialization routine.  Might be needed if the code is ROMized.
31  */
32 void
33 init_lib(void)
34 {
35 	u_int	u;
36 
37 	if (lib_inited) {
38 		return;
39 	}
40 	ipv4_works = (ISC_R_SUCCESS == isc_net_probeipv4());
41 	ipv6_works = (ISC_R_SUCCESS == isc_net_probeipv6());
42 	init_systime();
43 	/*
44 	 * Avoid -Wrestrict warnings by keeping a pointer to each buffer
45 	 * so the compiler can see copying from one buffer to another is
46 	 * not violating restrict qualifiers on, e.g. memcpy() args.
47 	 */
48 	for (u = 0; u < COUNTOF(lib_stringbuf); u++) {
49 		lib_stringbuf[u] = lib_stringbuf_storage[u];
50 	}
51 	isc_mutex_init(&lib_mutex);
52 	lib_inited = TRUE;
53 }
54 
55 
56 char *
57 lib_getbuf(void)
58 {
59 	static int	lib_nextbuf;
60 	int		mybuf;
61 
62 	if (!lib_inited) {
63 		init_lib();
64 	}
65 	isc_mutex_lock(&lib_mutex);
66 	mybuf = lib_nextbuf;
67 	lib_nextbuf = (1 + mybuf) % COUNTOF(lib_stringbuf);
68 	isc_mutex_unlock(&lib_mutex);
69 	zero_mem(lib_stringbuf[mybuf], LIB_BUFLENGTH);
70 
71 	return lib_stringbuf[mybuf];
72 }