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