lib/util: add nsec_time_diff to calulate diffs from timespecs
[nivanova/samba-autobuild/.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   return (tp1 - tp2) in microseconds
414 */
415 _PUBLIC_ int64_t nsec_time_diff(const struct timespec *tp1, const struct timespec *tp2)
416 {
417         int64_t sec_diff = tp1->tv_sec - tp2->tv_sec;
418         return (sec_diff * 1000000000) + (int64_t)(tp1->tv_nsec - tp2->tv_nsec);
419 }
420
421
422 /**
423   return a zero timeval
424 */
425 _PUBLIC_ struct timeval timeval_zero(void)
426 {
427         struct timeval tv;
428         tv.tv_sec = 0;
429         tv.tv_usec = 0;
430         return tv;
431 }
432
433 /**
434   return true if a timeval is zero
435 */
436 _PUBLIC_ bool timeval_is_zero(const struct timeval *tv)
437 {
438         return tv->tv_sec == 0 && tv->tv_usec == 0;
439 }
440
441 /**
442   return a timeval for the current time
443 */
444 _PUBLIC_ struct timeval timeval_current(void)
445 {
446         struct timeval tv;
447         GetTimeOfDay(&tv);
448         return tv;
449 }
450
451 /**
452   return a timeval struct with the given elements
453 */
454 _PUBLIC_ struct timeval timeval_set(uint32_t secs, uint32_t usecs)
455 {
456         struct timeval tv;
457         tv.tv_sec = secs;
458         tv.tv_usec = usecs;
459         return tv;
460 }
461
462
463 /**
464   return a timeval ofs microseconds after tv
465 */
466 _PUBLIC_ struct timeval timeval_add(const struct timeval *tv,
467                            uint32_t secs, uint32_t usecs)
468 {
469         struct timeval tv2 = *tv;
470         const unsigned int million = 1000000;
471         tv2.tv_sec += secs;
472         tv2.tv_usec += usecs;
473         tv2.tv_sec += tv2.tv_usec / million;
474         tv2.tv_usec = tv2.tv_usec % million;
475         return tv2;
476 }
477
478 /**
479   return the sum of two timeval structures
480 */
481 struct timeval timeval_sum(const struct timeval *tv1,
482                            const struct timeval *tv2)
483 {
484         return timeval_add(tv1, tv2->tv_sec, tv2->tv_usec);
485 }
486
487 /**
488   return a timeval secs/usecs into the future
489 */
490 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
491 {
492         struct timeval tv = timeval_current();
493         return timeval_add(&tv, secs, usecs);
494 }
495
496 /**
497   compare two timeval structures. 
498   Return -1 if tv1 < tv2
499   Return 0 if tv1 == tv2
500   Return 1 if tv1 > tv2
501 */
502 _PUBLIC_ int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
503 {
504         if (tv1->tv_sec  > tv2->tv_sec)  return 1;
505         if (tv1->tv_sec  < tv2->tv_sec)  return -1;
506         if (tv1->tv_usec > tv2->tv_usec) return 1;
507         if (tv1->tv_usec < tv2->tv_usec) return -1;
508         return 0;
509 }
510
511 /**
512   return true if a timer is in the past
513 */
514 _PUBLIC_ bool timeval_expired(const struct timeval *tv)
515 {
516         struct timeval tv2 = timeval_current();
517         if (tv2.tv_sec > tv->tv_sec) return true;
518         if (tv2.tv_sec < tv->tv_sec) return false;
519         return (tv2.tv_usec >= tv->tv_usec);
520 }
521
522 /**
523   return the number of seconds elapsed between two times
524 */
525 _PUBLIC_ double timeval_elapsed2(const struct timeval *tv1, const struct timeval *tv2)
526 {
527         return (tv2->tv_sec - tv1->tv_sec) + 
528                (tv2->tv_usec - tv1->tv_usec)*1.0e-6;
529 }
530
531 /**
532   return the number of seconds elapsed since a given time
533 */
534 _PUBLIC_ double timeval_elapsed(const struct timeval *tv)
535 {
536         struct timeval tv2 = timeval_current();
537         return timeval_elapsed2(tv, &tv2);
538 }
539
540 /**
541   return the lesser of two timevals
542 */
543 _PUBLIC_ struct timeval timeval_min(const struct timeval *tv1,
544                            const struct timeval *tv2)
545 {
546         if (tv1->tv_sec < tv2->tv_sec) return *tv1;
547         if (tv1->tv_sec > tv2->tv_sec) return *tv2;
548         if (tv1->tv_usec < tv2->tv_usec) return *tv1;
549         return *tv2;
550 }
551
552 /**
553   return the greater of two timevals
554 */
555 _PUBLIC_ struct timeval timeval_max(const struct timeval *tv1,
556                            const struct timeval *tv2)
557 {
558         if (tv1->tv_sec > tv2->tv_sec) return *tv1;
559         if (tv1->tv_sec < tv2->tv_sec) return *tv2;
560         if (tv1->tv_usec > tv2->tv_usec) return *tv1;
561         return *tv2;
562 }
563
564 /**
565   return the difference between two timevals as a timeval
566   if tv1 comes after tv2, then return a zero timeval
567   (this is *tv2 - *tv1)
568 */
569 _PUBLIC_ struct timeval timeval_until(const struct timeval *tv1,
570                              const struct timeval *tv2)
571 {
572         struct timeval t;
573         if (timeval_compare(tv1, tv2) >= 0) {
574                 return timeval_zero();
575         }
576         t.tv_sec = tv2->tv_sec - tv1->tv_sec;
577         if (tv1->tv_usec > tv2->tv_usec) {
578                 t.tv_sec--;
579                 t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
580         } else {
581                 t.tv_usec = tv2->tv_usec - tv1->tv_usec;
582         }
583         return t;
584 }
585
586
587 /**
588   convert a timeval to a NTTIME
589 */
590 _PUBLIC_ NTTIME timeval_to_nttime(const struct timeval *tv)
591 {
592         return 10*(tv->tv_usec + 
593                   ((TIME_FIXUP_CONSTANT + (uint64_t)tv->tv_sec) * 1000000));
594 }
595
596 /**
597   convert a NTTIME to a timeval
598 */
599 _PUBLIC_ void nttime_to_timeval(struct timeval *tv, NTTIME t)
600 {
601         if (tv == NULL) return;
602
603         t += 10/2;
604         t /= 10;
605         t -= TIME_FIXUP_CONSTANT*1000*1000;
606
607         tv->tv_sec  = t / 1000000;
608
609         if (TIME_T_MIN > tv->tv_sec || tv->tv_sec > TIME_T_MAX) {
610                 tv->tv_sec  = 0;
611                 tv->tv_usec = 0;
612                 return;
613         }
614         
615         tv->tv_usec = t - tv->tv_sec*1000000;
616 }
617
618 /*******************************************************************
619 yield the difference between *A and *B, in seconds, ignoring leap seconds
620 ********************************************************************/
621 static int tm_diff(struct tm *a, struct tm *b)
622 {
623         int ay = a->tm_year + (1900 - 1);
624         int by = b->tm_year + (1900 - 1);
625         int intervening_leap_days =
626                 (ay/4 - by/4) - (ay/100 - by/100) + (ay/400 - by/400);
627         int years = ay - by;
628         int days = 365*years + intervening_leap_days + (a->tm_yday - b->tm_yday);
629         int hours = 24*days + (a->tm_hour - b->tm_hour);
630         int minutes = 60*hours + (a->tm_min - b->tm_min);
631         int seconds = 60*minutes + (a->tm_sec - b->tm_sec);
632
633         return seconds;
634 }
635
636
637 int extra_time_offset=0;
638
639 /**
640   return the UTC offset in seconds west of UTC, or 0 if it cannot be determined
641  */
642 _PUBLIC_ int get_time_zone(time_t t)
643 {
644         struct tm *tm = gmtime(&t);
645         struct tm tm_utc;
646         if (!tm)
647                 return 0;
648         tm_utc = *tm;
649         tm = localtime(&t);
650         if (!tm)
651                 return 0;
652         return tm_diff(&tm_utc,tm)+60*extra_time_offset;
653 }
654
655 struct timespec nt_time_to_unix_timespec(NTTIME *nt)
656 {
657         int64_t d;
658         struct timespec ret;
659
660         if (*nt == 0 || *nt == (int64_t)-1) {
661                 ret.tv_sec = 0;
662                 ret.tv_nsec = 0;
663                 return ret;
664         }
665
666         d = (int64_t)*nt;
667         /* d is now in 100ns units, since jan 1st 1601".
668            Save off the ns fraction. */
669
670         /*
671          * Take the last seven decimal digits and multiply by 100.
672          * to convert from 100ns units to 1ns units.
673          */
674         ret.tv_nsec = (long) ((d % (1000 * 1000 * 10)) * 100);
675
676         /* Convert to seconds */
677         d /= 1000*1000*10;
678
679         /* Now adjust by 369 years to make the secs since 1970 */
680         d -= TIME_FIXUP_CONSTANT_INT;
681
682         if (d <= (int64_t)TIME_T_MIN) {
683                 ret.tv_sec = TIME_T_MIN;
684                 ret.tv_nsec = 0;
685                 return ret;
686         }
687
688         if (d >= (int64_t)TIME_T_MAX) {
689                 ret.tv_sec = TIME_T_MAX;
690                 ret.tv_nsec = 0;
691                 return ret;
692         }
693
694         ret.tv_sec = (time_t)d;
695         return ret;
696 }
697
698
699 /**
700   check if 2 NTTIMEs are equal.
701 */
702 bool nt_time_equal(NTTIME *t1, NTTIME *t2)
703 {
704         return *t1 == *t2;
705 }
706
707 /**
708  Check if it's a null timespec.
709 **/
710
711 bool null_timespec(struct timespec ts)
712 {
713         return ts.tv_sec == 0 || 
714                 ts.tv_sec == (time_t)0xFFFFFFFF || 
715                 ts.tv_sec == (time_t)-1;
716 }
717
718