mark all block comments that need format preserving so that
[openssl.git] / crypto / o_time.c
1 /* crypto/o_time.c -*- mode:C; c-file-style: "eay" -*- */
2 /* Written by Richard Levitte (richard@levitte.org) for the OpenSSL
3  * project 2001.
4  */
5 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
6  * project 2008.
7  */
8 /* ====================================================================
9  * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  *
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer. 
17  *
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in
20  *    the documentation and/or other materials provided with the
21  *    distribution.
22  *
23  * 3. All advertising materials mentioning features or use of this
24  *    software must display the following acknowledgment:
25  *    "This product includes software developed by the OpenSSL Project
26  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
27  *
28  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
29  *    endorse or promote products derived from this software without
30  *    prior written permission. For written permission, please contact
31  *    licensing@OpenSSL.org.
32  *
33  * 5. Products derived from this software may not be called "OpenSSL"
34  *    nor may "OpenSSL" appear in their names without prior written
35  *    permission of the OpenSSL Project.
36  *
37  * 6. Redistributions of any form whatsoever must retain the following
38  *    acknowledgment:
39  *    "This product includes software developed by the OpenSSL Project
40  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
41  *
42  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
43  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
45  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
46  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
47  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
48  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
49  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53  * OF THE POSSIBILITY OF SUCH DAMAGE.
54  * ====================================================================
55  *
56  * This product includes cryptographic software written by Eric Young
57  * (eay@cryptsoft.com).  This product includes software written by Tim
58  * Hudson (tjh@cryptsoft.com).
59  *
60  */
61
62 #include <openssl/e_os2.h>
63 #include <string.h>
64 #include "o_time.h"
65
66 #ifdef OPENSSL_SYS_VMS
67 # if __CRTL_VER >= 70000000 && \
68      (defined _POSIX_C_SOURCE || !defined _ANSI_C_SOURCE)
69 #  define VMS_GMTIME_OK
70 # endif
71 # ifndef VMS_GMTIME_OK
72 #  include <libdtdef.h>
73 #  include <lib$routines.h>
74 #  include <lnmdef.h>
75 #  include <starlet.h>
76 #  include <descrip.h>
77 #  include <stdlib.h>
78 # endif /* ndef VMS_GMTIME_OK */
79 #endif
80
81 struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result)
82         {
83         struct tm *ts = NULL;
84
85 #if defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_OS2) && (!defined(OPENSSL_SYS_VMS) || defined(gmtime_r)) && !defined(OPENSSL_SYS_MACOSX) && !defined(OPENSSL_SYS_SUNOS)
86         /* should return &data, but doesn't on some systems,
87            so we don't even look at the return value */
88         gmtime_r(timer,result);
89         ts = result;
90 #elif !defined(OPENSSL_SYS_VMS) || defined(VMS_GMTIME_OK)
91         ts = gmtime(timer);
92         if (ts == NULL)
93                 return NULL;
94
95         memcpy(result, ts, sizeof(struct tm));
96         ts = result;
97 #endif
98 #if defined( OPENSSL_SYS_VMS) && !defined( VMS_GMTIME_OK)
99         if (ts == NULL)
100                 {
101                 static $DESCRIPTOR(tabnam,"LNM$DCL_LOGICAL");
102                 static $DESCRIPTOR(lognam,"SYS$TIMEZONE_DIFFERENTIAL");
103                 char logvalue[256];
104                 unsigned int reslen = 0;
105                 struct {
106                         short buflen;
107                         short code;
108                         void *bufaddr;
109                         unsigned int *reslen;
110                 } itemlist[] = {
111                         { 0, LNM$_STRING, 0, 0 },
112                         { 0, 0, 0, 0 },
113                 };
114                 int status;
115                 time_t t;
116
117                 /* Get the value for SYS$TIMEZONE_DIFFERENTIAL */
118                 itemlist[0].buflen = sizeof(logvalue);
119                 itemlist[0].bufaddr = logvalue;
120                 itemlist[0].reslen = &reslen;
121                 status = sys$trnlnm(0, &tabnam, &lognam, 0, itemlist);
122                 if (!(status & 1))
123                         return NULL;
124                 logvalue[reslen] = '\0';
125
126                 t = *timer;
127
128 /* The following is extracted from the DEC C header time.h */
129 /*
130 **  Beginning in OpenVMS Version 7.0 mktime, time, ctime, strftime
131 **  have two implementations.  One implementation is provided
132 **  for compatibility and deals with time in terms of local time,
133 **  the other __utc_* deals with time in terms of UTC.
134 */
135 /* We use the same conditions as in said time.h to check if we should
136    assume that t contains local time (and should therefore be adjusted)
137    or UTC (and should therefore be left untouched). */
138 #if __CRTL_VER < 70000000 || defined _VMS_V6_SOURCE
139                 /* Get the numerical value of the equivalence string */
140                 status = atoi(logvalue);
141
142                 /* and use it to move time to GMT */
143                 t -= status;
144 #endif
145
146                 /* then convert the result to the time structure */
147
148                 /* Since there was no gmtime_r() to do this stuff for us,
149                    we have to do it the hard way. */
150                 {
151                 /*-
152                  * The VMS epoch is the astronomical Smithsonian date,
153                    if I remember correctly, which is November 17, 1858.
154                    Furthermore, time is measure in thenths of microseconds
155                    and stored in quadwords (64 bit integers).  unix_epoch
156                    below is January 1st 1970 expressed as a VMS time.  The
157                    following code was used to get this number:
158
159                    #include <stdio.h>
160                    #include <stdlib.h>
161                    #include <lib$routines.h>
162                    #include <starlet.h>
163
164                    main()
165                    {
166                      unsigned long systime[2];
167                      unsigned short epoch_values[7] =
168                        { 1970, 1, 1, 0, 0, 0, 0 };
169
170                      lib$cvt_vectim(epoch_values, systime);
171
172                      printf("%u %u", systime[0], systime[1]);
173                    }
174                 */
175                 unsigned long unix_epoch[2] = { 1273708544, 8164711 };
176                 unsigned long deltatime[2];
177                 unsigned long systime[2];
178                 struct vms_vectime
179                         {
180                         short year, month, day, hour, minute, second,
181                                 centi_second;
182                         } time_values;
183                 long operation;
184
185                 /* Turn the number of seconds since January 1st 1970 to
186                    an internal delta time.
187                    Note that lib$cvt_to_internal_time() will assume
188                    that t is signed, and will therefore break on 32-bit
189                    systems some time in 2038.
190                 */
191                 operation = LIB$K_DELTA_SECONDS;
192                 status = lib$cvt_to_internal_time(&operation,
193                         &t, deltatime);
194
195                 /* Add the delta time with the Unix epoch and we have
196                    the current UTC time in internal format */
197                 status = lib$add_times(unix_epoch, deltatime, systime);
198
199                 /* Turn the internal time into a time vector */
200                 status = sys$numtim(&time_values, systime);
201
202                 /* Fill in the struct tm with the result */
203                 result->tm_sec = time_values.second;
204                 result->tm_min = time_values.minute;
205                 result->tm_hour = time_values.hour;
206                 result->tm_mday = time_values.day;
207                 result->tm_mon = time_values.month - 1;
208                 result->tm_year = time_values.year - 1900;
209
210                 operation = LIB$K_DAY_OF_WEEK;
211                 status = lib$cvt_from_internal_time(&operation,
212                         &result->tm_wday, systime);
213                 result->tm_wday %= 7;
214
215                 operation = LIB$K_DAY_OF_YEAR;
216                 status = lib$cvt_from_internal_time(&operation,
217                         &result->tm_yday, systime);
218                 result->tm_yday--;
219
220                 result->tm_isdst = 0; /* There's no way to know... */
221
222                 ts = result;
223                 }
224                 }
225 #endif
226         return ts;
227         }
228
229 /* Take a tm structure and add an offset to it. This avoids any OS issues
230  * with restricted date types and overflows which cause the year 2038
231  * problem.
232  */
233
234 #define SECS_PER_DAY (24 * 60 * 60)
235
236 static long date_to_julian(int y, int m, int d);
237 static void julian_to_date(long jd, int *y, int *m, int *d);
238
239 int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec)
240         {
241         int offset_hms, offset_day;
242         long time_jd;
243         int time_year, time_month, time_day;
244         /* split offset into days and day seconds */
245         offset_day = offset_sec / SECS_PER_DAY;
246         /* Avoid sign issues with % operator */
247         offset_hms  = offset_sec - (offset_day * SECS_PER_DAY);
248         offset_day += off_day;
249         /* Add current time seconds to offset */
250         offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
251         /* Adjust day seconds if overflow */
252         if (offset_hms >= SECS_PER_DAY)
253                 {
254                 offset_day++;
255                 offset_hms -= SECS_PER_DAY;
256                 }
257         else if (offset_hms < 0)
258                 {
259                 offset_day--;
260                 offset_hms += SECS_PER_DAY;
261                 }
262
263         /* Convert date of time structure into a Julian day number.
264          */
265
266         time_year = tm->tm_year + 1900;
267         time_month = tm->tm_mon + 1;
268         time_day = tm->tm_mday;
269
270         time_jd = date_to_julian(time_year, time_month, time_day);
271
272         /* Work out Julian day of new date */
273         time_jd += offset_day;
274
275         if (time_jd < 0)
276                 return 0;
277
278         /* Convert Julian day back to date */
279
280         julian_to_date(time_jd, &time_year, &time_month, &time_day);
281
282         if (time_year < 1900 || time_year > 9999)
283                 return 0;
284
285         /* Update tm structure */
286
287         tm->tm_year = time_year - 1900;
288         tm->tm_mon = time_month - 1;
289         tm->tm_mday = time_day;
290
291         tm->tm_hour = offset_hms / 3600;
292         tm->tm_min = (offset_hms / 60) % 60;
293         tm->tm_sec = offset_hms % 60;
294
295         return 1;
296                 
297 }
298
299 /* Convert date to and from julian day
300  * Uses Fliegel & Van Flandern algorithm
301  */
302 static long date_to_julian(int y, int m, int d)
303 {
304         return (1461 * (y + 4800 + (m - 14) / 12)) / 4 +
305                 (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
306                 (3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 +
307                 d - 32075;
308 }
309
310 static void julian_to_date(long jd, int *y, int *m, int *d)
311         {
312         long  L = jd + 68569;
313         long  n = (4 * L) / 146097;
314         long  i, j;
315
316         L = L - (146097 * n + 3) / 4;
317         i = (4000 * (L + 1)) / 1461001;
318         L = L - (1461 * i) / 4 + 31;
319         j = (80 * L) / 2447;
320         *d = L - (2447 * j) / 80;
321         L = j / 11;
322         *m = j + 2 - (12 * L);
323         *y = 100 * (n - 49) + i + L;
324         }
325
326 #ifdef OPENSSL_TIME_TEST
327
328 #include <stdio.h>
329
330 /* Time checking test code. Check times are identical for a wide range of
331  * offsets. This should be run on a machine with 64 bit time_t or it will
332  * trigger the very errors the routines fix.
333  */
334
335 int main(int argc, char **argv)
336         {
337         long offset;
338         for (offset = 0; offset < 1000000; offset++)
339                 {
340                 check_time(offset);
341                 check_time(-offset);
342                 check_time(offset * 1000);
343                 check_time(-offset * 1000);
344                 }
345         }
346
347 int check_time(long offset)
348         {
349         struct tm tm1, tm2;
350         time_t t1, t2;
351         time(&t1);
352         t2 = t1 + offset;
353         OPENSSL_gmtime(&t2, &tm2);
354         OPENSSL_gmtime(&t1, &tm1);
355         OPENSSL_gmtime_adj(&tm1, 0, offset);
356         if ((tm1.tm_year == tm2.tm_year) &&
357             (tm1.tm_mon == tm2.tm_mon) &&
358             (tm1.tm_mday == tm2.tm_mday) &&
359             (tm1.tm_hour == tm2.tm_hour) &&
360             (tm1.tm_min == tm2.tm_min) &&
361             (tm1.tm_sec == tm2.tm_sec))
362                 return 1;
363         fprintf(stderr, "TIME ERROR!!\n");
364         fprintf(stderr, "Time1: %d/%d/%d, %d:%02d:%02d\n",
365                         tm2.tm_mday, tm2.tm_mon + 1, tm2.tm_year + 1900,
366                         tm2.tm_hour, tm2.tm_min, tm2.tm_sec);
367         fprintf(stderr, "Time2: %d/%d/%d, %d:%02d:%02d\n",
368                         tm1.tm_mday, tm1.tm_mon + 1, tm1.tm_year + 1900,
369                         tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
370         return 0;
371         }
372
373 #endif