summaryrefslogtreecommitdiff
path: root/tools/skrewt.c
blob: ed0e627081bc3e13cd26343467d1e19889f93b02 (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
///////////////////
// skrewt.c
//
// scrutinize email
//

#include <iostream>
#include <stdlib.h>             /* for exit() */
#include <string>               /* for strcmp() */
#include <ctype.h>              /* toupper */
#include <signal.h>

#include <stdio.h>              /* perror */
#include <sstream>
#include <vector>

using namespace std;

void usage(const int sts){
  (sts ? cerr : cout) <<
"Usage: skrewt [options]\n"
"\n"
"  Scrutinizes email.  Reads stdin, copies it to stdout.\n"
"  Exit result 0 means good, 21 means rejection (spam).\n"
"  Writes reason for rejection to stderr.\n"
"\n"
"  Typically used as a filter in a pipeline, along with spamc -E\n"
"  Options\n"
"    -help              print this msg (and exit immediately).\n"
"    -maxsize ii        msg size in bytes; anything bigger will be rejected.\n"
"\n"
"  Messages containing the string '-please-bounce-this-' will be rejected.\n"
"  Messages with no date will be rejected.\n"
;
  exit(sts);
}

//  error exit codes, mostly as stated in qmail.c
#define bar \
foo(good, 0) ;\
foo(spam, 21) ;\
foo(permerr, 31) ;\
foo(usage, 39) ;\
foo(greylisting, 70) ;\
foo(syserr, 71) ;\
foo(comerr, 74) ;

#define foo(name, num) const int ex_ ## name = num
bar
#undef foo


/////////////////////////////////////////////////////////
// Case insensitive comparison of strings

class lessthan_foldcase{
public:
  bool operator() (const std::string& a, const std::string& b) const {
    size_t a_len = a.length();
    size_t b_len = b.length();

    size_t lim = a_len < b_len ? a_len : b_len;

    for (size_t i=0; i<lim; ++i)
    {
            char cha = toupper(a[i]);
            char chb = toupper(b[i]);

            if (cha < chb) return true;
            if (cha > chb) return false;
    }
    // here if one is an extension of the other
    if ( a_len < b_len ) return true;
    return false;
  }
};


// Returns negative if a is less than b in alphabetical order
// returns 0 if they are the same, or positive if a is greater.
// Like perl cmp operator, but ignores case.
int cmp_casefold(const std::string& a, const std::string& b) {
  string::const_iterator aa, bb;
  aa = a.begin();
  bb = b.begin();
  while (aa != a.end() && bb != b.end()){
    char ca = tolower(*aa++);
    char cb = tolower(*bb++);
    if (ca != cb) return ca < cb ? -2 : 2;
  }
  if (aa != a.end()) return 1;          // a is longer
  if (bb != b.end()) return -1;         // b is longer
  return 0;
}


string toLower(const std::string& a){
  string rslt = a;
  string::iterator rr;
  for (rr = rslt.begin(); rr != rslt.end(); rr++){
    *rr = tolower(*rr);
  }
  return rslt;
}

////////////////
string ltrim(string foo){
  size_t where = foo.find_first_not_of(" \t\r\n");
  if (where == foo.npos) return foo;
  return foo.substr(where);
}

////////////////
// little utility to help with argument parsing:
//
int prefix(const string shorter, const string longer){
  return shorter == longer.substr(0, shorter.length());
}

void exeunt(const int sts){
  if (sts == ex_good) exit(sts);

  const char* foo = getenv("HI_Q_GROUP");
  if (!foo) exit(sts);

// No point in signalling ourself:
  sighandler_t rslt = signal(SIGUSR1, SIG_IGN);
  if (rslt == SIG_ERR) {
    cerr << "error setting signal" << endl;
  }
  int k = kill(-atoi(foo), SIGUSR1);
  if (k) {
    cerr << "kill failed on group " << atoi(foo) << " ... ";
    perror(0);
  }
  exit(sts);
}

string basename(const string path){
  size_t where = path.rfind("/");
  if (where != string::npos) return path.substr(1+where);
  return path;
}

string progname, progid;
int mypid;


/* Content-Type: text/plain; charset="us-ascii"                                         */
/* Content-Type: multipart/mixed; boundary="1170861315-1262462055-1341954763=:92165"    */
void parse_content(const string type_spec_line, string &maintype, string &boundary) {
      string mainline(type_spec_line);

      string get_type(toLower(mainline));
      size_t where = get_type.find_first_of(" \t;\n");
      if (where == string::npos) {
        // keep whole string
      }
      else {
        get_type = get_type.substr(0,where);
      }
      where = get_type.find("/");
      if (where == string::npos){
        maintype = "";
      } else {
        maintype = get_type.substr(0, where);
      }
}

#ifdef xxxxxxxxxxxxxxxxxxxx
      if
      if (0) cerr << "type (" << get_type << ")  "
            << (text_type?"text":"nope") << endl;


      string srch = "boundary=";
      where = headrec.find(srch);
      if (where != string::npos) {
        where += srch.length();
        boundary = headrec.substr(where);
        if (boundary[0] == '"') {
          boundary = boundary.substr(1);
          where = boundary.find_first_of("\"");
        } else {
          where = boundary.find_first_of(" \t;\n");
        }
        if (where == string::npos) {
          /* do nothing, boundary=boundary as a whole */
        } else {
          boundary = boundary.substr(0, where);
        }
      }
    }
#endif





////////////////////////////////////////////////////////////
int main(int _argc, const char** _argv){
////  pid_t pid = getpid();
////  cout << pid << endl;
////  cout << getpgid(pid) << endl;
  int argc(_argc);
  const char **argv(_argv);
  {
    progname = *argv++; argc--;
    mypid = getpid();
    stringstream binder;
    binder << basename(progname) << "[" << mypid << "]";
    progid = binder.str();
  }

  int maxsize(1000*1000);

  while (argc) {
    string arg(*argv); argv++; argc--;
    if (arg.substr(0,2) == "--") arg = arg.substr(1);
    if (prefix(arg, "-help")) {
      usage(0);
    }
    if (prefix(arg, "-maxsize")) {
      if (!argc) {
        cerr << "Option -maxsize requires an argument" << endl;
        exit(ex_usage);
      }
      maxsize = atoi(*argv); argv++; argc--;
    }
    if (arg.substr(0,1) == "-") {
      cerr << "Unrecognized option '" << arg << "'" << endl;
      cerr << "For help, try:  " << progname << " -help" << endl;
      exit(ex_usage);
    } else {
      cerr << "Extraneous verbiage '" << arg << "'" << endl;
      cerr << "For help, try:  " << progname << " -help" << endl;
      exit(ex_usage);
    }
  }

  int saw_blank_line(0);
  string boundary("x-xx-x");
  string date;
  string subject;
  string content_type;
  string message_id;
  int msgsize(0);
  vector<string> bigbuf;
  cerr <<  "hi there" << endl;

  for (;;){             // outer loop over all records in the header
    if (cin.eof()) break;
    if (cin.bad()) return 1;

    string headrec;
// on fail, go back to top of outer loop and check for eof versus bad
    if (getline(cin, headrec).fail()) continue;
    msgsize += headrec.length()+1;
    if (msgsize > maxsize) {
      cerr << progid << " rejection: bigger than " << maxsize << endl;
      exeunt(ex_spam);
    }
    cout << headrec << endl;
    bigbuf.push_back(headrec);  // for a folded record, this is the first line

    for (;;) {        // inner loop to build a multi-line record e.g. folded record:
      if (cin.eof()) break;
      if (cin.bad()) return 1;
      char ch;
      if (cin.get(ch).fail()) continue;
      cin.putback(ch);
      if (ch != ' ' && ch != '\t') break;
      string line;
// on fail, go back to top of inner loop and check for eof versus bad
      if (getline(cin, line).fail()) continue;
      msgsize += line.length()+1;
      if (msgsize > maxsize) {
        cerr << progid << " rejection: bigger than " << maxsize << endl;
        exeunt(ex_spam);
      }
      cout << line << endl;
      bigbuf.push_back(line);
      string cooked(line);
      if (cooked.length()){
        string::iterator ptr = cooked.end()-1;
        if (*ptr == '\r') cooked.erase(ptr);
      }
      headrec += "\n" + cooked;
    }
// here with a fully assembled header record
    int len = headrec.length();
    if (len && headrec[len-1] == '\r') len--;  // reduced length, not counting <cr>
    if (len == 0) {
      saw_blank_line = 1;
      break;            // no more headers in this message
    }

// here if it's a header line
    string headword;
    string rest;
    size_t where = headrec.find(":");
    if (where != string::npos) {
      headword = headrec.substr(0, where);
      rest = ltrim(headrec.substr(1+where));
    }
    headword = toLower(headword);
    if (0){
    } else if (headword == "date") {
      date = rest;
    } else if (headword == "subject") {
      subject = rest;
    } else if (headword == "content-type") {
      content_type = rest;
    }
    //xxxx  cout << headrec.length() << " ... ";
  }
  cerr << "headers are done. Delimited: " << saw_blank_line << endl;

// Headers are done.
// Do some early-stage thinking.

  if (subject.find("-please-bounce-this-") != string::npos) {
    cerr << progid << " rejection: by request" << endl;
    exeunt(ex_spam);
  }

  if (!date.length()) {
    cerr << progid << " rejection: no date" << endl;
    exeunt(ex_spam);              // disallow mail with no date
  }

  string contype;
  int textlines(0);
  parse_content(content_type, contype, boundary);
  int is_text = contype == "text";

// early-stage thinking has been done.
// Now spew the rest of the message
  cerr << "body begins: " << contype << " " << is_text << endl;
  int inheads(0);
  for (;;){             // outer loop over all lines in the body
    if (cin.eof()) break;
    if (cin.bad()) return 1;
    string line;
// on fail, go back to top of outer loop and check for eof versus bad
    if (getline(cin, line).fail()) continue;
    msgsize += line.length()+1;
    if (msgsize > maxsize) {
      cerr << progid << " rejection: bigger than " << maxsize << endl;
      exeunt(ex_spam);
    }
    bigbuf.push_back(line);
    cout << line << endl;
    if (line == "--" + boundary) {
      inheads = 1;
    } else {
      if (is_text) {
        if (ltrim(line).length()) textlines++;
      }
    }
  }

  if (0) cerr << "textlines: " << textlines << endl;
  if (000 && !textlines) {
    cerr << progid << " rejection: no text" << endl;
    exeunt(ex_spam);
  }
  cerr << progid << " normal completion" << endl;
  exit(ex_good);
}