show "? " cmd prompt
[mailx.git] / mbox.c
blob73809132d7b9c14d21f4bde93a8be3f8f4dc9c6a
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <unistd.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include "mbox.h"
10 static int file_size(int fd)
12 struct stat stat;
13 fstat(fd, &stat);
14 return stat.st_size;
17 static int read_file(int fd, char *buf, int len)
19 int nr = 0;
20 while (nr < len) {
21 int ret = read(fd, buf + nr, len - nr);
22 if (ret == -1 && (errno == EAGAIN || errno == EINTR))
23 continue;
24 if (ret <= 0)
25 break;
26 nr += ret;
28 return nr;
31 static char *mail_start(char *r)
33 char *s = r;
34 while (s) {
35 if (!strncmp("From ", s, 5) && (s == r || *(s - 1) == '\n'))
36 break;
37 s = strchr(s + 1, 'F');
39 return s;
42 static char *mail_hdrs(struct mail *mail, char *s)
44 while (s && *s && *s != '\r' && *s != '\n') {
45 if (!strncmp("Subject:", s, 5))
46 mail->subject = s;
47 s = strchr(s + 1, '\n');
48 s = s ? s + 1 : s;
50 return s;
53 static char *mail_read(struct mail *mail, char *s)
55 char *end;
56 mail->head = s;
57 s = mail_hdrs(mail, s);
58 end = mail_start(s);
59 mail->len = end - mail->head;
60 return end;
63 static void read_mails(struct mbox *mbox)
65 char *s = mbox->mbox;
66 while (s)
67 s = mail_read(&mbox->mails[mbox->n++], s);
70 struct mbox *mbox_alloc(char *filename)
72 struct mbox *mbox;
73 int fd = open(filename, O_RDONLY);
74 int len;
75 if (fd == -1)
76 return NULL;
77 mbox = malloc(sizeof(*mbox));
78 memset(mbox, 0, sizeof(*mbox));
79 len = file_size(fd);
80 mbox->mbox = malloc(len + 1);
81 mbox->len = read_file(fd, mbox->mbox, len);
82 mbox->mbox[len] = '\0';
83 close(fd);
84 read_mails(mbox);
85 return mbox;
88 void mbox_free(struct mbox *mbox)
90 free(mbox->mbox);
91 free(mbox);