]> diplodocus.org Git - mdfrm/blob - mdfrm.c
63a1bb47cef87eab76f78032e23112441f8fd8a8
[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 static char rcsid[] = "$Id$";
39
40 int
41 main(int argc, char *argv[])
42 {
43 char *dirname;
44 char buf[PATH_MAX];
45 DIR *dir;
46 struct dirent *dirent;
47 char *filename;
48 FILE *file;
49 char *line, *fromheader, *subjheader;
50 size_t len, fromcount, subjcount;
51
52 if (argv[1] && argv[1][0] == '-' && argv[1][1] == 'v') {
53 puts(rcsid);
54 return 0;
55 }
56
57 if (!(dirname = argv[1])) {
58 if (!(dirname = getenv("MAILDIR"))) {
59 if (!(dirname = getenv("HOME"))) {
60 errx(EX_UNAVAILABLE, "Could not find maildir.");
61 } else {
62 snprintf(buf, PATH_MAX, "%s/Maildir", dirname);
63 dirname = buf;
64 }
65 }
66 }
67
68 if (chdir(dirname) != 0) {
69 err(EX_OSERR, "Failed chdir(%s)", dirname);
70 }
71
72 if (chdir("new") != 0) {
73 err(EX_OSERR, "Failed chdir(%s/new)", dirname);
74 }
75
76 dir = opendir(".");
77 if (!dir) {
78 err(EX_OSERR, "Failed opendir(%s/new)", dirname);
79 }
80
81 fromheader = malloc(FROMCOUNT + 1);
82 subjheader = malloc(SUBJCOUNT + 1);
83 for (dirent = readdir(dir); dirent; dirent = readdir(dir)) {
84 filename = dirent->d_name;
85 if (filename[0] == '.') {
86 continue;
87 }
88
89 if (!(file = fopen(filename, "r"))) {
90 err(EX_OSERR, "Failed fopen(%s)", filename);
91 }
92
93 fromheader[0] = subjheader[0] = '\0';
94 fromcount = subjcount = 0;
95 while ((line = fgetln(file, &len))) {
96 if (len <= 1) {
97 break;
98 }
99 line[len - 1] = '\0';
100
101 if (len > FROMLEN
102 && strncmp(line, "From: ", FROMLEN) == 0) {
103 line += FROMLEN;
104 len -= FROMLEN;
105 if (len < FROMCOUNT) {
106 fromcount = len;
107 } else {
108 fromcount = FROMCOUNT;
109 }
110 strncpy(fromheader, line, fromcount);
111 } else if (len > SUBJLEN
112 && strncmp(line, "Subject: ", SUBJLEN) == 0) {
113 line += SUBJLEN;
114 len -= SUBJLEN;
115 if (len < SUBJCOUNT) {
116 subjcount = len;
117 } else {
118 subjcount = SUBJCOUNT;
119 }
120 strncpy(subjheader, line, subjcount);
121 }
122 }
123
124 printf("%-24s ", fromheader);
125 printf("%-53s\n", subjheader);
126 }
127
128 return 0;
129 }