summaryrefslogtreecommitdiff
path: root/mail.local/main.c
blob: e1c9e6f3ff1b09a230f58a83d847405f5b4908c0 (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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/* GNU mailutils - a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.

   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, 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., 675 Mass Ave, Cambridge, MA 02139, USA.  */

#include <mail.local.h>

int debug_level;
int multiple_delivery;
int ex_quota_tempfail;
int exit_code = EX_OK;
uid_t uid;
char *quotadbname = NULL;
int lock_timeout = 300;

#define MAXFD 64
#define EX_QUOTA() (ex_quota_tempfail ? EX_TEMPFAIL : EX_UNAVAILABLE)

void close_fds ();
FILE *make_tmp (const char *from, char **tempfile);
void deliver (FILE *fp, char *name);
void guess_retval (int ec);
void mailer_err (char *fmt, ...);
void notify_biff (mailbox_t mbox, char *name, size_t size);

const char *argp_program_version = "mail.local (" PACKAGE_STRING ")";
static char doc[] = "GNU mail.local -- the local MDA";
static char args_doc[] = "recipient [recipient ...]";

#define ARG_MULTIPLE_DELIVERY 1
#define ARG_QUOTA_TEMPFAIL 2

static struct argp_option options[] = 
{
  { "ex-multiple-delivery-success", ARG_MULTIPLE_DELIVERY, NULL, 0,
    "Don't return errors when delivering to multiple recipients", 0 },
  { "ex-quota-tempfail", ARG_QUOTA_TEMPFAIL, NULL, 0,
    "Return temporary failure if disk or mailbox quota is exceeded", 0 },
  { "from", 'f', "EMAIL", 0,
    "Specify the sender's name" },
  { NULL, 'r', NULL, OPTION_ALIAS, NULL },
#ifdef USE_DBM
  { "quota-db", 'q', "FILE", 0,
    "Specify path to quota database", 0 },
#endif
#ifdef WITH_GUILE
  { "source", 's', "PATTERN", 0,
    "Set name pattern for user-defined mail filters", 0 },
#endif
  { "debug", 'x',
#ifdef WITH_GUILE
    "{NUMBER|guile}",
#else
    "NUMBER",
#endif
    0,
    "Enable debugging", 0 },
  { "timeout", 't', "NUMBER", 0,
    "Set timeout for acquiring the lockfile" },
  { NULL,      0, NULL, 0, NULL, 0 }
};

static error_t parse_opt (int key, char *arg, struct argp_state *state);

static struct argp argp = {
  options,
  parse_opt,
  args_doc, 
  doc,
  NULL,
  NULL, NULL
};

static const char *argp_capa[] = {
  "auth",
  "common",
  "license",
  "mailbox",
  "logging",
  NULL
};

char *from = NULL;
char *progfile_pattern = NULL;

static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  switch (key)
    {
    case ARG_MULTIPLE_DELIVERY:
      multiple_delivery = 1;
      break;

    case ARG_QUOTA_TEMPFAIL:
      ex_quota_tempfail = 1;
      break;

    case 'r':
    case 'f':
      if (from != NULL)
	{
	  mu_error ("multiple --from options");
	  return EX_USAGE;
	}
      from = arg;
      break;

#ifdef USE_DBM
    case 'q':
      quotadbname = arg;
      break;
#endif

#ifdef WITH_GUILE	
      case 's':
	progfile_pattern = optarg;
	break;
#endif
	
      case 't':
	lock_timeout = strtoul (optarg, NULL, 0);
	break;
	
      case 'x':
	if (optarg)
	  {
#ifdef WITH_GUILE
	    if (strcmp (optarg, "guile") == 0)
	      debug_guile = 1;
	    else
#endif
	      debug_level = strtoul (optarg, NULL, 0);
	  }
	else
	  {
	    debug_level = 9;
#ifdef WITH_GUILE	    
	    debug_guile = 1;
#endif
	  }
	break;

    default:
      return ARGP_ERR_UNKNOWN;

    case ARGP_KEY_ERROR:
      exit (EX_USAGE);
    }
  return 0;
}

int
main (int argc, char *argv[])
{
  FILE *fp;
  char *tempfile = NULL;
  int arg_index;
  
  /* Preparative work: close inherited fds, force a reasonable umask
     and prepare a logging. */
  close_fds ();
  umask (0077);

  mu_argp_error_code = EX_CONFIG;
  MU_AUTH_REGISTER_ALL_MODULES();
  mu_argp_parse (&argp, &argc, &argv, 0, argp_capa, &arg_index, NULL);
  
  openlog ("mail.local", LOG_PID, log_facility);
  mu_error_set_print (mu_syslog_error_printer);
  
  uid = getuid ();

  argc -= arg_index;
  argv += arg_index;

  if (!argc)
    {
      mu_error ("Missing arguments. Try --help for more info");
      return EX_USAGE;
    }

  /* Register local mbox formats. */
  {
    list_t bookie;
    registrar_get_list (&bookie);
    list_append (bookie, mbox_record); 
    list_append (bookie, path_record);
    /* Possible supported mailers.  */
    list_append (bookie, sendmail_record);
    list_append (bookie, smtp_record);
  }

  fp = make_tmp (from, &tempfile);
  
  if (multiple_delivery)
    multiple_delivery = argc > 1;

#ifdef WITH_GUILE
  if (progfile_pattern)
    {
      struct mda_data mda_data;
      
      memset (&mda_data, 0, sizeof mda_data);
      mda_data.fp = fp;
      mda_data.argv = argv;
      mda_data.progfile_pattern = progfile_pattern;
      mda_data.tempfile = tempfile;
      return prog_mda (&mda_data);
    }
#endif
  
  unlink (tempfile);
  for (; *argv; argv++)
    mda (fp, *argv);
  return exit_code;
}

int
mda (FILE *fp, char *username)
{
  deliver (fp, username);

  if (multiple_delivery)
    exit_code = EX_OK;

  return exit_code;
}

void
close_fds ()
{
  int i;
  long fdlimit = MAXFD;

#if defined (HAVE_SYSCONF) && defined (_SC_OPEN_MAX)
  fdlimit = sysconf (_SC_OPEN_MAX);
#elif defined (HAVE_GETDTABLESIZE)
  fdlimit = getdtablesize ();
#endif

  for (i = 3; i < fdlimit; i++)
    close (i);
}

int
switch_user_id (struct mu_auth_data *auth, int user)
{
  int rc;
  uid_t uid;
  
  if (auth->change_uid == 0)
    return 0;
  
  if (user)
    uid = auth->uid;
  else
    uid = 0;
  
#if defined(HAVE_SETREUID)
  rc = setreuid (0, uid);
#elif defined(HAVE_SETRESUID)
  rc = setresuid (-1, uid, -1);
#elif defined(HAVE_SETEUID)
  rc = seteuid (uid);
#else
# error "No way to reset user privileges?"
#endif
  if (rc < 0)
    mailer_err ("setreuid(0, %d): %s (r=%d, e=%d)",
		uid, strerror (errno), getuid (), geteuid ());
  return rc;
}

FILE *
make_tmp (const char *from, char **tempfile)
{
  time_t t;
  FILE *fp;
  char *buf = NULL;
  size_t n = 0;
  int line;

  *tempfile = mu_tempname (NULL);
  fp = fopen (*tempfile, "w+");

  if (fp == NULL)
    {
      mailer_err ("unable to open temporary file");
      exit (exit_code);
    }

  line = 0;
  while (getline (&buf, &n, stdin) > 0)
    {
      line++;
      if (line == 1)
	{
	  if (memcmp (buf, "From ", 5))
	    {
	      struct mu_auth_data *auth = NULL;
	      if (!from)
		{
		  auth = mu_get_auth_by_uid (uid);
		  if (auth)
		    from = auth->name;
		}
	      if (from)
		{
		  time (&t);
		  fprintf (fp, "From %s %s", from, ctime (&t));
		}
	      else
		{
		  mailer_err ("Can't determine sender address");
		  exit (EX_UNAVAILABLE);
		}
	      if (auth)
		mu_auth_data_free (auth);
	    }
	}
      else if (!memcmp (buf, "From ", 5))
	fputc ('>', fp);
      if (fputs (buf, fp) == EOF)
	{
	  mailer_err ("temporary file write error");
	  fclose (fp);
	  return NULL;
	}
    }
  
  if (buf && strchr (buf, '\n') == NULL)
    putc ('\n', fp);
  
  putc ('\n', fp);
  free (buf);
  
  return fp;
}

void
deliver (FILE *fp, char *name)
{
  mailbox_t mbox;
  char *path;
  url_t url = NULL;
  size_t n = 0;
  locker_t lock;
  struct mu_auth_data *auth;
  int status;
  stream_t stream;
  size_t size;
  int failed = 0;
#if defined(USE_DBM)
  struct stat sb;
#endif  
  
  auth = mu_get_auth_by_name (name);
  if (!auth)
    {
      mailer_err ("%s: no such user", name);
      exit_code = EX_UNAVAILABLE;
      return;
    }
  
  path = strdup (auth->mailbox);
  if (!path)
    {
      mailer_err ("Out of memory");
      return;
    }

  if ((status = mailbox_create (&mbox, path)) != 0)
    {
      mailer_err ("can't open mailbox %s: %s", path, mu_errstring (status));
      free (path);
      return;
    }

  free (path);
      
  mailbox_get_url (mbox, &url);
  path = (char*) url_to_string (url);

  /* Actually open the mailbox. Switch to the user's euid to make
     sure the maildrop file will have right privileges, in case it
     will be created */
  if (switch_user_id (auth, 1))
    return;
  status = mailbox_open (mbox, MU_STREAM_RDWR|MU_STREAM_CREAT);
  if (switch_user_id (auth, 0))
    return;
  if (status != 0)
    {
      mailer_err ("can't open mailbox %s: %s", path, mu_errstring (status));
      mailbox_destroy (&mbox);
      return;
    }
  
  mailbox_get_locker (mbox, &lock);
  locker_set_flags (lock, MU_LOCKER_PID|MU_LOCKER_RETRY);
  locker_set_retries (lock, lock_timeout);

  status = locker_lock (lock);

  if (status)
    {
      mailer_err ("cannot lock mailbox '%s': %s", path, mu_errstring (status));
      mailbox_destroy (&mbox);
      exit_code = EX_TEMPFAIL;
      return;
    }

  if ((status = mailbox_get_stream (mbox, &stream)))
    {
      mailer_err ("can't get stream for mailbox %s: %s",
		  path, mu_errstring (status));
      mailbox_destroy (&mbox);
      return;
    }

  if ((status = stream_size (stream, (off_t *) &size)))
    {
      mailer_err ("can't get stream size (mailbox %s): %s",
		  path, mu_errstring (status));
      mailbox_destroy (&mbox);
      return;
    }

#if defined(USE_DBM)
  switch (check_quota (name, size, &n))
    {
    case MQUOTA_EXCEEDED:
      mailer_err ("%s: mailbox quota exceeded for this recipient", name);
      exit_code = EX_QUOTA();
      failed++;
      break;
    case MQUOTA_UNLIMITED:
      break;
    default:
      if (fstat (fileno (fp), &sb))
	{
	  mailer_err ("cannot stat tempfile: %s", strerror (errno));
	  exit_code = EX_UNAVAILABLE;
	  failed++;
	}
      else if (sb.st_size > n)
	{
	  mailer_err ("%s: message would exceed maximum mailbox size for this recipient",
		      name);
	  exit_code = EX_QUOTA();
	  failed++;
	}
      break;
    }
#endif
  
  if (!failed && switch_user_id (auth, 1) == 0)
    {
      off_t off = size;
      size_t nwr;
      char *buf = NULL;

      n = 0;
      status = 0;
      fseek (fp, 0, SEEK_SET);
      while (getline(&buf, &n, fp) > 0)
	{
	  status = stream_write (stream, buf, strlen (buf), off, &nwr);
	  if (status)
	    {
	      mailer_err ("error writing to mailbox: %s",
			  mu_errstring (status));
	      break;
	    }
	  off += nwr;
	}
      free (buf);
      switch_user_id (auth, 0);
    }

  if (!failed)
    notify_biff (mbox, name, size);

  locker_unlock (lock);

  mu_auth_data_free (auth);
  mailbox_close (mbox);
  mailbox_destroy (&mbox);
}

void
notify_biff (mailbox_t mbox, char *name, size_t size)
{
  static int fd = -1;
  url_t url = NULL;
  char *buf = NULL;
  static struct sockaddr_in inaddr;
    
  if (fd == -1)
    {
      struct servent *sp;
      
      if ((sp = getservbyname ("biff", "udp")) == NULL)
	return;

      inaddr.sin_family = AF_INET;
      inaddr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
      inaddr.sin_port = sp->s_port;
      
      fd = socket (AF_INET, SOCK_DGRAM, 0);
      if (fd < 0)
	fd = -2; /* Mark failed initialization */
    }

  if (fd < 0)
    return;
  
  mailbox_get_url (mbox, &url);
  asprintf (&buf, "%s@%ld:%s", name, size, url_to_string (url));
  if (buf)
    {
      sendto (fd, buf, strlen (buf), 0, (struct sockaddr *)&inaddr,
	      sizeof inaddr);
      free (buf);
    }
}

void
mailer_err (char *fmt, ...)
{
  va_list ap;

  guess_retval (errno);
  va_start (ap, fmt);
  vfprintf (stderr, fmt, ap);
  fprintf (stderr, "\n");
  mu_verror (fmt, ap);
  va_end (ap);
}

int temp_errors[] = {
#ifdef EAGAIN
  EAGAIN, /* Try again */
#endif
#ifdef EBUSY
  EBUSY, /* Device or resource busy */
#endif
#ifdef EPROCLIM
  EPROCLIM, /* Too many processes */
#endif
#ifdef EUSERS
  EUSERS, /* Too many users */
#endif
#ifdef ECONNABORTED
  ECONNABORTED, /* Software caused connection abort */
#endif
#ifdef ECONNREFUSED
  ECONNREFUSED, /* Connection refused */
#endif
#ifdef ECONNRESET
  ECONNRESET, /* Connection reset by peer */
#endif
#ifdef EDEADLK
  EDEADLK, /* Resource deadlock would occur */
#endif
#ifdef EDEADLOCK
  EDEADLOCK, /* Resource deadlock would occur */
#endif
#ifdef EFBIG
  EFBIG, /* File too large */
#endif
#ifdef EHOSTDOWN
  EHOSTDOWN, /* Host is down */
#endif
#ifdef EHOSTUNREACH
  EHOSTUNREACH, /* No route to host */
#endif
#ifdef EMFILE
  EMFILE, /* Too many open files */
#endif
#ifdef ENETDOWN
  ENETDOWN, /* Network is down */
#endif
#ifdef ENETUNREACH
  ENETUNREACH, /* Network is unreachable */
#endif
#ifdef ENETRESET
  ENETRESET, /* Network dropped connection because of reset */
#endif
#ifdef ENFILE
  ENFILE, /* File table overflow */
#endif
#ifdef ENOBUFS
  ENOBUFS, /* No buffer space available */
#endif
#ifdef ENOMEM
  ENOMEM, /* Out of memory */
#endif
#ifdef ENOSPC
  ENOSPC, /* No space left on device */
#endif
#ifdef EROFS
  EROFS, /* Read-only file system */
#endif
#ifdef ESTALE
  ESTALE, /* Stale NFS file handle */
#endif
#ifdef ETIMEDOUT
  ETIMEDOUT,  /* Connection timed out */
#endif
#ifdef EWOULDBLOCK
  EWOULDBLOCK, /* Operation would block */
#endif
};
  

void
guess_retval (int ec)
{
  int i;
  /* Temporary failures override hard errors. */
  if (exit_code == EX_TEMPFAIL)
    return;
#ifdef EDQUOT
  if (ec == EDQUOT)
    {
      exit_code = EX_QUOTA();
      return;
    }
#endif

  for (i = 0; i < sizeof (temp_errors)/sizeof (temp_errors[0]); i++)
    if (temp_errors[i] == ec)
      {
	exit_code = EX_TEMPFAIL;
	return;
      }
  exit_code = EX_UNAVAILABLE;
}





Return to:

Send suggestions and report system problems to the System administrator.