1 /*
2  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 #pragma ident	"%Z%%M%	%I%	%E% SMI"
7 
8 /* This code placed in the public domain by Mark W. Eichin */
9 
10 #include <stdio.h>
11 #include <k5-int.h>
12 
13 #ifdef HAVE_SYS_TYPES_H
14 #include <sys/types.h>
15 #endif
16 #ifdef HAVE_SYS_TIME_H
17 #include <sys/time.h>
18 #ifdef TIME_WITH_SYS_TIME
19 #include <time.h>
20 #endif
21 #else
22 #include <time.h>
23 #endif
24 
25 /* take a struct tm, return seconds from GMT epoch */
26 /* like mktime, this ignores tm_wday and tm_yday. */
27 /* unlike mktime, this does not set them... it only passes a return value. */
28 
29 static const int days_in_month[12] = {
30 0,				/* jan 31 */
31 31,				/* feb 28 */
32 59,				/* mar 31 */
33 90,				/* apr 30 */
34 120,				/* may 31 */
35 151,				/* jun 30 */
36 181,				/* jul 31 */
37 212,				/* aug 31 */
38 243,				/* sep 30 */
39 273,				/* oct 31 */
40 304,				/* nov 30 */
41 334				/* dec 31 */
42 };
43 
44 #define hasleapday(year) (year%400?(year%100?(year%4?0:1):0):1)
45 
46 time_t gmt_mktime(t)
47      struct tm* t;
48 {
49   time_t accum;
50 
51 #define assert_time(cnd) if(!(cnd)) return (time_t) -1
52 
53   assert_time(t->tm_year>=70);
54   assert_time(t->tm_year<=138);
55   assert_time(t->tm_mon>=0);
56   assert_time(t->tm_mon<=11);
57   assert_time(t->tm_mday>=1);
58   assert_time(t->tm_mday<=31);
59   assert_time(t->tm_hour>=0);
60   assert_time(t->tm_hour<=23);
61   assert_time(t->tm_min>=0);
62   assert_time(t->tm_min<=59);
63   assert_time(t->tm_sec>=0);
64   assert_time(t->tm_sec<=62);
65 
66 #undef assert_time
67 
68 
69   accum = t->tm_year - 70;
70   accum *= 365;			/* 365 days/normal year */
71 
72   /* add in leap day for all previous years */
73   accum += (t->tm_year - 69) / 4;
74   /* add in leap day for this year */
75   if(t->tm_mon >= 2)		/* march or later */
76     if(hasleapday((t->tm_year + 1900))) accum += 1;
77 
78   accum += days_in_month[t->tm_mon];
79   accum += t->tm_mday-1;	/* days of month are the only 1-based field */
80   accum *= 24;			/* 24 hour/day */
81   accum += t->tm_hour;
82   accum *= 60;			/* 60 minute/hour */
83   accum += t->tm_min;
84   accum *= 60;			/* 60 seconds/minute */
85   accum += t->tm_sec;
86 
87   return accum;
88 }
89