+/* mdfrm.c -- mdfrm(1) for maildir.
+ *
+ * $Id$
+ *
+ * This program is in the public domain.
+ */
+
+#include <sys/types.h>
+
+#include <dirent.h>
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sysexits.h>
+#include <unistd.h>
+
+/* Note that PATH_MAX is supposed to include the terminating null. */
+#ifndef PATH_MAX
+#ifndef MAXPATHLEN
+#define PATH_MAX 65
+#else
+#define PATH_MAX MAXPATHLEN
+#endif
+#endif
+
+enum {
+ FROMLEN = 6, /* "From: "*/
+ SUBJLEN = 9, /* "Subject: "*/
+
+ /* Number of characters for each field we actually output. This
+ * must also be changed in the printf functions at the end.
+ */
+ FROMCOUNT = 24,
+ SUBJCOUNT = 53
+};
+
+int
+main(int argc, char *argv[])
+{
+ char *dirname;
+ char buf[PATH_MAX];
+ DIR *dir;
+ struct dirent *dirent;
+ char *filename;
+ FILE *file;
+ char *line, *fromheader, *subjheader;
+ size_t len, fromcount, subjcount;
+
+ if (!(dirname = argv[1])) {
+ if (!(dirname = getenv("MAILDIR"))) {
+ if (!(dirname = getenv("HOME"))) {
+ errx(EX_UNAVAILABLE, "Could not find maildir.");
+ } else {
+ snprintf(buf, PATH_MAX, "%s/Maildir", dirname);
+ dirname = buf;
+ }
+ }
+ }
+
+ if (chdir(dirname) != 0) {
+ err(EX_OSERR, "Failed chdir(%s)", dirname);
+ }
+
+ if (chdir("new") != 0) {
+ err(EX_OSERR, "Failed chdir(%s/new)", dirname);
+ }
+
+ dir = opendir(".");
+ if (!dir) {
+ err(EX_OSERR, "Failed opendir(%s/new)", dirname);
+ }
+
+ fromheader = malloc(FROMCOUNT + 1);
+ subjheader = malloc(SUBJCOUNT + 1);
+ for (dirent = readdir(dir); dirent; dirent = readdir(dir)) {
+ filename = dirent->d_name;
+ if (filename[0] == '.') {
+ continue;
+ }
+
+ if (!(file = fopen(filename, "r"))) {
+ err(EX_OSERR, "Failed fopen(%s)", filename);
+ }
+
+ fromheader[0] = subjheader[0] = '\0';
+ fromcount = subjcount = 0;
+ while ((line = fgetln(file, &len))) {
+ if (len <= 1) {
+ break;
+ }
+ line[len - 1] = '\0';
+
+ if (len > FROMLEN
+ && strncmp(line, "From: ", FROMLEN) == 0) {
+ line += FROMLEN;
+ len -= FROMLEN;
+ if (len < FROMCOUNT) {
+ fromcount = len;
+ } else {
+ fromcount = FROMCOUNT;
+ }
+ strncpy(fromheader, line, fromcount);
+ } else if (len > SUBJLEN
+ && strncmp(line, "Subject: ", SUBJLEN) == 0) {
+ line += SUBJLEN;
+ len -= SUBJLEN;
+ if (len < SUBJCOUNT) {
+ subjcount = len;
+ } else {
+ subjcount = SUBJCOUNT;
+ }
+ strncpy(subjheader, line, subjcount);
+ }
+ }
+
+ printf("%-24s ", fromheader);
+ printf("%-53s\n", subjheader);
+ }
+
+ return 0;
+}