Ensure incoming timespec values correctly wrap at nsecs.
[mat/samba.git] / lib / util / time.c
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
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "system/time.h"
24
25 /**
26  * @file
27  * @brief time handling functions
28  */
29
30 #if (SIZEOF_LONG == 8)
31 #define TIME_FIXUP_CONSTANT_INT 11644473600L
32 #elif (SIZEOF_LONG_LONG == 8)
33 #define TIME_FIXUP_CONSTANT_INT 11644473600LL
34 #endif
35
36
37
38 /**
39  External access to time_t_min and time_t_max.
40 **/
41 _PUBLIC_ time_t get_time_t_max(void)
42 {
43         return TIME_T_MAX;
44 }
45
46 /**
47 a gettimeofday wrapper
48 **/
49 _PUBLIC_ void GetTimeOfDay(struct timeval *tval)
50 {
51 #ifdef HAVE_GETTIMEOFDAY_TZ
52         gettimeofday(tval,NULL);
53 #else
54         gettimeofday(tval);
55 #endif
56 }
57
58 /**
59 a wrapper to preferably get the monotonic time
60 **/
61 _PUBLIC_ void clock_gettime_mono(struct timespec *tp)
62 {
63         if (clock_gettime(CUSTOM_CLOCK_MONOTONIC,tp) != 0) {
64                 clock_gettime(CLOCK_REALTIME,tp);
65         }
66 }
67
68 /**
69 a wrapper to preferably get the monotonic time in seconds
70 as this is only second resolution we can use the cached
71 (and much faster) COARS clock variant
72 **/
73 _PUBLIC_ time_t time_mono(time_t *t)
74 {
75         struct timespec tp;
76         int rc = -1;
77 #ifdef CLOCK_MONOTONIC_COARSE
78         rc = clock_gettime(CLOCK_MONOTONIC_COARSE,&tp);
79 #endif
80         if (rc != 0) {
81                 clock_gettime_mono(&tp);
82         }
83         if (t != NULL) {
84                 *t = tp.tv_sec;
85         }
86         return tp.tv_sec;
87 }
88
89
90 #define TIME_FIXUP_CONSTANT 11644473600LL
91
92 time_t convert_timespec_to_time_t(struct timespec ts)
93 {
94         /* Ensure tv_nsec is less than 1sec. */
95         while (ts.tv_nsec > 1000000000) {
96                 ts.tv_sec += 1;
97                 ts.tv_nsec -= 1000000000;
98         }
99
100         /* 1 ns == 1,000,000,000 - one thousand millionths of a second.
101            increment if it's greater than 500 millionth of a second. */
102
103         if (ts.tv_nsec > 500000000) {
104                 return ts.tv_sec + 1;
105         }
106         return ts.tv_sec;
107 }
108
109 struct timespec convert_time_t_to_timespec(time_t t)
110 {
111         struct timespec ts;
112         ts.tv_sec = t;
113         ts.tv_nsec = 0;
114         return ts;
115 }
116
117
118
119 /**
120  Interpret an 8 byte "filetime" structure to a time_t
121  It's originally in "100ns units since jan 1st 1601"
122
123  An 8 byte value of 0xffffffffffffffff will be returned as a timespec of
124
125         tv_sec = 0
126         tv_nsec = 0;
127
128  Returns GMT.
129 **/
130 time_t nt_time_to_unix(NTTIME nt)
131 {
132         return convert_timespec_to_time_t(nt_time_to_unix_timespec(&nt));
133 }
134
135
136 /**
137 put a 8 byte filetime from a time_t
138 This takes GMT as input
139 **/
140 _PUBLIC_ void unix_to_nt_time(NTTIME *nt, time_t t)
141 {
142         uint64_t t2; 
143
144         if (t == (time_t)-1) {
145                 *nt = (NTTIME)-1LL;
146                 return;
147         }       
148
149         if (t == TIME_T_MAX) {
150                 *nt = 0x7fffffffffffffffLL;
151                 return;
152         }
153
154         if (t == 0) {
155                 *nt = 0;
156                 return;
157         }               
158
159         t2 = t;
160         t2 += TIME_FIXUP_CONSTANT_INT;
161         t2 *= 1000*1000*10;
162
163         *nt = t2;
164 }
165
166
167 /**
168 check if it's a null unix time
169 **/
170 _PUBLIC_ bool null_time(time_t t)
171 {
172         return t == 0 || 
173                 t == (time_t)0xFFFFFFFF || 
174                 t == (time_t)-1;
175 }
176
177
178 /**
179 check if it's a null NTTIME
180 **/
181 _PUBLIC_ bool null_nttime(NTTIME t)
182 {
183         return t == 0 || t == (NTTIME)-1;
184 }
185
186 /*******************************************************************
187   create a 16 bit dos packed date
188 ********************************************************************/
189 static uint16_t make_dos_date1(struct tm *t)
190 {
191         uint16_t ret=0;
192         ret = (((unsigned int)(t->tm_mon+1)) >> 3) | ((t->tm_year-80) << 1);
193         ret = ((ret&0xFF)<<8) | (t->tm_mday | (((t->tm_mon+1) & 0x7) << 5));
194         return ret;
195 }
196
197 /*******************************************************************
198   create a 16 bit dos packed time
199 ********************************************************************/
200 static uint16_t make_dos_time1(struct tm *t)
201 {
202         uint16_t ret=0;
203         ret = ((((unsigned int)t->tm_min >> 3)&0x7) | (((unsigned int)t->tm_hour) << 3));
204         ret = ((ret&0xFF)<<8) | ((t->tm_sec/2) | ((t->tm_min & 0x7) << 5));
205         return ret;
206 }
207
208 /*******************************************************************
209   create a 32 bit dos packed date/time from some parameters
210   This takes a GMT time and returns a packed localtime structure
211 ********************************************************************/
212 static uint32_t make_dos_date(time_t unixdate, int zone_offset)
213 {
214         struct tm *t;
215         uint32_t ret=0;
216
217         if (unixdate == 0) {
218                 return 0;
219         }
220
221         unixdate -= zone_offset;
222
223         t = gmtime(&unixdate);
224         if (!t) {
225                 return 0xFFFFFFFF;
226         }
227
228         ret = make_dos_date1(t);
229         ret = ((ret&0xFFFF)<<16) | make_dos_time1(t);
230
231         return ret;
232 }
233
234 /**
235 put a dos date into a buffer (time/date format)
236 This takes GMT time and puts local time in the buffer
237 **/
238 _PUBLIC_ void push_dos_date(uint8_t *buf, int offset, time_t unixdate, int zone_offset)
239 {
240         uint32_t x = make_dos_date(unixdate, zone_offset);
241         SIVAL(buf,offset,x);
242 }
243
244 /**
245 put a dos date into a buffer (date/time format)
246 This takes GMT time and puts local time in the buffer
247 **/
248 _PUBLIC_ void push_dos_date2(uint8_t *buf,int offset,time_t unixdate, int zone_offset)
249 {
250         uint32_t x;
251         x = make_dos_date(unixdate, zone_offset);
252         x = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
253         SIVAL(buf,offset,x);
254 }
255
256 /**
257 put a dos 32 bit "unix like" date into a buffer. This routine takes
258 GMT and converts it to LOCAL time before putting it (most SMBs assume
259 localtime for this sort of date)
260 **/
261 _PUBLIC_ void push_dos_date3(uint8_t *buf,int offset,time_t unixdate, int zone_offset)
262 {
263         if (!null_time(unixdate)) {
264                 unixdate -= zone_offset;
265         }
266         SIVAL(buf,offset,unixdate);
267 }
268
269 /*******************************************************************
270   interpret a 32 bit dos packed date/time to some parameters
271 ********************************************************************/
272 void interpret_dos_date(uint32_t date,int *year,int *month,int *day,int *hour,int *minute,int *second)
273 {
274         uint32_t p0,p1,p2,p3;
275
276         p0=date&0xFF; p1=((date&0xFF00)>>8)&0xFF; 
277         p2=((date&0xFF0000)>>16)&0xFF; p3=((date&0xFF000000)>>24)&0xFF;
278
279         *second = 2*(p0 & 0x1F);
280         *minute = ((p0>>5)&0xFF) + ((p1&0x7)<<3);
281         *hour = (p1>>3)&0xFF;
282         *day = (p2&0x1F);
283         *month = ((p2>>5)&0xFF) + ((p3&0x1)<<3) - 1;
284         *year = ((p3>>1)&0xFF) + 80;
285 }
286
287 /**
288   create a unix date (int GMT) from a dos date (which is actually in
289   localtime)
290 **/
291 _PUBLIC_ time_t pull_dos_date(const uint8_t *date_ptr, int zone_offset)
292 {
293         uint32_t dos_date=0;
294         struct tm t;
295         time_t ret;
296
297         dos_date = IVAL(date_ptr,0);
298
299         if (dos_date == 0) return (time_t)0;
300   
301         interpret_dos_date(dos_date,&t.tm_year,&t.tm_mon,
302                            &t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
303         t.tm_isdst = -1;
304   
305         ret = timegm(&t);
306
307         ret += zone_offset;
308
309         return ret;
310 }
311
312 /**
313 like make_unix_date() but the words are reversed
314 **/
315 _PUBLIC_ time_t pull_dos_date2(const uint8_t *date_ptr, int zone_offset)
316 {
317         uint32_t x,x2;
318
319         x = IVAL(date_ptr,0);
320         x2 = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
321         SIVAL(&x,0,x2);
322
323         return pull_dos_date((const uint8_t *)&x, zone_offset);
324 }
325
326 /**
327   create a unix GMT date from a dos date in 32 bit "unix like" format
328   these generally arrive as localtimes, with corresponding DST
329 **/
330 _PUBLIC_ time_t pull_dos_date3(const uint8_t *date_ptr, int zone_offset)
331 {
332         time_t t = (time_t)IVAL(date_ptr,0);
333         if (!null_time(t)) {
334                 t += zone_offset;
335         }
336         return t;
337 }
338
339
340 /**
341 return a HTTP/1.0 time string
342 **/
343 _PUBLIC_ char *http_timestring(TALLOC_CTX *mem_ctx, time_t t)
344 {
345         char *buf;
346         char tempTime[60];
347         struct tm *tm = localtime(&t);
348
349         if (t == TIME_T_MAX) {
350                 return talloc_strdup(mem_ctx, "never");
351         }
352
353         if (!tm) {
354                 return talloc_asprintf(mem_ctx,"%ld seconds since the Epoch",(long)t);
355         }
356
357 #ifndef HAVE_STRFTIME
358         buf = talloc_strdup(mem_ctx, asctime(tm));
359         if (buf[strlen(buf)-1] == '\n') {
360                 buf[strlen(buf)-1] = 0;
361         }
362 #else
363         strftime(tempTime, sizeof(tempTime)-1, "%a, %d %b %Y %H:%M:%S %Z", tm);
364         buf = talloc_strdup(mem_ctx, tempTime);
365 #endif /* !HAVE_STRFTIME */
366
367         return buf;
368 }
369
370 /**
371  Return the date and time as a string
372 **/
373 _PUBLIC_ char *timestring(TALLOC_CTX *mem_ctx, time_t t)
374 {
375         char *TimeBuf;
376         char tempTime[80];
377         struct tm *tm;
378
379         tm = localtime(&t);
380         if (!tm) {
381                 return talloc_asprintf(mem_ctx,
382                                        "%ld seconds since the Epoch",
383                                        (long)t);
384         }
385
386 #ifdef HAVE_STRFTIME
387         /* some versions of gcc complain about using %c. This is a bug
388            in the gcc warning, not a bug in this code. See a recent
389            strftime() manual page for details.
390          */
391         strftime(tempTime,sizeof(tempTime)-1,"%c %Z",tm);
392         TimeBuf = talloc_strdup(mem_ctx, tempTime);
393 #else
394         TimeBuf = talloc_strdup(mem_ctx, asctime(tm));
395 #endif
396
397         return TimeBuf;
398 }
399
400 /**
401   return a talloced string representing a NTTIME for human consumption
402 */
403 _PUBLIC_ const char *nt_time_string(TALLOC_CTX *mem_ctx, NTTIME nt)
404 {
405         time_t t;
406         if (nt == 0) {
407                 return "NTTIME(0)";
408         }
409         t = nt_time_to_unix(nt);
410         return timestring(mem_ctx, t);
411 }
412
413
414 /**
415   put a NTTIME into a packet
416 */
417 _PUBLIC_ void push_nttime(uint8_t *base, uint16_t offset, NTTIME t)
418 {
419         SBVAL(base, offset,   t);
420 }
421
422 /**
423   pull a NTTIME from a packet
424 */
425 _PUBLIC_ NTTIME pull_nttime(uint8_t *base, uint16_t offset)
426 {
427         NTTIME ret = BVAL(base, offset);
428         return ret;
429 }
430
431 /**
432   return (tv1 - tv2) in microseconds
433 */
434 _PUBLIC_ int64_t usec_time_diff(const struct timeval *tv1, const struct timeval *tv2)
435 {
436         int64_t sec_diff = tv1->tv_sec - tv2->tv_sec;
437         return (sec_diff * 1000000) + (int64_t)(tv1->tv_usec - tv2->tv_usec);
438 }
439
440 /**
441   return (tp1 - tp2) in microseconds
442 */
443 _PUBLIC_ int64_t nsec_time_diff(const struct timespec *tp1, const struct timespec *tp2)
444 {
445         int64_t sec_diff = tp1->tv_sec - tp2->tv_sec;
446         return (sec_diff * 1000000000) + (int64_t)(tp1->tv_nsec - tp2->tv_nsec);
447 }
448
449
450 /**
451   return a zero timeval
452 */
453 _PUBLIC_ struct timeval timeval_zero(void)
454 {
455         struct timeval tv;
456         tv.tv_sec = 0;
457         tv.tv_usec = 0;
458         return tv;
459 }
460
461 /**
462   return true if a timeval is zero
463 */
464 _PUBLIC_ bool timeval_is_zero(const struct timeval *tv)
465 {
466         return tv->tv_sec == 0 && tv->tv_usec == 0;
467 }
468
469 /**
470   return a timeval for the current time
471 */
472 _PUBLIC_ struct timeval timeval_current(void)
473 {
474         struct timeval tv;
475         GetTimeOfDay(&tv);
476         return tv;
477 }
478
479 /**
480   return a timeval struct with the given elements
481 */
482 _PUBLIC_ struct timeval timeval_set(uint32_t secs, uint32_t usecs)
483 {
484         struct timeval tv;
485         tv.tv_sec = secs;
486         tv.tv_usec = usecs;
487         return tv;
488 }
489
490
491 /**
492   return a timeval ofs microseconds after tv
493 */
494 _PUBLIC_ struct timeval timeval_add(const struct timeval *tv,
495                            uint32_t secs, uint32_t usecs)
496 {
497         struct timeval tv2 = *tv;
498         const unsigned int million = 1000000;
499         tv2.tv_sec += secs;
500         tv2.tv_usec += usecs;
501         tv2.tv_sec += tv2.tv_usec / million;
502         tv2.tv_usec = tv2.tv_usec % million;
503         return tv2;
504 }
505
506 /**
507   return the sum of two timeval structures
508 */
509 struct timeval timeval_sum(const struct timeval *tv1,
510                            const struct timeval *tv2)
511 {
512         return timeval_add(tv1, tv2->tv_sec, tv2->tv_usec);
513 }
514
515 /**
516   return a timeval secs/usecs into the future
517 */
518 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
519 {
520         struct timeval tv = timeval_current();
521         return timeval_add(&tv, secs, usecs);
522 }
523
524 /**
525   compare two timeval structures. 
526   Return -1 if tv1 < tv2
527   Return 0 if tv1 == tv2
528   Return 1 if tv1 > tv2
529 */
530 _PUBLIC_ int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
531 {
532         if (tv1->tv_sec  > tv2->tv_sec)  return 1;
533         if (tv1->tv_sec  < tv2->tv_sec)  return -1;
534         if (tv1->tv_usec > tv2->tv_usec) return 1;
535         if (tv1->tv_usec < tv2->tv_usec) return -1;
536         return 0;
537 }
538
539 /**
540   return true if a timer is in the past
541 */
542 _PUBLIC_ bool timeval_expired(const struct timeval *tv)
543 {
544         struct timeval tv2 = timeval_current();
545         if (tv2.tv_sec > tv->tv_sec) return true;
546         if (tv2.tv_sec < tv->tv_sec) return false;
547         return (tv2.tv_usec >= tv->tv_usec);
548 }
549
550 /**
551   return the number of seconds elapsed between two times
552 */
553 _PUBLIC_ double timeval_elapsed2(const struct timeval *tv1, const struct timeval *tv2)
554 {
555         return (tv2->tv_sec - tv1->tv_sec) + 
556                (tv2->tv_usec - tv1->tv_usec)*1.0e-6;
557 }
558
559 /**
560   return the number of seconds elapsed since a given time
561 */
562 _PUBLIC_ double timeval_elapsed(const struct timeval *tv)
563 {
564         struct timeval tv2 = timeval_current();
565         return timeval_elapsed2(tv, &tv2);
566 }
567
568 /**
569   return the lesser of two timevals
570 */
571 _PUBLIC_ struct timeval timeval_min(const struct timeval *tv1,
572                            const struct timeval *tv2)
573 {
574         if (tv1->tv_sec < tv2->tv_sec) return *tv1;
575         if (tv1->tv_sec > tv2->tv_sec) return *tv2;
576         if (tv1->tv_usec < tv2->tv_usec) return *tv1;
577         return *tv2;
578 }
579
580 /**
581   return the greater of two timevals
582 */
583 _PUBLIC_ struct timeval timeval_max(const struct timeval *tv1,
584                            const struct timeval *tv2)
585 {
586         if (tv1->tv_sec > tv2->tv_sec) return *tv1;
587         if (tv1->tv_sec < tv2->tv_sec) return *tv2;
588         if (tv1->tv_usec > tv2->tv_usec) return *tv1;
589         return *tv2;
590 }
591
592 /**
593   return the difference between two timevals as a timeval
594   if tv1 comes after tv2, then return a zero timeval
595   (this is *tv2 - *tv1)
596 */
597 _PUBLIC_ struct timeval timeval_until(const struct timeval *tv1,
598                              const struct timeval *tv2)
599 {
600         struct timeval t;
601         if (timeval_compare(tv1, tv2) >= 0) {
602                 return timeval_zero();
603         }
604         t.tv_sec = tv2->tv_sec - tv1->tv_sec;
605         if (tv1->tv_usec > tv2->tv_usec) {
606                 t.tv_sec--;
607                 t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
608         } else {
609                 t.tv_usec = tv2->tv_usec - tv1->tv_usec;
610         }
611         return t;
612 }
613
614
615 /**
616   convert a timeval to a NTTIME
617 */
618 _PUBLIC_ NTTIME timeval_to_nttime(const struct timeval *tv)
619 {
620         return 10*(tv->tv_usec + 
621                   ((TIME_FIXUP_CONSTANT + (uint64_t)tv->tv_sec) * 1000000));
622 }
623
624 /**
625   convert a NTTIME to a timeval
626 */
627 _PUBLIC_ void nttime_to_timeval(struct timeval *tv, NTTIME t)
628 {
629         if (tv == NULL) return;
630
631         t += 10/2;
632         t /= 10;
633         t -= TIME_FIXUP_CONSTANT*1000*1000;
634
635         tv->tv_sec  = t / 1000000;
636
637         if (TIME_T_MIN > tv->tv_sec || tv->tv_sec > TIME_T_MAX) {
638                 tv->tv_sec  = 0;
639                 tv->tv_usec = 0;
640                 return;
641         }
642         
643         tv->tv_usec = t - tv->tv_sec*1000000;
644 }
645
646 /*******************************************************************
647 yield the difference between *A and *B, in seconds, ignoring leap seconds
648 ********************************************************************/
649 static int tm_diff(struct tm *a, struct tm *b)
650 {
651         int ay = a->tm_year + (1900 - 1);
652         int by = b->tm_year + (1900 - 1);
653         int intervening_leap_days =
654                 (ay/4 - by/4) - (ay/100 - by/100) + (ay/400 - by/400);
655         int years = ay - by;
656         int days = 365*years + intervening_leap_days + (a->tm_yday - b->tm_yday);
657         int hours = 24*days + (a->tm_hour - b->tm_hour);
658         int minutes = 60*hours + (a->tm_min - b->tm_min);
659         int seconds = 60*minutes + (a->tm_sec - b->tm_sec);
660
661         return seconds;
662 }
663
664
665 int extra_time_offset=0;
666
667 /**
668   return the UTC offset in seconds west of UTC, or 0 if it cannot be determined
669  */
670 _PUBLIC_ int get_time_zone(time_t t)
671 {
672         struct tm *tm = gmtime(&t);
673         struct tm tm_utc;
674         if (!tm)
675                 return 0;
676         tm_utc = *tm;
677         tm = localtime(&t);
678         if (!tm)
679                 return 0;
680         return tm_diff(&tm_utc,tm)+60*extra_time_offset;
681 }
682
683 struct timespec nt_time_to_unix_timespec(NTTIME *nt)
684 {
685         int64_t d;
686         struct timespec ret;
687
688         if (*nt == 0 || *nt == (int64_t)-1) {
689                 ret.tv_sec = 0;
690                 ret.tv_nsec = 0;
691                 return ret;
692         }
693
694         d = (int64_t)*nt;
695         /* d is now in 100ns units, since jan 1st 1601".
696            Save off the ns fraction. */
697
698         /*
699          * Take the last seven decimal digits and multiply by 100.
700          * to convert from 100ns units to 1ns units.
701          */
702         ret.tv_nsec = (long) ((d % (1000 * 1000 * 10)) * 100);
703
704         /* Convert to seconds */
705         d /= 1000*1000*10;
706
707         /* Now adjust by 369 years to make the secs since 1970 */
708         d -= TIME_FIXUP_CONSTANT_INT;
709
710         if (d <= (int64_t)TIME_T_MIN) {
711                 ret.tv_sec = TIME_T_MIN;
712                 ret.tv_nsec = 0;
713                 return ret;
714         }
715
716         if (d >= (int64_t)TIME_T_MAX) {
717                 ret.tv_sec = TIME_T_MAX;
718                 ret.tv_nsec = 0;
719                 return ret;
720         }
721
722         ret.tv_sec = (time_t)d;
723         return ret;
724 }
725
726
727 /**
728   check if 2 NTTIMEs are equal.
729 */
730 bool nt_time_equal(NTTIME *t1, NTTIME *t2)
731 {
732         return *t1 == *t2;
733 }
734
735 /**
736  Check if it's a null timespec.
737 **/
738
739 bool null_timespec(struct timespec ts)
740 {
741         return ts.tv_sec == 0 || 
742                 ts.tv_sec == (time_t)0xFFFFFFFF || 
743                 ts.tv_sec == (time_t)-1;
744 }
745
746