1/* Convert struct partime into time_t.  */
2
3/* Copyright 1992, 1993, 1994, 1995 Paul Eggert
4   Distributed under license by the Free Software Foundation, Inc.
5
6This file is part of RCS.
7
8RCS is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 2, or (at your option)
11any later version.
12
13RCS is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with RCS; see the file COPYING.
20If not, write to the Free Software Foundation,
2159 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22
23Report problems and direct all questions to:
24
25    rcs-bugs@cs.purdue.edu
26
27*/
28
29#if has_conf_h
30#	include "conf.h"
31#else
32#	ifdef __STDC__
33#		define P(x) x
34#	else
35#		define const
36#		define P(x) ()
37#	endif
38#	include <stdlib.h>
39#	include <time.h>
40#endif
41
42#include "partime.h"
43#include "maketime.h"
44
45char const maketId[]
46  = "$Id: maketime.c 3476 2003-06-11 15:56:10Z darkwyrm $";
47
48static int isleap P((int));
49static int month_days P((struct tm const*));
50static time_t maketime P((struct partime const*,time_t));
51
52/*
53* For maximum portability, use only localtime and gmtime.
54* Make no assumptions about the time_t epoch or the range of time_t values.
55* Avoid mktime because it's not universal and because there's no easy,
56* portable way for mktime to yield the inverse of gmtime.
57*/
58
59#define TM_YEAR_ORIGIN 1900
60
61	static int
62isleap(y)
63	int y;
64{
65	return (y&3) == 0  &&  (y%100 != 0 || y%400 == 0);
66}
67
68static int const month_yday[] = {
69	/* days in year before start of months 0-12 */
70	0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
71};
72
73/* Yield the number of days in TM's month.  */
74	static int
75month_days(tm)
76	struct tm const *tm;
77{
78	int m = tm->tm_mon;
79	return month_yday[m+1] - month_yday[m]
80		+ (m==1 && isleap(tm->tm_year + TM_YEAR_ORIGIN));
81}
82
83/*
84* Convert UNIXTIME to struct tm form.
85* Use gmtime if available and if !LOCALZONE, localtime otherwise.
86*/
87	struct tm *
88time2tm(unixtime, localzone)
89	time_t unixtime;
90	int localzone;
91{
92	struct tm *tm;
93#	if TZ_must_be_set
94		static char const *TZ;
95		if (!TZ  &&  !(TZ = getenv("TZ")))
96			faterror("The TZ environment variable is not set; please set it to your timezone");
97#	endif
98	if (localzone  ||  !(tm = gmtime(&unixtime)))
99		tm = localtime(&unixtime);
100	return tm;
101}
102
103/* Yield A - B, measured in seconds.  */
104	time_t
105difftm(a, b)
106	struct tm const *a, *b;
107{
108	int ay = a->tm_year + (TM_YEAR_ORIGIN - 1);
109	int by = b->tm_year + (TM_YEAR_ORIGIN - 1);
110	int difference_in_day_of_year = a->tm_yday - b->tm_yday;
111	int intervening_leap_days = (
112		((ay >> 2) - (by >> 2))
113		- (ay/100 - by/100)
114		+ ((ay/100 >> 2) - (by/100 >> 2))
115	);
116	time_t difference_in_years = ay - by;
117	time_t difference_in_days = (
118		difference_in_years*365
119		+ (intervening_leap_days + difference_in_day_of_year)
120	);
121	return
122		(
123			(
124				24*difference_in_days
125				+ (a->tm_hour - b->tm_hour)
126			)*60 + (a->tm_min - b->tm_min)
127		)*60 + (a->tm_sec - b->tm_sec);
128}
129
130/*
131* Adjust time T by adding SECONDS.  SECONDS must be at most 24 hours' worth.
132* Adjust only T's year, mon, mday, hour, min and sec members;
133* plus adjust wday if it is defined.
134*/
135	void
136adjzone(t, seconds)
137	register struct tm *t;
138	long seconds;
139{
140	/*
141	* This code can be off by a second if SECONDS is not a multiple of 60,
142	* if T is local time, and if a leap second happens during this minute.
143	* But this bug has never occurred, and most likely will not ever occur.
144	* Liberia, the last country for which SECONDS % 60 was nonzero,
145	* switched to UTC in May 1972; the first leap second was in June 1972.
146	*/
147	int leap_second = t->tm_sec == 60;
148	long sec = seconds + (t->tm_sec - leap_second);
149	if (sec < 0) {
150	    if ((t->tm_min -= (59-sec)/60) < 0) {
151		if ((t->tm_hour -= (59-t->tm_min)/60) < 0) {
152		    t->tm_hour += 24;
153		    if (TM_DEFINED(t->tm_wday)  &&  --t->tm_wday < 0)
154			t->tm_wday = 6;
155		    if (--t->tm_mday <= 0) {
156			if (--t->tm_mon < 0) {
157			    --t->tm_year;
158			    t->tm_mon = 11;
159			}
160			t->tm_mday = month_days(t);
161		    }
162		}
163		t->tm_min += 24 * 60;
164	    }
165	    sec += 24L * 60 * 60;
166	} else
167	    if (60 <= (t->tm_min += sec/60))
168		if (24 <= (t->tm_hour += t->tm_min/60)) {
169		    t->tm_hour -= 24;
170		    if (TM_DEFINED(t->tm_wday)  &&  ++t->tm_wday == 7)
171			t->tm_wday = 0;
172		    if (month_days(t) < ++t->tm_mday) {
173			if (11 < ++t->tm_mon) {
174			    ++t->tm_year;
175			    t->tm_mon = 0;
176			}
177			t->tm_mday = 1;
178		    }
179		}
180	t->tm_min %= 60;
181	t->tm_sec = (int) (sec%60) + leap_second;
182}
183
184/*
185* Convert TM to time_t, using localtime if LOCALZONE and gmtime otherwise.
186* Use only TM's year, mon, mday, hour, min, and sec members.
187* Ignore TM's old tm_yday and tm_wday, but fill in their correct values.
188* Yield -1 on failure (e.g. a member out of range).
189* Posix 1003.1-1990 doesn't allow leap seconds, but some implementations
190* have them anyway, so allow them if localtime/gmtime does.
191*/
192	time_t
193tm2time(tm, localzone)
194	struct tm *tm;
195	int localzone;
196{
197	/* Cache the most recent t,tm pairs; 1 for gmtime, 1 for localtime.  */
198	static time_t t_cache[2];
199	static struct tm tm_cache[2];
200
201	time_t d, gt;
202	struct tm const *gtm;
203	/*
204	* The maximum number of iterations should be enough to handle any
205	* combinations of leap seconds, time zone rule changes, and solar time.
206	* 4 is probably enough; we use a bigger number just to be safe.
207	*/
208	int remaining_tries = 8;
209
210	/* Avoid subscript errors.  */
211	if (12 <= (unsigned)tm->tm_mon)
212	    return -1;
213
214	tm->tm_yday = month_yday[tm->tm_mon] + tm->tm_mday
215		-  (tm->tm_mon<2  ||  ! isleap(tm->tm_year + TM_YEAR_ORIGIN));
216
217	/* Make a first guess.  */
218	gt = t_cache[localzone];
219	gtm = gt ? &tm_cache[localzone] : time2tm(gt,localzone);
220
221	/* Repeatedly use the error from the guess to improve the guess.  */
222	while ((d = difftm(tm, gtm)) != 0) {
223		if (--remaining_tries == 0)
224			return -1;
225		gt += d;
226		gtm = time2tm(gt,localzone);
227	}
228	t_cache[localzone] = gt;
229	tm_cache[localzone] = *gtm;
230
231	/*
232	* Check that the guess actually matches;
233	* overflow can cause difftm to yield 0 even on differing times,
234	* or tm may have members out of range (e.g. bad leap seconds).
235	*/
236	if (   (tm->tm_year ^ gtm->tm_year)
237	    |  (tm->tm_mon  ^ gtm->tm_mon)
238	    |  (tm->tm_mday ^ gtm->tm_mday)
239	    |  (tm->tm_hour ^ gtm->tm_hour)
240	    |  (tm->tm_min  ^ gtm->tm_min)
241	    |  (tm->tm_sec  ^ gtm->tm_sec))
242		return -1;
243
244	tm->tm_wday = gtm->tm_wday;
245	return gt;
246}
247
248/*
249* Check *PT and convert it to time_t.
250* If it is incompletely specified, use DEFAULT_TIME to fill it out.
251* Use localtime if PT->zone is the special value TM_LOCAL_ZONE.
252* Yield -1 on failure.
253* ISO 8601 day-of-year and week numbers are not yet supported.
254*/
255	static time_t
256maketime(pt, default_time)
257	struct partime const *pt;
258	time_t default_time;
259{
260	int localzone, wday;
261	struct tm tm;
262	struct tm *tm0 = 0;
263	time_t r;
264
265	tm0 = 0; /* Keep gcc -Wall happy.  */
266	localzone = pt->zone==TM_LOCAL_ZONE;
267
268	tm = pt->tm;
269
270	if (TM_DEFINED(pt->ymodulus) || !TM_DEFINED(tm.tm_year)) {
271	    /* Get tm corresponding to current time.  */
272	    tm0 = time2tm(default_time, localzone);
273	    if (!localzone)
274		adjzone(tm0, pt->zone);
275	}
276
277	if (TM_DEFINED(pt->ymodulus))
278	    tm.tm_year +=
279		(tm0->tm_year + TM_YEAR_ORIGIN)/pt->ymodulus * pt->ymodulus;
280	else if (!TM_DEFINED(tm.tm_year)) {
281	    /* Set default year, month, day from current time.  */
282	    tm.tm_year = tm0->tm_year + TM_YEAR_ORIGIN;
283	    if (!TM_DEFINED(tm.tm_mon)) {
284		tm.tm_mon = tm0->tm_mon;
285		if (!TM_DEFINED(tm.tm_mday))
286		    tm.tm_mday = tm0->tm_mday;
287	    }
288	}
289
290	/* Convert from partime year (Gregorian) to Posix year.  */
291	tm.tm_year -= TM_YEAR_ORIGIN;
292
293	/* Set remaining default fields to be their minimum values.  */
294	if (!TM_DEFINED(tm.tm_mon)) tm.tm_mon = 0;
295	if (!TM_DEFINED(tm.tm_mday)) tm.tm_mday = 1;
296	if (!TM_DEFINED(tm.tm_hour)) tm.tm_hour = 0;
297	if (!TM_DEFINED(tm.tm_min)) tm.tm_min = 0;
298	if (!TM_DEFINED(tm.tm_sec)) tm.tm_sec = 0;
299
300	if (!localzone)
301	    adjzone(&tm, -pt->zone);
302	wday = tm.tm_wday;
303
304	/* Convert and fill in the rest of the tm.  */
305	r = tm2time(&tm, localzone);
306
307	/* Check weekday.  */
308	if (r != -1  &&  TM_DEFINED(wday)  &&  wday != tm.tm_wday)
309		return -1;
310
311	return r;
312}
313
314/* Parse a free-format date in SOURCE, yielding a Unix format time.  */
315	time_t
316str2time(source, default_time, default_zone)
317	char const *source;
318	time_t default_time;
319	long default_zone;
320{
321	struct partime pt;
322
323	if (*partime(source, &pt))
324	    return -1;
325	if (pt.zone == TM_UNDEFINED_ZONE)
326	    pt.zone = default_zone;
327	return maketime(&pt, default_time);
328}
329
330#if TEST
331#include <stdio.h>
332	int
333main(argc, argv) int argc; char **argv;
334{
335	time_t default_time = time((time_t *)0);
336	long default_zone = argv[1] ? atol(argv[1]) : 0;
337	char buf[1000];
338	while (gets(buf)) {
339		time_t t = str2time(buf, default_time, default_zone);
340		printf("%s", asctime(gmtime(&t)));
341	}
342	return 0;
343}
344#endif
345