main.c 26.1 KB
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 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
/* GNU Mailutils -- a suite of utilities for electronic mail
   Copyright (C) 1999, 2000, 2001, 2002, 2005, 
   2007, 2008 Free Software Foundation, Inc.

   GNU Mailutils 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 3, or (at your option)
   any later version.

   GNU Mailutils 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 GNU Mailutils; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
   MA 02110-1301 USA */

#include <mail.local.h>
#include "mailutils/libargp.h"

int multiple_delivery;     /* Don't return errors when delivering to multiple
			      recipients */
int ex_quota_tempfail;     /* Return temporary failure if mailbox quota is
			      exceeded. If this variable is not set, mail.local
			      will return "service unavailable" */
int exit_code = EX_OK;     /* Exit code to be used */
uid_t uid;                 /* Current user id */
char *quotadbname = NULL;  /* Name of mailbox quota database */
char *quota_query = NULL;  /* SQL query to retrieve mailbox quota */

/* Debuggig options */
int debug_level;           /* General debugging level */ 
int debug_flags;           /* Mailutils debugging flags */
int sieve_debug_flags;     /* Sieve debugging flags */
int sieve_enable_log;      /* Enables logging of executed Sieve actions */
char *message_id_header;   /* Use the value of this header as message
			      identifier when logging Sieve actions */
mu_debug_t mudebug;        /* Mailutils debugging object */


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

void close_fds (void);
int make_tmp (const char *from, mu_mailbox_t *mbx);
void deliver (mu_mailbox_t msg, char *name);
void guess_retval (int ec);
void notify_biff (mu_mailbox_t mbox, char *name, size_t size);

const char *program_version = "mail.local (" PACKAGE_STRING ")";
static char doc[] =
N_("GNU mail.local -- the local MDA")
"\v"
N_("Debug flags are:\n\
  g - guimb stack traces\n\
  T - mailutils traces (MU_DEBUG_TRACE0-MU_DEBUG_TRACE9)\n\
  P - network protocols (MU_DEBUG_PROT)\n\
  t - sieve trace (MU_SIEVE_DEBUG_TRACE)\n\
  i - sieve instructions trace (MU_SIEVE_DEBUG_INSTR)\n\
  l - sieve action logs\n\
  0-9 - Set mail.local debugging level\n");

static char args_doc[] = N_("recipient [recipient ...]");

#define ARG_MULTIPLE_DELIVERY 1
#define ARG_QUOTA_TEMPFAIL    2
#define ARG_MESSAGE_ID_HEADER 3
#define ARG_QUOTA_QUERY       4

static struct argp_option options[] = 
{
  { "ex-multiple-delivery-success", ARG_MULTIPLE_DELIVERY, NULL, 0,
    N_("Do not return errors when delivering to multiple recipients"), 0 },
  { "ex-quota-tempfail", ARG_QUOTA_TEMPFAIL, NULL, 0,
    N_("Return temporary failure if disk or mailbox quota is exceeded"), 0 },
  { "from", 'f', N_("EMAIL"), 0,
    N_("Specify the sender's name") },
  { NULL, 'r', NULL, OPTION_ALIAS, NULL },
#ifdef USE_DBM
  { "quota-db", 'q', N_("FILE"), 0,
    N_("Specify path to quota DBM database"), 0 },
#endif
#ifdef USE_SQL
  { "quota-query", ARG_QUOTA_QUERY, N_("STRING"), 0,
    N_("SQL query to retrieve mailbox quota"), 0 },
#endif
  { "sieve", 'S', N_("PATTERN"), 0,
    N_("Set name pattern for user-defined Sieve mail filters"), 0 },
  { "message-id-header", ARG_MESSAGE_ID_HEADER, N_("STRING"), 0,
    N_("Identify messages by the value of this header when logging Sieve actions"), 0 },
#ifdef WITH_GUILE
  { "source", 's', N_("PATTERN"), 0,
    N_("Set name pattern for user-defined Scheme mail filters"), 0 },
#endif
  { "debug", 'x', N_("FLAGS"), 0,
    N_("Enable debugging"), 0 },
  { 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",
  "debug",
  "license",
  "logging",
  "mailbox",
  "locking",
  "mailer",
  NULL
};

char *from = NULL;
char *progfile_pattern = NULL;
char *sieve_pattern = NULL;
char *saved_envelope;  /* A hack to spare mu_envelope_ calls */

#define D_DEFAULT "9s"

static void
set_debug_flags (mu_debug_t debug, const char *arg)
{
  for (; *arg; arg++)
    {
      switch (*arg)
	{
	case 'g':
#ifdef WITH_GUILE
	  debug_guile = 1;
#endif
	  break;

	case 't':
	  sieve_debug_flags |= MU_SIEVE_DEBUG_TRACE;
	  break;
	  
	case 'i':
	  sieve_debug_flags |= MU_SIEVE_DEBUG_INSTR;
	  break;
	  
	case 'l':
	  sieve_enable_log = 1;
	  break;
	  
	case 'T':
	  debug_flags |= MU_DEBUG_LEVEL_UPTO (MU_DEBUG_TRACE7);
	  break;
	  
	case 'P':
	  debug_flags |= MU_DEBUG_LEVEL_MASK (MU_DEBUG_PROT);
	  break;

	default:
	  if (isdigit (*arg))
	    debug_level = *arg - '0';
	  else if (debug)
	    mu_cfg_format_error (debug, MU_DEBUG_ERROR,
				 _("%c is not a valid debug flag"),
				 *arg);
	  else
	    mu_error (_("%c is not a valid debug flag"), *arg);
	  break;
	}
    }
}

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

  switch (key)
    {
    case ARG_MULTIPLE_DELIVERY:
      mu_argp_node_list_new (&lst, "ex-multiple-delivery-success", "yes");
      break;

    case ARG_QUOTA_TEMPFAIL:
      mu_argp_node_list_new (&lst, "ex-quota-tempfail", "yes");
      break;

    case ARG_MESSAGE_ID_HEADER:
      mu_argp_node_list_new (&lst, "message-id-header", arg);
      break;

    case ARG_QUOTA_QUERY:
      mu_argp_node_list_new (&lst, "quota-query", arg);
      break;
      
    case 'r':
    case 'f':
      if (from != NULL)
	{
	  argp_error (state, _("Multiple --from options"));
	  return EX_USAGE;
	}
      from = arg;
      break;
      
#ifdef USE_DBM
    case 'q':
      mu_argp_node_list_new (&lst, "quota-db", arg);
      break;
#endif

#ifdef WITH_GUILE	
    case 's':
      mu_argp_node_list_new (&lst, "source", arg);
      break;
#endif

    case 'S':
      mu_argp_node_list_new (&lst, "sieve", arg);
      break;
      
    case 'x':
      mu_argp_node_list_new (&lst, "debug", arg ? arg : D_DEFAULT);
      break;
      
    case ARGP_KEY_INIT:
      mu_argp_node_list_init (&lst);
      break;
      
    case ARGP_KEY_FINI:
      mu_argp_node_list_finish (&lst, NULL, NULL);
      break;
      
    default:
      return ARGP_ERR_UNKNOWN;

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


static int
cb_debug (mu_debug_t debug, void *data, char *arg)
{
  set_debug_flags (debug, arg);
  return 0;
}

struct mu_cfg_param mail_local_cfg_param[] = {
  { "ex-multiple-delivery-success", mu_cfg_bool, &multiple_delivery, 0, NULL,
    N_("In case of multiple delivery, exit with code 0 if at least one "
       "delivery succeeded.") },
  { "ex-quota-tempfail", mu_cfg_bool, &ex_quota_tempfail, 0, NULL,
    N_("Indicate temporary failure if the recipient is over his mail quota.")
  },
#ifdef USE_DBM
  { "quota-db", mu_cfg_string, &quotadbname, 0, NULL,
    N_("Name of DBM quota database file."),
    N_("file") },
#endif
#ifdef USE_SQL
  { "quota-query", mu_cfg_string, &quota_query, 0, NULL,
    N_("SQL query to retrieve mailbox quota.  This is deprecated, use "
       "sql { ... } instead."),
    N_("query") },
#endif
  { "sieve-filter", mu_cfg_string, &sieve_pattern, 0, NULL,
    N_("File name or name pattern for Sieve filter file."),
    N_("file-or-pattern") },
  { "message-id-header", mu_cfg_string, &message_id_header, 0, NULL,
    N_("When logging Sieve actions, identify messages by the value of "
       "this header."),
    N_("name") },
#ifdef WITH_GUILE
  { "guile-filter", mu_cfg_string, &progfile_pattern, 0, NULL,
    N_("File name or name pattern for Guile filter file."),
    N_("file-or-pattern") },
#endif
  { "debug", mu_cfg_callback, NULL, 0, cb_debug,
    N_("Set mail.local debug level.  Debug level consists of one or more "
       "of the following letters:\n"
       "  g - guimb stack traces\n"
       "  t - sieve trace (MU_SIEVE_DEBUG_TRACE)\n"
       "  i - sieve instructions trace (MU_SIEVE_DEBUG_INSTR)\n"
       "  l - sieve action logs\n") },
  { NULL }
};



static int
_sieve_debug_printer (void *unused, const char *fmt, va_list ap)
{
  mu_diag_vprintf (MU_DIAG_DEBUG, fmt, ap);
  return 0;
}

static void
_sieve_action_log (void *user_name,
		   const mu_sieve_locus_t *locus, size_t msgno,
		   mu_message_t msg,
		   const char *action, const char *fmt, va_list ap)
{
  int pfx = 0;
  mu_debug_t debug;

  mu_diag_get_debug (&debug);
  mu_debug_set_locus (debug, locus->source_file, locus->source_line);
  
  mu_diag_printf (MU_DIAG_NOTICE, _("(user %s) "), (char*) user_name);
  if (message_id_header)
    {
      mu_header_t hdr = NULL;
      char *val = NULL;
      mu_message_get_header (msg, &hdr);
      if (mu_header_aget_value (hdr, message_id_header, &val) == 0
	  || mu_header_aget_value (hdr, MU_HEADER_MESSAGE_ID, &val) == 0)
	{
	  pfx = 1;
	  mu_diag_printf (MU_DIAG_NOTICE, _("%s on msg %s"), action, val);
	  free (val);
	}
    }
  
  if (!pfx)
    {
      size_t uid = 0;
      mu_message_get_uid (msg, &uid);
      mu_diag_printf (MU_DIAG_NOTICE, _("%s on msg uid %d"), action, uid);
    }
  
  if (fmt && strlen (fmt))
    {
      mu_diag_printf (MU_DIAG_NOTICE, "; ");
      mu_diag_vprintf (MU_DIAG_NOTICE, fmt, ap);
    }
  mu_diag_printf (MU_DIAG_NOTICE, "\n");
  mu_debug_set_locus (debug, NULL, 0);
}

static int
_sieve_parse_error (void *user_name, const char *filename, int lineno,
		    const char *fmt, va_list ap)
{
  mu_debug_t debug;

  mu_diag_get_debug (&debug);
  if (filename)
    mu_debug_set_locus (debug, filename, lineno);

  mu_diag_printf (MU_DIAG_NOTICE, _("(user %s) "), (char*) user_name);
  mu_diag_vprintf (MU_DIAG_NOTICE, fmt, ap);
  mu_diag_printf (MU_DIAG_NOTICE, "\n");
  mu_debug_set_locus (debug, NULL, 0);
  return 0;
}

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

  /* Native Language Support */
  MU_APP_INIT_NLS ();

  /* Default locker settings */
  mu_locker_set_default_flags (MU_LOCKER_PID|MU_LOCKER_RETRY,
			       mu_locker_assign);
  mu_locker_set_default_retry_timeout (1);
  mu_locker_set_default_retry_count (300);

  /* Register needed modules */
  MU_AUTH_REGISTER_ALL_MODULES();
  /* Parse command line */
  mu_gocs_register ("sieve", mu_sieve_module_init);
  mu_argp_init (program_version, NULL);
  if (mu_app_init (&argp, argp_capa, mail_local_cfg_param,
		   argc, argv, 0, &arg_index, NULL))
    exit (EX_CONFIG);

  uid = getuid ();

  if (uid == 0)
    {
      mu_debug_t debug;

      openlog ("mail.local", LOG_PID, log_facility);
      mu_diag_get_debug (&debug);
      mu_debug_set_print (debug, mu_diag_syslog_printer, NULL);
    }
  
  if (debug_flags)
    {
      int rc;
      
      if ((rc = mu_debug_create (&mudebug, NULL)))
	{
	  mu_error (_("mu_debug_create failed: %s\n"), mu_strerror (rc));
	  exit (EX_TEMPFAIL);
	}
      if ((rc = mu_debug_set_level (mudebug, debug_flags)))
	{
	  mu_error (_("mu_debug_set_level failed: %s\n"),
		    mu_strerror (rc));
	  exit (EX_TEMPFAIL);
	}
    }
  
  argc -= arg_index;
  argv += arg_index;

  if (!argc)
    {
      if (uid)
	{
	  static char *s_argv[2];
	  struct mu_auth_data *auth = mu_get_auth_by_uid (uid);

	  if (!uid)
	    {
	      mu_error (_("Cannot get username"));
	      return EX_UNAVAILABLE;
	    }
	    
	  s_argv[0] = auth->name;
	  argv = s_argv;
	  argc = 1;
	}
      else
	{
	  mu_error (_("Missing arguments. Try --help for more info."));
	  return EX_USAGE;
	}
    }

  mu_register_all_formats ();
  /* Possible supported mailers.  */
  mu_registrar_record (mu_sendmail_record);
  mu_registrar_record (mu_smtp_record);

  if (make_tmp (from, &mbox))
    exit (exit_code);
  
  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.mbox = mbox;
      mda_data.argv = argv;
      mda_data.progfile_pattern = progfile_pattern;
      return prog_mda (&mda_data);
    }
#endif
  
  for (; *argv; argv++)
    mda (mbox, *argv);
  return exit_code;
}

int
sieve_test (struct mu_auth_data *auth, mu_mailbox_t mbx)
{
  int rc = 1;
  char *progfile;
    
  if (!sieve_pattern)
    return 1;

  progfile = mu_expand_path_pattern (sieve_pattern, auth->name);
  if (access (progfile, R_OK))
    {
      if (debug_level > 2)
	mu_diag_output (MU_DIAG_DEBUG, _("Access to %s failed: %m"), progfile);
    }
  else
    {
      mu_sieve_machine_t mach;
      rc = mu_sieve_machine_init (&mach, auth->name);
      if (rc)
	{
	  mu_error (_("Cannot initialize sieve machine: %s"),
		    mu_strerror (rc));
	}
      else
	{
	  mu_sieve_set_debug (mach, _sieve_debug_printer);
	  mu_sieve_set_debug_object (mach, mudebug);
	  mu_sieve_set_debug_level (mach, sieve_debug_flags);
	  mu_sieve_set_parse_error (mach, _sieve_parse_error);
	  if (sieve_enable_log)
	    mu_sieve_set_logger (mach, _sieve_action_log);
	  
	  rc = mu_sieve_compile (mach, progfile);
	  if (rc == 0)
	    {
	      mu_attribute_t attr;
	      mu_message_t msg = NULL;
		
	      mu_mailbox_get_message (mbx, 1, &msg);
	      mu_message_get_attribute (msg, &attr);
	      mu_attribute_unset_deleted (attr);
	      if (switch_user_id (auth, 1) == 0)
		{
		  chdir (auth->dir);
		
		  rc = mu_sieve_message (mach, msg);
 		  if (rc == 0)
		    rc = mu_attribute_is_deleted (attr) == 0;

		  switch_user_id (auth, 0);
		  chdir ("/");
		}
	      mu_sieve_machine_destroy (&mach);
	    }
	}
    }
  free (progfile);
  return rc;
}

int
mda (mu_mailbox_t mbx, char *username)
{
  deliver (mbx, 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 || 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 ("cannot set user priviledes", auth->name,
		"setreuid(0, %d): %s (r=%d, e=%d)",
		uid, strerror (errno), getuid (), geteuid ());
  return rc;
}

static int
tmp_write (mu_stream_t stream, mu_off_t *poffset, char *buf, size_t len)
{
  size_t n = 0;
  int status = mu_stream_write (stream, buf, len, *poffset, &n);
  if (status == 0 && n != len)
    status = EIO;
  *poffset += n;
  return status;
}

int
make_tmp (const char *from, mu_mailbox_t *mbox)
{
  mu_stream_t stream;
  char *buf = NULL;
  size_t n = 0;
  mu_off_t offset = 0;
  size_t line;
  int status;
  static char *newline = "\n";
  char *tempfile;
  
  tempfile = mu_tempname (NULL);
  if ((status = mu_file_stream_create (&stream, tempfile, MU_STREAM_RDWR)))
    {
      mailer_err ("Temporary failure", NULL,
		  _("Unable to open temporary file: %s"),
		  mu_strerror (status));
      exit (exit_code);
    }

  if ((status = mu_stream_open (stream)))
    {
      mailer_err ("Temporary failure", NULL,
		  _("unable to open temporary file: %s"), mu_strerror (status));
      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 t;
		  
		  time (&t);
		  asprintf (&saved_envelope, "From %s %s", from, ctime (&t));
		  status = tmp_write (stream, &offset, saved_envelope,
				      strlen (saved_envelope));
		}
	      else
		{
		  mailer_err ("Cannot determine sender address", NULL,
			      _("Cannot determine sender address"));
		  exit (EX_UNAVAILABLE);
		}
	      if (auth)
		mu_auth_data_free (auth);
	    }
	  else
	    {
	      saved_envelope = strdup (buf);
	      if (!saved_envelope)
		status = ENOMEM;
	    }
	}
      else if (!memcmp (buf, "From ", 5))
	{
	  static char *escape = ">";
	  status = tmp_write (stream, &offset, escape, 1);
	}

      if (!status)
	status = tmp_write (stream, &offset, buf, strlen (buf));
      
      if (status)
	{
	  mailer_err ("Temporary failure", NULL,
		      _("Error writing temporary file: %s"),
		      mu_strerror (status));
	  mu_stream_destroy (&stream, mu_stream_get_owner (stream));
	  return status;
	}
    }
  
  if (buf && strchr (buf, '\n') == NULL)
    status = tmp_write (stream, &offset, newline, 1);

  status = tmp_write (stream, &offset, newline, 1);
  free (buf);
  unlink (tempfile);
  free (tempfile);
  
  if (status)
    {
      errno = status;
      mailer_err ("Error writing temporary file", NULL,
		  _("Error writing temporary file: %s"), mu_strerror (status));
      mu_stream_destroy (&stream, mu_stream_get_owner (stream));
      return status;
    }

  mu_stream_flush (stream);
  if ((status = mu_mailbox_create (mbox, "/dev/null")) 
      || (status = mu_mailbox_open (*mbox, MU_STREAM_READ))
      || (status = mu_mailbox_set_stream (*mbox, stream)))
    {
      mailer_err ("Error opening temporary file", NULL,
		  _("Error opening temporary file: %s"),
		  mu_strerror (status));
      mu_stream_destroy (&stream, mu_stream_get_owner (stream));
      return status;
    }

  status = mu_mailbox_messages_count (*mbox, &n);
  if (status)
    {
      errno = status;
      mailer_err ("Error collecting message", NULL,
		  _("Error creating temporary message: %s"),
		  mu_strerror (status));
      mu_stream_destroy (&stream, mu_stream_get_owner (stream));
      return status;
    }

  return status;
}

void
deliver (mu_mailbox_t imbx, char *name)
{
  mu_mailbox_t mbox;
  mu_message_t msg;
  char *path;
  mu_url_t url = NULL;
  mu_locker_t lock;
  struct mu_auth_data *auth;
  int status;
  mu_stream_t istream, ostream;
  mu_off_t size;
  int failed = 0;
  
  auth = mu_get_auth_by_name (name);
  if (!auth)
    {
      mailer_err ("no such user", name,
		  _("%s: no such user"), name);
      exit_code = EX_UNAVAILABLE;
      return;
    }
  if (uid)
    auth->change_uid = 0;
  
  if (!sieve_test (auth, imbx))
    {
      exit_code = EX_OK;
      mu_auth_data_free (auth);
      return;
    }

  if ((status = mu_mailbox_get_message (imbx, 1, &msg)) != 0)
    {
      mailer_err ("cannot read message", name,
		  _("Cannot get message from the temporary mailbox: %s"),
		  mu_strerror (status));
      mu_auth_data_free (auth);
      return;
    }

  if ((status = mu_message_get_stream (msg, &istream)) != 0)
    {
      mailer_err ("cannot read message", name,
		  _("Cannot get input message stream: %s"),
		  mu_strerror (status));
      mu_auth_data_free (auth);
      return;
    }
  
  if ((status = mu_mailbox_create (&mbox, auth->mailbox)) != 0)
    {
      mailer_err ("cannot read message", name,
		  _("Cannot open mailbox %s: %s"),
		  auth->mailbox, mu_strerror (status));
      mu_auth_data_free (auth);
      return;
    }

  mu_mailbox_get_url (mbox, &url);
  path = (char*) mu_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 = mu_mailbox_open (mbox, MU_STREAM_RDWR|MU_STREAM_CREAT);
  if (switch_user_id (auth, 0))
    return;
  if (status != 0)
    {
      mailer_err ("cannot open mailbox", name,
		  _("Cannot open mailbox %s: %s"), path, mu_strerror (status));
      mu_mailbox_destroy (&mbox);
      return;
    }
  
  mu_mailbox_get_locker (mbox, &lock);

  status = mu_locker_lock (lock);

  if (status)
    {
      mailer_err ("cannot lock mailbox", name,
		  _("Cannot lock mailbox `%s': %s"), path,
		  mu_strerror (status));
      mu_mailbox_destroy (&mbox);
      exit_code = EX_TEMPFAIL;
      return;
    }

  if ((status = mu_mailbox_get_stream (mbox, &ostream)))
    {
      mailer_err ("cannot access mailbox", name,
		  _("Cannot get stream for mailbox %s: %s"),
		  path, mu_strerror (status));
      mu_mailbox_destroy (&mbox);
      return;
    }

  if ((status = mu_stream_size (ostream, &size)))
    {
      mailer_err ("cannot access mailbox", name,
		  _("Cannot get stream size (mailbox %s): %s"),
		  path, mu_strerror (status));
      mu_mailbox_destroy (&mbox);
      return;
    }

#if defined(USE_MAILBOX_QUOTAS)
  {
    mu_off_t n;
    mu_off_t isize;

    switch (check_quota (auth, size, &n))
      {
      case MQUOTA_EXCEEDED:
	mailer_err ("mailbox quota exceeded for this recipient", name,
		    _("%s: mailbox quota exceeded for this recipient"), name);
	exit_code = EX_QUOTA();
	failed++;
	break;
	
      case MQUOTA_UNLIMITED:
	break;
	
      default:
	if ((status = mu_stream_size (istream, &isize)))
	  {
	    mailer_err ("cannot access mailbox", name,
			_("Cannot get stream size (input message %s): %s"),
			path, mu_strerror (status));
	    exit_code = EX_UNAVAILABLE;
	    failed++;
	  }
	else if (isize > n)
	  {
	    mailer_err ("message would exceed maximum mailbox size for this recipient",
			name,
			_("%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)
    {
      size_t nrd;
      char *buf = NULL;
      mu_off_t bufsize = 1024;

      mu_stream_size (istream, &bufsize);
      for (; (buf = malloc (bufsize)) == NULL && bufsize > 1; bufsize /= 2)
	;
      
      if (!buf)
	{
	  status = errno = ENOMEM;
	  failed++;
	}
      else if ((status = mu_stream_seek (ostream, size, SEEK_SET)) != 0
	       || (status = mu_stream_seek (istream, 0, SEEK_SET) != 0))
	/* nothing: the error will be reported later */;
      else
	{
	  status = mu_stream_sequential_write (ostream, saved_envelope,
					       strlen (saved_envelope));
	  if (status == 0)
	    {
	      while ((status = mu_stream_sequential_read (istream,
							  buf, bufsize,
							  &nrd))
		     == 0
		     && nrd > 0)
		{
		  status = mu_stream_sequential_write (ostream, buf, nrd);
		  if (status)
		    break;
		}
	  
	      free (buf);
	    }
	}
      
      switch_user_id (auth, 0);

      if (status)
	{
	  /* Undo the delivery by truncating the mailbox back to its
	     original size */
	  int rc = mu_stream_truncate (ostream, size);
	  if (rc)
	    mailer_err ("write error", name,
			_("Error writing to mailbox: %s. Mailbox NOT truncated: %s"),
			mu_strerror (status), mu_strerror (rc));
	  else  
	    mailer_err ("write error", name,
			_("Error writing to mailbox: %s"),
	  	        mu_strerror (status));
	}
    }

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

  mu_locker_unlock (lock);

  mu_auth_data_free (auth);
  mu_mailbox_close (mbox);
  mu_mailbox_destroy (&mbox);
}

void
notify_biff (mu_mailbox_t mbox, char *name, size_t size)
{
  static int fd = -1;
  mu_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 (PF_INET, SOCK_DGRAM, 0);
      if (fd < 0)
	fd = -2; /* Mark failed initialization */
    }

  if (fd < 0)
    return;
  
  mu_mailbox_get_url (mbox, &url);
  asprintf (&buf, "%s@%lu:%s", name,
	    (unsigned long) size, mu_url_to_string (url));
  if (buf)
    {
      sendto (fd, buf, strlen (buf), 0, (struct sockaddr *)&inaddr,
	      sizeof inaddr);
      free (buf);
    }
}

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

  guess_retval (errno);
  if (arg)
    fprintf (stderr, "<%s>: %s", arg, msg);
  else
    fputs (msg, stderr);
  fputc ('\n', stderr);
  if (fmt)
    {
      va_start (ap, fmt);
      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;
}