File: mailfilter.cc

package info (click to toggle)
mailfilter 0.8.6-2
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 3,280 kB
  • ctags: 2,501
  • sloc: cpp: 2,452; sh: 1,393; ansic: 1,259; lex: 570; yacc: 468; makefile: 167; perl: 72
file content (444 lines) | stat: -rw-r--r-- 12,401 bytes parent folder | download | duplicates (2)
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// mailfilter.cc - source file for the mailfilter program
// Copyright (c) 2000 - 2012  Andreas Bauer <baueran@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <csignal>
#include <stdexcept>
#include <vector>
#include "mailfilter.hh"
#include "preferences.hh"
#include "feedback.hh"
#include "weeder.hh"

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

extern "C"
{
#include "time.h"
#include <sys/time.h>                                                    
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#else
#include "getopt.h"
#endif
}

using namespace std;

static struct option long_options[] =
  {
    {"help", 0, NULL, VALUE_HELP},
    {"verbose", 1, NULL, VALUE_VERBOSE},
    {"mailfilterrc", 1, NULL, VALUE_MAILFILTERRC},
    {"logfile", 1, NULL, VALUE_LOGFILE},
    {"ignore-time-stamps", 0, NULL, VALUE_TIMESTAMP},
    {"version", 0, NULL, VALUE_VERSION},
    {"test", 0, NULL, VALUE_TEST},
    {"return-value", 0, NULL, VALUE_RETURN},
    {0, 0, 0, 0}
  };

struct sigaction    sigact;
Weeder              weeder;
int                 mailbox_status;

void   init_app               (void);
bool   open_prefs             (string);
void   get_opts               (int argc, char* argv[]);
void   override_prefs         (string);
int    cmp_no_case            (const string&, const string&);
int    precompile_expressions (void);
void   connect_sigint         (int);
string int_to_string          (int);

int main (int argc, char* argv[])
{
  Feedback* logger = Feedback :: Instance ();
  time_t now;
  struct timeval tv;
  struct timezone tz;
  string options_set;
  int    return_val = 0;

  init_app ();

  // Read the user's command line options.
  if (argc > 1)
    get_opts (argc, argv);

  // Try to open the program's configuration file.
  if (!(Preferences :: Instance ().
	open (Preferences :: Instance ().rc_file ().c_str ())))
    {
      ERROR_MSG("The rcfile could not be opened.");
      return -1;
    }

  // If an rcfile was located, try to read it.  The error handling,
  // however, is done inside the Preferences class.  Should something
  // go wrong, we merely need to exit here.  There's no point in
  // logging to external files, since they may not yet be defined, or
  // even be writeable.
  try
    {
      if (!Preferences :: Instance ().load ())
	{
	  ERROR_MSG("Loading the rcfile failed.");
	  return -1;
	}
    }
  catch (const exception& r_err)
    {
      ERROR_MSG("Runtime exception occurred: "
		+ (string)r_err.what ());
      return -1;
    }

  // Now that the log file should be specified, try to open it and
  // spit out an error in case it can't be located, or the file
  // permissions don't allow writing to it.
  if (!logger->open (Preferences :: Instance ().log_file ().c_str ()))
  {
    if (Preferences :: Instance ().log_file ().length ())
      ERROR_MSG("Could not open log file '" +
		Preferences :: Instance ().log_file () + "' for writing.");
    else
      ERROR_MSG("Could not locate log file.");
    return -1;
  }

  // Set sigint signal handler
  sigact.sa_handler = connect_sigint;
  sigemptyset (&sigact.sa_mask);
  sigact.sa_flags = 0;
  
  if (sigaction (SIGINT, &sigact, NULL) < 0)
    {
      ERROR_MSG("Signal handler could not be installed.");
      exit (-1);
    }

  try
    {
      // Try to precompile all filters.
      if (precompile_expressions () != 0)
	return -1;
      
      // Start checking for spam mails in the user defined accounts.
      vector<Account> :: iterator cur_account = 
	Preferences :: Instance ().accounts ()->begin ();
      while (cur_account != Preferences :: Instance ().accounts ()->end ())
	{
	  gettimeofday (&tv, &tz);
	  now = tv.tv_sec;
	  
	  // Some versions of ctime () terminate with "\n\0", some don't.
	  string today_ = ctime (&now);
	  if (today_[today_.length () - 1] == '\n')
	    {
	      char* today = (char*)malloc (sizeof (char) * today_.length ());
	      snprintf (today, today_.length (), "%s", ctime (&now));
	      today_ = today;
	      free (today);
	    }
	  logger->print_msg ((string)PACKAGE_VERSION
			    + " querying "
			    + cur_account->usr () + "@"
			    + cur_account->server () + " on "
			    + today_ + ".",
			    3);
	  
	  if (cur_account->check () != 0)
	    {
	      logger->print_err ("Skipping account "
				 + cur_account->usr () + "@"
				 + cur_account->server ()
				 + " due to earlier errors.");
	      return_val = -1;
	    }
	  cur_account++;
	}
    }
  catch (const exception& r_err)
    {
      logger->print_err ("Runtime exception occurred: "
			+ (string)r_err.what ());
      return -1;
    }

  // Mailfilter can return the number of pending mails to be
  // downloaded, e.g., when embeddeding it into a script.
  if (Preferences :: Instance ().return_status ())
    return mailbox_status;
  return return_val;
}

// This function is being run before Mailfilter starts to read the
// configuration files and establishes any sort of network connection.
// All initialisation stuff should go in here.

void init_app (void)
{
  mailbox_status = 0;

#ifdef USE_NLS
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE_NAME, LOCALEDIR);
  textdomain (PACKAGE_NAME);
#endif
}

// The funciton getopts can be used to retrieve user specific command
// line options like '--help', for instance.  The rcfile file path is
// retrieve via get_opts_rcfile as we need to first read the rcfile,
// and then later use this function to override its settings.

void get_opts (int argc, char* argv[])
{
  int option = 0;
  int option_index = 0;

  while ((option = getopt_long (argc, argv, "hL:M:Vv:tir",
				long_options, &option_index)) != -1)
    {
      switch (option)
	{
	case 'h':
	case VALUE_HELP:
	  cout << "Mailfilter filters e-mail and removes spam in one ";
	  cout << "or many POP accounts." << endl;
	  cout << endl;
	  cout << "Usage: " << PACKAGE_NAME << " [OPTION]..." << endl;
	  cout << endl;
	  cout << "If a long option shows an argument as mandatory, ";
	  cout << "then " << endl;
	  cout << "it is mandatory for the equivalent short option ";
	  cout << "also." << endl;
	  cout << endl;
	  cout << "Options:" << endl;
	  cout << "  -h, --help                 ";
	  cout << "Display this help information" << endl;
	  cout << "  -L, --logfile=FILE         ";
	  cout << "Specify logfile location" << endl;
	  cout << "  -M, --mailfilterrc=FILE    ";
	  cout << "Specify rcfile location" << endl;
	  cout << "  -r, --return-value         ";
	  cout << "Enable additional return values" << endl;
	  cout << "  -t, --test                 ";
	  cout << "Simulate deletes" << endl;
	  cout << "  -i, --ignore-time-stamps   ";
	  cout << "Ignore invalid Message-ID time stamps (Do not use unless you know better!)" << endl;
	  cout << "  -v, --verbose=LEVEL        ";
	  cout << "Specify level of verbosity" << endl;
	  cout << "  -V, --version              ";
	  cout << "Display version information" << endl;
	  cout << endl;
	  cout << "Report bugs to ";
	  cout << "<baueran@users.sourceforge.net>." << endl;
	  exit (0);
	  break;
	case 'V':
	case VALUE_VERSION:
          cout << PACKAGE_NAME << " " << PACKAGE_VERSION << endl;
          cout << endl;
	  cout << PACKAGE_COPYRIGHT << endl;
          cout << endl;
          cout << "This is free software; see the source for copying ";
	  cout << "conditions.  There is NO warranty; not even for ";
	  cout << "MERCHANTABILITY or FITNESS FOR A PARTICULAR ";
	  cout << "PURPOSE." << endl;
          exit (0);
	  break;
        case 'L':
        case VALUE_LOGFILE:
          Preferences :: Instance ().set_log_file (optarg);
          break;
        case 'v':
        case VALUE_VERBOSE:
	  Preferences :: Instance ().set_verbose_level (atoi (optarg));
          break;
	case 't':
	case VALUE_TEST:
	  Preferences :: Instance ().set_test_mode ("yes");
	  break;
	case 'i':
	case VALUE_TIMESTAMP:
	  Preferences :: Instance().set_ignore_time_stamp();
	  break;
	case 'r':
	case VALUE_RETURN:
	  Preferences :: Instance ().set_return_status (true);
	  break;
	case 'M':
	case VALUE_MAILFILTERRC:
	  Preferences :: Instance ().set_rc_file (optarg);
	  break;
	default:
	  // Command line option not recognised.
	  cerr << "Try '" << argv[0]
	       << " --help' for more information." << endl;
	  exit (-1);
	}
    }
}

// This function precompiles the allow, deny, and score expressions
// of the user's rcfile.  It returns a value different to 0 upon error.

int precompile_expressions (void)
{
  int comp_err = 0;

  try
    {
      vector<Filter> :: iterator cur_filter = 
	Preferences :: Instance ().allow_filters ()->begin ();
      while (cur_filter != 
	     Preferences :: Instance ().allow_filters ()->end ())
	{
	  if ((comp_err = cur_filter->compile ()) != 0)
	    {
	      ERROR_MSG("Could not compile regular expression (allow).");
	      return comp_err;
	    }
	  cur_filter++;
	}
      
      cur_filter = Preferences :: Instance ().deny_filters ()->begin ();
      while (cur_filter != Preferences :: Instance ().deny_filters ()->end ())
	{ 
	  if ((comp_err = cur_filter->compile ()) != 0)
	    {
	      ERROR_MSG("Could not compile regular expression (deny).");
	      return comp_err;
	    }
	  cur_filter++;
	}
      
      vector<Score> :: iterator cur_score = 
	Preferences :: Instance ().score_filters ()->begin ();
      while (cur_score != Preferences :: Instance ().score_filters ()->end ())
	{
	  if ((comp_err = cur_score->compile ()) != 0)
	    {
	      ERROR_MSG("Could not compile regular expression (score).");
	      return comp_err;
	}
	  cur_score++;
	}
    }
  catch (...) {  throw;  }

  return comp_err;
}

// Comapre two strings, but disregard case-sensitivity.  Returns 0, if
// no differences could be determined, a negative integer if s is
// lexicographically before s2, and a positive integer otherwise.
// (See also Stroustrup �20.3.8.)

int cmp_no_case (const string& s, const string& s2)
{
  string :: const_iterator p = s.begin ();
  string :: const_iterator p2 = s2.begin ();
  
  while (p != s.end () && p2 != s2.end ())
    {
      if (toupper (*p) != toupper (*p2))
	return (toupper (*p) < toupper (*p2))? -1 : 1;
      ++p;
      ++p2;
    }

  return (s2.size () == s.size ())? 0 : (s.size () < s2.size ())? -1 : 1;
}

// This function executes the string given in command through a
// POSIX shell.  It returns the first string of the shell's
// output without the trailing '\n'; instead it terminates with
// '\0'.

string exec_shell (const char* command)
{
  FILE *fp;
  const int SIZEBUF = 256;
  static char buf [SIZEBUF];
  string cur_string;
  
  if ((fp = popen (command, "r")) != NULL)
    {
      if (fgets (buf, sizeof (buf), fp) == NULL)
	{
	  ERROR_MSG("popen failed.");
	  exit (-1);
	}
      cur_string = buf;
      
      if (cur_string[cur_string.size () - 1] != '\n')
	{
	  ERROR_MSG("popen failed.");
	  exit (-1);
	}
      else
	// Remove the trailing new line, or it messes up
	// the file paths in the config files.
	cur_string[cur_string.size () - 1] = '\0';
      
      if (pclose(fp) == -1)
	{
	  ERROR_MSG("pclose failed.");
	  exit (-1);
	}
    }
  
  return cur_string;
}

string int_to_string (int val)
{
  string tmp;
  ostringstream ostr;
  ostr << val;
  tmp = ostr.str ();
  return tmp;
}

void connect_sigint (int signo)
{
  sigset_t mask_set;
  sigset_t old_set;
  
  // Mask other signals while we prompt to cerr and finally quit
  signal (SIGINT, connect_sigint);
  sigfillset (&mask_set);
  sigprocmask (SIG_SETMASK, &mask_set, &old_set);

  cout << PACKAGE_NAME \
       << ": Error: Program abort due to signal "
       << signo
       << "." 
       << endl;
  exit (-1);
}