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