#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
+
#include "brum.h"
#define BUFSIZE 1024
int curbufsize;
+char mbox_write_buf[BUFSIZE];
+int mbox_write_pos;
+int mbox_write_err;
+
static void
new_header(char* buf, struct list* h)
{
printf("%s:%s",p->name,p->value);
}
-void
-do_action(struct action* a)
+static void
+write_char_to_mailbox(char c, int fd)
+{
+ int res;
+
+ if (mbox_write_err)
+ return;
+
+ if (!c){
+ if (!mbox_write_pos)
+ return;
+ res = write(fd, mbox_write_buf, mbox_write_pos);
+ if (res < 0)
+ mbox_write_err++;
+ mbox_write_pos = 0;
+ return;
+ }
+ if (mbox_write_pos >= BUFSIZE){
+ res = write(fd, mbox_write_buf, BUFSIZE);
+ if (res < 0)
+ mbox_write_err++;
+ mbox_write_pos = 0;
+ return;
+ }
+ mbox_write_buf[mbox_write_pos++] = c;
+}
+
+/* try to copy e-mail to mailbox, if it fails,
+ truncate mailbox to the original size */
+static int
+copy_email(int fd, struct email* email)
{
- //just deliver e-mail, do not look at left side now
-/* if (! a->r ){
+ off_t mb_end;
+
+ mb_end = lseek(fd, 0, SEEK_END);
+ if (mb_end < 1)
+ return -1;
+
+ /* init globals */
+ mbox_write_err = 0;
+ mbox_write_pos = 0;
+
+ /* headers */
+ struct hlist* ph;
+ char* pc;
+ LIST_FOREACH(ph, email->headers){
+ for (pc = ph->name; *pc; pc++)
+ write_char_to_mailbox(*pc, fd);
+ write_char_to_mailbox(':', fd);
+ write_char_to_mailbox(' ', fd);
+ for (pc = ph->value; *pc; pc++)
+ write_char_to_mailbox(*pc, fd);
+ write_char_to_mailbox('\n', fd);
+ }
- } else if (!strcmp(a->r,"pipe")){
- 1;
+ write_char_to_mailbox('\n', fd);
+ /* body */
+ //FIXME that nasty FROM
+ for (pc = email->body; *pc; pc++){
+ write_char_to_mailbox(*pc, fd);
}
-*/
+ /* flush the buffer */
+ write_char_to_mailbox(0, fd);
+
+ /* errors? */
+ if (mbox_write_err)
+ return -1;
+
+ return 0;
+}
+
+static int
+deliver_local_email(char* folder, struct email* email)
+{
+ int res = -1;
+ int is_default_mailbox = 0;
+ int fd;
+
+ if (!strcmp(default_mailbox, folder))
+ is_default_mailbox = 1;
+
+ fd = open_mailbox(folder, is_default_mailbox);
+ if (fd < 0){
+ if (is_default_mailbox)
+ return res;
+ else /* try to save to default mailbox instead */
+ return deliver_local_email(default_mailbox, email);
+ }
+
+ res = copy_email(fd, email);
+ if (res < 0){
+
+ /* try to deliver to the default mailbox */
+ if (is_default_mailbox)
+ return res;
+ else
+ return deliver_local_email(default_mailbox, email);
+ }
+
+ close_mailbox(fd, folder, is_default_mailbox);
+
+ return res;
+}
+
+void
+do_action(struct action* a)
+{
+ /* -> address */
+ if (! a->r && !a->l ){
+ deliver_local_email(a->s, &a->e);
+ }
}