]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/upas/filterkit/token.c
merging erik quanstros nupas
[plan9front.git] / sys / src / cmd / upas / filterkit / token.c
1 #include <u.h>
2 #include <libc.h>
3 #include <libsec.h>
4 #include "dat.h"
5
6 void
7 usage(void)
8 {
9         fprint(2, "usage: token key [token]\n");
10         exits("usage");
11 }
12
13 static char*
14 mktoken(char *key, long t)
15 {
16         char *now, token[64];
17         uchar digest[SHA1dlen];
18
19         now = ctime(t);
20         memset(now+11, ':', 8);
21         hmac_sha1((uchar*)now, strlen(now), (uchar*)key, strlen(key), digest, nil);
22         enc64(token, sizeof token, digest, sizeof digest);
23         return smprint("%.5s", token);
24 }
25
26 static char*
27 check_token(char *key, char *file)
28 {
29         char *s, buf[1024];
30         int i, fd, m;
31         long now;
32
33         fd = open(file, OREAD);
34         if(fd < 0)
35                 return "no match";
36         i = read(fd, buf, sizeof buf-1);
37         close(fd);
38         if(i < 0)
39                 return "no match";
40         buf[i] = 0;
41         now = time(0);
42         for(i = 0; i < 14; i++){
43                 s = mktoken(key, now-24*60*60*i);
44                 m = s != nil && strstr(buf, s) != nil;
45                 free(s);
46                 if(m)
47                         return nil;
48         }
49         return "no match";
50 }
51
52 static char*
53 create_token(char *key)
54 {
55         print("%s", mktoken(key, time(0)));
56         return nil;
57 }
58
59 void
60 main(int argc, char **argv)
61 {
62         ARGBEGIN {
63         } ARGEND;
64
65         switch(argc){
66         case 2:
67                 exits(check_token(argv[0], argv[1]));
68         case 1:
69                 exits(create_token(argv[0]));
70         default:
71                 usage();
72         }
73         exits(0);
74 }