]> diplodocus.org Git - mdfrm/blob - mdfrm.c
55fac72ecb8d27a96b4ac8cb8f8d8d92cc0cb55a
[mdfrm] / mdfrm.c
1 /* mdfrm.c -- mdfrm(1) for maildir.
2 *
3 * $Id$
4 *
5 * This program is in the public domain.
6 */
7
8 #include <sys/types.h>
9
10 #include <dirent.h>
11 #include <err.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sysexits.h>
16 #include <unistd.h>
17
18 /* Note that PATH_MAX is supposed to include the terminating null. */
19 #ifndef PATH_MAX
20 #ifndef MAXPATHLEN
21 #define PATH_MAX 65
22 #else
23 #define PATH_MAX MAXPATHLEN
24 #endif
25 #endif
26
27 enum {
28 FROMLEN = 6, /* "From: "*/
29 SUBJLEN = 9, /* "Subject: "*/
30
31 /* Number of characters for each field we actually output. This
32 * must also be changed in the printf functions at the end.
33 */
34 FROMCOUNT = 24,
35 SUBJCOUNT = 53
36 };
37
38 int
39 main(int argc, char *argv[])
40 {
41 char *dirname;
42 char buf[PATH_MAX];
43 DIR *dir;
44 struct dirent *dirent;
45 char *filename;
46 FILE *file;
47 char *line, *fromheader, *subjheader;
48 size_t len, fromcount, subjcount;
49
50 if (!(dirname = argv[1])) {
51 if (!(dirname = getenv("MAILDIR"))) {
52 if (!(dirname = getenv("HOME"))) {
53 errx(EX_UNAVAILABLE, "Could not find maildir.");
54 } else {
55 snprintf(buf, PATH_MAX, "%s/Maildir", dirname);
56 dirname = buf;
57 }
58 }
59 }
60
61 if (chdir(dirname) != 0) {
62 err(EX_OSERR, "Failed chdir(%s)", dirname);
63 }
64
65 if (chdir("new") != 0) {
66 err(EX_OSERR, "Failed chdir(%s/new)", dirname);
67 }
68
69 dir = opendir(".");
70 if (!dir) {
71 err(EX_OSERR, "Failed opendir(%s/new)", dirname);
72 }
73
74 fromheader = malloc(FROMCOUNT + 1);
75 subjheader = malloc(SUBJCOUNT + 1);
76 for (dirent = readdir(dir); dirent; dirent = readdir(dir)) {
77 filename = dirent->d_name;
78 if (filename[0] == '.') {
79 continue;
80 }
81
82 if (!(file = fopen(filename, "r"))) {
83 err(EX_OSERR, "Failed fopen(%s)", filename);
84 }
85
86 fromheader[0] = subjheader[0] = '\0';
87 fromcount = subjcount = 0;
88 while ((line = fgetln(file, &len))) {
89 if (len <= 1) {
90 break;
91 }
92 line[len - 1] = '\0';
93
94 if (len > FROMLEN
95 && strncmp(line, "From: ", FROMLEN) == 0) {
96 line += FROMLEN;
97 len -= FROMLEN;
98 if (len < FROMCOUNT) {
99 fromcount = len;
100 } else {
101 fromcount = FROMCOUNT;
102 }
103 strncpy(fromheader, line, fromcount);
104 } else if (len > SUBJLEN
105 && strncmp(line, "Subject: ", SUBJLEN) == 0) {
106 line += SUBJLEN;
107 len -= SUBJLEN;
108 if (len < SUBJCOUNT) {
109 subjcount = len;
110 } else {
111 subjcount = SUBJCOUNT;
112 }
113 strncpy(subjheader, line, subjcount);
114 }
115 }
116
117 printf("%-24s ", fromheader);
118 printf("%-53s\n", subjheader);
119 }
120
121 return 0;
122 }