1 /*
2    Unix SMB/CIFS implementation.
3    time handling functions
4 
5    Copyright (C) Andrew Tridgell 		1992-2004
6    Copyright (C) Stefan (metze) Metzmacher	2002
7    Copyright (C) Jeremy Allison			2007
8    Copyright (C) Andrew Bartlett                2011
9 
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23 
24 #include "replace.h"
25 #include "system/time.h"
26 #include "byteorder.h"
27 #include "time_basic.h"
28 #include "lib/util/time.h" /* Avoid /usr/include/time.h */
29 
30 /**
31  * @file
32  * @brief time handling functions
33  */
34 
35 #if (SIZEOF_LONG == 8)
36 #define TIME_FIXUP_CONSTANT_INT 11644473600L
37 #elif (SIZEOF_LONG_LONG == 8)
38 #define TIME_FIXUP_CONSTANT_INT 11644473600LL
39 #endif
40 
41 
42 
43 /**
44  External access to time_t_min and time_t_max.
45 **/
get_time_t_max(void)46 _PUBLIC_ time_t get_time_t_max(void)
47 {
48 	return TIME_T_MAX;
49 }
50 
51 /**
52 a wrapper to preferably get the monotonic time
53 **/
clock_gettime_mono(struct timespec * tp)54 _PUBLIC_ void clock_gettime_mono(struct timespec *tp)
55 {
56 /* prefer a suspend aware monotonic CLOCK_BOOTTIME: */
57 #ifdef CLOCK_BOOTTIME
58 	if (clock_gettime(CLOCK_BOOTTIME,tp) == 0) {
59 		return;
60 	}
61 #endif
62 /* then try the  monotonic clock: */
63 #ifndef CUSTOM_CLOCK_MONOTONIC_IS_REALTIME
64 	if (clock_gettime(CUSTOM_CLOCK_MONOTONIC,tp) == 0) {
65 		return;
66 	}
67 #endif
68 	clock_gettime(CLOCK_REALTIME,tp);
69 }
70 
71 /**
72 a wrapper to preferably get the monotonic time in seconds
73 **/
time_mono(time_t * t)74 _PUBLIC_ time_t time_mono(time_t *t)
75 {
76 	struct timespec tp;
77 
78 	clock_gettime_mono(&tp);
79 	if (t != NULL) {
80 		*t = tp.tv_sec;
81 	}
82 	return tp.tv_sec;
83 }
84 
85 
86 #define TIME_FIXUP_CONSTANT 11644473600LL
87 
convert_timespec_to_time_t(struct timespec ts)88 time_t convert_timespec_to_time_t(struct timespec ts)
89 {
90 	/* Ensure tv_nsec is less than 1sec. */
91 	while (ts.tv_nsec > 1000000000) {
92 		ts.tv_sec += 1;
93 		ts.tv_nsec -= 1000000000;
94 	}
95 
96 	/* 1 ns == 1,000,000,000 - one thousand millionths of a second.
97 	   increment if it's greater than 500 millionth of a second. */
98 
99 	if (ts.tv_nsec > 500000000) {
100 		return ts.tv_sec + 1;
101 	}
102 	return ts.tv_sec;
103 }
104 
convert_time_t_to_timespec(time_t t)105 struct timespec convert_time_t_to_timespec(time_t t)
106 {
107 	struct timespec ts;
108 	ts.tv_sec = t;
109 	ts.tv_nsec = 0;
110 	return ts;
111 }
112 
113 
114 
115 /**
116  Interpret an 8 byte "filetime" structure to a time_t
117  It's originally in "100ns units since jan 1st 1601"
118 
119  An 8 byte value of 0xffffffffffffffff will be returned as a timespec of
120 
121 	tv_sec = 0
122 	tv_nsec = 0;
123 
124  Returns GMT.
125 **/
nt_time_to_unix(NTTIME nt)126 time_t nt_time_to_unix(NTTIME nt)
127 {
128 	return convert_timespec_to_time_t(nt_time_to_unix_timespec(nt));
129 }
130 
131 
132 /**
133 put a 8 byte filetime from a time_t
134 This takes GMT as input
135 **/
unix_to_nt_time(NTTIME * nt,time_t t)136 _PUBLIC_ void unix_to_nt_time(NTTIME *nt, time_t t)
137 {
138 	uint64_t t2;
139 
140 	if (t == (time_t)-1) {
141 		*nt = (NTTIME)-1LL;
142 		return;
143 	}
144 
145 	if (t == TIME_T_MAX || t == INT64_MAX) {
146 		*nt = 0x7fffffffffffffffLL;
147 		return;
148 	}
149 
150 	if (t == 0) {
151 		*nt = 0;
152 		return;
153 	}
154 
155 	t2 = t;
156 	t2 += TIME_FIXUP_CONSTANT_INT;
157 	t2 *= 1000*1000*10;
158 
159 	*nt = t2;
160 }
161 
162 
163 /**
164 check if it's a null unix time
165 **/
null_time(time_t t)166 _PUBLIC_ bool null_time(time_t t)
167 {
168 	return t == 0 ||
169 		t == (time_t)0xFFFFFFFF ||
170 		t == (time_t)-1;
171 }
172 
173 
174 /**
175 check if it's a null NTTIME
176 **/
null_nttime(NTTIME t)177 _PUBLIC_ bool null_nttime(NTTIME t)
178 {
179 	return t == 0 || t == (NTTIME)-1;
180 }
181 
182 /*******************************************************************
183   create a 16 bit dos packed date
184 ********************************************************************/
make_dos_date1(struct tm * t)185 static uint16_t make_dos_date1(struct tm *t)
186 {
187 	uint16_t ret=0;
188 	ret = (((unsigned int)(t->tm_mon+1)) >> 3) | ((t->tm_year-80) << 1);
189 	ret = ((ret&0xFF)<<8) | (t->tm_mday | (((t->tm_mon+1) & 0x7) << 5));
190 	return ret;
191 }
192 
193 /*******************************************************************
194   create a 16 bit dos packed time
195 ********************************************************************/
make_dos_time1(struct tm * t)196 static uint16_t make_dos_time1(struct tm *t)
197 {
198 	uint16_t ret=0;
199 	ret = ((((unsigned int)t->tm_min >> 3)&0x7) | (((unsigned int)t->tm_hour) << 3));
200 	ret = ((ret&0xFF)<<8) | ((t->tm_sec/2) | ((t->tm_min & 0x7) << 5));
201 	return ret;
202 }
203 
204 /*******************************************************************
205   create a 32 bit dos packed date/time from some parameters
206   This takes a GMT time and returns a packed localtime structure
207 ********************************************************************/
make_dos_date(time_t unixdate,int zone_offset)208 static uint32_t make_dos_date(time_t unixdate, int zone_offset)
209 {
210 	struct tm *t;
211 	uint32_t ret=0;
212 
213 	if (unixdate == 0) {
214 		return 0;
215 	}
216 
217 	unixdate -= zone_offset;
218 
219 	t = gmtime(&unixdate);
220 	if (!t) {
221 		return 0xFFFFFFFF;
222 	}
223 
224 	ret = make_dos_date1(t);
225 	ret = ((ret&0xFFFF)<<16) | make_dos_time1(t);
226 
227 	return ret;
228 }
229 
230 /**
231 put a dos date into a buffer (time/date format)
232 This takes GMT time and puts local time in the buffer
233 **/
push_dos_date(uint8_t * buf,int offset,time_t unixdate,int zone_offset)234 _PUBLIC_ void push_dos_date(uint8_t *buf, int offset, time_t unixdate, int zone_offset)
235 {
236 	uint32_t x = make_dos_date(unixdate, zone_offset);
237 	SIVAL(buf,offset,x);
238 }
239 
240 /**
241 put a dos date into a buffer (date/time format)
242 This takes GMT time and puts local time in the buffer
243 **/
push_dos_date2(uint8_t * buf,int offset,time_t unixdate,int zone_offset)244 _PUBLIC_ void push_dos_date2(uint8_t *buf,int offset,time_t unixdate, int zone_offset)
245 {
246 	uint32_t x;
247 	x = make_dos_date(unixdate, zone_offset);
248 	x = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
249 	SIVAL(buf,offset,x);
250 }
251 
252 /**
253 put a dos 32 bit "unix like" date into a buffer. This routine takes
254 GMT and converts it to LOCAL time before putting it (most SMBs assume
255 localtime for this sort of date)
256 **/
push_dos_date3(uint8_t * buf,int offset,time_t unixdate,int zone_offset)257 _PUBLIC_ void push_dos_date3(uint8_t *buf,int offset,time_t unixdate, int zone_offset)
258 {
259 	if (!null_time(unixdate)) {
260 		unixdate -= zone_offset;
261 	}
262 	SIVAL(buf,offset,unixdate);
263 }
264 
265 /*******************************************************************
266   interpret a 32 bit dos packed date/time to some parameters
267 ********************************************************************/
interpret_dos_date(uint32_t date,int * year,int * month,int * day,int * hour,int * minute,int * second)268 void interpret_dos_date(uint32_t date,int *year,int *month,int *day,int *hour,int *minute,int *second)
269 {
270 	uint32_t p0,p1,p2,p3;
271 
272 	p0=date&0xFF; p1=((date&0xFF00)>>8)&0xFF;
273 	p2=((date&0xFF0000)>>16)&0xFF; p3=((date&0xFF000000)>>24)&0xFF;
274 
275 	*second = 2*(p0 & 0x1F);
276 	*minute = ((p0>>5)&0xFF) + ((p1&0x7)<<3);
277 	*hour = (p1>>3)&0xFF;
278 	*day = (p2&0x1F);
279 	*month = ((p2>>5)&0xFF) + ((p3&0x1)<<3) - 1;
280 	*year = ((p3>>1)&0xFF) + 80;
281 }
282 
283 /**
284   create a unix date (int GMT) from a dos date (which is actually in
285   localtime)
286 **/
pull_dos_date(const uint8_t * date_ptr,int zone_offset)287 _PUBLIC_ time_t pull_dos_date(const uint8_t *date_ptr, int zone_offset)
288 {
289 	uint32_t dos_date=0;
290 	struct tm t;
291 	time_t ret;
292 
293 	dos_date = IVAL(date_ptr,0);
294 
295 	if (dos_date == 0) return (time_t)0;
296 
297 	interpret_dos_date(dos_date,&t.tm_year,&t.tm_mon,
298 			   &t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
299 	t.tm_isdst = -1;
300 
301 	ret = timegm(&t);
302 
303 	ret += zone_offset;
304 
305 	return ret;
306 }
307 
308 /**
309 like make_unix_date() but the words are reversed
310 **/
pull_dos_date2(const uint8_t * date_ptr,int zone_offset)311 _PUBLIC_ time_t pull_dos_date2(const uint8_t *date_ptr, int zone_offset)
312 {
313 	uint32_t x,x2;
314 
315 	x = IVAL(date_ptr,0);
316 	x2 = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
317 	SIVAL(&x,0,x2);
318 
319 	return pull_dos_date((const uint8_t *)&x, zone_offset);
320 }
321 
322 /**
323   create a unix GMT date from a dos date in 32 bit "unix like" format
324   these generally arrive as localtimes, with corresponding DST
325 **/
pull_dos_date3(const uint8_t * date_ptr,int zone_offset)326 _PUBLIC_ time_t pull_dos_date3(const uint8_t *date_ptr, int zone_offset)
327 {
328 	time_t t = (time_t)IVAL(date_ptr,0);
329 
330 	if (t == (time_t)0xFFFFFFFF) {
331 		t = (time_t)-1;
332 	}
333 
334 	if (!null_time(t)) {
335 		t += zone_offset;
336 	}
337 	return t;
338 }
339 
340 /****************************************************************************
341  Return the date and time as a string
342 ****************************************************************************/
343 
timeval_string(TALLOC_CTX * ctx,const struct timeval * tp,bool hires)344 char *timeval_string(TALLOC_CTX *ctx, const struct timeval *tp, bool hires)
345 {
346 	struct timeval_buf tmp;
347 	char *result;
348 
349 	result = talloc_strdup(ctx, timeval_str_buf(tp, false, hires, &tmp));
350 	if (result == NULL) {
351 		return NULL;
352 	}
353 
354 	/*
355 	 * beautify the talloc_report output
356 	 *
357 	 * This is not just cosmetics. A C compiler might in theory make the
358 	 * talloc_strdup call above a tail call with the tail call
359 	 * optimization. This would render "tmp" invalid while talloc_strdup
360 	 * tries to duplicate it. The talloc_set_name_const call below puts
361 	 * the talloc_strdup call into non-tail position.
362 	 */
363 	talloc_set_name_const(result, result);
364 	return result;
365 }
366 
367 /****************************************************************************
368  Return the date and time as a string
369 ****************************************************************************/
370 
timespec_string_buf(const struct timespec * tp,bool hires,struct timeval_buf * buf)371 const char *timespec_string_buf(const struct timespec *tp,
372 				bool hires,
373 				struct timeval_buf *buf)
374 {
375 	time_t t;
376 	struct tm *tm = NULL;
377 	size_t len;
378 
379 	if (is_omit_timespec(tp)) {
380 		strlcpy(buf->buf, "SAMBA_UTIME_OMIT", sizeof(buf->buf));
381 		return buf->buf;
382 	}
383 
384 	t = (time_t)tp->tv_sec;
385 	tm = localtime(&t);
386 
387 	if (tm == NULL) {
388 		if (hires) {
389 			len = snprintf(buf->buf, sizeof(buf->buf),
390 				       "%ld.%09ld seconds since the Epoch",
391 				       (long)tp->tv_sec, (long)tp->tv_nsec);
392 		} else {
393 			len = snprintf(buf->buf, sizeof(buf->buf),
394 				       "%ld seconds since the Epoch", (long)t);
395 		}
396 	} else if (!hires) {
397 		len = snprintf(buf->buf, sizeof(buf->buf),
398 			       "%04d/%02d/%02d %02d:%02d:%02d",
399 			       1900 + tm->tm_year,
400 			       tm->tm_mon + 1,
401 			       tm->tm_mday,
402 			       tm->tm_hour,
403 			       tm->tm_min,
404 			       tm->tm_sec);
405 	} else {
406 		len = snprintf(buf->buf, sizeof(buf->buf),
407 			       "%04d/%02d/%02d %02d:%02d:%02d.%09ld",
408 			       1900 + tm->tm_year,
409 			       tm->tm_mon + 1,
410 			       tm->tm_mday,
411 			       tm->tm_hour,
412 			       tm->tm_min,
413 			       tm->tm_sec,
414 			       (long)tp->tv_nsec);
415 	}
416 	if (len == -1) {
417 		return "";
418 	}
419 
420 	return buf->buf;
421 }
422 
current_timestring(TALLOC_CTX * ctx,bool hires)423 char *current_timestring(TALLOC_CTX *ctx, bool hires)
424 {
425 	struct timeval tv;
426 
427 	GetTimeOfDay(&tv);
428 	return timeval_string(ctx, &tv, hires);
429 }
430 
431 /*
432  * Return date and time as a minimal string avoiding funny characters
433  * that may cause trouble in file names. We only use digits and
434  * underscore ... or a minus/hyphen if we got negative time.
435  */
minimal_timeval_string(TALLOC_CTX * ctx,const struct timeval * tp,bool hires)436 char *minimal_timeval_string(TALLOC_CTX *ctx, const struct timeval *tp, bool hires)
437 {
438 	time_t t;
439 	struct tm *tm;
440 
441 	t = (time_t)tp->tv_sec;
442 	tm = localtime(&t);
443 	if (!tm) {
444 		if (hires) {
445 			return talloc_asprintf(ctx, "%ld_%06ld",
446 					       (long)tp->tv_sec,
447 					       (long)tp->tv_usec);
448 		} else {
449 			return talloc_asprintf(ctx, "%ld", (long)t);
450 		}
451 	} else {
452 		if (hires) {
453 			return talloc_asprintf(ctx,
454 					       "%04d%02d%02d_%02d%02d%02d_%06ld",
455 					       tm->tm_year+1900,
456 					       tm->tm_mon+1,
457 					       tm->tm_mday,
458 					       tm->tm_hour,
459 					       tm->tm_min,
460 					       tm->tm_sec,
461 					       (long)tp->tv_usec);
462 		} else {
463 			return talloc_asprintf(ctx,
464 					       "%04d%02d%02d_%02d%02d%02d",
465 					       tm->tm_year+1900,
466 					       tm->tm_mon+1,
467 					       tm->tm_mday,
468 					       tm->tm_hour,
469 					       tm->tm_min,
470 					       tm->tm_sec);
471 		}
472 	}
473 }
474 
current_minimal_timestring(TALLOC_CTX * ctx,bool hires)475 char *current_minimal_timestring(TALLOC_CTX *ctx, bool hires)
476 {
477 	struct timeval tv;
478 
479 	GetTimeOfDay(&tv);
480 	return minimal_timeval_string(ctx, &tv, hires);
481 }
482 
483 /**
484 return a HTTP/1.0 time string
485 **/
http_timestring(TALLOC_CTX * mem_ctx,time_t t)486 _PUBLIC_ char *http_timestring(TALLOC_CTX *mem_ctx, time_t t)
487 {
488 	char *buf;
489 	char tempTime[60];
490 	struct tm *tm = localtime(&t);
491 
492 	if (t == TIME_T_MAX) {
493 		return talloc_strdup(mem_ctx, "never");
494 	}
495 
496 	if (!tm) {
497 		return talloc_asprintf(mem_ctx,"%ld seconds since the Epoch",(long)t);
498 	}
499 
500 #ifndef HAVE_STRFTIME
501 	buf = talloc_strdup(mem_ctx, asctime(tm));
502 	if (buf[strlen(buf)-1] == '\n') {
503 		buf[strlen(buf)-1] = 0;
504 	}
505 #else
506 	strftime(tempTime, sizeof(tempTime)-1, "%a, %d %b %Y %H:%M:%S %Z", tm);
507 	buf = talloc_strdup(mem_ctx, tempTime);
508 #endif /* !HAVE_STRFTIME */
509 
510 	return buf;
511 }
512 
513 /**
514  Return the date and time as a string
515 **/
timestring(TALLOC_CTX * mem_ctx,time_t t)516 _PUBLIC_ char *timestring(TALLOC_CTX *mem_ctx, time_t t)
517 {
518 	char *TimeBuf;
519 	char tempTime[80];
520 	struct tm *tm;
521 
522 	tm = localtime(&t);
523 	if (!tm) {
524 		return talloc_asprintf(mem_ctx,
525 				       "%ld seconds since the Epoch",
526 				       (long)t);
527 	}
528 
529 #ifdef HAVE_STRFTIME
530 	/* Some versions of gcc complain about using some special format
531 	 * specifiers. This is a bug in gcc, not a bug in this code. See a
532 	 * recent strftime() manual page for details. */
533 	strftime(tempTime,sizeof(tempTime)-1,"%a %b %e %X %Y %Z",tm);
534 	TimeBuf = talloc_strdup(mem_ctx, tempTime);
535 #else
536 	TimeBuf = talloc_strdup(mem_ctx, asctime(tm));
537 	if (TimeBuf == NULL) {
538 		return NULL;
539 	}
540 	if (TimeBuf[0] != '\0') {
541 		size_t len = strlen(TimeBuf);
542 		if (TimeBuf[len - 1] == '\n') {
543 			TimeBuf[len - 1] = '\0';
544 		}
545 	}
546 #endif
547 
548 	return TimeBuf;
549 }
550 
551 /**
552   return a talloced string representing a NTTIME for human consumption
553 */
nt_time_string(TALLOC_CTX * mem_ctx,NTTIME nt)554 _PUBLIC_ const char *nt_time_string(TALLOC_CTX *mem_ctx, NTTIME nt)
555 {
556 	time_t t;
557 	if (nt == 0) {
558 		return "NTTIME(0)";
559 	}
560 	t = nt_time_to_full_time_t(nt);
561 	return timestring(mem_ctx, t);
562 }
563 
564 
565 /**
566   put a NTTIME into a packet
567 */
push_nttime(uint8_t * base,uint16_t offset,NTTIME t)568 _PUBLIC_ void push_nttime(uint8_t *base, uint16_t offset, NTTIME t)
569 {
570 	SBVAL(base, offset,   t);
571 }
572 
573 /**
574   pull a NTTIME from a packet
575 */
pull_nttime(uint8_t * base,uint16_t offset)576 _PUBLIC_ NTTIME pull_nttime(uint8_t *base, uint16_t offset)
577 {
578 	NTTIME ret = BVAL(base, offset);
579 	return ret;
580 }
581 
582 /**
583   return (tv1 - tv2) in microseconds
584 */
usec_time_diff(const struct timeval * tv1,const struct timeval * tv2)585 _PUBLIC_ int64_t usec_time_diff(const struct timeval *tv1, const struct timeval *tv2)
586 {
587 	int64_t sec_diff = tv1->tv_sec - tv2->tv_sec;
588 	return (sec_diff * 1000000) + (int64_t)(tv1->tv_usec - tv2->tv_usec);
589 }
590 
591 /**
592   return (tp1 - tp2) in nanoseconds
593 */
nsec_time_diff(const struct timespec * tp1,const struct timespec * tp2)594 _PUBLIC_ int64_t nsec_time_diff(const struct timespec *tp1, const struct timespec *tp2)
595 {
596 	int64_t sec_diff = tp1->tv_sec - tp2->tv_sec;
597 	return (sec_diff * 1000000000) + (int64_t)(tp1->tv_nsec - tp2->tv_nsec);
598 }
599 
600 
601 /**
602   return a zero timeval
603 */
timeval_zero(void)604 _PUBLIC_ struct timeval timeval_zero(void)
605 {
606 	struct timeval tv;
607 	tv.tv_sec = 0;
608 	tv.tv_usec = 0;
609 	return tv;
610 }
611 
612 /**
613   return true if a timeval is zero
614 */
timeval_is_zero(const struct timeval * tv)615 _PUBLIC_ bool timeval_is_zero(const struct timeval *tv)
616 {
617 	return tv->tv_sec == 0 && tv->tv_usec == 0;
618 }
619 
620 /**
621   return a timeval for the current time
622 */
timeval_current(void)623 _PUBLIC_ struct timeval timeval_current(void)
624 {
625 	struct timeval tv;
626 	GetTimeOfDay(&tv);
627 	return tv;
628 }
629 
630 /**
631   return a timeval struct with the given elements
632 */
timeval_set(uint32_t secs,uint32_t usecs)633 _PUBLIC_ struct timeval timeval_set(uint32_t secs, uint32_t usecs)
634 {
635 	struct timeval tv;
636 	tv.tv_sec = secs;
637 	tv.tv_usec = usecs;
638 	return tv;
639 }
640 
641 
642 /**
643   return a timeval ofs microseconds after tv
644 */
timeval_add(const struct timeval * tv,uint32_t secs,uint32_t usecs)645 _PUBLIC_ struct timeval timeval_add(const struct timeval *tv,
646 			   uint32_t secs, uint32_t usecs)
647 {
648 	struct timeval tv2 = *tv;
649 	const unsigned int million = 1000000;
650 	tv2.tv_sec += secs;
651 	tv2.tv_usec += usecs;
652 	tv2.tv_sec += tv2.tv_usec / million;
653 	tv2.tv_usec = tv2.tv_usec % million;
654 	return tv2;
655 }
656 
657 /**
658   return the sum of two timeval structures
659 */
timeval_sum(const struct timeval * tv1,const struct timeval * tv2)660 struct timeval timeval_sum(const struct timeval *tv1,
661 			   const struct timeval *tv2)
662 {
663 	return timeval_add(tv1, tv2->tv_sec, tv2->tv_usec);
664 }
665 
666 /**
667   return a timeval secs/usecs into the future
668 */
timeval_current_ofs(uint32_t secs,uint32_t usecs)669 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
670 {
671 	struct timeval tv = timeval_current();
672 	return timeval_add(&tv, secs, usecs);
673 }
674 
675 /**
676   return a timeval milliseconds into the future
677 */
timeval_current_ofs_msec(uint32_t msecs)678 _PUBLIC_ struct timeval timeval_current_ofs_msec(uint32_t msecs)
679 {
680 	struct timeval tv = timeval_current();
681 	return timeval_add(&tv, msecs / 1000, (msecs % 1000) * 1000);
682 }
683 
684 /**
685   return a timeval microseconds into the future
686 */
timeval_current_ofs_usec(uint32_t usecs)687 _PUBLIC_ struct timeval timeval_current_ofs_usec(uint32_t usecs)
688 {
689 	struct timeval tv = timeval_current();
690 	return timeval_add(&tv, usecs / 1000000, usecs % 1000000);
691 }
692 
693 /**
694   compare two timeval structures.
695   Return -1 if tv1 < tv2
696   Return 0 if tv1 == tv2
697   Return 1 if tv1 > tv2
698 */
timeval_compare(const struct timeval * tv1,const struct timeval * tv2)699 _PUBLIC_ int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
700 {
701 	if (tv1->tv_sec  > tv2->tv_sec)  return 1;
702 	if (tv1->tv_sec  < tv2->tv_sec)  return -1;
703 	if (tv1->tv_usec > tv2->tv_usec) return 1;
704 	if (tv1->tv_usec < tv2->tv_usec) return -1;
705 	return 0;
706 }
707 
708 /**
709   return true if a timer is in the past
710 */
timeval_expired(const struct timeval * tv)711 _PUBLIC_ bool timeval_expired(const struct timeval *tv)
712 {
713 	struct timeval tv2 = timeval_current();
714 	if (tv2.tv_sec > tv->tv_sec) return true;
715 	if (tv2.tv_sec < tv->tv_sec) return false;
716 	return (tv2.tv_usec >= tv->tv_usec);
717 }
718 
719 /**
720   return the number of seconds elapsed between two times
721 */
timeval_elapsed2(const struct timeval * tv1,const struct timeval * tv2)722 _PUBLIC_ double timeval_elapsed2(const struct timeval *tv1, const struct timeval *tv2)
723 {
724 	return (tv2->tv_sec - tv1->tv_sec) +
725 	       (tv2->tv_usec - tv1->tv_usec)*1.0e-6;
726 }
727 
728 /**
729   return the number of seconds elapsed since a given time
730 */
timeval_elapsed(const struct timeval * tv)731 _PUBLIC_ double timeval_elapsed(const struct timeval *tv)
732 {
733 	struct timeval tv2 = timeval_current();
734 	return timeval_elapsed2(tv, &tv2);
735 }
736 /**
737  *   return the number of seconds elapsed between two times
738  **/
timespec_elapsed2(const struct timespec * ts1,const struct timespec * ts2)739 _PUBLIC_ double timespec_elapsed2(const struct timespec *ts1,
740 				const struct timespec *ts2)
741 {
742 	return (ts2->tv_sec - ts1->tv_sec) +
743 	       (ts2->tv_nsec - ts1->tv_nsec)*1.0e-9;
744 }
745 
746 /**
747  *   return the number of seconds elapsed since a given time
748  */
timespec_elapsed(const struct timespec * ts)749 _PUBLIC_ double timespec_elapsed(const struct timespec *ts)
750 {
751 	struct timespec ts2 = timespec_current();
752 	return timespec_elapsed2(ts, &ts2);
753 }
754 
755 /**
756   return the lesser of two timevals
757 */
timeval_min(const struct timeval * tv1,const struct timeval * tv2)758 _PUBLIC_ struct timeval timeval_min(const struct timeval *tv1,
759 			   const struct timeval *tv2)
760 {
761 	if (tv1->tv_sec < tv2->tv_sec) return *tv1;
762 	if (tv1->tv_sec > tv2->tv_sec) return *tv2;
763 	if (tv1->tv_usec < tv2->tv_usec) return *tv1;
764 	return *tv2;
765 }
766 
767 /**
768   return the greater of two timevals
769 */
timeval_max(const struct timeval * tv1,const struct timeval * tv2)770 _PUBLIC_ struct timeval timeval_max(const struct timeval *tv1,
771 			   const struct timeval *tv2)
772 {
773 	if (tv1->tv_sec > tv2->tv_sec) return *tv1;
774 	if (tv1->tv_sec < tv2->tv_sec) return *tv2;
775 	if (tv1->tv_usec > tv2->tv_usec) return *tv1;
776 	return *tv2;
777 }
778 
779 /**
780   return the difference between two timevals as a timeval
781   if tv1 comes after tv2, then return a zero timeval
782   (this is *tv2 - *tv1)
783 */
timeval_until(const struct timeval * tv1,const struct timeval * tv2)784 _PUBLIC_ struct timeval timeval_until(const struct timeval *tv1,
785 			     const struct timeval *tv2)
786 {
787 	struct timeval t;
788 	if (timeval_compare(tv1, tv2) >= 0) {
789 		return timeval_zero();
790 	}
791 	t.tv_sec = tv2->tv_sec - tv1->tv_sec;
792 	if (tv1->tv_usec > tv2->tv_usec) {
793 		t.tv_sec--;
794 		t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
795 	} else {
796 		t.tv_usec = tv2->tv_usec - tv1->tv_usec;
797 	}
798 	return t;
799 }
800 
801 
802 /**
803   convert a timeval to a NTTIME
804 */
timeval_to_nttime(const struct timeval * tv)805 _PUBLIC_ NTTIME timeval_to_nttime(const struct timeval *tv)
806 {
807 	return 10*(tv->tv_usec +
808 		  ((TIME_FIXUP_CONSTANT + (uint64_t)tv->tv_sec) * 1000000));
809 }
810 
811 /**
812   convert a NTTIME to a timeval
813 */
nttime_to_timeval(struct timeval * tv,NTTIME t)814 _PUBLIC_ void nttime_to_timeval(struct timeval *tv, NTTIME t)
815 {
816 	if (tv == NULL) return;
817 
818 	t += 10/2;
819 	t /= 10;
820 	t -= TIME_FIXUP_CONSTANT*1000*1000;
821 
822 	tv->tv_sec  = t / 1000000;
823 
824 	if (TIME_T_MIN > tv->tv_sec || tv->tv_sec > TIME_T_MAX) {
825 		tv->tv_sec  = 0;
826 		tv->tv_usec = 0;
827 		return;
828 	}
829 
830 	tv->tv_usec = t - tv->tv_sec*1000000;
831 }
832 
833 /*******************************************************************
834 yield the difference between *A and *B, in seconds, ignoring leap seconds
835 ********************************************************************/
tm_diff(struct tm * a,struct tm * b)836 static int tm_diff(struct tm *a, struct tm *b)
837 {
838 	int ay = a->tm_year + (1900 - 1);
839 	int by = b->tm_year + (1900 - 1);
840 	int intervening_leap_days =
841 		(ay/4 - by/4) - (ay/100 - by/100) + (ay/400 - by/400);
842 	int years = ay - by;
843 	int days = 365*years + intervening_leap_days + (a->tm_yday - b->tm_yday);
844 	int hours = 24*days + (a->tm_hour - b->tm_hour);
845 	int minutes = 60*hours + (a->tm_min - b->tm_min);
846 	int seconds = 60*minutes + (a->tm_sec - b->tm_sec);
847 
848 	return seconds;
849 }
850 
851 
852 /**
853   return the UTC offset in seconds west of UTC, or 0 if it cannot be determined
854  */
get_time_zone(time_t t)855 _PUBLIC_ int get_time_zone(time_t t)
856 {
857 	struct tm *tm = gmtime(&t);
858 	struct tm tm_utc;
859 	if (!tm)
860 		return 0;
861 	tm_utc = *tm;
862 	tm = localtime(&t);
863 	if (!tm)
864 		return 0;
865 	return tm_diff(&tm_utc,tm);
866 }
867 
nt_time_to_unix_timespec(NTTIME nt)868 struct timespec nt_time_to_unix_timespec(NTTIME nt)
869 {
870 	int64_t d;
871 	struct timespec ret;
872 
873 	if (nt == 0 || nt == (int64_t)-1) {
874 		ret.tv_sec = 0;
875 		ret.tv_nsec = 0;
876 		return ret;
877 	}
878 
879 	d = (int64_t)nt;
880 	/* d is now in 100ns units, since jan 1st 1601".
881 	   Save off the ns fraction. */
882 
883 	/*
884 	 * Take the last seven decimal digits and multiply by 100.
885 	 * to convert from 100ns units to 1ns units.
886 	 */
887         ret.tv_nsec = (long) ((d % (1000 * 1000 * 10)) * 100);
888 
889 	/* Convert to seconds */
890 	d /= 1000*1000*10;
891 
892 	/* Now adjust by 369 years to make the secs since 1970 */
893 	d -= TIME_FIXUP_CONSTANT_INT;
894 
895 	if (d <= (int64_t)TIME_T_MIN) {
896 		ret.tv_sec = TIME_T_MIN;
897 		ret.tv_nsec = 0;
898 		return ret;
899 	}
900 
901 	if (d >= (int64_t)TIME_T_MAX) {
902 		ret.tv_sec = TIME_T_MAX;
903 		ret.tv_nsec = 0;
904 		return ret;
905 	}
906 
907 	ret.tv_sec = (time_t)d;
908 	return ret;
909 }
910 
911 
912 /**
913   check if 2 NTTIMEs are equal.
914 */
nt_time_equal(NTTIME * t1,NTTIME * t2)915 bool nt_time_equal(NTTIME *t1, NTTIME *t2)
916 {
917 	return *t1 == *t2;
918 }
919 
920 /**
921  Check if it's a null timespec.
922 **/
923 
null_timespec(struct timespec ts)924 bool null_timespec(struct timespec ts)
925 {
926 	return ts.tv_sec == 0 ||
927 		ts.tv_sec == (time_t)0xFFFFFFFF ||
928 		ts.tv_sec == (time_t)-1;
929 }
930 
931 /****************************************************************************
932  Convert a normalized timeval to a timespec.
933 ****************************************************************************/
934 
convert_timeval_to_timespec(const struct timeval tv)935 struct timespec convert_timeval_to_timespec(const struct timeval tv)
936 {
937 	struct timespec ts;
938 	ts.tv_sec = tv.tv_sec;
939 	ts.tv_nsec = tv.tv_usec * 1000;
940 	return ts;
941 }
942 
943 /****************************************************************************
944  Convert a normalized timespec to a timeval.
945 ****************************************************************************/
946 
convert_timespec_to_timeval(const struct timespec ts)947 struct timeval convert_timespec_to_timeval(const struct timespec ts)
948 {
949 	struct timeval tv;
950 	tv.tv_sec = ts.tv_sec;
951 	tv.tv_usec = ts.tv_nsec / 1000;
952 	return tv;
953 }
954 
955 /****************************************************************************
956  Return a timespec for the current time
957 ****************************************************************************/
958 
timespec_current(void)959 _PUBLIC_ struct timespec timespec_current(void)
960 {
961 	struct timespec ts;
962 	clock_gettime(CLOCK_REALTIME, &ts);
963 	return ts;
964 }
965 
966 /****************************************************************************
967  Return the lesser of two timespecs.
968 ****************************************************************************/
969 
timespec_min(const struct timespec * ts1,const struct timespec * ts2)970 struct timespec timespec_min(const struct timespec *ts1,
971 			   const struct timespec *ts2)
972 {
973 	if (ts1->tv_sec < ts2->tv_sec) return *ts1;
974 	if (ts1->tv_sec > ts2->tv_sec) return *ts2;
975 	if (ts1->tv_nsec < ts2->tv_nsec) return *ts1;
976 	return *ts2;
977 }
978 
979 /****************************************************************************
980   compare two timespec structures.
981   Return -1 if ts1 < ts2
982   Return 0 if ts1 == ts2
983   Return 1 if ts1 > ts2
984 ****************************************************************************/
985 
timespec_compare(const struct timespec * ts1,const struct timespec * ts2)986 _PUBLIC_ int timespec_compare(const struct timespec *ts1, const struct timespec *ts2)
987 {
988 	if (ts1->tv_sec  > ts2->tv_sec)  return 1;
989 	if (ts1->tv_sec  < ts2->tv_sec)  return -1;
990 	if (ts1->tv_nsec > ts2->tv_nsec) return 1;
991 	if (ts1->tv_nsec < ts2->tv_nsec) return -1;
992 	return 0;
993 }
994 
995 /****************************************************************************
996  Round up a timespec if nsec > 500000000, round down if lower,
997  then zero nsec.
998 ****************************************************************************/
999 
round_timespec_to_sec(struct timespec * ts)1000 void round_timespec_to_sec(struct timespec *ts)
1001 {
1002 	ts->tv_sec = convert_timespec_to_time_t(*ts);
1003 	ts->tv_nsec = 0;
1004 }
1005 
1006 /****************************************************************************
1007  Round a timespec to usec value.
1008 ****************************************************************************/
1009 
round_timespec_to_usec(struct timespec * ts)1010 void round_timespec_to_usec(struct timespec *ts)
1011 {
1012 	struct timeval tv = convert_timespec_to_timeval(*ts);
1013 	*ts = convert_timeval_to_timespec(tv);
1014 	while (ts->tv_nsec > 1000000000) {
1015 		ts->tv_sec += 1;
1016 		ts->tv_nsec -= 1000000000;
1017 	}
1018 }
1019 
1020 /****************************************************************************
1021  Round a timespec to NTTIME resolution.
1022 ****************************************************************************/
1023 
round_timespec_to_nttime(struct timespec * ts)1024 void round_timespec_to_nttime(struct timespec *ts)
1025 {
1026 	ts->tv_nsec = (ts->tv_nsec / 100) * 100;
1027 }
1028 
1029 /****************************************************************************
1030  Put a 8 byte filetime from a struct timespec. Uses GMT.
1031 ****************************************************************************/
1032 
unix_timespec_to_nt_time(struct timespec ts)1033 _PUBLIC_ NTTIME unix_timespec_to_nt_time(struct timespec ts)
1034 {
1035 	uint64_t d;
1036 
1037 	if (ts.tv_sec ==0 && ts.tv_nsec == 0) {
1038 		return 0;
1039 	}
1040 	if (ts.tv_sec == TIME_T_MAX) {
1041 		return 0x7fffffffffffffffLL;
1042 	}
1043 	if (ts.tv_sec == (time_t)-1) {
1044 		return (uint64_t)-1;
1045 	}
1046 
1047 	d = ts.tv_sec;
1048 	d += TIME_FIXUP_CONSTANT_INT;
1049 	d *= 1000*1000*10;
1050 	/* d is now in 100ns units. */
1051 	d += (ts.tv_nsec / 100);
1052 
1053 	return d;
1054 }
1055 
1056 /*
1057  * Functions supporting the full range of time_t and struct timespec values,
1058  * including 0, -1 and all other negative values. These functions don't use 0 or
1059  * -1 values as sentinel to denote "unset" variables, but use the POSIX 2008
1060  * define UTIME_OMIT from utimensat(2).
1061  */
1062 
1063 /**
1064  * Check if it's a to be omitted timespec.
1065  **/
is_omit_timespec(const struct timespec * ts)1066 bool is_omit_timespec(const struct timespec *ts)
1067 {
1068 	return ts->tv_nsec == SAMBA_UTIME_OMIT;
1069 }
1070 
1071 /**
1072  * Return a to be omitted timespec.
1073  **/
make_omit_timespec(void)1074 struct timespec make_omit_timespec(void)
1075 {
1076 	return (struct timespec){.tv_nsec = SAMBA_UTIME_OMIT};
1077 }
1078 
1079 /**
1080  * Like unix_timespec_to_nt_time() but without the special casing of tv_sec=0
1081  * and -1. Also dealing with SAMBA_UTIME_OMIT.
1082  **/
full_timespec_to_nt_time(const struct timespec * _ts)1083 NTTIME full_timespec_to_nt_time(const struct timespec *_ts)
1084 {
1085 	struct timespec ts = *_ts;
1086 	uint64_t d;
1087 
1088 	if (is_omit_timespec(_ts)) {
1089 		return NTTIME_OMIT;
1090 	}
1091 
1092 	/* Ensure tv_nsec is less than 1 sec. */
1093 	while (ts.tv_nsec > 1000000000) {
1094 		if (ts.tv_sec > TIME_T_MAX) {
1095 			return NTTIME_MAX;
1096 		}
1097 		ts.tv_sec += 1;
1098 		ts.tv_nsec -= 1000000000;
1099 	}
1100 
1101 	if (ts.tv_sec >= TIME_T_MAX) {
1102 		return NTTIME_MAX;
1103 	}
1104 	if ((ts.tv_sec + TIME_FIXUP_CONSTANT_INT) <= 0) {
1105 		return NTTIME_MIN;
1106 	}
1107 
1108 	d = TIME_FIXUP_CONSTANT_INT;
1109 	d += ts.tv_sec;
1110 
1111 	d *= 1000*1000*10;
1112 	/* d is now in 100ns units. */
1113 	d += (ts.tv_nsec / 100);
1114 
1115 	return d;
1116 }
1117 
1118 /**
1119  * Like nt_time_to_unix_timespec() but allowing negative tv_sec values and
1120  * returning NTTIME=0 and -1 as struct timespec {.tv_nsec = SAMBA_UTIME_OMIT}.
1121  *
1122  * See also: is_omit_timespec().
1123  **/
nt_time_to_full_timespec(NTTIME nt)1124 struct timespec nt_time_to_full_timespec(NTTIME nt)
1125 {
1126 	int64_t d;
1127 	struct timespec ret;
1128 
1129 	if (nt == NTTIME_OMIT) {
1130 		return make_omit_timespec();
1131 	}
1132 	if (nt == NTTIME_FREEZE) {
1133 		/*
1134 		 * This should be returned as SAMBA_UTIME_FREEZE in the
1135 		 * future.
1136 		 */
1137 		return make_omit_timespec();
1138 	}
1139 	if (nt > NTTIME_MAX) {
1140 		nt = NTTIME_MAX;
1141 	}
1142 
1143 	d = (int64_t)nt;
1144 	/* d is now in 100ns units, since jan 1st 1601".
1145 	   Save off the ns fraction. */
1146 
1147 	/*
1148 	 * Take the last seven decimal digits and multiply by 100.
1149 	 * to convert from 100ns units to 1ns units.
1150 	 */
1151         ret.tv_nsec = (long) ((d % (1000 * 1000 * 10)) * 100);
1152 
1153 	/* Convert to seconds */
1154 	d /= 1000*1000*10;
1155 
1156 	/* Now adjust by 369 years to make the secs since 1970 */
1157 	d -= TIME_FIXUP_CONSTANT_INT;
1158 
1159 	if (d >= (int64_t)TIME_T_MAX) {
1160 		ret.tv_sec = TIME_T_MAX;
1161 		ret.tv_nsec = 0;
1162 		return ret;
1163 	}
1164 
1165 	ret.tv_sec = (time_t)d;
1166 	return ret;
1167 }
1168 
1169 /**
1170  * Note: this function uses the full time_t range as valid date values including
1171  * (time_t)0 and -1. That means that struct timespec sentinel values (cf
1172  * is_omit_timespec()) can't be converted to sentinel values in a time_t
1173  * representation. Callers should therefor check the NTTIME value with
1174  * null_nttime() before calling this function.
1175  **/
full_timespec_to_time_t(const struct timespec * _ts)1176 time_t full_timespec_to_time_t(const struct timespec *_ts)
1177 {
1178 	struct timespec ts = *_ts;
1179 
1180 	if (is_omit_timespec(_ts)) {
1181 		/*
1182 		 * Unfortunately there's no sensible sentinel value in the
1183 		 * time_t range that is not conflicting with a valid time value
1184 		 * ((time_t)0 and -1 are valid time values). Bite the bullit and
1185 		 * return 0.
1186 		 */
1187 		return 0;
1188 	}
1189 
1190 	/* Ensure tv_nsec is less than 1sec. */
1191 	while (ts.tv_nsec > 1000000000) {
1192 		ts.tv_sec += 1;
1193 		ts.tv_nsec -= 1000000000;
1194 	}
1195 
1196 	/* 1 ns == 1,000,000,000 - one thousand millionths of a second.
1197 	   increment if it's greater than 500 millionth of a second. */
1198 
1199 	if (ts.tv_nsec > 500000000) {
1200 		return ts.tv_sec + 1;
1201 	}
1202 	return ts.tv_sec;
1203 }
1204 
1205 /**
1206  * Like nt_time_to_unix() but supports negative time_t values.
1207  *
1208  * Note: this function uses the full time_t range as valid date values including
1209  * (time_t)0 and -1. That means that NTTIME sentinel values of 0 and -1 which
1210  * represent a "not-set" value, can't be converted to sentinel values in a
1211  * time_t representation. Callers should therefor check the NTTIME value with
1212  * null_nttime() before calling this function.
1213  **/
nt_time_to_full_time_t(NTTIME nt)1214 time_t nt_time_to_full_time_t(NTTIME nt)
1215 {
1216 	struct timespec ts;
1217 
1218 	ts = nt_time_to_full_timespec(nt);
1219 	return full_timespec_to_time_t(&ts);
1220 }
1221 
1222 /**
1223  * Like time_t_to_unix_timespec() but supports negative time_t values.
1224  *
1225  * This version converts (time_t)0 and -1 to an is_omit_timespec(), so 0 and -1
1226  * can't be used as valid date values. The function supports values < -1 though.
1227  **/
time_t_to_full_timespec(time_t t)1228 struct timespec time_t_to_full_timespec(time_t t)
1229 {
1230 	if (null_time(t)) {
1231 		return (struct timespec){.tv_nsec = SAMBA_UTIME_OMIT};
1232 	}
1233 	return (struct timespec){.tv_sec = t};
1234 }
1235