summaryrefslogtreecommitdiff
path: root/tools/greylist.c
blob: 8adac056e3823f3c25b8d0956c7a9c5b760d7028 (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
#include <stdlib.h>             /* for exit(), getenv() */
#include <iostream>
#include <string>

#include <sys/types.h>          /* for stat() */
#include <sys/stat.h>           /* for stat() */
#include <unistd.h>             /* for stat() */
#include <stdio.h>              /* for perror */
#include <errno.h>              /* for ENOENT */
#include <fstream>              /* for ofstream() */
#include <fcntl.h>              /* for creat() */
using namespace std;

const int sa_good = 0;
const int bug_bait_grey = 1;
// qmail_queue and spamc have similar interpretations here:
const int sa_syserr = 71;

pid_t mypid;
string progname;

void dump(const string var){
  char* str = getenv(var.c_str());
  cerr << progname 
    << "[" << mypid << "] "
    << var;
  if (str) cerr << " is set to '" << str << "'" << endl;
  else  cerr << " is not set." << endl;
}

const string dirname("/var/qmail/greylist");

   //       int stat(const char *path, struct stat *buf);
   //       int fstat(int fd, struct stat *buf);
   //       int lstat(const char *path, struct stat *buf);

int main(int argc, char** argv){
  mypid = getpid();
  progname = argv[0];
//  dump("TCPREMOTEIP");
//  dump("TCPREMOTEHOST");

  char* ipvar = getenv("TCPREMOTEIP");
  if (!ipvar) {
    cerr << progname << ": TCPREMOTEIP not set???" << endl;
    exit(sa_syserr);
  }
  string ipbase = ipvar;

// see if our directory exists:
  struct stat dirstat;
  int rslt = stat(dirname.c_str(), &dirstat);
  if (rslt != 0){
    if (errno != ENOENT) {
      cerr << progname << ": stat failed for '"
        << dirname << "' : ";
      perror(0);
    }
    rslt = mkdir(dirname.c_str(), 0755);
    if (rslt != 0) {
      cerr << progname
        << "uid " << getuid()
        << ": mkdir failed for '"
        << dirname << "' : ";
      perror(0);
      exit(sa_syserr);
    }
  }
  
  string ipname = dirname + "/" + ipbase;
  struct stat ipstat;
  rslt = stat(ipname.c_str(), &ipstat);
  if (rslt != 0){
    if (errno != ENOENT) {
      cerr << progname << ": stat failed for '"
        << ipname << "' : ";
      perror(0);
    }
    ofstream foo;
    int fd = creat(ipname.c_str(), 0644);
    if (fd < 0){
      cerr << progname << ": create failed for '"
        << ipname << "' : ";
      perror(0);
    }
    close(fd);
    return(bug_bait_grey);
  } else {
    cerr <<  "file exists: " << ipname << endl;
  }
  return 0;
}