1 /*
2  * Copyright 2005 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 /*
9  * lib/kadm/str_conv.c
10  *
11  * Copyright 1995, 1999 by the Massachusetts Institute of Technology.
12  * All Rights Reserved.
13  *
14  * Export of this software from the United States of America may
15  *   require a specific license from the United States Government.
16  *   It is the responsibility of any person or organization contemplating
17  *   export to obtain such a license before exporting.
18  *
19  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
20  * distribute this software and its documentation for any purpose and
21  * without fee is hereby granted, provided that the above copyright
22  * notice appear in all copies and that both that copyright notice and
23  * this permission notice appear in supporting documentation, and that
24  * the name of M.I.T. not be used in advertising or publicity pertaining
25  * to distribution of the software without specific, written prior
26  * permission.  Furthermore if you modify this software you must label
27  * your software as modified software and not distribute it in such a
28  * fashion that it might be confused with the original M.I.T. software.
29  * M.I.T. makes no representations about the suitability of
30  * this software for any purpose.  It is provided "as is" without express
31  * or implied warranty.
32  *
33  */
34 
35 /*
36  * str_conv.c - Convert between strings and Kerberos internal data.
37  */
38 
39 /*
40  * Table of contents:
41  *
42  * String decoding:
43  * ----------------
44  * krb5_string_to_salttype()	- Convert string to salttype (krb5_int32)
45  * krb5_string_to_timestamp()	- Convert string to krb5_timestamp.
46  * krb5_string_to_deltat()	- Convert string to krb5_deltat.
47  *
48  * String encoding:
49  * ----------------
50  * krb5_salttype_to_string()	- Convert salttype (krb5_int32) to string.
51  * krb5_timestamp_to_string()	- Convert krb5_timestamp to string.
52  * krb5_timestamp_to_sfstring()	- Convert krb5_timestamp to short filled string
53  * krb5_deltat_to_string()	- Convert krb5_deltat to string.
54  */
55 
56 #include "k5-int.h"
57 #include <ctype.h>
58 
59 /* Salt type conversions */
60 
61 /*
62  * Local data structures.
63  */
64 struct salttype_lookup_entry {
65     krb5_int32		stt_enctype;		/* Salt type		*/
66     const char *	stt_specifier;		/* How to recognize it	*/
67     const char *	stt_output;		/* How to spit it out	*/
68 };
69 
70 /*
71  * Lookup tables.
72  */
73 
74 static const struct salttype_lookup_entry salttype_table[] = {
75 /* salt type			input specifier	output string  */
76 /*-----------------------------	--------------- ---------------*/
77 { KRB5_KDB_SALTTYPE_NORMAL,	"normal",	"Version 5"	  },
78 { KRB5_KDB_SALTTYPE_V4,		"v4",		"Version 4"	  },
79 { KRB5_KDB_SALTTYPE_NOREALM,	"norealm",	"Version 5 - No Realm" },
80 { KRB5_KDB_SALTTYPE_ONLYREALM,	"onlyrealm",	"Version 5 - Realm Only" },
81 { KRB5_KDB_SALTTYPE_SPECIAL,	"special",	"Special" },
82 { KRB5_KDB_SALTTYPE_AFS3,	"afs3",		"AFS version 3"    }
83 };
84 static const int salttype_table_nents = sizeof(salttype_table)/
85 					sizeof(salttype_table[0]);
86 
87 krb5_error_code KRB5_CALLCONV
88 krb5_string_to_salttype(char *string, krb5_int32 *salttypep)
89 {
90     int i;
91     int found;
92 
93     found = 0;
94     for (i=0; i<salttype_table_nents; i++) {
95 	if (!strcasecmp(string, salttype_table[i].stt_specifier)) {
96 	    found = 1;
97 	    *salttypep = salttype_table[i].stt_enctype;
98 	    break;
99 	}
100     }
101     return((found) ? 0 : EINVAL);
102 }
103 
104 /*
105  * Internal datatype to string routines.
106  *
107  * These routines return 0 for success, EINVAL for invalid parameter, ENOMEM
108  * if the supplied buffer/length will not contain the output.
109  */
110 krb5_error_code KRB5_CALLCONV
111 krb5_salttype_to_string(krb5_int32 salttype, char *buffer, size_t buflen)
112 {
113     int i;
114     const char *out;
115 
116     out = (char *) NULL;
117     for (i=0; i<salttype_table_nents; i++) {
118 	if (salttype ==  salttype_table[i].stt_enctype) {
119 	    out = salttype_table[i].stt_output;
120 	    break;
121 	}
122     }
123     if (out) {
124 	if (buflen > strlen(out))
125 	    strcpy(buffer, out);
126 	else
127 	    out = (char *) NULL;
128 	return((out) ? 0 : ENOMEM);
129     }
130     else
131 	return(EINVAL);
132 }
133 
134 /* (absolute) time conversions */
135 
136 #ifndef HAVE_STRFTIME
137 #undef strftime
138 #define strftime my_strftime
139 static size_t strftime (char *, size_t, const char *, const struct tm *);
140 #endif
141 
142 #ifdef HAVE_STRPTIME
143 #ifdef NEED_STRPTIME_PROTO
144 extern char *strptime (const char *, const char *,
145 			    struct tm *)
146 #ifdef __cplusplus
147     throw()
148 #endif
149     ;
150 #endif
151 #else /* HAVE_STRPTIME */
152 #undef strptime
153 #define strptime my_strptime
154 static char *strptime (const char *, const char *, struct tm *);
155 #endif
156 
157 krb5_error_code KRB5_CALLCONV
158 krb5_string_to_timestamp(char *string, krb5_timestamp *timestampp)
159 {
160     int i;
161     struct tm timebuf;
162     time_t now, ret_time;
163     char *s;
164     static const char * const atime_format_table[] = {
165 	"%Y%m%d%H%M%S",		/* yyyymmddhhmmss		*/
166 	"%Y.%m.%d.%H.%M.%S",	/* yyyy.mm.dd.hh.mm.ss		*/
167 	"%y%m%d%H%M%S",		/* yymmddhhmmss			*/
168 	"%y.%m.%d.%H.%M.%S",	/* yy.mm.dd.hh.mm.ss		*/
169 	"%y%m%d%H%M",		/* yymmddhhmm			*/
170 	"%H%M%S",		/* hhmmss			*/
171 	"%H%M",			/* hhmm				*/
172 	"%T",			/* hh:mm:ss			*/
173 	"%R",			/* hh:mm			*/
174 	/* The following not really supported unless native strptime present */
175 	"%x:%X",		/* locale-dependent short format */
176 	"%d-%b-%Y:%T",		/* dd-month-yyyy:hh:mm:ss	*/
177 	"%d-%b-%Y:%R"		/* dd-month-yyyy:hh:mm		*/
178     };
179     static const int atime_format_table_nents =
180 	sizeof(atime_format_table)/sizeof(atime_format_table[0]);
181 
182 
183     now = time((time_t *) NULL);
184     for (i=0; i<atime_format_table_nents; i++) {
185         /* We reset every time throughout the loop as the manual page
186 	 * indicated that no guarantees are made as to preserving timebuf
187 	 * when parsing fails
188 	 */
189 #ifdef HAVE_LOCALTIME_R
190 	(void) localtime_r(&now, &timebuf);
191 #else
192 	memcpy(&timebuf, localtime(&now), sizeof(timebuf));
193 #endif
194 	if ((s = strptime(string, atime_format_table[i], &timebuf))
195 	    && (s != string)) {
196  	    /* See if at end of buffer - otherwise partial processing */
197 	    while(*s != 0 && isspace((int) *s)) s++;
198 	    if (*s != 0)
199 	        continue;
200 	    if (timebuf.tm_year <= 0)
201 		continue;	/* clearly confused */
202 	    ret_time = mktime(&timebuf);
203 	    if (ret_time == (time_t) -1)
204 		continue;	/* clearly confused */
205 	    *timestampp = (krb5_timestamp) ret_time;
206 	    return 0;
207 	}
208     }
209     return(EINVAL);
210 }
211 
212 krb5_error_code KRB5_CALLCONV
213 krb5_timestamp_to_string(krb5_timestamp timestamp, char *buffer, size_t buflen)
214 {
215     int ret;
216     time_t timestamp2 = timestamp;
217     struct tm tmbuf;
218     const char *fmt = "%c"; /* This is to get around gcc -Wall warning that
219 			       the year returned might be two digits */
220 
221 #ifdef HAVE_LOCALTIME_R
222     (void) localtime_r(&timestamp2, &tmbuf);
223 #else
224     memcpy(&tmbuf, localtime(&timestamp2), sizeof(tmbuf));
225 #endif
226     ret = strftime(buffer, buflen, fmt, &tmbuf);
227     if (ret == 0 || ret == buflen)
228 	return(ENOMEM);
229     return(0);
230 }
231 
232 krb5_error_code KRB5_CALLCONV
233 krb5_timestamp_to_sfstring(krb5_timestamp timestamp, char *buffer, size_t buflen, char *pad)
234 {
235     struct tm	*tmp;
236     size_t i;
237     size_t	ndone;
238     time_t timestamp2 = timestamp;
239     struct tm tmbuf;
240 
241     static const char * const sftime_format_table[] = {
242 	"%c",			/* Default locale-dependent date and time */
243 	"%d %b %Y %T",		/* dd mon yyyy hh:mm:ss			*/
244 	"%x %X",		/* locale-dependent short format	*/
245 	"%d/%m/%Y %R"		/* dd/mm/yyyy hh:mm			*/
246     };
247     static const int sftime_format_table_nents =
248 	sizeof(sftime_format_table)/sizeof(sftime_format_table[0]);
249 
250 #ifdef HAVE_LOCALTIME_R
251     tmp = localtime_r(&timestamp2, &tmbuf);
252 #else
253     memcpy((tmp = &tmbuf), localtime(&timestamp2), sizeof(tmbuf));
254 #endif
255     ndone = 0;
256     for (i=0; i<sftime_format_table_nents; i++) {
257 	if ((ndone = strftime(buffer, buflen, sftime_format_table[i], tmp)))
258 	    break;
259     }
260     if (!ndone) {
261 #define sftime_default_len	2+1+2+1+4+1+2+1+2+1
262 	if (buflen >= sftime_default_len) {
263 	    sprintf(buffer, "%02d/%02d/%4d %02d:%02d",
264 		    tmp->tm_mday, tmp->tm_mon+1, 1900+tmp->tm_year,
265 		    tmp->tm_hour, tmp->tm_min);
266 	    ndone = strlen(buffer);
267 	}
268     }
269     if (ndone && pad) {
270 	for (i=ndone; i<buflen-1; i++)
271 	    buffer[i] = *pad;
272 	buffer[buflen-1] = '\0';
273     }
274     return((ndone) ? 0 : ENOMEM);
275 }
276 
277 #ifdef SUNW_INC_DEAD_CODE
278 /* relative time (delta-t) conversions */
279 
280 /* string->deltat is in deltat.y */
281 
282 krb5_error_code KRB5_CALLCONV
283 krb5_deltat_to_string(krb5_deltat deltat, char *buffer, size_t buflen)
284 {
285     int			days, hours, minutes, seconds;
286     krb5_deltat		dt;
287 
288     /*
289      * We want something like ceil(log10(2**(nbits-1))) + 1.  That log
290      * value is log10(2)*(nbits-1) or log10(2**8)*(nbits-1)/8.  So,
291      * 2.4... is log10(256), rounded up.  Add one to handle leading
292      * minus, and one more to force int cast to round the value up.
293      * This doesn't include room for a trailing nul.
294      *
295      * This will break if bytes are more than 8 bits.
296      */
297 #define MAX_CHARS_FOR_INT_TYPE(TYPE)	((int) (2 + 2.408241 * sizeof (TYPE)))
298     char tmpbuf[MAX_CHARS_FOR_INT_TYPE(int) * 4 + 8];
299 
300     days = (int) (deltat / (24*3600L));
301     dt = deltat % (24*3600L);
302     hours = (int) (dt / 3600);
303     dt %= 3600;
304     minutes = (int) (dt / 60);
305     seconds = (int) (dt % 60);
306 
307     memset (tmpbuf, 0, sizeof (tmpbuf));
308     if (days == 0)
309 	sprintf(buffer, "%d:%02d:%02d", hours, minutes, seconds);
310     else if (hours || minutes || seconds)
311 	sprintf(buffer, "%d %s %02d:%02d:%02d", days,
312 		(days > 1) ? "days" : "day",
313 		hours, minutes, seconds);
314     else
315 	sprintf(buffer, "%d %s", days,
316 		(days > 1) ? "days" : "day");
317     if (tmpbuf[sizeof(tmpbuf)-1] != 0)
318 	/* Something must be very wrong with my math above, or the
319 	   assumptions going into it...  */
320 	abort ();
321     if (strlen (tmpbuf) > buflen)
322 	return ENOMEM;
323     else
324 	strncpy (buffer, tmpbuf, buflen);
325     return 0;
326 }
327 #endif /* SUNW_INC_DEAD_CODE */
328 
329 #undef __P
330 #define __P(X) X
331 
332 #if !defined (HAVE_STRFTIME) || !defined (HAVE_STRPTIME)
333 #undef _CurrentTimeLocale
334 #define _CurrentTimeLocale (&dummy_locale_info)
335 
336 struct dummy_locale_info_t {
337     char d_t_fmt[15];
338     char t_fmt_ampm[12];
339     char t_fmt[9];
340     char d_fmt[9];
341     char day[7][10];
342     char abday[7][4];
343     char mon[12][10];
344     char abmon[12][4];
345     char am_pm[2][3];
346 };
347 static const struct dummy_locale_info_t dummy_locale_info = {
348     "%a %b %d %X %Y",		/* %c */
349     "%I:%M:%S %p",		/* %r */
350     "%H:%M:%S",			/* %X */
351     "%m/%d/%y",			/* %x */
352     { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
353       "Saturday" },
354     { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" },
355     { "January", "February", "March", "April", "May", "June",
356       "July", "August", "September", "October", "November", "December" },
357     { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
358       "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" },
359     { "AM", "PM" },
360 };
361 #undef  TM_YEAR_BASE
362 #define TM_YEAR_BASE 1900
363 #endif
364 
365 #ifndef HAVE_STRFTIME
366 #undef  DAYSPERLYEAR
367 #define DAYSPERLYEAR 366
368 #undef  DAYSPERNYEAR
369 #define DAYSPERNYEAR 365
370 #undef  DAYSPERWEEK
371 #define DAYSPERWEEK 7
372 #undef  isleap
373 #define isleap(N)	((N % 4) == 0 && (N % 100 != 0 || N % 400 == 0))
374 #undef  tzname
375 #define tzname my_tzname
376 static const char *const tzname[2] = { 0, 0 };
377 #undef  tzset
378 #define tzset()
379 
380 #include "strftime.c"
381 #endif
382 
383 #ifndef HAVE_STRPTIME
384 #include "strptime.c"
385 #endif
386