1/* Convert struct partime into time_t.  */
2
3/* Copyright 1992, 1993, 1994, 1995, 1997 Paul Eggert
4   Distributed under license by the Free Software Foundation, Inc.
5
6   This file is part of RCS.
7
8   RCS 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 2, or (at your option)
11   any later version.
12
13   RCS 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 RCS; see the file COPYING.
20   If not, write to the Free Software Foundation,
21   59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22
23   Report problems and direct all questions to:
24
25	rcs-bugs@cs.purdue.edu
26
27 */
28
29/* For maximum portability, use only localtime and gmtime.
30   Make no assumptions about the time_t epoch or the range of time_t values.
31   Avoid mktime because it's not universal and because there's no easy,
32   portable way for mktime to yield the inverse of gmtime.  */
33
34#if has_conf_h
35# include <conf.h>
36#else
37# if HAVE_CONFIG_H
38#  include <config.h>
39# else
40#  ifndef __STDC__
41#   define const
42#  endif
43# endif
44  /* MIPS RISCOS4.52 defines time_t in <sys/types.h> not <time.h>.  */
45# include <sys/types.h>
46# if HAVE_LIMITS_H
47#  include <limits.h>
48# endif
49# ifndef LONG_MIN
50# define LONG_MIN (-1-2147483647L)
51# endif
52# if STDC_HEADERS
53#  include <stdlib.h>
54# endif
55# include <time.h>
56# ifdef __STDC__
57#  define P(x) x
58# else
59#  define P(x) ()
60# endif
61#endif
62
63#include <partime.h>
64#include <maketime.h>
65
66char const maket_id[] =
67  "$Id: maketime.c 8008 2004-06-16 21:22:10Z korli $";
68
69static int isleap P ((int));
70static int month_days P ((struct tm const *));
71static time_t maketime P ((struct partime const *, time_t));
72
73/* Suppose A1 + B1 = SUM1, using 2's complement arithmetic ignoring overflow.
74   Suppose A, B and SUM have the same respective signs as A1, B1, and SUM1.
75   Then this yields nonzero if overflow occurred during the addition.
76   Overflow occurs if A and B have the same sign, but A and SUM differ in sign.
77   Use `^' to test whether signs differ, and `< 0' to isolate the sign.  */
78#define overflow_sum_sign(a, b, sum) ((~((a) ^ (b)) & ((a) ^ (sum))) < 0)
79
80/* Quotient and remainder when dividing A by B,
81   truncating towards minus infinity, where B is positive.  */
82#define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
83#define MOD(a, b) ((a) % (b) + (b) * ((a) % (b) < 0))
84
85/* Number of days in 400 consecutive Gregorian years.  */
86#define Y400_DAYS (365 * 400L + 100 - 4 + 1)
87
88/* Number of years to add to tm_year to get Gregorian year.  */
89#define TM_YEAR_ORIGIN 1900
90
91static int
92isleap (y)
93     int y;
94{
95  return (y & 3) == 0 && (y % 100 != 0 || y % 400 == 0);
96}
97
98/* days in year before start of months 0-12 */
99static int const month_yday[] =
100{
101  0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
102};
103
104/* Yield the number of days in TM's month.  */
105static int
106month_days (tm)
107     struct tm const *tm;
108{
109  int m = tm->tm_mon;
110  return (month_yday[m + 1] - month_yday[m]
111	  + (m == 1 && isleap (tm->tm_year + TM_YEAR_ORIGIN)));
112}
113
114/* Convert UNIXTIME to struct tm form.
115   Use gmtime if available and if !LOCALZONE, localtime otherwise.  */
116struct tm *
117time2tm (unixtime, localzone)
118     time_t unixtime;
119     int localzone;
120{
121  struct tm *tm;
122#ifdef TZ_is_unset
123  static char const *TZ;
124  if (!TZ && !(TZ = getenv ("TZ")))
125    TZ_is_unset ("The TZ environment variable is not set; please set it to your timezone");
126#endif
127  if (localzone || !(tm = gmtime (&unixtime)))
128    tm = localtime (&unixtime);
129  return tm;
130}
131
132/* Yield A - B, measured in seconds.  */
133time_t
134difftm (a, b)
135     struct tm const *a;
136     struct tm const *b;
137{
138  int ay = a->tm_year + (TM_YEAR_ORIGIN - 1);
139  int by = b->tm_year + (TM_YEAR_ORIGIN - 1);
140  int ac = DIV (ay, 100);
141  int bc = DIV (by, 100);
142  int difference_in_day_of_year = a->tm_yday - b->tm_yday;
143  int intervening_leap_days = (((ay >> 2) - (by >> 2))
144			       - (ac - bc)
145			       + ((ac >> 2) - (bc >> 2)));
146  time_t difference_in_years = ay - by;
147  time_t difference_in_days
148    = (difference_in_years * 365
149       + (intervening_leap_days + difference_in_day_of_year));
150  return (((((difference_in_days * 24
151	      + (a->tm_hour - b->tm_hour))
152	     * 60)
153	    + (a->tm_min - b->tm_min))
154	   * 60)
155	  + (a->tm_sec - b->tm_sec));
156}
157
158/* Adjust time T by adding SECONDS.
159   The absolute value of SECONDS cannot exceed 59 * INT_MAX,
160   and also cannot exceed one month's worth of seconds;
161   this is enough to handle any POSIX or real-life daylight-saving offset.
162   Adjust only T's year, mon, mday, hour, min and sec members;
163   plus adjust wday if it is defined.  */
164void
165adjzone (t, seconds)
166     register struct tm *t;
167     long seconds;
168{
169  int days = 0;
170
171  /* This code can be off by a second if SECONDS is not a multiple of 60,
172     if T is local time, and if a leap second happens during this minute.
173     But this bug has never occurred, and most likely will not ever occur.
174     Liberia, the last country for which SECONDS % 60 was nonzero,
175     switched to UTC in May 1972; the first leap second was in June 1972.  */
176  int leap_second = t->tm_sec == 60;
177  long sec = seconds + (t->tm_sec - leap_second);
178  if (sec < 0)
179    {
180      if ((t->tm_min -= (59 - sec) / 60) < 0
181	  && (t->tm_hour -= (59 - t->tm_min) / 60) < 0)
182	{
183	  days = - ((23 - t->tm_hour) / 24);
184	  if ((t->tm_mday += days) <= 0)
185	    {
186	      if (--t->tm_mon < 0)
187		{
188		  --t->tm_year;
189		  t->tm_mon = 11;
190		}
191	      t->tm_mday += month_days (t);
192	    }
193	}
194    }
195  else
196    {
197      if (60 <= (t->tm_min += sec / 60)
198	  && (24 <= (t->tm_hour += t->tm_min / 60)))
199	{
200	  days = t->tm_hour / 24;
201	  if (month_days (t) < (t->tm_mday += days))
202	    {
203	      if (11 < ++t->tm_mon)
204		{
205		  ++t->tm_year;
206		  t->tm_mon = 0;
207		}
208	      t->tm_mday = 1;
209	    }
210	}
211    }
212  if (TM_DEFINED (t->tm_wday))
213    t->tm_wday = MOD (t->tm_wday + days, 7);
214  t->tm_hour = MOD (t->tm_hour, 24);
215  t->tm_min = MOD (t->tm_min, 60);
216  t->tm_sec = (int) MOD (sec, 60) + leap_second;
217}
218
219/* Convert TM to time_t, using localtime if LOCALZONE and gmtime otherwise.
220   Use only TM's year, mon, mday, hour, min, and sec members.
221   Ignore TM's old tm_yday and tm_wday, but fill in their correct values.
222   Yield -1 on failure (e.g. a member out of range).
223   POSIX 1003.1 doesn't allow leap seconds, but some implementations
224   have them anyway, so allow them if localtime/gmtime does.  */
225time_t
226tm2time (tm, localzone)
227     struct tm *tm;
228     int localzone;
229{
230  /* Cache the most recent t,tm pairs; 1 for gmtime, 1 for localtime.  */
231  static time_t t_cache[2];
232  static struct tm tm_cache[2];
233
234  time_t d, gt;
235  struct tm const *gtm;
236  /* The maximum number of iterations should be enough to handle any
237     combinations of leap seconds, time zone rule changes, and solar time.
238     4 is probably enough; we use a bigger number just to be safe.  */
239  int remaining_tries = 8;
240
241  /* Avoid subscript errors.  */
242  if (12 <= (unsigned) tm->tm_mon)
243    return -1;
244
245  tm->tm_yday = month_yday[tm->tm_mon] + tm->tm_mday
246    - (tm->tm_mon < 2 || !isleap (tm->tm_year + TM_YEAR_ORIGIN));
247
248  /* Make a first guess.  */
249  gt = t_cache[localzone];
250  gtm = gt ? &tm_cache[localzone] : time2tm (gt, localzone);
251
252  /* Repeatedly use the error from the guess to improve the guess.  */
253  while ((d = difftm (tm, gtm)) != 0)
254    {
255      if (--remaining_tries == 0)
256	return -1;
257      gt += d;
258      gtm = time2tm (gt, localzone);
259    }
260
261  /* Check that the guess actually matches;
262     overflow can cause difftm to yield 0 even on differing times,
263     or tm may have members out of range (e.g. bad leap seconds).  */
264#define TM_DIFFER(a,b) \
265		( \
266			((a)->tm_year ^ (b)->tm_year) | \
267			((a)->tm_mon ^ (b)->tm_mon) | \
268			((a)->tm_mday ^ (b)->tm_mday) | \
269			((a)->tm_hour ^ (b)->tm_hour) | \
270			((a)->tm_min ^ (b)->tm_min) | \
271			((a)->tm_sec ^ (b)->tm_sec) \
272		)
273  if (TM_DIFFER (tm, gtm))
274    {
275      /* If gt is a leap second, try gt+1; if it is one greater than
276         a leap second, try gt-1; otherwise, it doesn't matter.
277         Leap seconds always fall at month end.  */
278      int yd = tm->tm_year - gtm->tm_year;
279      gt += yd + (yd ? 0 : tm->tm_mon - gtm->tm_mon);
280      gtm = time2tm (gt, localzone);
281      if (TM_DIFFER (tm, gtm))
282	return -1;
283    }
284  t_cache[localzone] = gt;
285  tm_cache[localzone] = *gtm;
286
287  tm->tm_wday = gtm->tm_wday;
288  return gt;
289}
290
291/* Check *PT and convert it to time_t.
292   If it is incompletely specified, use DEFAULT_TIME to fill it out.
293   Use localtime if PT->zone is the special value TM_LOCAL_ZONE.
294   Yield -1 on failure.
295   ISO 8601 day-of-year and week numbers are not yet supported.  */
296static time_t
297maketime (pt, default_time)
298     struct partime const *pt;
299     time_t default_time;
300{
301  int localzone, wday, year;
302  struct tm tm;
303  struct tm *tm0 = 0;
304  time_t r;
305  int use_ordinal_day;
306
307  tm0 = 0;			/* Keep gcc -Wall happy.  */
308  localzone = pt->zone == TM_LOCAL_ZONE;
309
310  tm = pt->tm;
311  year = tm.tm_year;
312  wday = tm.tm_wday;
313  use_ordinal_day = (!TM_DEFINED (tm.tm_mday)
314		     && TM_DEFINED (wday) && TM_DEFINED (pt->wday_ordinal));
315
316  if (use_ordinal_day || TM_DEFINED (pt->ymodulus) || !TM_DEFINED (year))
317    {
318      /* Get tm corresponding to default time.  */
319      tm0 = time2tm (default_time, localzone);
320      if (!localzone)
321	adjzone (tm0, pt->zone);
322    }
323
324  if (use_ordinal_day)
325    tm.tm_mday = (tm0->tm_mday
326		  + ((wday - tm0->tm_wday + 7) % 7
327		     + 7 * (pt->wday_ordinal - (pt->wday_ordinal != 0))));
328
329  if (TM_DEFINED (pt->ymodulus))
330    {
331      /* Yield a year closest to the default that has the given modulus.  */
332      int year0 = tm0->tm_year + TM_YEAR_ORIGIN;
333      int y0 = MOD (year0, pt->ymodulus);
334      int d = 2 * (year - y0);
335      year += (((year0 - y0) / pt->ymodulus
336	        + (pt->ymodulus < d ? -1 : d < -pt->ymodulus))
337	       * pt->ymodulus);
338    }
339  else if (!TM_DEFINED (year))
340    {
341      /* Set default year, month, day from current time.  */
342      year = tm0->tm_year + TM_YEAR_ORIGIN;
343      if (!TM_DEFINED (tm.tm_mon))
344	{
345	  tm.tm_mon = tm0->tm_mon;
346	  if (!TM_DEFINED (tm.tm_mday))
347	    tm.tm_mday = tm0->tm_mday;
348	}
349    }
350
351  /* Set remaining default fields to be their minimum values.  */
352  if (!TM_DEFINED (tm.tm_mon))
353    tm.tm_mon = 0;
354  if (!TM_DEFINED (tm.tm_mday))
355    tm.tm_mday = 1;
356  if (!TM_DEFINED (tm.tm_hour))
357    tm.tm_hour = 0;
358  if (!TM_DEFINED (tm.tm_min))
359    tm.tm_min = 0;
360  if (!TM_DEFINED (tm.tm_sec))
361    tm.tm_sec = 0;
362
363  tm.tm_year = year - TM_YEAR_ORIGIN;
364  if ((year < tm.tm_year) != (TM_YEAR_ORIGIN < 0))
365    return -1;
366
367  if (!localzone)
368    {
369      adjzone (&tm, -pt->zone);
370      wday = tm.tm_wday;
371    }
372
373  /* Convert and fill in the rest of the tm.  */
374  r = tm2time (&tm, localzone);
375  if (r == -1)
376    return r;
377
378  /* Check weekday.  */
379  if (TM_DEFINED (wday) && wday != tm.tm_wday)
380    return -1;
381
382  /* Add relative time, except for seconds.
383     We handle seconds separately, at the end,
384     so that leap seconds are handled properly.  */
385  if (pt->tmr.tm_year | pt->tmr.tm_mon | pt->tmr.tm_mday
386      | pt->tmr.tm_hour | pt->tmr.tm_min)
387    {
388      int years = tm.tm_year + pt->tmr.tm_year;
389      int mons = tm.tm_mon + pt->tmr.tm_mon;
390      int mdays = tm.tm_mday + pt->tmr.tm_mday;
391      int hours = tm.tm_hour + pt->tmr.tm_hour;
392      int mins = tm.tm_min + pt->tmr.tm_min;
393
394      int carried_hours = DIV (mins, 60);
395      int hours1 = hours + carried_hours;
396      int carried_days = DIV (hours1, 24);
397      int mdays1 = mdays + carried_days;
398
399      int mon0 = MOD (mons, 12);
400      int carried_years0 = DIV (mons, 12);
401      int year0 = years + carried_years0;
402      int yday0 = (month_yday[mon0]
403		   - (mon0 < 2 || !isleap (year0 + TM_YEAR_ORIGIN)));
404
405      int yday1 = yday0 + mdays1;
406      int carried_years1 = DIV (yday1, Y400_DAYS) * 400;
407      int year1 = year0 + carried_years1;
408      int yday2 = MOD (yday1, Y400_DAYS);
409      int leap;
410
411      if (overflow_sum_sign (tm.tm_year, pt->tmr.tm_year, years)
412	  | overflow_sum_sign (tm.tm_mon, pt->tmr.tm_mon, mons)
413	  | overflow_sum_sign (tm.tm_mday, pt->tmr.tm_mday, mdays)
414	  | overflow_sum_sign (tm.tm_hour, pt->tmr.tm_hour, hours)
415	  | overflow_sum_sign (tm.tm_min, pt->tmr.tm_min, mins)
416	  | overflow_sum_sign (hours, carried_hours, hours1)
417	  | overflow_sum_sign (mdays, carried_days, mdays1)
418	  | overflow_sum_sign (years, carried_years0, year0)
419	  | overflow_sum_sign (yday0, mdays1, yday1)
420	  | overflow_sum_sign (year0, carried_years1, year1))
421	return -1;
422
423      for (;;)
424	{
425	  int days_per_year = 365 + (leap = isleap (year1 + TM_YEAR_ORIGIN));
426	  if (yday2 < days_per_year)
427	    break;
428	  yday2 -= days_per_year;
429	  year1++;
430	}
431
432      tm.tm_year = year1;
433
434      {
435	int mon;
436	for (mon = 11;
437	     (tm.tm_mday = (yday2 - month_yday[mon] + (mon < 2 || !leap))) <= 0;
438	     mon--)
439	  continue;
440	tm.tm_mon = mon;
441      }
442
443      tm.tm_hour = MOD (hours1, 24);
444      tm.tm_min = MOD (mins, 60);
445
446      r = tm2time (&tm, localzone);
447      if (r == -1)
448	return r;
449    }
450
451  /* Add the seconds' part of relative time.  */
452  {
453    time_t rs = r + pt->tmr.tm_sec;
454    if ((pt->tmr.tm_sec < 0) != (rs < r))
455      return -1;
456    return rs;
457  }
458}
459
460/* Parse a free-format date in *SOURCE, yielding a Unix format time.
461   Update *SOURCE to point to the first character after the date.
462   If *SOURCE is missing some information, take defaults from
463   DEFAULT_TIME and DEFAULT_ZONE.  *SOURCE may even be the empty
464   string or an immediately invalid string, in which case the default
465   time and zone is used.
466   Return (time_t) -1 if the time is invalid or cannot be represented.  */
467time_t
468str2time (source, default_time, default_zone)
469     char const **source;
470     time_t default_time;
471     long default_zone;
472{
473  struct partime pt;
474
475  *source = partime (*source, &pt);
476  if (pt.zone == TM_UNDEFINED_ZONE)
477    pt.zone = default_zone;
478  return maketime (&pt, default_time);
479}
480
481#ifdef TEST
482#include <stdio.h>
483int
484main (argc, argv)
485     int argc;
486     char **argv;
487{
488  time_t default_time = time ((time_t *) 0);
489  long default_zone = argv[1] ? atol (argv[1]) : TM_LOCAL_ZONE;
490  char buf[1000];
491  while (fgets (buf, sizeof (buf), stdin))
492    {
493      char const *p = buf;
494      time_t t = str2time (&p, default_time, default_zone);
495      printf ("`%.*s' -> %s",
496	      (int) (p - buf - (p[0] == '\0' && p[-1] == '\n')), buf,
497	      asctime ((argv[1] ? gmtime : localtime) (&t)));
498    }
499  return 0;
500}
501#endif
502