9 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
10 #define MIN(a, b) ((a) < (b) ? (a) : (b))
11 #define MAXLINE (1 << 7)
12 #define BUFSIZE (1 << 12)
13 #define PAGER "pgmail"
14 #define NHEAD (1 << 4)
16 static char *hdr_filt
[] = {
17 "Subject:", "From:", "To:", "Cc:", "Date:", "User-Agent:",
18 "X-Mailer", "Organization"};
20 static char buf
[BUFSIZE
];
24 static int read_line(char *dst
, int size
)
28 int cur_len
= MIN(len
- cur
, size
- nw
- 1);
29 char *nl
= memchr(buf
+ cur
, '\n', cur_len
);
30 int nr
= nl
? nl
- buf
- cur
+ 1 : cur_len
;
32 memcpy(dst
+ nw
, buf
+ cur
, nr
);
37 if (nl
|| nw
== size
- 1)
40 if ((len
= read(STDIN_FILENO
, buf
, BUFSIZE
)) <= 0)
46 static void till_eol(char *s
)
49 while (*s
&& *s
!= '\r' && *s
!= '\n')
55 static char *cut_int(char *dst
, char *s
)
65 static void cmd_page(struct mbox
*mbox
, char *args
)
74 args
= cut_int(num
, args
);
77 if (n
< 0 && n
>= mbox
->n
)
79 mail
= &mbox
->mails
[n
];
82 if (!(pid
= fork())) {
83 char *args
[] = {PAGER
, NULL
};
85 dup2(fds
[0], STDIN_FILENO
);
90 hdr_len
= mail_head(mail
, head
, sizeof(head
),
91 hdr_filt
, ARRAY_SIZE(hdr_filt
));
92 write(fds
[1], head
, hdr_len
);
93 write(fds
[1], mail
->body
, mail
->body_len
);
95 waitpid(pid
, NULL
, 0);
98 static char *cut_cmd(char *dst
, char *s
)
100 while (isalpha(*s
)) {
107 static char *put_int(char *s
, int n
, int w
)
110 for (i
= 0; i
< w
; i
++) {
111 s
[w
- i
- 1] = n
|| !i
? '0' + n
% 10 : ' ';
117 static void cmd_head(struct mbox
*mbox
, char *args
)
120 int beg
= mbox
->c
/ NHEAD
* NHEAD
;
121 int end
= MIN(beg
+ NHEAD
, mbox
->n
);
124 for (i
= beg
; i
< end
; i
++) {
127 *s
++ = i
== mbox
->c
? '>' : ' ';
128 s
= put_int(s
, i
, 5);
131 write(STDOUT_FILENO
, fmt
, strlen(fmt
));
132 if (mbox
->mails
[i
].subject
)
133 till_eol(mbox
->mails
[i
].subject
+ 9);
137 static void prompt(void)
139 write(STDOUT_FILENO
, "? ", 2);
142 static void print(char *s
)
144 write(STDOUT_FILENO
, s
, strlen(s
));
147 static void loop(struct mbox
*mbox
)
152 while (read_line(line
, sizeof(line
)) > 0) {
153 char *args
= cut_cmd(cmd
, line
);
154 int len
= strlen(cmd
);
156 if (mbox
->c
< mbox
->n
+ 1) {
158 cmd_page(mbox
, args
);
165 if (!strncmp("page", cmd
, len
))
166 cmd_page(mbox
, args
);
167 if (!strncmp("header", cmd
, len
))
168 cmd_head(mbox
, args
);
169 if (!strncmp("quit", cmd
, len
))
171 if (!strncmp("x", cmd
, len
) || !strncmp("exit", cmd
, len
))
177 int main(int argc
, char *argv
[])
181 char *filename
= NULL
;
183 if (!strcmp("-f", argv
[i
]))
184 filename
= argv
[++i
];
186 mbox
= mbox_alloc(filename
);