Removed 'extern int DEBUGLEVEL' as it is now in the smb.h header.
[samba.git] / source3 / lib / time.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    time handling functions
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 /*
25   This stuff was largely rewritten by Paul Eggert <eggert@twinsun.com>
26   in May 1996 
27   */
28
29
30 int serverzone=0;
31 int extra_time_offset = 0;
32
33 #ifndef CHAR_BIT
34 #define CHAR_BIT 8
35 #endif
36
37 #ifndef TIME_T_MIN
38 #define TIME_T_MIN ((time_t)0 < (time_t) -1 ? (time_t) 0 \
39                     : ~ (time_t) 0 << (sizeof (time_t) * CHAR_BIT - 1))
40 #endif
41 #ifndef TIME_T_MAX
42 #define TIME_T_MAX (~ (time_t) 0 - TIME_T_MIN)
43 #endif
44
45
46
47 /*******************************************************************
48 a gettimeofday wrapper
49 ********************************************************************/
50 void GetTimeOfDay(struct timeval *tval)
51 {
52 #ifdef HAVE_GETTIMEOFDAY_TZ
53         gettimeofday(tval,NULL);
54 #else
55         gettimeofday(tval);
56 #endif
57 }
58
59 #define TM_YEAR_BASE 1900
60
61 /*******************************************************************
62 yield the difference between *A and *B, in seconds, ignoring leap seconds
63 ********************************************************************/
64 static int tm_diff(struct tm *a, struct tm *b)
65 {
66   int ay = a->tm_year + (TM_YEAR_BASE - 1);
67   int by = b->tm_year + (TM_YEAR_BASE - 1);
68   int intervening_leap_days =
69     (ay/4 - by/4) - (ay/100 - by/100) + (ay/400 - by/400);
70   int years = ay - by;
71   int days = 365*years + intervening_leap_days + (a->tm_yday - b->tm_yday);
72   int hours = 24*days + (a->tm_hour - b->tm_hour);
73   int minutes = 60*hours + (a->tm_min - b->tm_min);
74   int seconds = 60*minutes + (a->tm_sec - b->tm_sec);
75
76   return seconds;
77 }
78
79 /*******************************************************************
80   return the UTC offset in seconds west of UTC, or 0 if it cannot be determined
81   ******************************************************************/
82 static int TimeZone(time_t t)
83 {
84   struct tm *tm = gmtime(&t);
85   struct tm tm_utc;
86   if (!tm)
87     return 0;
88   tm_utc = *tm;
89   tm = localtime(&t);
90   if (!tm)
91     return 0;
92   return tm_diff(&tm_utc,tm);
93
94 }
95
96
97 /*******************************************************************
98 init the time differences
99 ********************************************************************/
100 void TimeInit(void)
101 {
102   serverzone = TimeZone(time(NULL));
103
104   if ((serverzone % 60) != 0) {
105           DEBUG(1,("WARNING: Your timezone is not a multiple of 1 minute.\n"));
106   }
107
108   DEBUG(4,("Serverzone is %d\n",serverzone));
109 }
110
111
112 /*******************************************************************
113 return the same value as TimeZone, but it should be more efficient.
114
115 We keep a table of DST offsets to prevent calling localtime() on each 
116 call of this function. This saves a LOT of time on many unixes.
117
118 Updated by Paul Eggert <eggert@twinsun.com>
119 ********************************************************************/
120 static int TimeZoneFaster(time_t t)
121 {
122   static struct dst_table {time_t start,end; int zone;} *tdt, *dst_table = NULL;
123   static int table_size = 0;
124   int i;
125   int zone = 0;
126
127   if (t == 0) t = time(NULL);
128
129   /* Tunis has a 8 day DST region, we need to be careful ... */
130 #define MAX_DST_WIDTH (365*24*60*60)
131 #define MAX_DST_SKIP (7*24*60*60)
132
133   for (i=0;i<table_size;i++)
134     if (t >= dst_table[i].start && t <= dst_table[i].end) break;
135
136   if (i<table_size) {
137     zone = dst_table[i].zone;
138   } else {
139     time_t low,high;
140
141     zone = TimeZone(t);
142     tdt = (struct dst_table *)Realloc(dst_table,
143                                               sizeof(dst_table[0])*(i+1));
144     if (!tdt) {
145       DEBUG(0,("TimeZoneFaster: out of memory!\n"));
146       SAFE_FREE(dst_table);
147       table_size = 0;
148     } else {
149       dst_table = tdt;
150       table_size++;
151
152       dst_table[i].zone = zone; 
153       dst_table[i].start = dst_table[i].end = t;
154     
155       /* no entry will cover more than 6 months */
156       low = t - MAX_DST_WIDTH/2;
157       if (t < low)
158         low = TIME_T_MIN;
159       
160       high = t + MAX_DST_WIDTH/2;
161       if (high < t)
162         high = TIME_T_MAX;
163       
164       /* widen the new entry using two bisection searches */
165       while (low+60*60 < dst_table[i].start) {
166         if (dst_table[i].start - low > MAX_DST_SKIP*2)
167           t = dst_table[i].start - MAX_DST_SKIP;
168         else
169           t = low + (dst_table[i].start-low)/2;
170         if (TimeZone(t) == zone)
171           dst_table[i].start = t;
172         else
173           low = t;
174       }
175
176       while (high-60*60 > dst_table[i].end) {
177         if (high - dst_table[i].end > MAX_DST_SKIP*2)
178           t = dst_table[i].end + MAX_DST_SKIP;
179         else
180           t = high - (high-dst_table[i].end)/2;
181         if (TimeZone(t) == zone)
182           dst_table[i].end = t;
183         else
184           high = t;
185       }
186 #if 0
187       DEBUG(1,("Added DST entry from %s ",
188                asctime(localtime(&dst_table[i].start))));
189       DEBUG(1,("to %s (%d)\n",asctime(localtime(&dst_table[i].end)),
190                dst_table[i].zone));
191 #endif
192     }
193   }
194   return zone;
195 }
196
197 /****************************************************************************
198   return the UTC offset in seconds west of UTC, adjusted for extra time offset
199   **************************************************************************/
200 int TimeDiff(time_t t)
201 {
202   return TimeZoneFaster(t) + 60*extra_time_offset;
203 }
204
205
206 /****************************************************************************
207   return the UTC offset in seconds west of UTC, adjusted for extra time
208   offset, for a local time value.  If ut = lt + LocTimeDiff(lt), then
209   lt = ut - TimeDiff(ut), but the converse does not necessarily hold near
210   daylight savings transitions because some local times are ambiguous.
211   LocTimeDiff(t) equals TimeDiff(t) except near daylight savings transitions.
212   +**************************************************************************/
213 static int LocTimeDiff(time_t lte)
214 {
215   time_t lt = lte - 60*extra_time_offset;
216   int d = TimeZoneFaster(lt);
217   time_t t = lt + d;
218
219   /* if overflow occurred, ignore all the adjustments so far */
220   if (((lte < lt) ^ (extra_time_offset < 0))  |  ((t < lt) ^ (d < 0)))
221     t = lte;
222
223   /* now t should be close enough to the true UTC to yield the right answer */
224   return TimeDiff(t);
225 }
226
227
228 /****************************************************************************
229 try to optimise the localtime call, it can be quite expensive on some machines
230 ****************************************************************************/
231 struct tm *LocalTime(time_t *t)
232 {
233   time_t t2 = *t;
234
235   t2 -= TimeDiff(t2);
236
237   return(gmtime(&t2));
238 }
239
240 #define TIME_FIXUP_CONSTANT (369.0*365.25*24*60*60-(3.0*24*60*60+6.0*60*60))
241
242 /****************************************************************************
243 interpret an 8 byte "filetime" structure to a time_t
244 It's originally in "100ns units since jan 1st 1601"
245
246 It appears to be kludge-GMT (at least for file listings). This means
247 its the GMT you get by taking a localtime and adding the
248 serverzone. This is NOT the same as GMT in some cases. This routine
249 converts this to real GMT.
250 ****************************************************************************/
251 time_t nt_time_to_unix(NTTIME *nt)
252 {
253   double d;
254   time_t ret;
255   /* The next two lines are a fix needed for the 
256      broken SCO compiler. JRA. */
257   time_t l_time_min = TIME_T_MIN;
258   time_t l_time_max = TIME_T_MAX;
259
260   if (nt->high == 0) return(0);
261
262   d = ((double)nt->high)*4.0*(double)(1<<30);
263   d += (nt->low&0xFFF00000);
264   d *= 1.0e-7;
265  
266   /* now adjust by 369 years to make the secs since 1970 */
267   d -= TIME_FIXUP_CONSTANT;
268
269   if (!(l_time_min <= d && d <= l_time_max))
270     return(0);
271
272   ret = (time_t)(d+0.5);
273
274   /* this takes us from kludge-GMT to real GMT */
275   ret -= serverzone;
276   ret += LocTimeDiff(ret);
277
278   return(ret);
279 }
280
281
282
283 /****************************************************************************
284 interprets an nt time into a unix time_t
285 ****************************************************************************/
286 time_t interpret_long_date(char *p)
287 {
288         NTTIME nt;
289         nt.low = IVAL(p,0);
290         nt.high = IVAL(p,4);
291         return nt_time_to_unix(&nt);
292 }
293
294 /****************************************************************************
295 put a 8 byte filetime from a time_t
296 This takes real GMT as input and converts to kludge-GMT
297 ****************************************************************************/
298 void unix_to_nt_time(NTTIME *nt, time_t t)
299 {
300         double d;
301
302         if (t==0)
303         {
304                 nt->low = 0;
305                 nt->high = 0;
306                 return;
307         }
308         if (t == -1)
309         {
310                 nt->low = 0xffffffff;
311                 nt->high = 0xffffffff;
312                 return;
313         }               
314
315         /* this converts GMT to kludge-GMT */
316         t -= LocTimeDiff(t) - serverzone; 
317
318         d = (double)(t);
319         d += TIME_FIXUP_CONSTANT;
320         d *= 1.0e7;
321
322         nt->high = (uint32)(d * (1.0/(4.0*(double)(1<<30))));
323         nt->low  = (uint32)(d - ((double)nt->high)*4.0*(double)(1<<30));
324 }
325
326
327 /****************************************************************************
328 take an NTTIME structure, containing high / low time.  convert to unix time.
329 lkclXXXX this may need 2 SIVALs not a memcpy.  we'll see...
330 ****************************************************************************/
331 void put_long_date(char *p,time_t t)
332 {
333         NTTIME nt;
334         unix_to_nt_time(&nt, t);
335         SIVAL(p, 0, nt.low);
336         SIVAL(p, 4, nt.high);
337 }
338
339 /****************************************************************************
340 check if it's a null mtime
341 ****************************************************************************/
342 BOOL null_mtime(time_t mtime)
343 {
344   if (mtime == 0 || mtime == 0xFFFFFFFF || mtime == (time_t)-1)
345     return(True);
346   return(False);
347 }
348
349 /*******************************************************************
350   create a 16 bit dos packed date
351 ********************************************************************/
352 static uint16 make_dos_date1(struct tm *t)
353 {
354   uint16 ret=0;
355   ret = (((unsigned)(t->tm_mon+1)) >> 3) | ((t->tm_year-80) << 1);
356   ret = ((ret&0xFF)<<8) | (t->tm_mday | (((t->tm_mon+1) & 0x7) << 5));
357   return(ret);
358 }
359
360 /*******************************************************************
361   create a 16 bit dos packed time
362 ********************************************************************/
363 static uint16 make_dos_time1(struct tm *t)
364 {
365   uint16 ret=0;
366   ret = ((((unsigned)t->tm_min >> 3)&0x7) | (((unsigned)t->tm_hour) << 3));
367   ret = ((ret&0xFF)<<8) | ((t->tm_sec/2) | ((t->tm_min & 0x7) << 5));
368   return(ret);
369 }
370
371 /*******************************************************************
372   create a 32 bit dos packed date/time from some parameters
373   This takes a GMT time and returns a packed localtime structure
374 ********************************************************************/
375 static uint32 make_dos_date(time_t unixdate)
376 {
377   struct tm *t;
378   uint32 ret=0;
379
380   t = LocalTime(&unixdate);
381   if (!t)
382     return 0xFFFFFFFF;
383
384   ret = make_dos_date1(t);
385   ret = ((ret&0xFFFF)<<16) | make_dos_time1(t);
386
387   return(ret);
388 }
389
390 /*******************************************************************
391 put a dos date into a buffer (time/date format)
392 This takes GMT time and puts local time in the buffer
393 ********************************************************************/
394 void put_dos_date(char *buf,int offset,time_t unixdate)
395 {
396   uint32 x = make_dos_date(unixdate);
397   SIVAL(buf,offset,x);
398 }
399
400 /*******************************************************************
401 put a dos date into a buffer (date/time format)
402 This takes GMT time and puts local time in the buffer
403 ********************************************************************/
404 void put_dos_date2(char *buf,int offset,time_t unixdate)
405 {
406   uint32 x = make_dos_date(unixdate);
407   x = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
408   SIVAL(buf,offset,x);
409 }
410
411 /*******************************************************************
412 put a dos 32 bit "unix like" date into a buffer. This routine takes
413 GMT and converts it to LOCAL time before putting it (most SMBs assume
414 localtime for this sort of date)
415 ********************************************************************/
416 void put_dos_date3(char *buf,int offset,time_t unixdate)
417 {
418   if (!null_mtime(unixdate))
419     unixdate -= TimeDiff(unixdate);
420   SIVAL(buf,offset,unixdate);
421 }
422
423 /*******************************************************************
424   interpret a 32 bit dos packed date/time to some parameters
425 ********************************************************************/
426 static void interpret_dos_date(uint32 date,int *year,int *month,int *day,int *hour,int *minute,int *second)
427 {
428   uint32 p0,p1,p2,p3;
429
430   p0=date&0xFF; p1=((date&0xFF00)>>8)&0xFF; 
431   p2=((date&0xFF0000)>>16)&0xFF; p3=((date&0xFF000000)>>24)&0xFF;
432
433   *second = 2*(p0 & 0x1F);
434   *minute = ((p0>>5)&0xFF) + ((p1&0x7)<<3);
435   *hour = (p1>>3)&0xFF;
436   *day = (p2&0x1F);
437   *month = ((p2>>5)&0xFF) + ((p3&0x1)<<3) - 1;
438   *year = ((p3>>1)&0xFF) + 80;
439 }
440
441 /*******************************************************************
442   create a unix date (int GMT) from a dos date (which is actually in
443   localtime)
444 ********************************************************************/
445 time_t make_unix_date(void *date_ptr)
446 {
447   uint32 dos_date=0;
448   struct tm t;
449   time_t ret;
450
451   dos_date = IVAL(date_ptr,0);
452
453   if (dos_date == 0) return(0);
454   
455   interpret_dos_date(dos_date,&t.tm_year,&t.tm_mon,
456                      &t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
457   t.tm_isdst = -1;
458   
459   /* mktime() also does the local to GMT time conversion for us */
460   ret = mktime(&t);
461
462   return(ret);
463 }
464
465 /*******************************************************************
466 like make_unix_date() but the words are reversed
467 ********************************************************************/
468 time_t make_unix_date2(void *date_ptr)
469 {
470   uint32 x,x2;
471
472   x = IVAL(date_ptr,0);
473   x2 = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
474   SIVAL(&x,0,x2);
475
476   return(make_unix_date((void *)&x));
477 }
478
479 /*******************************************************************
480   create a unix GMT date from a dos date in 32 bit "unix like" format
481   these generally arrive as localtimes, with corresponding DST
482   ******************************************************************/
483 time_t make_unix_date3(void *date_ptr)
484 {
485   time_t t = (time_t)IVAL(date_ptr,0);
486   if (!null_mtime(t))
487     t += LocTimeDiff(t);
488   return(t);
489 }
490
491
492 /***************************************************************************
493 return a HTTP/1.0 time string
494   ***************************************************************************/
495 char *http_timestring(time_t t)
496 {
497   static fstring buf;
498   struct tm *tm = LocalTime(&t);
499
500   if (!tm)
501     slprintf(buf,sizeof(buf)-1,"%ld seconds since the Epoch",(long)t);
502   else
503 #ifndef HAVE_STRFTIME
504   fstrcpy(buf, asctime(tm));
505   if(buf[strlen(buf)-1] == '\n')
506     buf[strlen(buf)-1] = 0;
507 #else /* !HAVE_STRFTIME */
508   strftime(buf, sizeof(buf)-1, "%a, %d %b %Y %H:%M:%S %Z", tm);
509 #endif /* !HAVE_STRFTIME */
510   return buf;
511 }
512
513
514
515 /****************************************************************************
516  Return the date and time as a string
517 ****************************************************************************/
518
519 char *timestring(BOOL hires)
520 {
521         static fstring TimeBuf;
522         struct timeval tp;
523         time_t t;
524         struct tm *tm;
525
526         if (hires) {
527                 GetTimeOfDay(&tp);
528                 t = (time_t)tp.tv_sec;
529         } else {
530                 t = time(NULL);
531         }
532         tm = LocalTime(&t);
533         if (!tm) {
534                 if (hires) {
535                         slprintf(TimeBuf,
536                                  sizeof(TimeBuf)-1,
537                                  "%ld.%06ld seconds since the Epoch",
538                                  (long)tp.tv_sec, 
539                                  (long)tp.tv_usec);
540                 } else {
541                         slprintf(TimeBuf,
542                                  sizeof(TimeBuf)-1,
543                                  "%ld seconds since the Epoch",
544                                  (long)t);
545                 }
546         } else {
547 #ifdef HAVE_STRFTIME
548                 if (hires) {
549                         strftime(TimeBuf,sizeof(TimeBuf)-1,"%Y/%m/%d %H:%M:%S",tm);
550                         slprintf(TimeBuf+strlen(TimeBuf),
551                                  sizeof(TimeBuf)-1 - strlen(TimeBuf), 
552                                  ".%06ld", 
553                                  (long)tp.tv_usec);
554                 } else {
555                         strftime(TimeBuf,100,"%Y/%m/%d %H:%M:%S",tm);
556                 }
557 #else
558                 if (hires) {
559                         slprintf(TimeBuf, 
560                                  sizeof(TimeBuf)-1, 
561                                  "%s.%06ld", 
562                                  asctime(tm), 
563                                  (long)tp.tv_usec);
564                 } else {
565                         fstrcpy(TimeBuf, asctime(tm));
566                 }
567 #endif
568         }
569         return(TimeBuf);
570 }
571
572 /****************************************************************************
573   return the best approximation to a 'create time' under UNIX from a stat
574   structure.
575 ****************************************************************************/
576
577 time_t get_create_time(SMB_STRUCT_STAT *st,BOOL fake_dirs)
578 {
579   time_t ret, ret1;
580
581   if(S_ISDIR(st->st_mode) && fake_dirs)
582     return (time_t)315493200L;          /* 1/1/1980 */
583     
584   ret = MIN(st->st_ctime, st->st_mtime);
585   ret1 = MIN(ret, st->st_atime);
586
587   if(ret1 != (time_t)0)
588     return ret1;
589
590   /*
591    * One of ctime, mtime or atime was zero (probably atime).
592    * Just return MIN(ctime, mtime).
593    */
594   return ret;
595 }
596
597 /****************************************************************************
598 initialise an NTTIME to -1, which means "unknown" or "don't expire"
599 ****************************************************************************/
600
601 void init_nt_time(NTTIME *nt)
602 {
603         nt->high = 0x7FFFFFFF;
604         nt->low = 0xFFFFFFFF;
605 }