summaryrefslogtreecommitdiff
path: root/src/maildir.c
blob: a755177d8070f0f49dcc306b559d9cfd1cd5c89b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "maildir.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "direntry.h"
#include "env.h"
#include "logmsg.h"
#include "str.h"
#include "stralloc.h"

#include "datetime.h"
#include "now.h"
#include "prioq.h"

#define WHO "maildir"

int maildir_chdir()
{
  char *maildir;
  maildir = env_get("MAILDIR");
  if (!maildir) logmsg(WHO, 111, ERROR, "MAILDIR not set");
  if (chdir(maildir) == -1) logmsg(WHO, 110, FATAL, B("unable to chdir to: ", maildir));
  return 0;
}

void maildir_clean(stralloc *tmpname)
{
  DIR *dir;
  direntry *d;
  datetime_sec time;
  struct stat st;

  time = now();

  dir = opendir("tmp");
  if (!dir) return;

  while ((d = readdir(dir))) {
    if (d->d_name[0] == '.') continue;
    if (!stralloc_copys(tmpname, "tmp/")) break;
    if (!stralloc_cats(tmpname, d->d_name)) break;
    if (!stralloc_0(tmpname)) break;
    if (stat(tmpname->s, &st) == 0)
      if (time > st.st_atime + 129600) unlink(tmpname->s);
  }
  closedir(dir);
}

static int append(prioq *pq, stralloc *filenames, char *subdir, datetime_sec time)
{
  DIR *dir;
  direntry *d;
  struct prioq_elt pe;
  unsigned int pos;
  struct stat st;

  dir = opendir(subdir);
  if (!dir) logmsg(WHO, 112, FATAL, B("unable to scan $MAILDIR/:", subdir));

  while ((d = readdir(dir))) {
    if (d->d_name[0] == '.') continue;
    pos = filenames->len;
    if (!stralloc_cats(filenames, subdir)) break;
    if (!stralloc_cats(filenames, "/")) break;
    if (!stralloc_cats(filenames, d->d_name)) break;
    if (!stralloc_0(filenames)) break;
    if (stat(filenames->s + pos, &st) == 0) {
      if (st.st_mtime < time) { /* don't want to mix up the order */
        pe.dt = st.st_mtime;
        pe.id = pos;
        if (!prioq_insert(pq, &pe)) break;
      }
    }
  }

  closedir(dir);
  if (d) logmsg(WHO, 112, FATAL, B("unable to read $MAILDIR/:", subdir));
  return 0;
}

int maildir_scan(prioq *pq, stralloc *filenames, int flagnew, int flagcur)
{
  struct prioq_elt pe;
  datetime_sec time;

  if (!stralloc_copys(filenames, "")) return 0;
  while (prioq_min(pq, &pe)) prioq_delmin(pq);

  time = now();

  if (flagnew && append(pq, filenames, "new", time) == -1) return -1;
  if (flagcur && append(pq, filenames, "cur", time) == -1) return -1;
  return 0;
}