acmecert: Fix cryptography bugs.
[utils.git] / krb5mapcc.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <ctype.h>
6 #include <dirent.h>
7 #include <fcntl.h>
8 #include <string.h>
9
10 int isnumeric(char *str)
11 {
12     while(*str) {
13         if(!isdigit(*str))
14             return(0);
15         str++;
16     }
17     return(1);
18 }
19
20 char *findcc(int fd)
21 {
22     int ret, dlen;
23     static char retbuf[1024];
24     char readbuf[1024];
25     char *p, *p2;
26     
27     dlen = 0;
28     p = readbuf;
29     do {
30         if(dlen == 1024)
31             dlen = 0;
32         ret = read(fd, readbuf + dlen, sizeof(readbuf) - dlen);
33         if(ret < 0) {
34             perror("read environ");
35             return(NULL);
36         }
37         dlen += ret;
38         
39         while((p = memchr(readbuf, 0, dlen)) != NULL) {
40             if((p2 = strchr(readbuf, '=')) != NULL) {
41                 *(p2++) = 0;
42                 if(!strcasecmp(readbuf, "KRB5CCNAME") && !strncasecmp(p2, "FILE:", 5)) {
43                     if(strlen(p2 + 5) >= sizeof(retbuf)) {
44                         fprintf(stderr, "really long ccname!\n");
45                         return(NULL);
46                     }
47                     strcpy(retbuf, p2 + 5);
48                     return(retbuf);
49                 }
50             }
51             p++;
52             memmove(readbuf, p, dlen -= (p - readbuf));
53         }
54     } while(ret != 0);
55     return(NULL);
56 }
57
58 int main(int argc, char **argv)
59 {
60     int fd;
61     DIR *proc;
62     struct dirent *de;
63     char envbuf[1024];
64     char *p, *cc;
65     
66     if((proc = opendir("/proc")) == NULL) {
67         perror("/proc");
68         exit(1);
69     }
70     while((de = readdir(proc)) != NULL) {
71         if(!isnumeric(de->d_name))
72             continue;
73         if(strlen(de->d_name) > 30)
74             continue;
75         
76         p = envbuf;
77         strcpy(p, "/proc/");
78         p += 6;
79         strcpy(p, de->d_name);
80         p += strlen(de->d_name);
81         *(p++) = '/';
82         strcpy(p, "environ");
83         
84         if((fd = open(envbuf, O_RDONLY)) < 0)
85             continue;
86         cc = findcc(fd);
87         close(fd);
88         
89         if(cc != NULL) {
90             printf("%s %s\n", de->d_name, cc);
91         }
92     }
93     closedir(proc);
94     return(0);
95 }