xref: /freebsd/contrib/unbound/compat/ctime_r.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
1 /* taken from ldns 1.6.1 */
2 #include "config.h"
3 #ifdef HAVE_TIME_H
4 #include <time.h>
5 #endif
6 #include "util/locks.h"
7 
8 /** the lock for ctime buffer */
9 static lock_basic_type ctime_lock;
10 /** has it been inited */
11 static int ctime_r_init = 0;
12 
13 /** cleanup ctime_r on exit */
14 static void
15 ctime_r_cleanup(void)
16 {
17 	if(ctime_r_init) {
18 		ctime_r_init = 0;
19 		lock_basic_destroy(&ctime_lock);
20 	}
21 }
22 
23 char *ctime_r(const time_t *timep, char *buf)
24 {
25 	char* result;
26 	if(!ctime_r_init) {
27 		/* still small race where this init can be done twice,
28 		 * which is mostly harmless */
29 		ctime_r_init = 1;
30 		lock_basic_init(&ctime_lock);
31 		atexit(&ctime_r_cleanup);
32 	}
33 	lock_basic_lock(&ctime_lock);
34 	result = ctime(timep);
35 	if(buf && result) {
36 		if(strlen(result) > 10 && result[7]==' ' && result[8]=='0')
37 			result[8]=' '; /* fix error in windows ctime */
38 		strcpy(buf, result);
39 	}
40 	lock_basic_unlock(&ctime_lock);
41 	return result;
42 }
43