xref: /netbsd-src/external/ibm-public/postfix/dist/src/global/conv_time.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /*	$NetBSD: conv_time.c,v 1.1.1.2 2011/03/02 19:32:13 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	conv_time 3
6 /* SUMMARY
7 /*	time value conversion
8 /* SYNOPSIS
9 /*	#include <conv_time.h>
10 /*
11 /*	int	conv_time(strval, timval, def_unit);
12 /*	const char *strval;
13 /*	int	*timval;
14 /*	int	def_unit;
15 /* DESCRIPTION
16 /*	conv_time() converts a numerical time value with optional
17 /*	one-letter suffix that specifies an explicit time unit: s
18 /*	(seconds), m (minutes), h (hours), d (days) or w (weeks).
19 /*	Internally, time is represented in seconds.
20 /*
21 /*	Arguments:
22 /* .IP strval
23 /*	Input value.
24 /* .IP timval
25 /*	Result pointer.
26 /* .IP def_unit
27 /*	The default time unit suffix character.
28 /* DIAGNOSTICS
29 /*	The result value is non-zero in case of success, zero in
30 /*	case of a bad time value or a bad time unit suffix.
31 /* LICENSE
32 /* .ad
33 /* .fi
34 /*	The Secure Mailer license must be distributed with this software.
35 /* AUTHOR(S)
36 /*	Wietse Venema
37 /*	IBM T.J. Watson Research
38 /*	P.O. Box 704
39 /*	Yorktown Heights, NY 10598, USA
40 /*--*/
41 
42 /* System library. */
43 
44 #include <sys_defs.h>
45 #include <limits.h>			/* INT_MAX */
46 #include <stdlib.h>
47 #include <errno.h>
48 
49 /* Utility library. */
50 
51 #include <msg.h>
52 
53 /* Global library. */
54 
55 #include <conv_time.h>
56 
57 #define MINUTE	(60)
58 #define HOUR	(60 * MINUTE)
59 #define DAY	(24 * HOUR)
60 #define WEEK	(7 * DAY)
61 
62 /* conv_time - convert time value */
63 
64 int     conv_time(const char *strval, int *timval, int def_unit)
65 {
66     char   *end;
67     int     intval;
68     long    longval;
69 
70     errno = 0;
71     intval = longval = strtol(strval, &end, 10);
72     if (*strval == 0 || errno == ERANGE || longval != intval || intval < 0
73 	|| (*end != 0 && end[1] != 0))
74 	return (0);
75 
76     switch (*end ? *end : def_unit) {
77     case 'w':
78 	if (intval < INT_MAX / WEEK) {
79 	    *timval = intval * WEEK;
80 	    return (1);
81 	} else {
82 	    return (0);
83 	}
84     case 'd':
85 	if (intval < INT_MAX / DAY) {
86 	    *timval = intval * DAY;
87 	    return (1);
88 	} else {
89 	    return (0);
90 	}
91     case 'h':
92 	if (intval < INT_MAX / HOUR) {
93 	    *timval = intval * HOUR;
94 	    return (1);
95 	} else {
96 	    return (0);
97 	}
98     case 'm':
99 	if (intval < INT_MAX / MINUTE) {
100 	    *timval = intval * MINUTE;
101 	    return (1);
102 	} else {
103 	    return (0);
104 	}
105     case 's':
106 	*timval = intval;
107 	return (1);
108     }
109     return (0);
110 }
111