Completely reworked the path convertion functions
[mmh] / uip / slocal.c
1 /*
2 ** slocal.c -- asynchronously filter and deliver new mail
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 /*
10 **  Under sendmail, users should add the line
11 **
12 **      "| /usr/local/nmh/lib/slocal"
13 **
14 **  to their $HOME/.forward file.
15 **
16 */
17
18 /* Changed to use getutent() and friends.  Assumes that when getutent() exists,
19 ** a number of other things also exist.  Please check.
20 ** Ruud de Rooij <ruud@ruud.org>  Sun, 28 May 2000 17:28:55 +0200
21 */
22
23 #include <h/mh.h>
24 #include <h/dropsbr.h>
25 #include <h/rcvmail.h>
26 #include <h/signals.h>
27 #include <h/tws.h>
28 #include <h/mts.h>
29 #include <h/utils.h>
30
31 #include <pwd.h>
32 #include <signal.h>
33 #include <sys/ioctl.h>
34 #include <fcntl.h>
35
36 #ifdef INITGROUPS_HEADER
37 #include INITGROUPS_HEADER
38 #else
39 /*
40 ** On AIX 4.1, initgroups() is defined and even documented (giving the
41 ** parameter types as char* and int), but doesn't have a prototype in any
42 ** of the system header files.  AIX 4.3, SunOS 4.1.3, and ULTRIX 4.2A have
43 ** the same problem.
44 */
45 extern int  initgroups(char*, int);
46 #endif
47
48 /*
49 ** This define is needed for Berkeley db v2 and above to
50 ** make the header file expose the 'historical' ndbm APIs.
51 ** We define it unconditionally because this is simple and
52 ** harmless.
53 */
54 #define DB_DBM_HSEARCH 1
55 #ifdef NDBM_HEADER
56 #include NDBM_HEADER
57 #endif
58
59 #include <utmp.h>
60
61 #ifndef HAVE_GETUTENT
62 # ifndef UTMP_FILE
63 #  ifdef _PATH_UTMP
64 #   define UTMP_FILE _PATH_UTMP
65 #  else
66 #   define UTMP_FILE "/etc/utmp"
67 #  endif
68 # endif
69 #endif
70
71 static struct swit switches[] = {
72 #define ADDRSW  0
73         { "addr address", 0 },
74 #define USERSW  1
75         { "user name", 0 },
76 #define FILESW  2
77         { "file file", 0 },
78 #define SENDERSW  3
79         { "sender address", 0 },
80 #define MAILBOXSW  4
81         { "mailbox file", 0 },
82 #define HOMESW  5
83         { "home directory", -4 },
84 #define INFOSW  6
85         { "info data", 0 },
86 #define MAILSW  7
87         { "maildelivery file", 0 },
88 #define VERBSW  8
89         { "verbose", 0 },
90 #define NVERBSW  9
91         { "noverbose", 0 },
92 #define SUPPRESSDUP   10
93         { "suppressdup", 0 },
94 #define NSUPPRESSDUP 11
95         { "nosuppressdup", 0 },
96 #define DEBUGSW  12
97         { "debug", 0 },
98 #define VERSIONSW  13
99         { "version", 0 },
100 #define HELPSW  14
101         { "help", 0 },
102         { NULL, 0 }
103 };
104
105 static int globbed = 0;  /* have we built "vars" table yet? */
106 static int parsed = 0;  /* have we built header field table yet   */
107 static int utmped = 0;  /* have we scanned umtp(x) file yet */
108 static int suppressdup = 0;  /* are we suppressing duplicate messages? */
109
110 static int verbose = 0;
111 static int debug = 0;
112
113 static char *addr = NULL;
114 static char *user = NULL;
115 static char *info = NULL;
116 static char *file = NULL;
117 static char *sender = NULL;
118 static char *envelope = NULL;  /* envelope information ("From " line)  */
119 static char *mbox = NULL;
120 static char *home = NULL;
121
122 static struct passwd *pw;  /* passwd file entry */
123
124 static char ddate[BUFSIZ];  /* record the delivery date */
125 struct tws *now;
126
127 static jmp_buf myctx;
128
129 /* flags for pair->p_flags */
130 #define P_NIL  0x00
131 #define P_ADR  0x01  /* field is address */
132 #define P_HID  0x02  /* special (fake) field */
133 #define P_CHK  0x04
134
135 struct pair {
136         char *p_name;
137         char *p_value;
138         char  p_flags;
139 };
140
141 #define NVEC 100
142
143 /*
144 ** Lookup table for matching fields and patterns
145 ** in messages.  The rest of the table is added
146 ** when the message is parsed.
147 */
148 static struct pair hdrs[NVEC + 1] = {
149         { "source",  NULL, P_HID },
150         { "addr",  NULL, P_HID },
151         { "Return-Path",  NULL, P_ADR },
152         { "Reply-To",  NULL, P_ADR },
153         { "From",  NULL, P_ADR },
154         { "Sender",  NULL, P_ADR },
155         { "To",  NULL, P_ADR },
156         { "cc",  NULL, P_ADR },
157         { "Resent-Reply-To", NULL, P_ADR },
158         { "Resent-From",  NULL, P_ADR },
159         { "Resent-Sender",   NULL, P_ADR },
160         { "Resent-To",  NULL, P_ADR },
161         { "Resent-cc",  NULL, P_ADR },
162         { NULL, NULL, 0 }
163 };
164
165 /*
166 ** The list of builtin variables to expand in a string
167 ** before it is executed by the "pipe" or "qpipe" action.
168 */
169 static struct pair vars[] = {
170         { "sender",   NULL, P_NIL },
171         { "address",  NULL, P_NIL },
172         { "size",  NULL, P_NIL },
173         { "reply-to", NULL, P_CHK },
174         { "info",  NULL, P_NIL },
175         { NULL, NULL, 0 }
176 };
177
178 extern char **environ;
179
180 /*
181 ** static prototypes
182 */
183 static int localmail(int, char *);
184 static int usr_delivery(int, char *, int);
185 static int split(char *, char **);
186 static int parse(int);
187 static void expand(char *, char *, int);
188 static void glob(int);
189 static struct pair *lookup(struct pair *, char *);
190 static int logged_in(void);
191 static int timely(char *, char *);
192 static int usr_file(int, char *, int);
193 static int usr_pipe(int, char *, char *, char **, int);
194 static int usr_folder(int, char *);
195 static RETSIGTYPE alrmser(int);
196 static void get_sender(char *, char **);
197 static int copy_message(int, char *, int);
198 static void verbose_printf(char *fmt, ...);
199 static void adorn(char *, char *, ...);
200 static void debug_printf(char *fmt, ...);
201 static int suppress_duplicates(int, char *);
202 static char *trim(char *);
203
204
205 int
206 main(int argc, char **argv)
207 {
208         int fd, status;
209         FILE *fp = stdin;
210         char *cp, *mdlvr = NULL, buf[BUFSIZ];
211         char mailbox[BUFSIZ], tmpfil[BUFSIZ];
212         char **argp, **arguments;
213
214 #ifdef LOCALE
215         setlocale(LC_ALL, "");
216 #endif
217         invo_name = mhbasename(*argv);
218
219         /* foil search of user profile/context */
220         if (context_foil(NULL) == -1)
221                 done(1);
222
223         mts_init(invo_name);
224         arguments = getarguments(invo_name, argc, argv, 0);
225         argp = arguments;
226
227         /* Parse arguments */
228         while ((cp = *argp++)) {
229                 if (*cp == '-') {
230                         switch (smatch(++cp, switches)) {
231                                 case AMBIGSW:
232                                         ambigsw(cp, switches);
233                                         done(1);
234                                 case UNKWNSW:
235                                         adios(NULL, "-%s unknown", cp);
236
237                                 case HELPSW:
238                                         snprintf(buf, sizeof(buf), "%s [switches] [address info sender]", invo_name);
239                                         print_help(buf, switches, 0);
240                                         done(1);
241                                 case VERSIONSW:
242                                         print_version(invo_name);
243                                         done(1);
244
245                                 case ADDRSW:
246                                         if (!(addr = *argp++))
247                                                 /* allow -xyz arguments */
248                                                 adios(NULL, "missing argument to %s", argp[-2]);
249                                         continue;
250                                 case INFOSW:
251                                         if (!(info = *argp++))
252                                                 /* allow -xyz arguments */
253                                                 adios(NULL, "missing argument to %s", argp[-2]);
254                                         continue;
255                                 case USERSW:
256                                         if (!(user = *argp++))
257                                                 /* allow -xyz arguments */
258                                                 adios(NULL, "missing argument to %s", argp[-2]);
259                                         continue;
260                                 case FILESW:
261                                         if (!(file = *argp++) || *file == '-')
262                                                 adios(NULL, "missing argument to %s", argp[-2]);
263                                         continue;
264                                 case SENDERSW:
265                                         if (!(sender = *argp++))
266                                                 /* allow -xyz arguments */
267                                                 adios(NULL, "missing argument to %s", argp[-2]);
268                                         continue;
269                                 case MAILBOXSW:
270                                         if (!(mbox = *argp++) || *mbox == '-')
271                                                 adios(NULL, "missing argument to %s", argp[-2]);
272                                         continue;
273                                 case HOMESW:
274                                         if (!(home = *argp++) || *home == '-')
275                                                 adios(NULL, "missing argument to %s", argp[-2]);
276                                         continue;
277
278                                 case MAILSW:
279                                         if (!(cp = *argp++) || *cp == '-')
280                                                 adios(NULL, "missing argument to %s", argp[-2]);
281                                         if (mdlvr)
282                                                 adios(NULL, "only one maildelivery file at a time!");
283                                         mdlvr = cp;
284                                         continue;
285
286                                 case VERBSW:
287                                         verbose++;
288                                         continue;
289                                 case NVERBSW:
290                                         verbose = 0;
291                                         continue;
292
293                                 case SUPPRESSDUP:
294                                         suppressdup++;
295                                         continue;
296                                 case NSUPPRESSDUP:
297                                         suppressdup = 0;
298                                         continue;
299                                 case DEBUGSW:
300                                         debug++;
301                                         continue;
302                         }
303                 }
304
305                 switch (argp - (argv + 1)) {
306                         case 1:
307                                 addr = cp;
308                                 break;
309
310                         case 2:
311                                 info = cp;
312                                 break;
313
314                         case 3:
315                                 sender = cp;
316                                 break;
317                 }
318         }
319
320         if (addr == NULL)
321                 addr = getusername();
322         if (user == NULL)
323                 user = (cp = strchr(addr, '.')) ? ++cp : addr;
324         if ((pw = getpwnam(user)) == NULL)
325                 adios(NULL, "no such local user as %s", user);
326
327         if (chdir(pw->pw_dir) == -1)
328                 chdir("/");
329         umask(0077);
330
331         if (geteuid() == 0) {
332                 setgid(pw->pw_gid);
333                 initgroups(pw->pw_name, pw->pw_gid);
334                 setuid(pw->pw_uid);
335         }
336
337         if (info == NULL)
338                 info = "";
339
340         setbuf(stdin, NULL);
341
342         /* Record the delivery time */
343         if ((now = dlocaltimenow()) == NULL)
344                 adios(NULL, "unable to ascertain local time");
345         snprintf(ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow(0));
346
347         /*
348         ** Copy the message to a temporary file
349         */
350         if (file) {
351                 int tempfd;
352
353                 /* getting message from file */
354                 if ((tempfd = open(file, O_RDONLY)) == -1)
355                         adios(file, "unable to open");
356                 if (debug)
357                         debug_printf("retrieving message from file \"%s\"\n",
358                                         file);
359                 if ((fd = copy_message(tempfd, tmpfil, 1)) == -1)
360                         adios(NULL, "unable to create temporary file");
361                 close(tempfd);
362         } else {
363                 /* getting message from stdin */
364                 if (debug)
365                         debug_printf("retrieving message from stdin\n");
366                 if ((fd = copy_message(fileno(stdin), tmpfil, 1)) == -1)
367                         adios(NULL, "unable to create temporary file");
368         }
369
370         if (debug)
371                 debug_printf("temporary file=\"%s\"\n", tmpfil);
372
373         /*
374         ** Delete the temp file now or a copy of every single message
375         ** passed through slocal will be left in the /tmp directory until
376         ** deleted manually!  This unlink() used to be under an 'else'
377         ** of the 'if (debug)' above, but since some people like to
378         ** always run slocal with -debug and log the results, the /tmp
379         ** directory would get choked over time.  Of course, now that
380         ** we always delete the temp file, the "temporary file=" message
381         ** above is somewhat pointless -- someone watching debug output
382         ** wouldn't have a chance to 'tail -f' or 'ln' the temp file
383         ** before it's unlinked.  The best thing would be to delay this
384         ** unlink() until later if debug == 1, but I'll leave that for
385         ** someone who cares about the temp-file-accessing functionality
386         ** (they'll have to watch out for cases where we adios()).
387         */
388         unlink(tmpfil);
389
390         if (!(fp = fdopen(fd, "r+")))
391                 adios(NULL, "unable to access temporary file");
392
393         /*
394         ** If no sender given, extract it
395         ** from envelope information.
396         */
397         if (sender == NULL)
398                 get_sender(envelope, &sender);
399
400         if (mbox == NULL) {
401                 snprintf(mailbox, sizeof(mailbox), "%s/%s",
402                                 mmdfldir[0] ? mmdfldir : pw->pw_dir,
403                                 mmdflfil[0] ? mmdflfil : pw->pw_name);
404                 mbox = mailbox;
405         }
406         if (home == NULL)
407                 home = pw->pw_dir;
408
409         if (debug) {
410                 debug_printf("addr=\"%s\"\n", trim(addr));
411                 debug_printf("user=\"%s\"\n", trim(user));
412                 debug_printf("info=\"%s\"\n", trim(info));
413                 debug_printf("sender=\"%s\"\n", trim(sender));
414                 debug_printf("envelope=\"%s\"\n",
415                                 envelope ? trim(envelope) : "");
416                 debug_printf("mbox=\"%s\"\n", trim(mbox));
417                 debug_printf("home=\"%s\"\n", trim(home));
418                 debug_printf("ddate=\"%s\"\n", trim(ddate));
419                 debug_printf("now=%02d:%02d\n\n", now->tw_hour, now->tw_min);
420         }
421
422         /* deliver the message */
423         status = localmail(fd, mdlvr);
424
425         done(status != -1 ? RCV_MOK : RCV_MBX);
426         return 1;
427 }
428
429
430 /*
431 ** Main routine for delivering message.
432 */
433
434 static int
435 localmail(int fd, char *mdlvr)
436 {
437         /* check if this message is a duplicate */
438         if (suppressdup && suppress_duplicates(fd, mdlvr ?
439                         mdlvr : ".maildelivery") == DONE)
440                 return 0;
441
442         /* delivery according to personal Maildelivery file */
443         if (usr_delivery(fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
444                 return 0;
445
446         /* delivery according to global Maildelivery file */
447         if (usr_delivery(fd, maildelivery, 1) != -1)
448                 return 0;
449
450         if (verbose)
451                 verbose_printf("(delivering to standard mail spool)\n");
452
453         /* last resort - deliver to standard mail spool */
454 #ifdef SLOCAL_MBOX
455         return usr_file(fd, mbox, MBOX_FORMAT);
456 #else
457         return usr_file(fd, mbox, MMDF_FORMAT);
458 #endif
459 }
460
461
462 #define matches(a,b) (stringdex(b, a) >= 0)
463
464 /*
465 ** Parse the delivery file, and process incoming message.
466 */
467
468 static int
469 usr_delivery(int fd, char *delivery, int su)
470 {
471         int i, accept, status=1, won, vecp, next;
472         char *field, *pattern, *action, *result, *string;
473         char buffer[BUFSIZ], tmpbuf[BUFSIZ];
474         char *cp, *vec[NVEC];
475         struct stat st;
476         struct pair *p;
477         FILE *fp;
478
479         /* open the delivery file */
480         if ((fp = fopen(delivery, "r")) == NULL)
481                 return -1;
482
483         /* check if delivery file has bad ownership or permissions */
484         if (fstat(fileno(fp), &st) == -1 ||
485                         (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid)) ||
486                         st.st_mode & (S_IWGRP|S_IWOTH)) {
487                 if (verbose) {
488                         verbose_printf("WARNING: %s has bad ownership/modes (su=%d,uid=%d,owner=%d,mode=0%o)\n", delivery, su, (int) pw->pw_uid, (int) st.st_uid, (int) st.st_mode);
489                 }
490                 return -1;
491         }
492
493         won = 0;
494         next = 1;
495
496         /* read and process delivery file */
497         while (fgets(buffer, sizeof(buffer), fp)) {
498                 /* skip comments and empty lines */
499                 if (*buffer == '#' || *buffer == '\n')
500                         continue;
501
502                 /* zap trailing newline */
503                 if ((cp = strchr(buffer, '\n')))
504                         *cp = 0;
505
506                 /* split buffer into fields */
507                 vecp = split(buffer, vec);
508
509                 /* check for too few fields */
510                 if (vecp < 5) {
511                         if (debug)
512                                 debug_printf("WARNING: entry with only %d fields, skipping.\n", vecp);
513                         continue;
514                 }
515
516                 if (debug) {
517                         for (i = 0; vec[i]; i++)
518                                 debug_printf("vec[%d]: \"%s\"\n",
519                                                 i, trim(vec[i]));
520                 }
521
522                 field   = vec[0];
523                 pattern = vec[1];
524                 action  = vec[2];
525                 result  = vec[3];
526                 string  = vec[4];
527
528                 /* find out how to perform the action */
529                 switch (result[0]) {
530                         case 'N':
531                         case 'n':
532                                 /*
533                                 ** If previous condition failed, don't
534                                 ** do this - else fall through
535                                 */
536                                  if (!next)
537                                         continue;  /* else fall */
538
539                         case '?':
540                                 /*
541                                 ** If already delivered, skip this action.
542                                 ** Else consider delivered if action is
543                                 ** successful.
544                                 */
545                                 if (won)
546                                         continue;  /* else fall */
547
548                         case 'A':
549                         case 'a':
550                                 /*
551                                 ** Take action, and consider delivered if
552                                 ** action is successful.
553                                 */
554                                 accept = 1;
555                                 break;
556
557                         case 'R':
558                         case 'r':
559                         default:
560                                 /*
561                                 ** Take action, but don't consider delivered,
562                                 ** even if action is successful
563                                 */
564                                 accept = 0;
565                                 break;
566                 }
567
568                 if (vecp > 5) {
569                         if (!mh_strcasecmp(vec[5], "select")) {
570                                 if (logged_in() != -1)
571                                         continue;
572                                 if (vecp > 7 && timely(vec[6], vec[7]) == -1)
573                                         continue;
574                         }
575                 }
576
577                 /* check if the field matches */
578                 switch (*field) {
579                         case '*':
580                         /* always matches */
581                                 break;
582
583                         case 'd':
584                         /*
585                         ** "default" matches only if the message hasn't
586                         ** been delivered yet.
587                         */
588                                 if (!mh_strcasecmp(field, "default")) {
589                                         if (won)
590                                                 continue;
591                                         break;
592                                 }  /* else fall */
593
594                         default:
595                                 /* parse message and build lookup table */
596                                 if (!parsed && parse(fd) == -1) {
597                                         fclose(fp);
598                                         return -1;
599                                 }
600                                 /*
601                                 ** find header field in lookup table, and
602                                 ** see if the pattern matches.
603                                 */
604                                 if ((p = lookup(hdrs, field)) &&
605                                                 (p->p_value != NULL) &&
606                                                 matches(p->p_value, pattern)
607                                                 ) {
608                                         next = 1;
609                                 } else {
610                                         next = 0;
611                                         continue;
612                                 }
613                                 break;
614                 }
615
616                 /* find out the action to perform */
617                 switch (*action) {
618                         case 'q':
619                                 /* deliver to quoted pipe */
620                                 if (mh_strcasecmp(action, "qpipe"))
621                                         continue;  /* else fall */
622                         case '^':
623                                 expand(tmpbuf, string, fd);
624                                 if (split(tmpbuf, vec) < 1)
625                                         continue;
626                                 status = usr_pipe(fd, tmpbuf, vec[0], vec, 0);
627                                 break;
628
629                         case 'p':
630                                 /* deliver to pipe */
631                                 if (mh_strcasecmp(action, "pipe"))
632                                         continue;  /* else fall */
633                         case '|':
634                                 vec[2] = "sh";
635                                 vec[3] = "-c";
636                                 expand(tmpbuf, string, fd);
637                                 vec[4] = tmpbuf;
638                                 vec[5] = NULL;
639                                 status = usr_pipe(fd, tmpbuf, "/bin/sh",
640                                                 vec + 2, 0);
641                                 break;
642
643                         case 'f':
644                                 /* mbox format */
645                                 if (!mh_strcasecmp(action, "file")) {
646                                         status = usr_file(fd, string,
647                                                         MBOX_FORMAT);
648                                         break;
649                                 }
650                                 /* deliver to nmh folder */
651                                 else if (mh_strcasecmp(action, "folder"))
652                                         continue;  /* else fall */
653                         case '+':
654                                 status = usr_folder(fd, string);
655                                 break;
656
657                         case 'm':
658                                 /* mmdf format */
659                                 if (!mh_strcasecmp(action, "mmdf")) {
660                                         status = usr_file(fd, string,
661                                                         MMDF_FORMAT);
662                                         break;
663                                 }
664                                 /* mbox format */
665                                 else if (mh_strcasecmp(action, "mbox"))
666                                         continue;  /* else fall */
667
668                         case '>':
669                                 /* mbox format */
670                                 status = usr_file(fd, string, MBOX_FORMAT);
671                                 break;
672
673                         case 'd':
674                                 /* ignore message */
675                                 if (mh_strcasecmp(action, "destroy"))
676                                         continue;
677                                 status = 0;
678                                 break;
679                 }
680
681                 if (status)
682                         next = 0;  /* action failed, mark for 'N' result */
683
684                 if (accept && status == 0)
685                         won++;
686         }
687
688         fclose(fp);
689         return (won ? 0 : -1);
690 }
691
692
693 #define QUOTE  '\\'
694
695 /*
696 ** Split buffer into fields (delimited by whitespace or
697 ** comma's).  Return the number of fields found.
698 */
699
700 static int
701 split(char *cp, char **vec)
702 {
703         int i;
704         unsigned char *s;
705
706         s = cp;
707
708         /* split into a maximum of NVEC fields */
709         for (i = 0; i <= NVEC;) {
710                 vec[i] = NULL;
711
712                 /* zap any whitespace and comma's */
713                 while (isspace(*s) || *s == ',')
714                         *s++ = 0;
715
716                 /* end of buffer, time to leave */
717                 if (*s == 0)
718                         break;
719
720                 /* get double quote text as a single field */
721                 if (*s == '"') {
722                         for (vec[i++] = ++s; *s && *s != '"'; s++) {
723                                 /*
724                                 ** Check for escaped double quote.  We need
725                                 ** to shift the string to remove slash.
726                                 */
727                                 if (*s == QUOTE) {
728                                         if (*++s == '"')
729                                                 strcpy(s - 1, s);
730                                         s--;
731                                 }
732                         }
733                         if (*s == '"')  /* zap trailing double quote */
734                                 *s++ = 0;
735                         continue;
736                 }
737
738                 if (*s == QUOTE && *++s != '"')
739                         s--;
740                 vec[i++] = s++;
741
742                 /* move forward to next field delimiter */
743                 while (*s && !isspace(*s) && *s != ',')
744                         s++;
745         }
746         vec[i] = NULL;
747
748         return i;
749 }
750
751
752 /*
753 ** Parse the headers of a message, and build the
754 ** lookup table for matching fields and patterns.
755 */
756
757 static int
758 parse(int fd)
759 {
760         int i, state;
761         int fd1;
762         char *cp, *dp, *lp;
763         char name[NAMESZ], field[BUFSIZ];
764         struct pair *p, *q;
765         FILE  *in;
766
767         if (parsed++)
768                 return 0;
769
770         /* get a new FILE pointer to message */
771         if ((fd1 = dup(fd)) == -1)
772                 return -1;
773         if ((in = fdopen(fd1, "r")) == NULL) {
774                 close(fd1);
775                 return -1;
776         }
777         rewind(in);
778
779         /* add special entries to lookup table */
780         if ((p = lookup(hdrs, "source")))
781                 p->p_value = getcpy(sender);
782         if ((p = lookup(hdrs, "addr")))
783                 p->p_value = getcpy(addr);
784
785         /*
786          * Scan the headers of the message and build
787          * a lookup table.
788          */
789         for (i = 0, state = FLD;;) {
790                 switch (state = m_getfld(state, name, field, sizeof(field),
791                                 in)) {
792                         case FLD:
793                         case FLDEOF:
794                         case FLDPLUS:
795                                 lp = getcpy(field);
796                                 while (state == FLDPLUS) {
797                                         state = m_getfld(state, name, field,
798                                                         sizeof(field), in);
799                                         lp = add(field, lp);
800                                 }
801                                 for (p = hdrs; p->p_name; p++) {
802                                         if (!mh_strcasecmp(p->p_name, name)) {
803                                                 if (!(p->p_flags & P_HID)) {
804                                                         if ((cp = p->p_value)) {
805                                                                 if (p->p_flags & P_ADR) {
806                                                                         dp = cp + strlen(cp) - 1;
807                                                                         if (*dp == '\n')
808                                                                                 *dp = 0;
809                                                                         cp = add(",\n\t", cp);
810                                                                 } else {
811                                                                         cp = add("\t", cp);
812                                                                 }
813                                                         }
814                                                         p->p_value = add(lp, cp);
815                                                 }
816                                                 free(lp);
817                                                 break;
818                                         }
819                                 }
820                                 if (p->p_name == NULL && i < NVEC) {
821                                         p->p_name = getcpy(name);
822                                         p->p_value = lp;
823                                         p->p_flags = P_NIL;
824                                         p++, i++;
825                                         p->p_name = NULL;
826                                 }
827                                 if (state != FLDEOF)
828                                         continue;
829                                 break;
830
831                         case BODY:
832                         case BODYEOF:
833                         case FILEEOF:
834                                 break;
835
836                         case LENERR:
837                         case FMTERR:
838                                 advise(NULL, "format error in message");
839                                 break;
840
841                         default:
842                                 advise(NULL, "internal error in m_getfld");
843                                 fclose(in);
844                                 return -1;
845                 }
846                 break;
847         }
848         fclose(in);
849
850         if ((p = lookup(vars, "reply-to"))) {
851                 if ((q = lookup(hdrs, "reply-to")) == NULL ||
852                                 q->p_value == NULL)
853                         q = lookup(hdrs, "from");
854                 p->p_value = getcpy(q ? q->p_value : "");
855                 p->p_flags &= ~P_CHK;
856                 if (debug)
857                         debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
858                                         p - vars, p->p_name, trim(p->p_value));
859         }
860         if (debug) {
861                 for (p = hdrs; p->p_name; p++)
862                         debug_printf("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
863                                 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
864         }
865
866         return 0;
867 }
868
869
870 #define LPAREN '('
871 #define RPAREN ')'
872
873 /*
874 ** Expand any builtin variables such as $(sender),
875 ** $(address), etc., in a string.
876 */
877
878 static void
879 expand(char *s1, char *s2, int fd)
880 {
881         char c, *cp;
882         struct pair *p;
883
884         if (!globbed)
885                 glob(fd);
886
887         while ((c = *s2++)) {
888                 if (c != '$' || *s2 != LPAREN) {
889                         *s1++ = c;
890                 } else {
891                         for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
892                                 continue;
893                         if (*s2 != RPAREN) {
894                                 s2 = --cp;
895                                 continue;
896                         }
897                         *s2++ = 0;
898                         if ((p = lookup(vars, cp))) {
899                                 if (!parsed && (p->p_flags & P_CHK))
900                                         parse(fd);
901
902                                 strcpy(s1, p->p_value);
903                                 s1 += strlen(s1);
904                         }
905                 }
906         }
907         *s1 = 0;
908 }
909
910
911 /*
912 ** Fill in the information missing from the "vars"
913 ** table, which is necessary to expand any builtin
914 ** variables in the string for a "pipe" or "qpipe"
915 ** action.
916 */
917
918 static void
919 glob(int fd)
920 {
921         char buffer[BUFSIZ];
922         struct stat st;
923         struct pair *p;
924
925         if (globbed++)
926                 return;
927
928         if ((p = lookup(vars, "sender")))
929                 p->p_value = getcpy(sender);
930         if ((p = lookup(vars, "address")))
931                 p->p_value = getcpy(addr);
932         if ((p = lookup(vars, "size"))) {
933                 snprintf(buffer, sizeof(buffer), "%d",
934                                 fstat(fd, &st) != -1 ? (int) st.st_size : 0);
935                 p->p_value = getcpy(buffer);
936         }
937         if ((p = lookup(vars, "info")))
938                 p->p_value = getcpy(info);
939
940         if (debug) {
941                 for (p = vars; p->p_name; p++)
942                         debug_printf("vars[%d]: name=\"%s\" value=\"%s\"\n",
943                                         p - vars, p->p_name, trim(p->p_value));
944         }
945 }
946
947
948 /*
949 ** Find a matching name in a lookup table.  If found,
950 ** return the "pairs" entry, else return NULL.
951 */
952
953 static struct pair *
954 lookup(struct pair *pairs, char *key)
955 {
956         for (; pairs->p_name; pairs++)
957                 if (!mh_strcasecmp(pairs->p_name, key))
958                         return pairs;
959
960         return NULL;
961 }
962
963
964 /*
965 ** Check utmp(x) file to see if user is currently
966 ** logged in.
967 */
968
969 #ifdef HAVE_GETUTENT
970 static int
971 logged_in(void)
972 {
973         struct utmp * utp;
974
975         if (utmped)
976                 return utmped;
977
978         setutent();
979
980         while ((utp = getutent()) != NULL) {
981                 if (
982 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
983                                 utp->ut_type == USER_PROCESS &&
984 #endif
985                                 utp->ut_name[0] != 0 &&
986                                 strncmp(user, utp->ut_name,
987                                 sizeof(utp->ut_name)) == 0) {
988                         if (debug)
989                                 continue;
990                         endutent();
991                         return (utmped = DONE);
992                 }
993         }
994
995         endutent();
996         return (utmped = NOTOK);
997 }
998 #else
999 static int
1000 logged_in(void)
1001 {
1002         struct utmp ut;
1003         FILE *uf;
1004
1005         if (utmped)
1006                 return utmped;
1007
1008         if ((uf = fopen(UTMP_FILE, "r")) == NULL)
1009                 return NOTOK;
1010
1011         while (fread((char *) &ut, sizeof(ut), 1, uf) == 1) {
1012                 if (ut.ut_name[0] != 0 &&
1013                                 strncmp(user, ut.ut_name, sizeof(ut.ut_name))
1014                                 == 0) {
1015                         if (debug)
1016                                 continue;
1017                         fclose(uf);
1018                         return (utmped = DONE);
1019                 }
1020         }
1021
1022         fclose(uf);
1023         return (utmped = NOTOK);
1024 }
1025 #endif
1026
1027 #define check(t,a,b)  if (t < a || t > b) return -1
1028 #define cmpar(h1,m1,h2,m2)  if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1029
1030 static int
1031 timely(char *t1, char *t2)
1032 {
1033         int t1hours, t1mins, t2hours, t2mins;
1034
1035         if (sscanf(t1, "%d:%d", &t1hours, &t1mins) != 2)
1036                 return -1;
1037         check(t1hours, 0, 23);
1038         check(t1mins, 0, 59);
1039
1040         if (sscanf(t2, "%d:%d", &t2hours, &t2mins) != 2)
1041                 return -1;
1042         check(t2hours, 0, 23);
1043         check(t2mins, 0, 59);
1044
1045         cmpar(now->tw_hour, now->tw_min, t1hours, t1mins);
1046         cmpar(t2hours, t2mins, now->tw_hour, now->tw_min);
1047
1048         return -1;
1049 }
1050
1051
1052 /*
1053 ** Deliver message by appending to a file.
1054 */
1055
1056 static int
1057 usr_file(int fd, char *mailbox, int mbx_style)
1058 {
1059         int md, mapping;
1060
1061         if (verbose)
1062                 verbose_printf("delivering to file \"%s\"", mailbox);
1063
1064         if (mbx_style == MBOX_FORMAT) {
1065                 if (verbose)
1066                         verbose_printf(" (mbox style)");
1067                 mapping = 0;
1068         } else {
1069                 if (verbose)
1070                         verbose_printf(" (mmdf style)");
1071                 mapping = 1;
1072         }
1073
1074         /* open and lock the file */
1075         if ((md = mbx_open(mailbox, mbx_style, pw->pw_uid, pw->pw_gid,
1076                         m_gmprot())) == -1) {
1077                 if (verbose)
1078                         adorn("", "unable to open:");
1079                 return -1;
1080         }
1081
1082         lseek(fd, (off_t) 0, SEEK_SET);
1083
1084         /* append message to file */
1085         if (mbx_copy(mailbox, mbx_style, md, fd, mapping, NULL, verbose)
1086                         == -1) {
1087                 if (verbose)
1088                         adorn("", "error writing to:");
1089                 return -1;
1090         }
1091
1092         /* close and unlock file */
1093         if (mbx_close(mailbox, md) == NOTOK) {
1094                 if (verbose)
1095                         adorn("", "error closing:");
1096                 return -1;
1097         }
1098
1099         if (verbose)
1100                 verbose_printf(", success.\n");
1101         return 0;
1102 }
1103
1104
1105 /*
1106 ** Deliver message to a nmh folder.
1107 */
1108
1109 static int
1110 usr_folder(int fd, char *string)
1111 {
1112         int status;
1113         char folder[BUFSIZ], *vec[3];
1114
1115         /* get folder name ready */
1116         if (*string == '+')
1117                 strncpy(folder, string, sizeof(folder));
1118         else
1119                 snprintf(folder, sizeof(folder), "+%s", string);
1120
1121         if (verbose)
1122                 verbose_printf("delivering to folder \"%s\"", folder + 1);
1123
1124         vec[0] = "rcvstore";
1125         vec[1] = folder;
1126         vec[2] = NULL;
1127
1128         /* use rcvstore to put message in folder */
1129         status = usr_pipe(fd, "rcvstore", rcvstoreproc, vec, 1);
1130
1131 #if 0
1132         /*
1133         ** Currently, verbose status messages are handled by usr_pipe().
1134         */
1135         if (verbose) {
1136                 if (status == 0)
1137                         verbose_printf(", success.\n");
1138                 else
1139                         verbose_printf(", failed.\n");
1140         }
1141 #endif
1142
1143         return status;
1144 }
1145
1146 /*
1147 ** Deliver message to a process.
1148 */
1149
1150 static int
1151 usr_pipe(int fd, char *cmd, char *pgm, char **vec, int suppress)
1152 {
1153         pid_t child_id;
1154         int i, bytes, seconds, status;
1155         struct stat st;
1156
1157         if (verbose && !suppress)
1158                 verbose_printf("delivering to pipe \"%s\"", cmd);
1159
1160         lseek(fd, (off_t) 0, SEEK_SET);
1161
1162         for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1163                 sleep(5);
1164
1165         switch (child_id) {
1166                 case -1:
1167                         /* fork error */
1168                         if (verbose)
1169                                 adorn("fork", "unable to");
1170                         return -1;
1171
1172                 case 0:
1173                         /* child process */
1174                         if (fd != 0)
1175                                 dup2(fd, 0);
1176                         freopen("/dev/null", "w", stdout);
1177                         freopen("/dev/null", "w", stderr);
1178                         if (fd != 3)
1179                                 dup2(fd, 3);
1180                         closefds(4);
1181
1182 #ifdef TIOCNOTTY
1183                         if ((fd = open("/dev/tty", O_RDWR)) != -1) {
1184                                 ioctl(fd, TIOCNOTTY, NULL);
1185                                 close(fd);
1186                         }
1187 #endif /* TIOCNOTTY */
1188
1189                         /* put in own process group */
1190                         setpgid((pid_t) 0, getpid());
1191
1192                         *environ = NULL;
1193                         m_putenv("USER", pw->pw_name);
1194                         m_putenv("HOME", pw->pw_dir);
1195                         m_putenv("SHELL", pw->pw_shell);
1196
1197                         execvp(pgm, vec);
1198                         _exit(-1);
1199
1200                 default:
1201                         /* parent process */
1202                         if (!setjmp(myctx)) {
1203                                 SIGNAL(SIGALRM, alrmser);
1204                                 bytes = fstat(fd, &st) != -1 ?
1205                                                 (int) st.st_size : 100;
1206
1207                                 /*
1208                                 ** amount of time to wait depends on
1209                                 ** message size
1210                                 */
1211                                 if (bytes <= 100) {
1212                                         /* give at least 5 minutes */
1213                                         seconds = 300;
1214                                 } else if (bytes >= 90000) {
1215                                         /* a half hour is long enough */
1216                                         seconds = 1800;
1217                                 } else {
1218                                         seconds = (bytes / 60) + 300;
1219                                 }
1220                                 alarm((unsigned int) seconds);
1221                                 status = pidwait(child_id, 0);
1222                                 alarm(0);
1223
1224                                 if (verbose) {
1225                                         if (status == 0)
1226                                                 verbose_printf(", success.\n");
1227                                         else
1228                                                 if ((status & 0xff00) == 0xff00)
1229                                                         verbose_printf(", system error\n");
1230                                                 else
1231                                                         pidstatus(status, stdout, ", failed");
1232                                 }
1233                                 return (status == 0 ? 0 : -1);
1234                         } else {
1235                                 /*
1236                                 ** Ruthlessly kill the child and anything
1237                                 ** else in its process group.
1238                                 */
1239                                 KILLPG(child_id, SIGKILL);
1240                                 if (verbose)
1241                                         verbose_printf(", timed-out; terminated\n");
1242                                 return -1;
1243                         }
1244         }
1245 }
1246
1247
1248 static RETSIGTYPE
1249 alrmser(int i)
1250 {
1251 #ifndef RELIABLE_SIGNALS
1252         SIGNAL(SIGALRM, alrmser);
1253 #endif
1254
1255         longjmp(myctx, DONE);
1256 }
1257
1258
1259 /*
1260 ** Get the `sender' from the envelope
1261 ** information ("From " line).
1262 */
1263
1264 static void
1265 get_sender(char *envelope, char **sender)
1266 {
1267         int i;
1268         unsigned char *cp;
1269         unsigned char buffer[BUFSIZ];
1270
1271         if (envelope == NULL) {
1272                 *sender = getcpy("");
1273                 return;
1274         }
1275
1276         i = strlen("From ");
1277         strncpy(buffer, envelope + i, sizeof(buffer));
1278         if ((cp = strchr(buffer, '\n'))) {
1279                 *cp = 0;
1280                 cp -= 24;
1281                 if (cp < buffer)
1282                         cp = buffer;
1283         } else {
1284                 cp = buffer;
1285         }
1286         *cp = 0;
1287
1288         for (cp = buffer + strlen(buffer) - 1; cp >= buffer; cp--)
1289                 if (isspace(*cp))
1290                         *cp = 0;
1291                 else
1292                         break;
1293         *sender = getcpy(buffer);
1294 }
1295
1296
1297 /*
1298 ** Copy message into a temporary file.
1299 ** While copying, it will do some header processing
1300 ** including the extraction of the envelope information.
1301 */
1302
1303 static int
1304 copy_message(int qd, char *tmpfil, int fold)
1305 {
1306         int i, first = 1, fd1, fd2;
1307         char buffer[BUFSIZ];
1308         FILE *qfp, *ffp;
1309         char *tfile = NULL;
1310
1311         tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1312         if (tfile == NULL) return -1;
1313         fchmod(fd1, 0600);
1314         strncpy(tmpfil, tfile, BUFSIZ);
1315
1316         if (!fold) {
1317                 while ((i = read(qd, buffer, sizeof(buffer))) > 0)
1318                         if (write(fd1, buffer, i) != i) {
1319 you_lose:
1320                                 close(fd1);
1321                                 unlink(tmpfil);
1322                                 return -1;
1323                         }
1324                 if (i == -1)
1325                         goto you_lose;
1326                 lseek(fd1, (off_t) 0, SEEK_SET);
1327                 return fd1;
1328         }
1329
1330         /* dup the fd for incoming message */
1331         if ((fd2 = dup(qd)) == -1) {
1332                 close(fd1);
1333                 return -1;
1334         }
1335
1336         /* now create a FILE pointer for it */
1337         if ((qfp = fdopen(fd2, "r")) == NULL) {
1338                 close(fd1);
1339                 close(fd2);
1340                 return -1;
1341         }
1342
1343         /* dup the fd for temporary file */
1344         if ((fd2 = dup(fd1)) == -1) {
1345                 close(fd1);
1346                 fclose(qfp);
1347                 return -1;
1348         }
1349
1350         /* now create a FILE pointer for it */
1351         if ((ffp = fdopen(fd2, "r+")) == NULL) {
1352                 close(fd1);
1353                 close(fd2);
1354                 fclose(qfp);
1355                 return -1;
1356         }
1357
1358         /*
1359         ** copy message into temporary file
1360         ** and massage the headers.  Save
1361         ** a copy of the "From " line for later.
1362         */
1363         i = strlen("From ");
1364         while (fgets(buffer, sizeof(buffer), qfp)) {
1365                 if (first) {
1366                         first = 0;
1367                         if (!strncmp(buffer, "From ", i)) {
1368 #ifdef RPATHS
1369                                 char *fp, *cp, *hp, *ep;
1370 #endif
1371                                 /*
1372                                 ** get copy of envelope information
1373                                 ** ("From " line)
1374                                 */
1375                                 envelope = getcpy(buffer);
1376
1377 #if 0
1378                                 /*
1379                                 ** First go ahead and put "From " line
1380                                 ** in message
1381                                 */
1382                                 fputs(buffer, ffp);
1383                                 if (ferror(ffp))
1384                                         goto fputs_error;
1385 #endif
1386
1387 #ifdef RPATHS
1388                                 /*
1389                                 ** Now create a "Return-Path:" line
1390                                 ** from the "From " line.
1391                                 */
1392                                 hp = cp = strchr(fp = envelope + i, ' ');
1393                                 while ((hp = strchr(++hp, 'r')))
1394                                         if (uprf(hp, "remote from")) {
1395                                                 hp = strrchr(hp, ' ');
1396                                                 break;
1397                                         }
1398                                 if (hp) {
1399                                         /*
1400                                         ** return path for UUCP style
1401                                         ** addressing
1402                                         */
1403                                         ep = strchr(++hp, '\n');
1404                                         snprintf(buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n", (int)(ep - hp), hp, (int)(cp - fp), fp);
1405                                 } else {
1406                                         /*
1407                                         ** return path for standard domain
1408                                         ** addressing
1409                                         */
1410                                         snprintf(buffer, sizeof(buffer), "Return-Path: %.*s\n", (int)(cp - fp), fp);
1411                                 }
1412
1413                                 /* Add Return-Path header to message */
1414                                 fputs(buffer, ffp);
1415                                 if (ferror(ffp))
1416                                         goto fputs_error;
1417 #endif
1418                                 /* Put the delivery date in message */
1419                                 fputs(ddate, ffp);
1420                                 if (ferror(ffp))
1421                                         goto fputs_error;
1422
1423                                 continue;
1424                         }
1425                 }
1426
1427                 fputs(buffer, ffp);
1428                 if (ferror(ffp))
1429                         goto fputs_error;
1430         }
1431
1432         fclose(ffp);
1433         if (ferror(qfp)) {
1434                 close(fd1);
1435                 fclose(qfp);
1436                 return -1;
1437         }
1438         fclose(qfp);
1439         lseek(fd1, (off_t) 0, SEEK_SET);
1440         return fd1;
1441
1442
1443 fputs_error:
1444         close(fd1);
1445         fclose(ffp);
1446         fclose(qfp);
1447         return -1;
1448 }
1449
1450 /*
1451 ** Trim strings for pretty printing of debugging output
1452 */
1453
1454 static char *
1455 trim(char *cp)
1456 {
1457         char buffer[BUFSIZ*4];
1458         unsigned char *bp, *sp;
1459
1460         if (cp == NULL)
1461                 return NULL;
1462
1463         /* copy string into temp buffer */
1464         strncpy(buffer, cp, sizeof(buffer));
1465         bp = buffer;
1466
1467         /* skip over leading whitespace */
1468         while (isspace(*bp))
1469                 bp++;
1470
1471         /* start at the end and zap trailing whitespace */
1472         for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1473                 if (isspace(*sp))
1474                         *sp = 0;
1475                 else
1476                         break;
1477         }
1478
1479         /* replace remaining whitespace with spaces */
1480         for (sp = bp; *sp; sp++)
1481                 if (isspace(*sp))
1482                         *sp = ' ';
1483
1484         /* now return a copy */
1485         return getcpy(bp);
1486 }
1487
1488 /*
1489 ** Function for printing `verbose' messages.
1490 */
1491
1492 static void
1493 verbose_printf(char *fmt, ...)
1494 {
1495         va_list ap;
1496
1497         va_start(ap, fmt);
1498         vfprintf(stdout, fmt, ap);
1499         va_end(ap);
1500
1501         fflush(stdout);  /* now flush output */
1502 }
1503
1504
1505 /*
1506 ** Function for printing `verbose' delivery
1507 ** error messages.
1508 */
1509
1510 static void
1511 adorn(char *what, char *fmt, ...)
1512 {
1513         va_list ap;
1514         int eindex;
1515         char *s;
1516
1517         eindex = errno;  /* save the errno */
1518         fprintf(stdout, ", ");
1519
1520         va_start(ap, fmt);
1521         vfprintf(stdout, fmt, ap);
1522         va_end(ap);
1523
1524         if (what) {
1525                 if (*what)
1526                         fprintf(stdout, " %s: ", what);
1527                 if ((s = strerror(eindex)))
1528                         fprintf(stdout, "%s", s);
1529                 else
1530                         fprintf(stdout, "Error %d", eindex);
1531         }
1532
1533         fputc('\n', stdout);
1534         fflush(stdout);
1535 }
1536
1537
1538 /*
1539 ** Function for printing `debug' messages.
1540 */
1541
1542 static void
1543 debug_printf(char *fmt, ...)
1544 {
1545         va_list ap;
1546
1547         va_start(ap, fmt);
1548         vfprintf(stderr, fmt, ap);
1549         va_end(ap);
1550 }
1551
1552
1553 /*
1554 ** Check ndbm/db file(s) to see if the Message-Id of this
1555 ** message matches the Message-Id of a previous message,
1556 ** so we can discard it.  If it doesn't match, we add the
1557 ** Message-Id of this message to the ndbm/db file.
1558 */
1559 static int
1560 suppress_duplicates(int fd, char *file)
1561 {
1562         int fd1, lockfd, state, result;
1563         char *cp, buf[BUFSIZ], name[NAMESZ];
1564         datum key, value;
1565         DBM *db;
1566         FILE *in;
1567
1568         if ((fd1 = dup(fd)) == -1)
1569                 return -1;
1570         if (!(in = fdopen(fd1, "r"))) {
1571                 close(fd1);
1572                 return -1;
1573         }
1574         rewind(in);
1575
1576         for (state = FLD;;) {
1577                 state = m_getfld(state, name, buf, sizeof(buf), in);
1578                 switch (state) {
1579                         case FLD:
1580                         case FLDPLUS:
1581                         case FLDEOF:
1582                                 /* Search for the message ID */
1583                                 if (mh_strcasecmp(name, "Message-ID")) {
1584                                         while (state == FLDPLUS)
1585                                                 state = m_getfld(state, name, buf, sizeof(buf), in);
1586                                         continue;
1587                                 }
1588
1589                                 cp = getcpy(buf);
1590                                 while (state == FLDPLUS) {
1591                                         state = m_getfld(state, name, buf, sizeof(buf), in);
1592                                         cp = add(buf, cp);
1593                                 }
1594                                 key.dptr = trimcpy(cp);
1595                                 key.dsize = strlen(key.dptr) + 1;
1596                                 free(cp);
1597                                 cp = key.dptr;
1598
1599                                 if (!(db = dbm_open(file, O_RDWR | O_CREAT,
1600                                                 0600))) {
1601                                         advise(file, "unable to perform dbm_open on");
1602                                         free(cp);
1603                                         fclose(in);
1604                                         return -1;
1605                                 }
1606                                 /*
1607                                 ** Since it is difficult to portable
1608                                 ** lock a ndbm file, we will open and
1609                                 ** lock the Maildelivery file instead.
1610                                 ** This will fail if your Maildelivery
1611                                 ** file doesn't exist.
1612                                 */
1613                                 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1614                                         advise(file, "unable to perform file locking on");
1615                                         free(cp);
1616                                         fclose(in);
1617                                         return -1;
1618                                 }
1619                                 value = dbm_fetch(db, key);
1620                                 if (value.dptr) {
1621                                         if (verbose)
1622                                                 verbose_printf("Message-ID: %s\n            already received on %s", cp, value.dptr);
1623                                         result = DONE;
1624                                 } else {
1625                                         value.dptr  = ddate + sizeof("Delivery-Date:");
1626                                         value.dsize = strlen(value.dptr) + 1;
1627                                         if (dbm_store(db, key, value, DBM_INSERT))
1628                                                 advise(file, "possibly corrupt file");
1629                                         result = 0;
1630                                 }
1631
1632                                 dbm_close(db);
1633                                 lkclose(lockfd, file);
1634                                 free(cp);
1635                                 fclose(in);
1636                                 return result;
1637                                 break;
1638
1639                    case BODY:
1640                    case BODYEOF:
1641                    case FILEEOF:
1642                                 break;
1643
1644                    case LENERR:
1645                    case FMTERR:
1646                    default:
1647                                 break;
1648                 }
1649
1650                 break;
1651         }
1652
1653         fclose(in);
1654         return 0;
1655 }