debug: add an empty line
[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    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 **/
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 **/
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 **/
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
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
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 **/
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 **/
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 **/
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 **/
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 ********************************************************************/
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 ********************************************************************/
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 ********************************************************************/
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 **/
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 **/
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 **/
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 ********************************************************************/
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 **/
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 **/
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 **/
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         if (!null_time(t)) {
330                 t += zone_offset;
331         }
332         return t;
333 }
334
335 /****************************************************************************
336  Return the date and time as a string
337 ****************************************************************************/
338
339 char *timeval_string(TALLOC_CTX *ctx, const struct timeval *tp, bool hires)
340 {
341         struct timeval_buf tmp;
342         char *result;
343
344         result = talloc_strdup(ctx, timeval_str_buf(tp, false, hires, &tmp));
345         if (result == NULL) {
346                 return NULL;
347         }
348
349         /*
350          * beautify the talloc_report output
351          *
352          * This is not just cosmetics. A C compiler might in theory make the
353          * talloc_strdup call above a tail call with the tail call
354          * optimization. This would render "tmp" invalid while talloc_strdup
355          * tries to duplicate it. The talloc_set_name_const call below puts
356          * the talloc_strdup call into non-tail position.
357          */
358         talloc_set_name_const(result, result);
359         return result;
360 }
361
362 char *current_timestring(TALLOC_CTX *ctx, bool hires)
363 {
364         struct timeval tv;
365
366         GetTimeOfDay(&tv);
367         return timeval_string(ctx, &tv, hires);
368 }
369
370 /*
371  * Return date and time as a minimal string avoiding funny characters
372  * that may cause trouble in file names. We only use digits and
373  * underscore ... or a minus/hyphen if we got negative time.
374  */
375 char *minimal_timeval_string(TALLOC_CTX *ctx, const struct timeval *tp, bool hires)
376 {
377         time_t t;
378         struct tm *tm;
379
380         t = (time_t)tp->tv_sec;
381         tm = localtime(&t);
382         if (!tm) {
383                 if (hires) {
384                         return talloc_asprintf(ctx, "%ld_%06ld",
385                                                (long)tp->tv_sec,
386                                                (long)tp->tv_usec);
387                 } else {
388                         return talloc_asprintf(ctx, "%ld", (long)t);
389                 }
390         } else {
391                 if (hires) {
392                         return talloc_asprintf(ctx,
393                                                "%04d%02d%02d_%02d%02d%02d_%06ld",
394                                                tm->tm_year+1900,
395                                                tm->tm_mon+1,
396                                                tm->tm_mday,
397                                                tm->tm_hour,
398                                                tm->tm_min,
399                                                tm->tm_sec,
400                                                (long)tp->tv_usec);
401                 } else {
402                         return talloc_asprintf(ctx,
403                                                "%04d%02d%02d_%02d%02d%02d",
404                                                tm->tm_year+1900,
405                                                tm->tm_mon+1,
406                                                tm->tm_mday,
407                                                tm->tm_hour,
408                                                tm->tm_min,
409                                                tm->tm_sec);
410                 }
411         }
412 }
413
414 char *current_minimal_timestring(TALLOC_CTX *ctx, bool hires)
415 {
416         struct timeval tv;
417
418         GetTimeOfDay(&tv);
419         return minimal_timeval_string(ctx, &tv, hires);
420 }
421
422 /**
423 return a HTTP/1.0 time string
424 **/
425 _PUBLIC_ char *http_timestring(TALLOC_CTX *mem_ctx, time_t t)
426 {
427         char *buf;
428         char tempTime[60];
429         struct tm *tm = localtime(&t);
430
431         if (t == TIME_T_MAX) {
432                 return talloc_strdup(mem_ctx, "never");
433         }
434
435         if (!tm) {
436                 return talloc_asprintf(mem_ctx,"%ld seconds since the Epoch",(long)t);
437         }
438
439 #ifndef HAVE_STRFTIME
440         buf = talloc_strdup(mem_ctx, asctime(tm));
441         if (buf[strlen(buf)-1] == '\n') {
442                 buf[strlen(buf)-1] = 0;
443         }
444 #else
445         strftime(tempTime, sizeof(tempTime)-1, "%a, %d %b %Y %H:%M:%S %Z", tm);
446         buf = talloc_strdup(mem_ctx, tempTime);
447 #endif /* !HAVE_STRFTIME */
448
449         return buf;
450 }
451
452 /**
453  Return the date and time as a string
454 **/
455 _PUBLIC_ char *timestring(TALLOC_CTX *mem_ctx, time_t t)
456 {
457         char *TimeBuf;
458         char tempTime[80];
459         struct tm *tm;
460
461         tm = localtime(&t);
462         if (!tm) {
463                 return talloc_asprintf(mem_ctx,
464                                        "%ld seconds since the Epoch",
465                                        (long)t);
466         }
467
468 #ifdef HAVE_STRFTIME
469         /* Some versions of gcc complain about using some special format
470          * specifiers. This is a bug in gcc, not a bug in this code. See a
471          * recent strftime() manual page for details. */
472         strftime(tempTime,sizeof(tempTime)-1,"%a %b %e %X %Y %Z",tm);
473         TimeBuf = talloc_strdup(mem_ctx, tempTime);
474 #else
475         TimeBuf = talloc_strdup(mem_ctx, asctime(tm));
476         if (TimeBuf == NULL) {
477                 return NULL;
478         }
479         if (TimeBuf[0] != '\0') {
480                 size_t len = strlen(TimeBuf);
481                 if (TimeBuf[len - 1] == '\n') {
482                         TimeBuf[len - 1] = '\0';
483                 }
484         }
485 #endif
486
487         return TimeBuf;
488 }
489
490 /**
491   return a talloced string representing a NTTIME for human consumption
492 */
493 _PUBLIC_ const char *nt_time_string(TALLOC_CTX *mem_ctx, NTTIME nt)
494 {
495         time_t t;
496         if (nt == 0) {
497                 return "NTTIME(0)";
498         }
499         t = nt_time_to_unix(nt);
500         return timestring(mem_ctx, t);
501 }
502
503
504 /**
505   put a NTTIME into a packet
506 */
507 _PUBLIC_ void push_nttime(uint8_t *base, uint16_t offset, NTTIME t)
508 {
509         SBVAL(base, offset,   t);
510 }
511
512 /**
513   pull a NTTIME from a packet
514 */
515 _PUBLIC_ NTTIME pull_nttime(uint8_t *base, uint16_t offset)
516 {
517         NTTIME ret = BVAL(base, offset);
518         return ret;
519 }
520
521 /**
522   return (tv1 - tv2) in microseconds
523 */
524 _PUBLIC_ int64_t usec_time_diff(const struct timeval *tv1, const struct timeval *tv2)
525 {
526         int64_t sec_diff = tv1->tv_sec - tv2->tv_sec;
527         return (sec_diff * 1000000) + (int64_t)(tv1->tv_usec - tv2->tv_usec);
528 }
529
530 /**
531   return (tp1 - tp2) in nanoseconds
532 */
533 _PUBLIC_ int64_t nsec_time_diff(const struct timespec *tp1, const struct timespec *tp2)
534 {
535         int64_t sec_diff = tp1->tv_sec - tp2->tv_sec;
536         return (sec_diff * 1000000000) + (int64_t)(tp1->tv_nsec - tp2->tv_nsec);
537 }
538
539
540 /**
541   return a zero timeval
542 */
543 _PUBLIC_ struct timeval timeval_zero(void)
544 {
545         struct timeval tv;
546         tv.tv_sec = 0;
547         tv.tv_usec = 0;
548         return tv;
549 }
550
551 /**
552   return true if a timeval is zero
553 */
554 _PUBLIC_ bool timeval_is_zero(const struct timeval *tv)
555 {
556         return tv->tv_sec == 0 && tv->tv_usec == 0;
557 }
558
559 /**
560   return a timeval for the current time
561 */
562 _PUBLIC_ struct timeval timeval_current(void)
563 {
564         struct timeval tv;
565         GetTimeOfDay(&tv);
566         return tv;
567 }
568
569 /**
570   return a timeval struct with the given elements
571 */
572 _PUBLIC_ struct timeval timeval_set(uint32_t secs, uint32_t usecs)
573 {
574         struct timeval tv;
575         tv.tv_sec = secs;
576         tv.tv_usec = usecs;
577         return tv;
578 }
579
580
581 /**
582   return a timeval ofs microseconds after tv
583 */
584 _PUBLIC_ struct timeval timeval_add(const struct timeval *tv,
585                            uint32_t secs, uint32_t usecs)
586 {
587         struct timeval tv2 = *tv;
588         const unsigned int million = 1000000;
589         tv2.tv_sec += secs;
590         tv2.tv_usec += usecs;
591         tv2.tv_sec += tv2.tv_usec / million;
592         tv2.tv_usec = tv2.tv_usec % million;
593         return tv2;
594 }
595
596 /**
597   return the sum of two timeval structures
598 */
599 struct timeval timeval_sum(const struct timeval *tv1,
600                            const struct timeval *tv2)
601 {
602         return timeval_add(tv1, tv2->tv_sec, tv2->tv_usec);
603 }
604
605 /**
606   return a timeval secs/usecs into the future
607 */
608 _PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
609 {
610         struct timeval tv = timeval_current();
611         return timeval_add(&tv, secs, usecs);
612 }
613
614 /**
615   return a timeval milliseconds into the future
616 */
617 _PUBLIC_ struct timeval timeval_current_ofs_msec(uint32_t msecs)
618 {
619         struct timeval tv = timeval_current();
620         return timeval_add(&tv, msecs / 1000, (msecs % 1000) * 1000);
621 }
622
623 /**
624   return a timeval microseconds into the future
625 */
626 _PUBLIC_ struct timeval timeval_current_ofs_usec(uint32_t usecs)
627 {
628         struct timeval tv = timeval_current();
629         return timeval_add(&tv, usecs / 1000000, usecs % 1000000);
630 }
631
632 /**
633   compare two timeval structures. 
634   Return -1 if tv1 < tv2
635   Return 0 if tv1 == tv2
636   Return 1 if tv1 > tv2
637 */
638 _PUBLIC_ int timeval_compare(const struct timeval *tv1, const struct timeval *tv2)
639 {
640         if (tv1->tv_sec  > tv2->tv_sec)  return 1;
641         if (tv1->tv_sec  < tv2->tv_sec)  return -1;
642         if (tv1->tv_usec > tv2->tv_usec) return 1;
643         if (tv1->tv_usec < tv2->tv_usec) return -1;
644         return 0;
645 }
646
647 /**
648   return true if a timer is in the past
649 */
650 _PUBLIC_ bool timeval_expired(const struct timeval *tv)
651 {
652         struct timeval tv2 = timeval_current();
653         if (tv2.tv_sec > tv->tv_sec) return true;
654         if (tv2.tv_sec < tv->tv_sec) return false;
655         return (tv2.tv_usec >= tv->tv_usec);
656 }
657
658 /**
659   return the number of seconds elapsed between two times
660 */
661 _PUBLIC_ double timeval_elapsed2(const struct timeval *tv1, const struct timeval *tv2)
662 {
663         return (tv2->tv_sec - tv1->tv_sec) + 
664                (tv2->tv_usec - tv1->tv_usec)*1.0e-6;
665 }
666
667 /**
668   return the number of seconds elapsed since a given time
669 */
670 _PUBLIC_ double timeval_elapsed(const struct timeval *tv)
671 {
672         struct timeval tv2 = timeval_current();
673         return timeval_elapsed2(tv, &tv2);
674 }
675 /**
676  *   return the number of seconds elapsed between two times
677  **/
678 _PUBLIC_ double timespec_elapsed2(const struct timespec *ts1,
679                                 const struct timespec *ts2)
680 {
681         return (ts2->tv_sec - ts1->tv_sec) +
682                (ts2->tv_nsec - ts1->tv_nsec)*1.0e-9;
683 }
684
685 /**
686  *   return the number of seconds elapsed since a given time
687  */
688 _PUBLIC_ double timespec_elapsed(const struct timespec *ts)
689 {
690         struct timespec ts2 = timespec_current();
691         return timespec_elapsed2(ts, &ts2);
692 }
693
694 /**
695   return the lesser of two timevals
696 */
697 _PUBLIC_ struct timeval timeval_min(const struct timeval *tv1,
698                            const struct timeval *tv2)
699 {
700         if (tv1->tv_sec < tv2->tv_sec) return *tv1;
701         if (tv1->tv_sec > tv2->tv_sec) return *tv2;
702         if (tv1->tv_usec < tv2->tv_usec) return *tv1;
703         return *tv2;
704 }
705
706 /**
707   return the greater of two timevals
708 */
709 _PUBLIC_ struct timeval timeval_max(const struct timeval *tv1,
710                            const struct timeval *tv2)
711 {
712         if (tv1->tv_sec > tv2->tv_sec) return *tv1;
713         if (tv1->tv_sec < tv2->tv_sec) return *tv2;
714         if (tv1->tv_usec > tv2->tv_usec) return *tv1;
715         return *tv2;
716 }
717
718 /**
719   return the difference between two timevals as a timeval
720   if tv1 comes after tv2, then return a zero timeval
721   (this is *tv2 - *tv1)
722 */
723 _PUBLIC_ struct timeval timeval_until(const struct timeval *tv1,
724                              const struct timeval *tv2)
725 {
726         struct timeval t;
727         if (timeval_compare(tv1, tv2) >= 0) {
728                 return timeval_zero();
729         }
730         t.tv_sec = tv2->tv_sec - tv1->tv_sec;
731         if (tv1->tv_usec > tv2->tv_usec) {
732                 t.tv_sec--;
733                 t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec);
734         } else {
735                 t.tv_usec = tv2->tv_usec - tv1->tv_usec;
736         }
737         return t;
738 }
739
740
741 /**
742   convert a timeval to a NTTIME
743 */
744 _PUBLIC_ NTTIME timeval_to_nttime(const struct timeval *tv)
745 {
746         return 10*(tv->tv_usec + 
747                   ((TIME_FIXUP_CONSTANT + (uint64_t)tv->tv_sec) * 1000000));
748 }
749
750 /**
751   convert a NTTIME to a timeval
752 */
753 _PUBLIC_ void nttime_to_timeval(struct timeval *tv, NTTIME t)
754 {
755         if (tv == NULL) return;
756
757         t += 10/2;
758         t /= 10;
759         t -= TIME_FIXUP_CONSTANT*1000*1000;
760
761         tv->tv_sec  = t / 1000000;
762
763         if (TIME_T_MIN > tv->tv_sec || tv->tv_sec > TIME_T_MAX) {
764                 tv->tv_sec  = 0;
765                 tv->tv_usec = 0;
766                 return;
767         }
768         
769         tv->tv_usec = t - tv->tv_sec*1000000;
770 }
771
772 /*******************************************************************
773 yield the difference between *A and *B, in seconds, ignoring leap seconds
774 ********************************************************************/
775 static int tm_diff(struct tm *a, struct tm *b)
776 {
777         int ay = a->tm_year + (1900 - 1);
778         int by = b->tm_year + (1900 - 1);
779         int intervening_leap_days =
780                 (ay/4 - by/4) - (ay/100 - by/100) + (ay/400 - by/400);
781         int years = ay - by;
782         int days = 365*years + intervening_leap_days + (a->tm_yday - b->tm_yday);
783         int hours = 24*days + (a->tm_hour - b->tm_hour);
784         int minutes = 60*hours + (a->tm_min - b->tm_min);
785         int seconds = 60*minutes + (a->tm_sec - b->tm_sec);
786
787         return seconds;
788 }
789
790
791 /**
792   return the UTC offset in seconds west of UTC, or 0 if it cannot be determined
793  */
794 _PUBLIC_ int get_time_zone(time_t t)
795 {
796         struct tm *tm = gmtime(&t);
797         struct tm tm_utc;
798         if (!tm)
799                 return 0;
800         tm_utc = *tm;
801         tm = localtime(&t);
802         if (!tm)
803                 return 0;
804         return tm_diff(&tm_utc,tm);
805 }
806
807 struct timespec nt_time_to_unix_timespec(NTTIME nt)
808 {
809         int64_t d;
810         struct timespec ret;
811
812         if (nt == 0 || nt == (int64_t)-1) {
813                 ret.tv_sec = 0;
814                 ret.tv_nsec = 0;
815                 return ret;
816         }
817
818         d = (int64_t)nt;
819         /* d is now in 100ns units, since jan 1st 1601".
820            Save off the ns fraction. */
821
822         /*
823          * Take the last seven decimal digits and multiply by 100.
824          * to convert from 100ns units to 1ns units.
825          */
826         ret.tv_nsec = (long) ((d % (1000 * 1000 * 10)) * 100);
827
828         /* Convert to seconds */
829         d /= 1000*1000*10;
830
831         /* Now adjust by 369 years to make the secs since 1970 */
832         d -= TIME_FIXUP_CONSTANT_INT;
833
834         if (d <= (int64_t)TIME_T_MIN) {
835                 ret.tv_sec = TIME_T_MIN;
836                 ret.tv_nsec = 0;
837                 return ret;
838         }
839
840         if (d >= (int64_t)TIME_T_MAX) {
841                 ret.tv_sec = TIME_T_MAX;
842                 ret.tv_nsec = 0;
843                 return ret;
844         }
845
846         ret.tv_sec = (time_t)d;
847         return ret;
848 }
849
850
851 /**
852   check if 2 NTTIMEs are equal.
853 */
854 bool nt_time_equal(NTTIME *t1, NTTIME *t2)
855 {
856         return *t1 == *t2;
857 }
858
859 /**
860  Check if it's a null timespec.
861 **/
862
863 bool null_timespec(struct timespec ts)
864 {
865         return ts.tv_sec == 0 || 
866                 ts.tv_sec == (time_t)0xFFFFFFFF || 
867                 ts.tv_sec == (time_t)-1;
868 }
869
870 /****************************************************************************
871  Convert a normalized timeval to a timespec.
872 ****************************************************************************/
873
874 struct timespec convert_timeval_to_timespec(const struct timeval tv)
875 {
876         struct timespec ts;
877         ts.tv_sec = tv.tv_sec;
878         ts.tv_nsec = tv.tv_usec * 1000;
879         return ts;
880 }
881
882 /****************************************************************************
883  Convert a normalized timespec to a timeval.
884 ****************************************************************************/
885
886 struct timeval convert_timespec_to_timeval(const struct timespec ts)
887 {
888         struct timeval tv;
889         tv.tv_sec = ts.tv_sec;
890         tv.tv_usec = ts.tv_nsec / 1000;
891         return tv;
892 }
893
894 /****************************************************************************
895  Return a timespec for the current time
896 ****************************************************************************/
897
898 _PUBLIC_ struct timespec timespec_current(void)
899 {
900         struct timespec ts;
901         clock_gettime(CLOCK_REALTIME, &ts);
902         return ts;
903 }
904
905 /****************************************************************************
906  Return the lesser of two timespecs.
907 ****************************************************************************/
908
909 struct timespec timespec_min(const struct timespec *ts1,
910                            const struct timespec *ts2)
911 {
912         if (ts1->tv_sec < ts2->tv_sec) return *ts1;
913         if (ts1->tv_sec > ts2->tv_sec) return *ts2;
914         if (ts1->tv_nsec < ts2->tv_nsec) return *ts1;
915         return *ts2;
916 }
917
918 /****************************************************************************
919   compare two timespec structures. 
920   Return -1 if ts1 < ts2
921   Return 0 if ts1 == ts2
922   Return 1 if ts1 > ts2
923 ****************************************************************************/
924
925 _PUBLIC_ int timespec_compare(const struct timespec *ts1, const struct timespec *ts2)
926 {
927         if (ts1->tv_sec  > ts2->tv_sec)  return 1;
928         if (ts1->tv_sec  < ts2->tv_sec)  return -1;
929         if (ts1->tv_nsec > ts2->tv_nsec) return 1;
930         if (ts1->tv_nsec < ts2->tv_nsec) return -1;
931         return 0;
932 }
933
934 /****************************************************************************
935  Round up a timespec if nsec > 500000000, round down if lower,
936  then zero nsec.
937 ****************************************************************************/
938
939 void round_timespec_to_sec(struct timespec *ts)
940 {
941         ts->tv_sec = convert_timespec_to_time_t(*ts);
942         ts->tv_nsec = 0;
943 }
944
945 /****************************************************************************
946  Round a timespec to usec value.
947 ****************************************************************************/
948
949 void round_timespec_to_usec(struct timespec *ts)
950 {
951         struct timeval tv = convert_timespec_to_timeval(*ts);
952         *ts = convert_timeval_to_timespec(tv);
953         while (ts->tv_nsec > 1000000000) {
954                 ts->tv_sec += 1;
955                 ts->tv_nsec -= 1000000000;
956         }
957 }
958
959 /****************************************************************************
960  Put a 8 byte filetime from a struct timespec. Uses GMT.
961 ****************************************************************************/
962
963 _PUBLIC_ NTTIME unix_timespec_to_nt_time(struct timespec ts)
964 {
965         uint64_t d;
966
967         if (ts.tv_sec ==0 && ts.tv_nsec == 0) {
968                 return 0;
969         }
970         if (ts.tv_sec == TIME_T_MAX) {
971                 return 0x7fffffffffffffffLL;
972         }
973         if (ts.tv_sec == (time_t)-1) {
974                 return (uint64_t)-1;
975         }
976
977         d = ts.tv_sec;
978         d += TIME_FIXUP_CONSTANT_INT;
979         d *= 1000*1000*10;
980         /* d is now in 100ns units. */
981         d += (ts.tv_nsec / 100);
982
983         return d;
984 }