2 * Copyright (c) 2003-2017 Lev Walkin <vlm@lionet.info>. All rights reserved.
3 * Redistribution and modifications are permitted subject to BSD license.
5 #define _POSIX_PTHREAD_SEMANTICS /* for Sun */
6 #define _REENTRANT /* for Sun */
7 #define __EXTENSIONS__ /* for Sun */
9 #define _BSD_SOURCE /* for timegm(3) */
11 #include <asn_internal.h>
12 #include <GeneralizedTime.h>
15 #include "/usr/include/time.h"
18 #endif /* __CYGWIN__ */
24 #pragma message( "PLEASE STOP AND READ!")
25 #pragma message( " localtime_r is implemented via localtime(), which may be not thread-safe.")
26 #pragma message( " gmtime_r is implemented via gmtime(), which may be not thread-safe.")
28 #pragma message( " You must fix the code by inserting appropriate locking")
29 #pragma message( " if you want to use asn_GT2time() or asn_UT2time().")
30 #pragma message( "PLEASE STOP AND READ!")
32 static struct tm *localtime_r(const time_t *tloc, struct tm *result) {
34 if((tm = localtime(tloc)))
35 return memcpy(result, tm, sizeof(struct tm));
39 static struct tm *gmtime_r(const time_t *tloc, struct tm *result) {
41 if((tm = gmtime(tloc)))
42 return memcpy(result, tm, sizeof(struct tm));
46 #define tzset() _tzset()
47 #define putenv(c) _putenv(c)
48 #define _EMULATE_TIMEGM
52 #if defined(sun) || defined(__sun) || defined(__solaris__)
53 #define _EMULATE_TIMEGM
57 * Where to look for offset from GMT, Phase I.
58 * Several platforms are known.
60 #if defined(__FreeBSD__) \
61 || (defined(__GNUC__) && defined(__APPLE_CC__)) \
62 || (defined __GLIBC__ && __GLIBC__ >= 2)
64 #define HAVE_TM_GMTOFF
65 #endif /* BSDs and newer glibc */
68 * Where to look for offset from GMT, Phase II.
71 #define GMTOFF(tm) ((tm).tm_gmtoff)
72 #else /* HAVE_TM_GMTOFF */
73 #define GMTOFF(tm) (-timezone)
74 #endif /* HAVE_TM_GMTOFF */
77 #pragma message( "PLEASE STOP AND READ!")
78 #pragma message( " timegm() is implemented via getenv(\"TZ\")/setenv(\"TZ\"), which may be not thread-safe.")
80 #pragma message( " You must fix the code by inserting appropriate locking")
81 #pragma message( " if you want to use asn_GT2time() or asn_UT2time().")
82 #pragma message( "PLEASE STOP AND READ!")
84 #if (defined(_EMULATE_TIMEGM) || !defined(HAVE_TM_GMTOFF))
85 #warning "PLEASE STOP AND READ!"
86 #warning " timegm() is implemented via getenv(\"TZ\")/setenv(\"TZ\"), which may be not thread-safe."
88 #warning " You must fix the code by inserting appropriate locking"
89 #warning " if you want to use asn_GT2time() or asn_UT2time()."
90 #warning "PLEASE STOP AND READ!"
91 #endif /* _EMULATE_TIMEGM */
95 * Override our GMTOFF decision for other known platforms.
99 static long GMTOFF(struct tm a){
101 time_t local_time, gmt_time;
105 gmt_time = time (NULL);
107 lt = gmtime(&gmt_time);
109 local_time = mktime(lt);
110 return (gmt_time - local_time);
112 #define _EMULATE_TIMEGM
114 #endif /* __CYGWIN__ */
116 #define ATZVARS do { \
119 #define ATZSAVETZ do { \
120 tzold = getenv("TZ"); \
122 size_t tzlen = strlen(tzold); \
123 if(tzlen < sizeof(tzoldbuf)) { \
124 tzold = memcpy(tzoldbuf, tzold, tzlen + 1); \
126 char *dupptr = tzold; \
127 tzold = MALLOC(tzlen + 1); \
128 if(tzold) memcpy(tzold, dupptr, tzlen + 1); \
130 setenv("TZ", "UTC", 1); \
134 #define ATZOLDTZ do { \
136 setenv("TZ", tzold, 1); \
138 if(tzold != tzoldbuf) \
144 } while(0); } while(0);
147 #ifdef _EMULATE_TIMEGM
149 static time_t timegm(struct tm *tm) {
157 #endif /* _EMULATE_TIMEGM */
161 #ifndef ASN___INTERNAL_TEST_MODE
164 * GeneralizedTime basic type description.
166 static const ber_tlv_tag_t asn_DEF_GeneralizedTime_tags[] = {
167 (ASN_TAG_CLASS_UNIVERSAL | (24 << 2)), /* [UNIVERSAL 24] IMPLICIT ...*/
168 (ASN_TAG_CLASS_UNIVERSAL | (26 << 2)), /* [UNIVERSAL 26] IMPLICIT ...*/
169 (ASN_TAG_CLASS_UNIVERSAL | (4 << 2)) /* ... OCTET STRING */
171 static asn_per_constraints_t asn_DEF_GeneralizedTime_per_constraints = {
172 { APC_CONSTRAINED, 7, 7, 0x20, 0x7e }, /* Value */
173 { APC_SEMI_CONSTRAINED, -1, -1, 0, 0 }, /* Size */
176 asn_TYPE_operation_t asn_OP_GeneralizedTime = {
178 GeneralizedTime_print,
179 GeneralizedTime_compare,
180 OCTET_STRING_decode_ber, /* Implemented in terms of OCTET STRING */
181 GeneralizedTime_encode_der,
182 OCTET_STRING_decode_xer_utf8,
183 GeneralizedTime_encode_xer,
184 #ifdef ASN_DISABLE_OER_SUPPORT
188 OCTET_STRING_decode_oer,
189 OCTET_STRING_encode_oer,
190 #endif /* ASN_DISABLE_OER_SUPPORT */
191 #ifdef ASN_DISABLE_PER_SUPPORT
197 OCTET_STRING_decode_uper,
198 OCTET_STRING_encode_uper,
199 OCTET_STRING_decode_aper,
200 OCTET_STRING_encode_aper,
201 #endif /* ASN_DISABLE_PER_SUPPORT */
202 GeneralizedTime_random_fill,
203 0 /* Use generic outmost tag fetcher */
205 asn_TYPE_descriptor_t asn_DEF_GeneralizedTime = {
208 &asn_OP_GeneralizedTime,
209 asn_DEF_GeneralizedTime_tags,
210 sizeof(asn_DEF_GeneralizedTime_tags)
211 / sizeof(asn_DEF_GeneralizedTime_tags[0]) - 2,
212 asn_DEF_GeneralizedTime_tags,
213 sizeof(asn_DEF_GeneralizedTime_tags)
214 / sizeof(asn_DEF_GeneralizedTime_tags[0]),
215 { 0, &asn_DEF_GeneralizedTime_per_constraints, GeneralizedTime_constraint },
216 0, 0, /* No members */
220 #endif /* ASN___INTERNAL_TEST_MODE */
223 * Check that the time looks like the time.
226 GeneralizedTime_constraint(const asn_TYPE_descriptor_t *td, const void *sptr,
227 asn_app_constraint_failed_f *ctfailcb,
229 const GeneralizedTime_t *st = (const GeneralizedTime_t *)sptr;
232 errno = EPERM; /* Just an unlikely error code */
233 tloc = asn_GT2time(st, 0, 0);
234 if(tloc == -1 && errno != EPERM) {
235 ASN__CTFAIL(app_key, td, sptr,
236 "%s: Invalid time format: %s (%s:%d)",
237 td->name, strerror(errno), __FILE__, __LINE__);
245 GeneralizedTime_encode_der(const asn_TYPE_descriptor_t *td, const void *sptr,
246 int tag_mode, ber_tlv_tag_t tag,
247 asn_app_consume_bytes_f *cb, void *app_key) {
248 GeneralizedTime_t *st;
249 asn_enc_rval_t erval = {0,0,0};
250 int fv, fd; /* seconds fraction value and number of digits */
255 * Encode as a canonical DER.
258 tloc = asn_GT2time_frac((const GeneralizedTime_t *)sptr, &fv, &fd, &tm,
259 1); /* Recognize time */
260 if(tloc == -1 && errno != EPERM) {
261 /* Failed to recognize time. Fail completely. */
265 st = asn_time2GT_frac(0, &tm, fv, fd, 1); /* Save time canonically */
266 if(!st) ASN__ENCODE_FAILED; /* Memory allocation failure. */
268 erval = OCTET_STRING_encode_der(td, st, tag_mode, tag, cb, app_key);
270 ASN_STRUCT_FREE(*td, st);
275 #ifndef ASN___INTERNAL_TEST_MODE
278 GeneralizedTime_encode_xer(const asn_TYPE_descriptor_t *td, const void *sptr,
279 int ilevel, enum xer_encoder_flags_e flags,
280 asn_app_consume_bytes_f *cb, void *app_key) {
281 if(flags & XER_F_CANONICAL) {
282 GeneralizedTime_t *gt;
284 int fv, fd; /* fractional parts */
288 if(asn_GT2time_frac((const GeneralizedTime_t *)sptr,
289 &fv, &fd, &tm, 1) == -1
293 gt = asn_time2GT_frac(0, &tm, fv, fd, 1);
294 if(!gt) ASN__ENCODE_FAILED;
296 rv = OCTET_STRING_encode_xer_utf8(td, sptr, ilevel, flags,
298 ASN_STRUCT_FREE(asn_DEF_GeneralizedTime, gt);
301 return OCTET_STRING_encode_xer_utf8(td, sptr, ilevel, flags,
306 #endif /* ASN___INTERNAL_TEST_MODE */
309 GeneralizedTime_print(const asn_TYPE_descriptor_t *td, const void *sptr,
310 int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
311 const GeneralizedTime_t *st = (const GeneralizedTime_t *)sptr;
313 (void)td; /* Unused argument */
314 (void)ilevel; /* Unused argument */
322 if(asn_GT2time(st, &tm, 1) == -1 && errno != EPERM)
323 return (cb("<bad-value>", 11, app_key) < 0) ? -1 : 0;
325 ret = snprintf(buf, sizeof(buf),
326 "%04d-%02d-%02d %02d:%02d:%02d (GMT)",
327 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
328 tm.tm_hour, tm.tm_min, tm.tm_sec);
329 assert(ret > 0 && ret < (int)sizeof(buf));
330 return (cb(buf, ret, app_key) < 0) ? -1 : 0;
332 return (cb("<absent>", 8, app_key) < 0) ? -1 : 0;
337 asn_GT2time(const GeneralizedTime_t *st, struct tm *ret_tm, int as_gmt) {
338 return asn_GT2time_frac(st, 0, 0, ret_tm, as_gmt);
342 asn_GT2time_prec(const GeneralizedTime_t *st, int *frac_value, int frac_digits, struct tm *ret_tm, int as_gmt) {
347 tloc = asn_GT2time_frac(st, &fv, &fd, ret_tm, as_gmt);
349 return asn_GT2time_frac(st, 0, 0, ret_tm, as_gmt);
350 if(fd == 0 || frac_digits <= 0) {
353 while(fd > frac_digits)
355 while(fd < frac_digits) {
356 if(fv < INT_MAX / 10) {
360 /* Too long precision request */
373 asn_GT2time_frac(const GeneralizedTime_t *st, int *frac_value, int *frac_digits, struct tm *ret_tm, int as_gmt) {
379 int gmtoff = 0; /* h + m */
380 int offset_specified = 0;
385 if(!st || !st->buf) {
390 end = buf + st->size;
399 * Decode first 10 bytes: "AAAAMMJJhh"
401 memset(&tm_s, 0, sizeof(tm_s));
404 #define B2F(var) do { \
405 unsigned ch = *buf; \
406 if(ch < 0x30 || ch > 0x39) { \
410 var = var * 10 + (ch - 0x30); \
414 #define B2T(var) B2F(tm_s.var)
416 B2T(tm_year); /* 1: A */
417 B2T(tm_year); /* 2: A */
418 B2T(tm_year); /* 3: A */
419 B2T(tm_year); /* 4: A */
420 B2T(tm_mon); /* 5: M */
421 B2T(tm_mon); /* 6: M */
422 B2T(tm_mday); /* 7: J */
423 B2T(tm_mday); /* 8: J */
424 B2T(tm_hour); /* 9: h */
425 B2T(tm_hour); /* 0: h */
427 if(buf == end) goto local_finish;
430 * Parse [mm[ss[(.|,)ffff]]]
434 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
435 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
436 tm_s.tm_min = (*buf++) - 0x30;
437 if(buf == end) { errno = EINVAL; return -1; }
440 case 0x2B: case 0x2D: /* +, - */
449 if(buf == end) goto local_finish;
452 * Parse [mm[ss[(.|,)ffff]]]
456 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
457 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
458 tm_s.tm_sec = (*buf++) - 0x30;
459 if(buf == end) { errno = EINVAL; return -1; }
462 case 0x2B: case 0x2D: /* +, - */
471 if(buf == end) goto local_finish;
474 * Parse [mm[ss[(.|,)ffff]]]
478 case 0x2C: case 0x2E: /* (.|,) */
480 * Process fractions of seconds.
482 for(buf++; buf < end; buf++) {
484 /* GCC 4.x is being too smart without volatile */
486 case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
487 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
488 if(fvalue < INT_MAX/10) {
489 fvalue = fvalue * 10 + (v - 0x30);
492 /* Not enough precision, ignore */
502 if(buf == end) goto local_finish;
505 case 0x2B: case 0x2D: /* +, - */
524 if(buf[-3] == 0x2D) /* Negative */
529 if((end - buf) == 2) {
532 } else if(end != buf) {
537 gmtoff = gmtoff * (3600 * gmtoff_h + 60 * gmtoff_m);
542 offset_specified = 1;
550 if((tm_s.tm_mon > 12 || tm_s.tm_mon < 1)
551 || (tm_s.tm_mday > 31 || tm_s.tm_mday < 1)
552 || (tm_s.tm_hour > 23)
553 || (tm_s.tm_sec > 60)
560 tm_s.tm_mon -= 1; /* 0 - 11 */
561 tm_s.tm_year -= 1900;
564 tm_s.tm_sec -= gmtoff;
566 /*** AT THIS POINT tm_s is either GMT or local (unknown) ****/
568 if(offset_specified) {
569 tloc = timegm(&tm_s);
572 * Without an offset (or "Z"),
573 * we can only guess that it is a local zone.
574 * Interpret it in this fashion.
576 tloc = mktime(&tm_s);
585 if(offset_specified) {
588 if(gmtime_r(&tloc, ret_tm) == 0) {
594 if(localtime_r(&tloc, ret_tm) == 0) {
601 /* Fractions of seconds */
602 if(frac_value) *frac_value = fvalue;
603 if(frac_digits) *frac_digits = fdigits;
609 asn_time2GT(GeneralizedTime_t *opt_gt, const struct tm *tm, int force_gmt) {
610 return asn_time2GT_frac(opt_gt, tm, 0, 0, force_gmt);
614 asn_time2GT_frac(GeneralizedTime_t *opt_gt, const struct tm *tm, int frac_value, int frac_digits, int force_gmt) {
617 const unsigned int buf_size =
618 4 + 2 + 2 /* yyyymmdd */
619 + 2 + 2 + 2 /* hhmmss */
620 + 1 + 9 /* .fffffffff */
628 /* Check arguments */
634 /* Pre-allocate a buffer of sufficient yet small length */
635 buf = (char *)MALLOC(buf_size);
638 gmtoff = GMTOFF(*tm);
640 if(force_gmt && gmtoff) {
642 tm_s.tm_sec -= gmtoff;
643 timegm(&tm_s); /* Fix the time */
645 #ifdef HAVE_TM_GMTOFF
646 assert(!GMTOFF(tm_s)); /* Will fix itself */
647 #else /* !HAVE_TM_GMTOFF */
652 size = snprintf(buf, buf_size, "%04d%02d%02d%02d%02d%02d",
661 /* Could be assert(size == 14); */
670 * Deal with fractions.
672 if(frac_value > 0 && frac_digits > 0) {
673 char *end = p + 1 + 9; /* '.' + maximum 9 digits */
678 /* Place bounds on precision */
679 while(frac_digits-- > 9)
682 /* emulate fbase = pow(10, frac_digits) */
683 for(fbase = 1; frac_digits--;)
687 int digit = frac_value / fbase;
688 if(digit > 9) { z = 0; break; }
692 } while(fbase > 0 && frac_value > 0 && z < end);
694 for(--z; *z == 0x30; --z); /* Strip zeroes */
701 *p++ = 0x5a; /* "Z" */
707 ret = snprintf(p, buf_size - size, "%+03ld%02ld",
708 gmtoff / 3600, labs(gmtoff % 3600) / 60);
719 FREEMEM(opt_gt->buf);
721 opt_gt = (GeneralizedTime_t *)CALLOC(1, sizeof *opt_gt);
722 if(!opt_gt) { FREEMEM(buf); return 0; }
725 opt_gt->buf = (unsigned char *)buf;
731 asn_random_fill_result_t
732 GeneralizedTime_random_fill(const asn_TYPE_descriptor_t *td, void **sptr,
733 const asn_encoding_constraints_t *constraints,
735 asn_random_fill_result_t result_ok = {ARFILL_OK, 1};
736 asn_random_fill_result_t result_failed = {ARFILL_FAILED, 0};
737 asn_random_fill_result_t result_skipped = {ARFILL_SKIPPED, 0};
738 static const char *values[] = {
739 "19700101000000", "19700101000000-0000", "19700101000000+0000",
740 "19700101000000Z", "19700101000000.3Z", "19821106210623.3",
741 "19821106210629.3Z", "19691106210827.3-0500", "19821106210629.456",
743 size_t rnd = asn_random_between(0, sizeof(values)/sizeof(values[0])-1);
747 if(max_length < sizeof("yyyymmddhhmmss") && !*sptr) {
748 return result_skipped;
752 if(OCTET_STRING_fromBuf(*sptr, values[rnd], -1) != 0) {
753 if(!sptr) return result_failed;
756 *sptr = OCTET_STRING_new_fromBuf(td, values[rnd], -1);
757 if(!sptr) return result_failed;
764 GeneralizedTime_compare(const asn_TYPE_descriptor_t *td, const void *aptr,
766 const GeneralizedTime_t *a = aptr;
767 const GeneralizedTime_t *b = bptr;
772 int afrac_value, afrac_digits;
773 int bfrac_value, bfrac_digits;
778 at = asn_GT2time_frac(a, &afrac_value, &afrac_digits, 0, 0);
781 bt = asn_GT2time_frac(b, &bfrac_value, &bfrac_digits, 0, 0);
784 if(at == -1 && aerr != EPERM) {
785 if(bt == -1 && berr != EPERM) {
786 return OCTET_STRING_compare(td, aptr, bptr);
790 } else if(bt == -1 && berr != EPERM) {
793 /* Both values are valid. */
800 } else if(afrac_digits == bfrac_digits) {
801 if(afrac_value == bfrac_value) {
804 if(afrac_value < bfrac_value) {
809 } else if(afrac_digits == 0) {
811 } else if(bfrac_digits == 0) {
814 double afrac = (double)afrac_value / afrac_digits;
815 double bfrac = (double)bfrac_value / bfrac_digits;
818 } else if(afrac > bfrac) {
824 } else if(!a && !b) {