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