summaryrefslogtreecommitdiff
path: root/src/maildir-delete.cc
blob: b0abb2a6fa3c173dea005fc3b030862a351a0737 (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
/**  --------------------------------------------------------------------
 *  @file maildir-delete.cc
 *  @brief Implementation of the Maildir class.
 *  @author Andreas Aardal Hanssen
 *  @date 2002-2005
 *  -----------------------------------------------------------------  **/
#include "maildir.h"

#include <errno.h>

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

using namespace ::std;
using namespace Binc;

namespace {

  bool recursiveDelete(const string &path)
  {
    DIR *mydir = opendir(path.c_str());
    if (mydir == 0) return false;

    struct dirent *mydirent;
    while ((mydirent = readdir(mydir)) != 0) {
      string d = mydirent->d_name;
      if (d == "." || d == "..") continue;

      string f = path + "/" + d;

      struct stat mystat;
      if (lstat(f.c_str(), &mystat) != 0) {
        if (errno == ENOENT) continue;
        return false;
      }

      if (S_ISDIR(mystat.st_mode)) {
        if (!recursiveDelete(f)) {
          closedir(mydir);
          return false;
        }
        if (rmdir(f.c_str()) != 0 && errno != ENOENT) {
          closedir(mydir);
          return false;
        }
      } else {
        if (unlink(f.c_str()) != 0 && errno != ENOENT) {
          closedir(mydir);
          return false;
        }
      }
    }

    closedir(mydir);
    return true;
  }
}

//------------------------------------------------------------------------
bool Binc::Maildir::deleteMailbox(const string &s_in)
{
  if (s_in == ".") {
    setLastError("disallowed by rule");
    return false;
  }

  if (!recursiveDelete(s_in)) {
    setLastError("error deleting Maildir - status is undefined");
    return false;
  }

  if (rmdir(s_in.c_str()) != 0) {
    setLastError("error deleting Maildir: " + string(strerror(errno)) + " - status is undefined");
    return false;
  }

  return true;
}