xref: /plan9/sys/src/cmd/auth/lib/getexpiration.c (revision ff8c3af2f44d95267f67219afa20ba82ff6cf7e4)
1 #include <u.h>
2 #include <libc.h>
3 #include <ctype.h>
4 #include "authcmdlib.h"
5 
6 /*
7  * get the date in the format yyyymmdd
8  */
9 Tm
10 getdate(char *d)
11 {
12 	Tm date;
13 	int i;
14 
15 	date.year = date.mon = date.mday = 0;
16 	date.hour = date.min = date.sec = 0;
17 	for(i = 0; i < 8; i++)
18 		if(!isdigit(d[i]))
19 			return date;
20 	date.year = (d[0]-'0')*1000 + (d[1]-'0')*100 + (d[2]-'0')*10 + d[3]-'0';
21 	date.year -= 1900;
22 	d += 4;
23 	date.mon = (d[0]-'0')*10 + d[1]-'0' - 1;
24 	d += 2;
25 	date.mday = (d[0]-'0')*10 + d[1]-'0';
26 	date.yday = 0;
27 	return date;
28 }
29 
30 long
31 getexpiration(char *db, char *u)
32 {
33 	char buf[Maxpath];
34 	char prompt[128];
35 	char cdate[32];
36 	Tm date;
37 	ulong secs, now, fd;
38 	int n;
39 
40 	/* read current expiration (if any) */
41 	snprint(buf, sizeof buf, "%s/%s/expire", db, u);
42 	fd = open(buf, OREAD);
43 	buf[0] = 0;
44 	if(fd >= 0){
45 		n = read(fd, buf, sizeof(buf)-1);
46 		if(n > 0)
47 			buf[n-1] = 0;
48 		close(fd);
49 	}
50 
51 	if(buf[0]){
52 		if(strncmp(buf, "never", 5)){
53 			secs = atoi(buf);
54 			memmove(&date, localtime(secs), sizeof(date));
55 			sprint(buf, "%4.4d%2.2d%2.2d", date.year+1900, date.mon+1, date.mday);
56 		} else
57 			buf[5] = 0;
58 	} else
59 		strcpy(buf, "never");
60 	sprint(prompt, "Expiration date (YYYYMMDD or never)[return = %s]: ", buf);
61 
62 	now = time(0);
63 	for(;;){
64 		readln(prompt, cdate, sizeof cdate, 0);
65 		if(*cdate == 0)
66 			return -1;
67 		if(strcmp(cdate, "never") == 0)
68 			return 0;
69 		date = getdate(cdate);
70 		secs = tm2sec(&date);
71 		if(secs > now && secs < now + 2*365*24*60*60)
72 			break;
73 		print("expiration time must fall between now and 2 years from now\n");
74 	}
75 	return secs;
76 }
77