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