Adding Andrews buffer overflow fixes into the main branch.
[samba.git] / source / lib / time.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    time handling functions
5    Copyright (C) Andrew Tridgell 1992-1997
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 GETTIMEOFDAY1
55   gettimeofday(tval);
56 #else
57   gettimeofday(tval,NULL);
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   return seconds;
78 }
79
80 /*******************************************************************
81   return the UTC offset in seconds west of UTC
82   ******************************************************************/
83 static int TimeZone(time_t t)
84 {
85   struct tm tm_utc = *(gmtime(&t));
86   return tm_diff(&tm_utc,localtime(&t));
87 }
88
89
90 /*******************************************************************
91 init the time differences
92 ********************************************************************/
93 void TimeInit(void)
94 {
95   serverzone = TimeZone(time(NULL));
96   DEBUG(4,("Serverzone is %d\n",serverzone));
97 }
98
99
100 /*******************************************************************
101 return the same value as TimeZone, but it should be more efficient.
102
103 We keep a table of DST offsets to prevent calling localtime() on each 
104 call of this function. This saves a LOT of time on many unixes.
105
106 Updated by Paul Eggert <eggert@twinsun.com>
107 ********************************************************************/
108 static int TimeZoneFaster(time_t t)
109 {
110   static struct dst_table {time_t start,end; int zone;} *dst_table = NULL;
111   static int table_size = 0;
112   int i;
113   int zone = 0;
114
115   if (t == 0) t = time(NULL);
116
117   /* Tunis has a 8 day DST region, we need to be careful ... */
118 #define MAX_DST_WIDTH (365*24*60*60)
119 #define MAX_DST_SKIP (7*24*60*60)
120
121   for (i=0;i<table_size;i++)
122     if (t >= dst_table[i].start && t <= dst_table[i].end) break;
123
124   if (i<table_size) {
125     zone = dst_table[i].zone;
126   } else {
127     time_t low,high;
128
129     zone = TimeZone(t);
130     dst_table = (struct dst_table *)Realloc(dst_table,
131                                               sizeof(dst_table[0])*(i+1));
132     if (!dst_table) {
133       table_size = 0;
134     } else {
135       table_size++;
136
137       dst_table[i].zone = zone; 
138       dst_table[i].start = dst_table[i].end = t;
139     
140       /* no entry will cover more than 6 months */
141       low = t - MAX_DST_WIDTH/2;
142       if (t < low)
143         low = TIME_T_MIN;
144       
145       high = t + MAX_DST_WIDTH/2;
146       if (high < t)
147         high = TIME_T_MAX;
148       
149       /* widen the new entry using two bisection searches */
150       while (low+60*60 < dst_table[i].start) {
151         if (dst_table[i].start - low > MAX_DST_SKIP*2)
152           t = dst_table[i].start - MAX_DST_SKIP;
153         else
154           t = low + (dst_table[i].start-low)/2;
155         if (TimeZone(t) == zone)
156           dst_table[i].start = t;
157         else
158           low = t;
159       }
160
161       while (high-60*60 > dst_table[i].end) {
162         if (high - dst_table[i].end > MAX_DST_SKIP*2)
163           t = dst_table[i].end + MAX_DST_SKIP;
164         else
165           t = high - (high-dst_table[i].end)/2;
166         if (TimeZone(t) == zone)
167           dst_table[i].end = t;
168         else
169           high = t;
170       }
171 #if 0
172       DEBUG(1,("Added DST entry from %s ",
173                asctime(localtime(&dst_table[i].start))));
174       DEBUG(1,("to %s (%d)\n",asctime(localtime(&dst_table[i].end)),
175                dst_table[i].zone));
176 #endif
177     }
178   }
179   return zone;
180 }
181
182 /****************************************************************************
183   return the UTC offset in seconds west of UTC, adjusted for extra time offset
184   **************************************************************************/
185 int TimeDiff(time_t t)
186 {
187   return TimeZoneFaster(t) + 60*extra_time_offset;
188 }
189
190
191 /****************************************************************************
192   return the UTC offset in seconds west of UTC, adjusted for extra time
193   offset, for a local time value.  If ut = lt + LocTimeDiff(lt), then
194   lt = ut - TimeDiff(ut), but the converse does not necessarily hold near
195   daylight savings transitions because some local times are ambiguous.
196   LocTimeDiff(t) equals TimeDiff(t) except near daylight savings transitions.
197   +**************************************************************************/
198 static int LocTimeDiff(time_t lte)
199 {
200   time_t lt = lte - 60*extra_time_offset;
201   int d = TimeZoneFaster(lt);
202   time_t t = lt + d;
203
204   /* if overflow occurred, ignore all the adjustments so far */
205   if (((lte < lt) ^ (extra_time_offset < 0))  |  ((t < lt) ^ (d < 0)))
206     t = lte;
207
208   /* now t should be close enough to the true UTC to yield the right answer */
209   return TimeDiff(t);
210 }
211
212
213 /****************************************************************************
214 try to optimise the localtime call, it can be quite expenive on some machines
215 ****************************************************************************/
216 struct tm *LocalTime(time_t *t)
217 {
218   time_t t2 = *t;
219
220   t2 -= TimeDiff(t2);
221
222   return(gmtime(&t2));
223 }
224
225
226 #define TIME_FIXUP_CONSTANT (369.0*365.25*24*60*60-(3.0*24*60*60+6.0*60*60))
227
228 /****************************************************************************
229 interpret an 8 byte "filetime" structure to a time_t
230 It's originally in "100ns units since jan 1st 1601"
231
232 It appears to be kludge-GMT (at least for file listings). This means
233 its the GMT you get by taking a localtime and adding the
234 serverzone. This is NOT the same as GMT in some cases. This routine
235 converts this to real GMT.
236 ****************************************************************************/
237 time_t interpret_long_date(char *p)
238 {
239   double d;
240   time_t ret;
241   uint32 tlow,thigh;
242   tlow = IVAL(p,0);
243   thigh = IVAL(p,4);
244
245   if (thigh == 0) return(0);
246
247   d = ((double)thigh)*4.0*(double)(1<<30);
248   d += (tlow&0xFFF00000);
249   d *= 1.0e-7;
250  
251   /* now adjust by 369 years to make the secs since 1970 */
252   d -= TIME_FIXUP_CONSTANT;
253
254   if (!(TIME_T_MIN <= d && d <= TIME_T_MAX))
255     return(0);
256
257   ret = (time_t)(d+0.5);
258
259   /* this takes us from kludge-GMT to real GMT */
260   ret -= serverzone;
261   ret += LocTimeDiff(ret);
262
263   return(ret);
264 }
265
266
267 /****************************************************************************
268 put a 8 byte filetime from a time_t
269 This takes real GMT as input and converts to kludge-GMT
270 ****************************************************************************/
271 void put_long_date(char *p,time_t t)
272 {
273   uint32 tlow,thigh;
274   double d;
275
276   if (t==0) {
277     SIVAL(p,0,0); SIVAL(p,4,0);
278     return;
279   }
280
281   /* this converts GMT to kludge-GMT */
282   t -= TimeDiff(t) - serverzone; 
283
284   d = (double) (t);
285
286   d += TIME_FIXUP_CONSTANT;
287
288   d *= 1.0e7;
289
290   thigh = (uint32)(d * (1.0/(4.0*(double)(1<<30))));
291   tlow = (uint32)(d - ((double)thigh)*4.0*(double)(1<<30));
292
293   SIVAL(p,0,tlow);
294   SIVAL(p,4,thigh);
295 }
296
297
298 /****************************************************************************
299 check if it's a null mtime
300 ****************************************************************************/
301 static BOOL null_mtime(time_t mtime)
302 {
303   if (mtime == 0 || mtime == 0xFFFFFFFF || mtime == (time_t)-1)
304     return(True);
305   return(False);
306 }
307
308 /*******************************************************************
309   create a 16 bit dos packed date
310 ********************************************************************/
311 static uint16 make_dos_date1(time_t unixdate,struct tm *t)
312 {
313   uint16 ret=0;
314   ret = (((unsigned)(t->tm_mon+1)) >> 3) | ((t->tm_year-80) << 1);
315   ret = ((ret&0xFF)<<8) | (t->tm_mday | (((t->tm_mon+1) & 0x7) << 5));
316   return(ret);
317 }
318
319 /*******************************************************************
320   create a 16 bit dos packed time
321 ********************************************************************/
322 static uint16 make_dos_time1(time_t unixdate,struct tm *t)
323 {
324   uint16 ret=0;
325   ret = ((((unsigned)t->tm_min >> 3)&0x7) | (((unsigned)t->tm_hour) << 3));
326   ret = ((ret&0xFF)<<8) | ((t->tm_sec/2) | ((t->tm_min & 0x7) << 5));
327   return(ret);
328 }
329
330 /*******************************************************************
331   create a 32 bit dos packed date/time from some parameters
332   This takes a GMT time and returns a packed localtime structure
333 ********************************************************************/
334 static uint32 make_dos_date(time_t unixdate)
335 {
336   struct tm *t;
337   uint32 ret=0;
338
339   t = LocalTime(&unixdate);
340
341   ret = make_dos_date1(unixdate,t);
342   ret = ((ret&0xFFFF)<<16) | make_dos_time1(unixdate,t);
343
344   return(ret);
345 }
346
347 /*******************************************************************
348 put a dos date into a buffer (time/date format)
349 This takes GMT time and puts local time in the buffer
350 ********************************************************************/
351 void put_dos_date(char *buf,int offset,time_t unixdate)
352 {
353   uint32 x = make_dos_date(unixdate);
354   SIVAL(buf,offset,x);
355 }
356
357 /*******************************************************************
358 put a dos date into a buffer (date/time format)
359 This takes GMT time and puts local time in the buffer
360 ********************************************************************/
361 void put_dos_date2(char *buf,int offset,time_t unixdate)
362 {
363   uint32 x = make_dos_date(unixdate);
364   x = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
365   SIVAL(buf,offset,x);
366 }
367
368 /*******************************************************************
369 put a dos 32 bit "unix like" date into a buffer. This routine takes
370 GMT and converts it to LOCAL time before putting it (most SMBs assume
371 localtime for this sort of date)
372 ********************************************************************/
373 void put_dos_date3(char *buf,int offset,time_t unixdate)
374 {
375   if (!null_mtime(unixdate))
376     unixdate -= TimeDiff(unixdate);
377   SIVAL(buf,offset,unixdate);
378 }
379
380 /*******************************************************************
381   interpret a 32 bit dos packed date/time to some parameters
382 ********************************************************************/
383 static void interpret_dos_date(uint32 date,int *year,int *month,int *day,int *hour,int *minute,int *second)
384 {
385   uint32 p0,p1,p2,p3;
386
387   p0=date&0xFF; p1=((date&0xFF00)>>8)&0xFF; 
388   p2=((date&0xFF0000)>>16)&0xFF; p3=((date&0xFF000000)>>24)&0xFF;
389
390   *second = 2*(p0 & 0x1F);
391   *minute = ((p0>>5)&0xFF) + ((p1&0x7)<<3);
392   *hour = (p1>>3)&0xFF;
393   *day = (p2&0x1F);
394   *month = ((p2>>5)&0xFF) + ((p3&0x1)<<3) - 1;
395   *year = ((p3>>1)&0xFF) + 80;
396 }
397
398 /*******************************************************************
399   create a unix date (int GMT) from a dos date (which is actually in
400   localtime)
401 ********************************************************************/
402 time_t make_unix_date(void *date_ptr)
403 {
404   uint32 dos_date=0;
405   struct tm t;
406   time_t ret;
407
408   dos_date = IVAL(date_ptr,0);
409
410   if (dos_date == 0) return(0);
411   
412   interpret_dos_date(dos_date,&t.tm_year,&t.tm_mon,
413                      &t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec);
414   t.tm_isdst = -1;
415   
416   /* mktime() also does the local to GMT time conversion for us */
417   ret = mktime(&t);
418
419   return(ret);
420 }
421
422 /*******************************************************************
423 like make_unix_date() but the words are reversed
424 ********************************************************************/
425 time_t make_unix_date2(void *date_ptr)
426 {
427   uint32 x,x2;
428
429   x = IVAL(date_ptr,0);
430   x2 = ((x&0xFFFF)<<16) | ((x&0xFFFF0000)>>16);
431   SIVAL(&x,0,x2);
432
433   return(make_unix_date((void *)&x));
434 }
435
436 /*******************************************************************
437   create a unix GMT date from a dos date in 32 bit "unix like" format
438   these generally arrive as localtimes, with corresponding DST
439   ******************************************************************/
440 time_t make_unix_date3(void *date_ptr)
441 {
442   time_t t = IVAL(date_ptr,0);
443   if (!null_mtime(t))
444     t += LocTimeDiff(t);
445   return(t);
446 }
447
448 /****************************************************************************
449 set the time on a file
450 ****************************************************************************/
451 BOOL set_filetime(char *fname,time_t mtime)
452 {  
453   struct utimbuf times;
454
455   if (null_mtime(mtime)) return(True);
456
457   times.modtime = times.actime = mtime;
458
459   if (sys_utime(fname,&times)) {
460     DEBUG(4,("set_filetime(%s) failed: %s\n",fname,strerror(errno)));
461   }
462     
463   return(True);
464 }
465
466
467 /****************************************************************************
468   return the date and time as a string
469 ****************************************************************************/
470 char *timestring(void )
471 {
472   static fstring TimeBuf;
473   time_t t = time(NULL);
474   struct tm *tm = LocalTime(&t);
475
476 #ifdef NO_STRFTIME
477   fstrcpy(TimeBuf, asctime(tm));
478 #elif defined(CLIX) || defined(CONVEX)
479   strftime(TimeBuf,100,"%m/%d/%y %I:%M:%S %p",tm);
480 #elif defined(AMPM)
481   strftime(TimeBuf,100,"%D %r",tm);
482 #elif defined(TZ_TIME)
483   {
484     int zone = TimeDiff(t);
485     int absZoneMinutes = (zone<0 ? -zone : zone) / 60;
486     size_t len = strftime(TimeBuf,sizeof(TimeBuf)-6,"%D %T",tm);
487     sprintf(TimeBuf+len," %c%02d%02d",
488             zone<0?'+':'-',absZoneMinutes/60,absZoneMinutes%60);
489   }
490 #else
491   strftime(TimeBuf,100,"%D %T",tm);
492 #endif
493   return(TimeBuf);
494 }
495