52e323afe3edcf55dda7ea17b2f8727f7d94d1c4
[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 = r1bindex (*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),
239                                                 "%s [switches] [address info sender]", invo_name);
240                                         print_help (buf, switches, 0);
241                                         done (1);
242                                 case VERSIONSW:
243                                         print_version(invo_name);
244                                         done (1);
245
246                                 case ADDRSW:
247                                         if (!(addr = *argp++))
248                                                 /* allow -xyz arguments */
249                                                 adios (NULL, "missing argument to %s", argp[-2]);
250                                         continue;
251                                 case INFOSW:
252                                         if (!(info = *argp++))
253                                                 /* allow -xyz arguments */
254                                                 adios (NULL, "missing argument to %s", argp[-2]);
255                                         continue;
256                                 case USERSW:
257                                         if (!(user = *argp++))
258                                                 /* allow -xyz arguments */
259                                                 adios (NULL, "missing argument to %s", argp[-2]);
260                                         continue;
261                                 case FILESW:
262                                         if (!(file = *argp++) || *file == '-')
263                                                 adios (NULL, "missing argument to %s", argp[-2]);
264                                         continue;
265                                 case SENDERSW:
266                                         if (!(sender = *argp++))
267                                                 /* allow -xyz arguments */
268                                                 adios (NULL, "missing argument to %s", argp[-2]);
269                                         continue;
270                                 case MAILBOXSW:
271                                         if (!(mbox = *argp++) || *mbox == '-')
272                                                 adios (NULL, "missing argument to %s", argp[-2]);
273                                         continue;
274                                 case HOMESW:
275                                         if (!(home = *argp++) || *home == '-')
276                                                 adios (NULL, "missing argument to %s", argp[-2]);
277                                         continue;
278
279                                 case MAILSW:
280                                         if (!(cp = *argp++) || *cp == '-')
281                                                 adios (NULL, "missing argument to %s", argp[-2]);
282                                         if (mdlvr)
283                                                 adios (NULL, "only one maildelivery file at a time!");
284                                         mdlvr = cp;
285                                         continue;
286
287                                 case VERBSW:
288                                         verbose++;
289                                         continue;
290                                 case NVERBSW:
291                                         verbose = 0;
292                                         continue;
293
294                                 case SUPPRESSDUP:
295                                         suppressdup++;
296                                         continue;
297                                 case NSUPPRESSDUP:
298                                         suppressdup = 0;
299                                         continue;
300                                 case DEBUGSW:
301                                         debug++;
302                                         continue;
303                         }
304                 }
305
306                 switch (argp - (argv + 1)) {
307                         case 1:
308                                 addr = cp;
309                                 break;
310
311                         case 2:
312                                 info = cp;
313                                 break;
314
315                         case 3:
316                                 sender = cp;
317                                 break;
318                 }
319         }
320
321         if (addr == NULL)
322                 addr = getusername ();
323         if (user == NULL)
324                 user = (cp = strchr(addr, '.')) ? ++cp : addr;
325         if ((pw = getpwnam (user)) == NULL)
326                 adios (NULL, "no such local user as %s", user);
327
328         if (chdir (pw->pw_dir) == -1)
329                 chdir ("/");
330         umask (0077);
331
332         if (geteuid() == 0) {
333                 setgid (pw->pw_gid);
334                 initgroups (pw->pw_name, pw->pw_gid);
335                 setuid (pw->pw_uid);
336         }
337
338         if (info == NULL)
339                 info = "";
340
341         setbuf (stdin, NULL);
342
343         /* Record the delivery time */
344         if ((now = dlocaltimenow ()) == NULL)
345                 adios (NULL, "unable to ascertain local time");
346         snprintf (ddate, sizeof(ddate), "Delivery-Date: %s\n", dtimenow (0));
347
348         /*
349         ** Copy the message to a temporary file
350         */
351         if (file) {
352                 int tempfd;
353
354                 /* getting message from file */
355                 if ((tempfd = open (file, O_RDONLY)) == -1)
356                         adios (file, "unable to open");
357                 if (debug)
358                         debug_printf ("retrieving message from file \"%s\"\n", 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 &&
439                         suppress_duplicates(fd,
440                         mdlvr ? mdlvr : ".maildelivery") == DONE)
441                 return 0;
442
443         /* delivery according to personal Maildelivery file */
444         if (usr_delivery (fd, mdlvr ? mdlvr : ".maildelivery", 0) != -1)
445                 return 0;
446
447         /* delivery according to global Maildelivery file */
448         if (usr_delivery (fd, maildelivery, 1) != -1)
449                 return 0;
450
451         if (verbose)
452                 verbose_printf ("(delivering to standard mail spool)\n");
453
454         /* last resort - deliver to standard mail spool */
455 #ifdef SLOCAL_MBOX
456         return usr_file (fd, mbox, MBOX_FORMAT);
457 #else
458         return usr_file (fd, mbox, MMDF_FORMAT);
459 #endif
460 }
461
462
463 #define matches(a,b) (stringdex (b, a) >= 0)
464
465 /*
466 ** Parse the delivery file, and process incoming message.
467 */
468
469 static int
470 usr_delivery (int fd, char *delivery, int su)
471 {
472         int i, accept, status=1, won, vecp, next;
473         char *field, *pattern, *action, *result, *string;
474         char buffer[BUFSIZ], tmpbuf[BUFSIZ];
475         char *cp, *vec[NVEC];
476         struct stat st;
477         struct pair *p;
478         FILE *fp;
479
480         /* open the delivery file */
481         if ((fp = fopen (delivery, "r")) == NULL)
482                 return -1;
483
484         /* check if delivery file has bad ownership or permissions */
485         if (fstat (fileno (fp), &st) == -1
486                         || (st.st_uid != 0 && (su || st.st_uid != pw->pw_uid))
487                         || st.st_mode & (S_IWGRP|S_IWOTH)) {
488                 if (verbose) {
489                         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);
490                 }
491                 return -1;
492         }
493
494         won = 0;
495         next = 1;
496
497         /* read and process delivery file */
498         while (fgets (buffer, sizeof(buffer), fp)) {
499                 /* skip comments and empty lines */
500                 if (*buffer == '#' || *buffer == '\n')
501                         continue;
502
503                 /* zap trailing newline */
504                 if ((cp = strchr(buffer, '\n')))
505                         *cp = 0;
506
507                 /* split buffer into fields */
508                 vecp = split (buffer, vec);
509
510                 /* check for too few fields */
511                 if (vecp < 5) {
512                         if (debug)
513                                 debug_printf ("WARNING: entry with only %d fields, skipping.\n", vecp);
514                         continue;
515                 }
516
517                 if (debug) {
518                         for (i = 0; vec[i]; i++)
519                                 debug_printf ("vec[%d]: \"%s\"\n",
520                                                 i, trim(vec[i]));
521                 }
522
523                 field   = vec[0];
524                 pattern = vec[1];
525                 action  = vec[2];
526                 result  = vec[3];
527                 string  = vec[4];
528
529                 /* find out how to perform the action */
530                 switch (result[0]) {
531                         case 'N':
532                         case 'n':
533                                 /*
534                                 ** If previous condition failed, don't
535                                 ** do this - else fall through
536                                 */
537                                  if (!next)
538                                         continue;  /* else fall */
539
540                         case '?':
541                                 /*
542                                 ** If already delivered, skip this action.
543                                 ** Else consider delivered if action is
544                                 ** successful.
545                                 */
546                                 if (won)
547                                         continue;  /* else fall */
548
549                         case 'A':
550                         case 'a':
551                                 /*
552                                 ** Take action, and consider delivered if
553                                 ** action is successful.
554                                 */
555                                 accept = 1;
556                                 break;
557
558                         case 'R':
559                         case 'r':
560                         default:
561                                 /*
562                                 ** Take action, but don't consider delivered,
563                                 ** even if action is successful
564                                 */
565                                 accept = 0;
566                                 break;
567                 }
568
569                 if (vecp > 5) {
570                         if (!mh_strcasecmp (vec[5], "select")) {
571                                 if (logged_in () != -1)
572                                         continue;
573                                 if (vecp > 7 && timely (vec[6], vec[7]) == -1)
574                                         continue;
575                         }
576                 }
577
578                 /* check if the field matches */
579                 switch (*field) {
580                         case '*':
581                         /* always matches */
582                                 break;
583
584                         case 'd':
585                         /*
586                         ** "default" matches only if the message hasn't
587                         ** been delivered yet.
588                         */
589                                 if (!mh_strcasecmp (field, "default")) {
590                                         if (won)
591                                                 continue;
592                                         break;
593                                 }  /* else fall */
594
595                         default:
596                                 /* parse message and build lookup table */
597                                 if (!parsed && parse (fd) == -1) {
598                                         fclose (fp);
599                                         return -1;
600                                 }
601                                 /*
602                                 ** find header field in lookup table, and
603                                 ** see if the pattern matches.
604                                 */
605                                 if ((p = lookup (hdrs, field)) &&
606                                                 (p->p_value != NULL) &&
607                                                 matches (p->p_value, pattern)
608                                                 ) {
609                                         next = 1;
610                                 } else {
611                                         next = 0;
612                                         continue;
613                                 }
614                                 break;
615                 }
616
617                 /* find out the action to perform */
618                 switch (*action) {
619                         case 'q':
620                                 /* deliver to quoted pipe */
621                                 if (mh_strcasecmp (action, "qpipe"))
622                                         continue;  /* else fall */
623                         case '^':
624                                 expand (tmpbuf, string, fd);
625                                 if (split (tmpbuf, vec) < 1)
626                                         continue;
627                                 status = usr_pipe (fd, tmpbuf, vec[0], vec, 0);
628                                 break;
629
630                         case 'p':
631                                 /* deliver to pipe */
632                                 if (mh_strcasecmp (action, "pipe"))
633                                         continue;  /* else fall */
634                         case '|':
635                                 vec[2] = "sh";
636                                 vec[3] = "-c";
637                                 expand (tmpbuf, string, fd);
638                                 vec[4] = tmpbuf;
639                                 vec[5] = NULL;
640                                 status = usr_pipe (fd, tmpbuf, "/bin/sh",
641                                                 vec + 2, 0);
642                                 break;
643
644                         case 'f':
645                                 /* mbox format */
646                                 if (!mh_strcasecmp (action, "file")) {
647                                         status = usr_file (fd, string,
648                                                         MBOX_FORMAT);
649                                         break;
650                                 }
651                                 /* deliver to nmh folder */
652                                 else if (mh_strcasecmp (action, "folder"))
653                                         continue;  /* else fall */
654                         case '+':
655                                 status = usr_folder (fd, string);
656                                 break;
657
658                         case 'm':
659                                 /* mmdf format */
660                                 if (!mh_strcasecmp (action, "mmdf")) {
661                                         status = usr_file (fd, string,
662                                                         MMDF_FORMAT);
663                                         break;
664                                 }
665                                 /* mbox format */
666                                 else if (mh_strcasecmp (action, "mbox"))
667                                         continue;  /* else fall */
668
669                         case '>':
670                                 /* mbox format */
671                                 status = usr_file (fd, string, MBOX_FORMAT);
672                                 break;
673
674                         case 'd':
675                                 /* ignore message */
676                                 if (mh_strcasecmp (action, "destroy"))
677                                         continue;
678                                 status = 0;
679                                 break;
680                 }
681
682                 if (status) 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 = add (field, NULL);
796                                 while (state == FLDPLUS) {
797                                         state = m_getfld (state, name, field, sizeof(field), in);
798                                         lp = add (field, lp);
799                                 }
800                                 for (p = hdrs; p->p_name; p++) {
801                                         if (!mh_strcasecmp (p->p_name, name)) {
802                                                 if (!(p->p_flags & P_HID)) {
803                                                         if ((cp = p->p_value)) {
804                                                                 if (p->p_flags & P_ADR) {
805                                                                         dp = cp + strlen (cp) - 1;
806                                                                         if (*dp == '\n')
807                                                                                 *dp = 0;
808                                                                         cp = add (",\n\t", cp);
809                                                                 } else {
810                                                                         cp = add ("\t", cp);
811                                                                 }
812                                                         }
813                                                         p->p_value = add (lp, cp);
814                                                 }
815                                                 free (lp);
816                                                 break;
817                                         }
818                                 }
819                                 if (p->p_name == NULL && i < NVEC) {
820                                         p->p_name = getcpy (name);
821                                         p->p_value = lp;
822                                         p->p_flags = P_NIL;
823                                         p++, i++;
824                                         p->p_name = NULL;
825                                 }
826                                 if (state != FLDEOF)
827                                         continue;
828                                 break;
829
830                         case BODY:
831                         case BODYEOF:
832                         case FILEEOF:
833                                 break;
834
835                         case LENERR:
836                         case FMTERR:
837                                 advise (NULL, "format error in message");
838                                 break;
839
840                         default:
841                                 advise (NULL, "internal error in m_getfld");
842                                 fclose (in);
843                                 return -1;
844                 }
845                 break;
846         }
847         fclose (in);
848
849         if ((p = lookup (vars, "reply-to"))) {
850                 if ((q = lookup (hdrs, "reply-to")) == NULL || q->p_value == NULL)
851                         q = lookup (hdrs, "from");
852                 p->p_value = getcpy (q ? q->p_value : "");
853                 p->p_flags &= ~P_CHK;
854                 if (debug)
855                         debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
856                                         p - vars, p->p_name, trim(p->p_value));
857         }
858         if (debug) {
859                 for (p = hdrs; p->p_name; p++)
860                         debug_printf ("hdrs[%d]: name=\"%s\" value=\"%s\"\n",
861                                 p - hdrs, p->p_name, p->p_value ? trim(p->p_value) : "");
862         }
863
864         return 0;
865 }
866
867
868 #define LPAREN '('
869 #define RPAREN ')'
870
871 /*
872 ** Expand any builtin variables such as $(sender),
873 ** $(address), etc., in a string.
874 */
875
876 static void
877 expand (char *s1, char *s2, int fd)
878 {
879         char c, *cp;
880         struct pair *p;
881
882         if (!globbed)
883                 glob (fd);
884
885         while ((c = *s2++)) {
886                 if (c != '$' || *s2 != LPAREN) {
887                         *s1++ = c;
888                 } else {
889                         for (cp = ++s2; *s2 && *s2 != RPAREN; s2++)
890                                 continue;
891                         if (*s2 != RPAREN) {
892                                 s2 = --cp;
893                                 continue;
894                         }
895                         *s2++ = 0;
896                         if ((p = lookup (vars, cp))) {
897                                 if (!parsed && (p->p_flags & P_CHK))
898                                         parse (fd);
899
900                                 strcpy (s1, p->p_value);
901                                 s1 += strlen (s1);
902                         }
903                 }
904         }
905         *s1 = 0;
906 }
907
908
909 /*
910 ** Fill in the information missing from the "vars"
911 ** table, which is necessary to expand any builtin
912 ** variables in the string for a "pipe" or "qpipe"
913 ** action.
914 */
915
916 static void
917 glob (int fd)
918 {
919         char buffer[BUFSIZ];
920         struct stat st;
921         struct pair *p;
922
923         if (globbed++)
924                 return;
925
926         if ((p = lookup (vars, "sender")))
927                 p->p_value = getcpy (sender);
928         if ((p = lookup (vars, "address")))
929                 p->p_value = getcpy (addr);
930         if ((p = lookup (vars, "size"))) {
931                 snprintf (buffer, sizeof(buffer), "%d",
932                                 fstat (fd, &st) != -1 ? (int) st.st_size : 0);
933                 p->p_value = getcpy (buffer);
934         }
935         if ((p = lookup (vars, "info")))
936                 p->p_value = getcpy (info);
937
938         if (debug) {
939                 for (p = vars; p->p_name; p++)
940                         debug_printf ("vars[%d]: name=\"%s\" value=\"%s\"\n",
941                                         p - vars, p->p_name, trim(p->p_value));
942         }
943 }
944
945
946 /*
947 ** Find a matching name in a lookup table.  If found,
948 ** return the "pairs" entry, else return NULL.
949 */
950
951 static struct pair *
952 lookup (struct pair *pairs, char *key)
953 {
954         for (; pairs->p_name; pairs++)
955                 if (!mh_strcasecmp (pairs->p_name, key))
956                         return pairs;
957
958         return NULL;
959 }
960
961
962 /*
963 ** Check utmp(x) file to see if user is currently
964 ** logged in.
965 */
966
967 #ifdef HAVE_GETUTENT
968 static int
969 logged_in (void)
970 {
971         struct utmp * utp;
972
973         if (utmped)
974                 return utmped;
975
976         setutent();
977
978         while ((utp = getutent()) != NULL) {
979                 if (
980 #ifdef HAVE_STRUCT_UTMP_UT_TYPE
981                                 utp->ut_type == USER_PROCESS &&
982 #endif
983                                 utp->ut_name[0] != 0 &&
984                                 strncmp (user, utp->ut_name,
985                                 sizeof(utp->ut_name)) == 0) {
986                         if (debug)
987                                 continue;
988                         endutent();
989                         return (utmped = DONE);
990                 }
991         }
992
993         endutent();
994         return (utmped = NOTOK);
995 }
996 #else
997 static int
998 logged_in (void)
999 {
1000         struct utmp ut;
1001         FILE *uf;
1002
1003         if (utmped)
1004                 return utmped;
1005
1006         if ((uf = fopen (UTMP_FILE, "r")) == NULL)
1007                 return NOTOK;
1008
1009         while (fread ((char *) &ut, sizeof(ut), 1, uf) == 1) {
1010                 if (ut.ut_name[0] != 0 &&
1011                                 strncmp (user, ut.ut_name, sizeof(ut.ut_name))
1012                                 == 0) {
1013                         if (debug)
1014                                 continue;
1015                         fclose (uf);
1016                         return (utmped = DONE);
1017                 }
1018         }
1019
1020         fclose (uf);
1021         return (utmped = NOTOK);
1022 }
1023 #endif
1024
1025 #define check(t,a,b)  if (t < a || t > b) return -1
1026 #define cmpar(h1,m1,h2,m2)  if (h1 < h2 || (h1 == h2 && m1 < m2)) return 0
1027
1028 static int
1029 timely (char *t1, char *t2)
1030 {
1031         int t1hours, t1mins, t2hours, t2mins;
1032
1033         if (sscanf (t1, "%d:%d", &t1hours, &t1mins) != 2)
1034                 return -1;
1035         check (t1hours, 0, 23);
1036         check (t1mins, 0, 59);
1037
1038         if (sscanf (t2, "%d:%d", &t2hours, &t2mins) != 2)
1039                 return -1;
1040         check (t2hours, 0, 23);
1041         check (t2mins, 0, 59);
1042
1043         cmpar (now->tw_hour, now->tw_min, t1hours, t1mins);
1044         cmpar (t2hours, t2mins, now->tw_hour, now->tw_min);
1045
1046         return -1;
1047 }
1048
1049
1050 /*
1051 ** Deliver message by appending to a file.
1052 */
1053
1054 static int
1055 usr_file (int fd, char *mailbox, int mbx_style)
1056 {
1057         int md, mapping;
1058
1059         if (verbose)
1060                 verbose_printf ("delivering to file \"%s\"", mailbox);
1061
1062         if (mbx_style == MBOX_FORMAT) {
1063                 if (verbose)
1064                         verbose_printf (" (mbox style)");
1065                 mapping = 0;
1066         } else {
1067                 if (verbose)
1068                         verbose_printf (" (mmdf style)");
1069                 mapping = 1;
1070         }
1071
1072         /* open and lock the file */
1073         if ((md = mbx_open (mailbox, mbx_style, pw->pw_uid, pw->pw_gid,
1074                         m_gmprot())) == -1) {
1075                 if (verbose)
1076                         adorn ("", "unable to open:");
1077                 return -1;
1078         }
1079
1080         lseek (fd, (off_t) 0, SEEK_SET);
1081
1082         /* append message to file */
1083         if (mbx_copy (mailbox, mbx_style, md, fd, mapping, NULL, verbose)
1084                         == -1) {
1085                 if (verbose)
1086                         adorn ("", "error writing to:");
1087                 return -1;
1088         }
1089
1090         /* close and unlock file */
1091         if (mbx_close (mailbox, md) == NOTOK) {
1092                 if (verbose)
1093                         adorn ("", "error closing:");
1094                 return -1;
1095         }
1096
1097         if (verbose)
1098                 verbose_printf (", success.\n");
1099         return 0;
1100 }
1101
1102
1103 /*
1104 ** Deliver message to a nmh folder.
1105 */
1106
1107 static int
1108 usr_folder (int fd, char *string)
1109 {
1110         int status;
1111         char folder[BUFSIZ], *vec[3];
1112
1113         /* get folder name ready */
1114         if (*string == '+')
1115                 strncpy(folder, string, sizeof(folder));
1116         else
1117                 snprintf(folder, sizeof(folder), "+%s", string);
1118
1119         if (verbose)
1120                 verbose_printf ("delivering to folder \"%s\"", folder + 1);
1121
1122         vec[0] = "rcvstore";
1123         vec[1] = folder;
1124         vec[2] = NULL;
1125
1126         /* use rcvstore to put message in folder */
1127         status = usr_pipe (fd, "rcvstore", rcvstoreproc, vec, 1);
1128
1129 #if 0
1130         /*
1131         ** Currently, verbose status messages are handled by usr_pipe().
1132         */
1133         if (verbose) {
1134                 if (status == 0)
1135                         verbose_printf (", success.\n");
1136                 else
1137                         verbose_printf (", failed.\n");
1138         }
1139 #endif
1140
1141         return status;
1142 }
1143
1144 /*
1145 ** Deliver message to a process.
1146 */
1147
1148 static int
1149 usr_pipe (int fd, char *cmd, char *pgm, char **vec, int suppress)
1150 {
1151         pid_t child_id;
1152         int i, bytes, seconds, status;
1153         struct stat st;
1154
1155         if (verbose && !suppress)
1156                 verbose_printf ("delivering to pipe \"%s\"", cmd);
1157
1158         lseek (fd, (off_t) 0, SEEK_SET);
1159
1160         for (i = 0; (child_id = fork()) == -1 && i < 5; i++)
1161                 sleep (5);
1162
1163         switch (child_id) {
1164                 case -1:
1165                         /* fork error */
1166                         if (verbose)
1167                                 adorn ("fork", "unable to");
1168                         return -1;
1169
1170                 case 0:
1171                         /* child process */
1172                         if (fd != 0)
1173                                 dup2 (fd, 0);
1174                         freopen ("/dev/null", "w", stdout);
1175                         freopen ("/dev/null", "w", stderr);
1176                         if (fd != 3)
1177                                 dup2 (fd, 3);
1178                         closefds (4);
1179
1180 #ifdef TIOCNOTTY
1181                         if ((fd = open ("/dev/tty", O_RDWR)) != -1) {
1182                                 ioctl (fd, TIOCNOTTY, NULL);
1183                                 close (fd);
1184                         }
1185 #endif /* TIOCNOTTY */
1186
1187                         /* put in own process group */
1188                         setpgid ((pid_t) 0, getpid ());
1189
1190                         *environ = NULL;
1191                         m_putenv ("USER", pw->pw_name);
1192                         m_putenv ("HOME", pw->pw_dir);
1193                         m_putenv ("SHELL", pw->pw_shell);
1194
1195                         execvp (pgm, vec);
1196                         _exit (-1);
1197
1198                 default:
1199                         /* parent process */
1200                         if (!setjmp (myctx)) {
1201                                 SIGNAL (SIGALRM, alrmser);
1202                                 bytes = fstat (fd, &st) != -1 ?
1203                                                 (int) st.st_size : 100;
1204
1205                                 /*
1206                                 ** amount of time to wait depends on
1207                                 ** message size
1208                                 */
1209                                 if (bytes <= 100) {
1210                                         /* give at least 5 minutes */
1211                                         seconds = 300;
1212                                 } else if (bytes >= 90000) {
1213                                         /* a half hour is long enough */
1214                                         seconds = 1800;
1215                                 } else {
1216                                         seconds = (bytes / 60) + 300;
1217                                 }
1218                                 alarm ((unsigned int) seconds);
1219                                 status = pidwait (child_id, 0);
1220                                 alarm (0);
1221
1222                                 if (verbose) {
1223                                         if (status == 0)
1224                                                 verbose_printf (", success.\n");
1225                                         else
1226                                                 if ((status & 0xff00) == 0xff00)
1227                                                         verbose_printf (", system error\n");
1228                                                 else
1229                                                         pidstatus (status, stdout, ", failed");
1230                                 }
1231                                 return (status == 0 ? 0 : -1);
1232                         } else {
1233                                 /*
1234                                 ** Ruthlessly kill the child and anything
1235                                 ** else in its process group.
1236                                 */
1237                                 KILLPG(child_id, SIGKILL);
1238                                 if (verbose)
1239                                         verbose_printf (", timed-out; terminated\n");
1240                                 return -1;
1241                         }
1242         }
1243 }
1244
1245
1246 static RETSIGTYPE
1247 alrmser (int i)
1248 {
1249 #ifndef RELIABLE_SIGNALS
1250         SIGNAL (SIGALRM, alrmser);
1251 #endif
1252
1253         longjmp (myctx, DONE);
1254 }
1255
1256
1257 /*
1258 ** Get the `sender' from the envelope
1259 ** information ("From " line).
1260 */
1261
1262 static void
1263 get_sender (char *envelope, char **sender)
1264 {
1265         int i;
1266         unsigned char *cp;
1267         unsigned char buffer[BUFSIZ];
1268
1269         if (envelope == NULL) {
1270                 *sender = getcpy ("");
1271                 return;
1272         }
1273
1274         i = strlen ("From ");
1275         strncpy (buffer, envelope + i, sizeof(buffer));
1276         if ((cp = strchr(buffer, '\n'))) {
1277                 *cp = 0;
1278                 cp -= 24;
1279                 if (cp < buffer)
1280                         cp = buffer;
1281         } else {
1282                 cp = buffer;
1283         }
1284         *cp = 0;
1285
1286         for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1287                 if (isspace (*cp))
1288                         *cp = 0;
1289                 else
1290                         break;
1291         *sender = getcpy (buffer);
1292 }
1293
1294
1295 /*
1296 ** Copy message into a temporary file.
1297 ** While copying, it will do some header processing
1298 ** including the extraction of the envelope information.
1299 */
1300
1301 static int
1302 copy_message (int qd, char *tmpfil, int fold)
1303 {
1304         int i, first = 1, fd1, fd2;
1305         char buffer[BUFSIZ];
1306         FILE *qfp, *ffp;
1307         char *tfile = NULL;
1308
1309         tfile = m_mktemp2(NULL, invo_name, &fd1, NULL);
1310         if (tfile == NULL) return -1;
1311         fchmod(fd1, 0600);
1312         strncpy (tmpfil, tfile, BUFSIZ);
1313
1314         if (!fold) {
1315                 while ((i = read (qd, buffer, sizeof(buffer))) > 0)
1316                         if (write (fd1, buffer, i) != i) {
1317 you_lose:
1318                                 close (fd1);
1319                                 unlink (tmpfil);
1320                                 return -1;
1321                         }
1322                 if (i == -1)
1323                         goto you_lose;
1324                 lseek (fd1, (off_t) 0, SEEK_SET);
1325                 return fd1;
1326         }
1327
1328         /* dup the fd for incoming message */
1329         if ((fd2 = dup (qd)) == -1) {
1330                 close (fd1);
1331                 return -1;
1332         }
1333
1334         /* now create a FILE pointer for it */
1335         if ((qfp = fdopen (fd2, "r")) == NULL) {
1336                 close (fd1);
1337                 close (fd2);
1338                 return -1;
1339         }
1340
1341         /* dup the fd for temporary file */
1342         if ((fd2 = dup (fd1)) == -1) {
1343                 close (fd1);
1344                 fclose (qfp);
1345                 return -1;
1346         }
1347
1348         /* now create a FILE pointer for it */
1349         if ((ffp = fdopen (fd2, "r+")) == NULL) {
1350                 close (fd1);
1351                 close (fd2);
1352                 fclose (qfp);
1353                 return -1;
1354         }
1355
1356         /*
1357         ** copy message into temporary file
1358         ** and massage the headers.  Save
1359         ** a copy of the "From " line for later.
1360         */
1361         i = strlen ("From ");
1362         while (fgets (buffer, sizeof(buffer), qfp)) {
1363                 if (first) {
1364                         first = 0;
1365                         if (!strncmp (buffer, "From ", i)) {
1366 #ifdef RPATHS
1367                                 char *fp, *cp, *hp, *ep;
1368 #endif
1369                                 /*
1370                                 ** get copy of envelope information
1371                                 ** ("From " line)
1372                                 */
1373                                 envelope = getcpy (buffer);
1374
1375 #if 0
1376                                 /*
1377                                 ** First go ahead and put "From " line
1378                                 ** in message
1379                                 */
1380                                 fputs (buffer, ffp);
1381                                 if (ferror (ffp))
1382                                         goto fputs_error;
1383 #endif
1384
1385 #ifdef RPATHS
1386                                 /*
1387                                 ** Now create a "Return-Path:" line
1388                                 ** from the "From " line.
1389                                 */
1390                                 hp = cp = strchr(fp = envelope + i, ' ');
1391                                 while ((hp = strchr(++hp, 'r')))
1392                                         if (uprf (hp, "remote from")) {
1393                                                 hp = strrchr(hp, ' ');
1394                                                 break;
1395                                         }
1396                                 if (hp) {
1397                                         /*
1398                                         ** return path for UUCP style
1399                                         ** addressing
1400                                         */
1401                                         ep = strchr(++hp, '\n');
1402                                         snprintf (buffer, sizeof(buffer), "Return-Path: %.*s!%.*s\n", (int)(ep - hp), hp, (int)(cp - fp), fp);
1403                                 } else {
1404                                         /*
1405                                         ** return path for standard domain
1406                                         ** addressing
1407                                         */
1408                                         snprintf (buffer, sizeof(buffer), "Return-Path: %.*s\n", (int)(cp - fp), fp);
1409                                 }
1410
1411                                 /* Add Return-Path header to message */
1412                                 fputs (buffer, ffp);
1413                                 if (ferror (ffp))
1414                                         goto fputs_error;
1415 #endif
1416                                 /* Put the delivery date in message */
1417                                 fputs (ddate, ffp);
1418                                 if (ferror (ffp))
1419                                         goto fputs_error;
1420
1421                                 continue;
1422                         }
1423                 }
1424
1425                 fputs (buffer, ffp);
1426                 if (ferror (ffp))
1427                         goto fputs_error;
1428         }
1429
1430         fclose (ffp);
1431         if (ferror (qfp)) {
1432                 close (fd1);
1433                 fclose (qfp);
1434                 return -1;
1435         }
1436         fclose (qfp);
1437         lseek (fd1, (off_t) 0, SEEK_SET);
1438         return fd1;
1439
1440
1441 fputs_error:
1442         close (fd1);
1443         fclose (ffp);
1444         fclose (qfp);
1445         return -1;
1446 }
1447
1448 /*
1449 ** Trim strings for pretty printing of debugging output
1450 */
1451
1452 static char *
1453 trim (char *cp)
1454 {
1455         char buffer[BUFSIZ*4];
1456         unsigned char *bp, *sp;
1457
1458         if (cp == NULL)
1459                 return NULL;
1460
1461         /* copy string into temp buffer */
1462         strncpy (buffer, cp, sizeof(buffer));
1463         bp = buffer;
1464
1465         /* skip over leading whitespace */
1466         while (isspace(*bp))
1467                 bp++;
1468
1469         /* start at the end and zap trailing whitespace */
1470         for (sp = bp + strlen(bp) - 1; sp >= bp; sp--) {
1471                 if (isspace(*sp))
1472                         *sp = 0;
1473                 else
1474                         break;
1475         }
1476
1477         /* replace remaining whitespace with spaces */
1478         for (sp = bp; *sp; sp++)
1479                 if (isspace(*sp))
1480                         *sp = ' ';
1481
1482         /* now return a copy */
1483         return getcpy(bp);
1484 }
1485
1486 /*
1487 ** Function for printing `verbose' messages.
1488 */
1489
1490 static void
1491 verbose_printf (char *fmt, ...)
1492 {
1493         va_list ap;
1494
1495         va_start(ap, fmt);
1496         vfprintf (stdout, fmt, ap);
1497         va_end(ap);
1498
1499         fflush (stdout);  /* now flush output */
1500 }
1501
1502
1503 /*
1504 ** Function for printing `verbose' delivery
1505 ** error messages.
1506 */
1507
1508 static void
1509 adorn (char *what, char *fmt, ...)
1510 {
1511         va_list ap;
1512         int eindex;
1513         char *s;
1514
1515         eindex = errno;  /* save the errno */
1516         fprintf (stdout, ", ");
1517
1518         va_start(ap, fmt);
1519         vfprintf (stdout, fmt, ap);
1520         va_end(ap);
1521
1522         if (what) {
1523                 if (*what)
1524                         fprintf (stdout, " %s: ", what);
1525                 if ((s = strerror (eindex)))
1526                         fprintf (stdout, "%s", s);
1527                 else
1528                         fprintf (stdout, "Error %d", eindex);
1529         }
1530
1531         fputc ('\n', stdout);
1532         fflush (stdout);
1533 }
1534
1535
1536 /*
1537 ** Function for printing `debug' messages.
1538 */
1539
1540 static void
1541 debug_printf (char *fmt, ...)
1542 {
1543         va_list ap;
1544
1545         va_start(ap, fmt);
1546         vfprintf (stderr, fmt, ap);
1547         va_end(ap);
1548 }
1549
1550
1551 /*
1552 ** Check ndbm/db file(s) to see if the Message-Id of this
1553 ** message matches the Message-Id of a previous message,
1554 ** so we can discard it.  If it doesn't match, we add the
1555 ** Message-Id of this message to the ndbm/db file.
1556 */
1557 static int
1558 suppress_duplicates (int fd, char *file)
1559 {
1560         int fd1, lockfd, state, result;
1561         char *cp, buf[BUFSIZ], name[NAMESZ];
1562         datum key, value;
1563         DBM *db;
1564         FILE *in;
1565
1566         if ((fd1 = dup (fd)) == -1)
1567                 return -1;
1568         if (!(in = fdopen (fd1, "r"))) {
1569                 close (fd1);
1570                 return -1;
1571         }
1572         rewind (in);
1573
1574         for (state = FLD;;) {
1575                 state = m_getfld (state, name, buf, sizeof(buf), in);
1576                 switch (state) {
1577                         case FLD:
1578                         case FLDPLUS:
1579                         case FLDEOF:
1580                                 /* Search for the message ID */
1581                                 if (mh_strcasecmp (name, "Message-ID")) {
1582                                         while (state == FLDPLUS)
1583                                                 state = m_getfld (state, name, buf, sizeof(buf), in);
1584                                         continue;
1585                                 }
1586
1587                                 cp = add (buf, NULL);
1588                                 while (state == FLDPLUS) {
1589                                         state = m_getfld (state, name, buf, sizeof(buf), in);
1590                                         cp = add (buf, cp);
1591                                 }
1592                                 key.dptr = trimcpy (cp);
1593                                 key.dsize = strlen (key.dptr) + 1;
1594                                 free (cp);
1595                                 cp = key.dptr;
1596
1597                                 if (!(db = dbm_open (file, O_RDWR | O_CREAT, 0600))) {
1598                                         advise (file, "unable to perform dbm_open on");
1599                                         free (cp);
1600                                         fclose (in);
1601                                         return -1;
1602                                 }
1603                                 /*
1604                                 ** Since it is difficult to portable
1605                                 ** lock a ndbm file, we will open and
1606                                 ** lock the Maildelivery file instead.
1607                                 ** This will fail if your Maildelivery
1608                                 ** file doesn't exist.
1609                                 */
1610                                 if ((lockfd = lkopen(file, O_RDWR, 0)) == -1) {
1611                                         advise (file, "unable to perform file locking on");
1612                                         free (cp);
1613                                         fclose (in);
1614                                         return -1;
1615                                 }
1616                                 value = dbm_fetch (db, key);
1617                                 if (value.dptr) {
1618                                         if (verbose)
1619                                                 verbose_printf ("Message-ID: %s\n            already received on %s", cp, value.dptr);
1620                                         result = DONE;
1621                                 } else {
1622                                         value.dptr  = ddate + sizeof("Delivery-Date:");
1623                                         value.dsize = strlen(value.dptr) + 1;
1624                                         if (dbm_store (db, key, value, DBM_INSERT))
1625                                                 advise (file, "possibly corrupt file");
1626                                         result = 0;
1627                                 }
1628
1629                                 dbm_close (db);
1630                                 lkclose(lockfd, file);
1631                                 free (cp);
1632                                 fclose (in);
1633                                 return result;
1634                                 break;
1635
1636                    case BODY:
1637                    case BODYEOF:
1638                    case FILEEOF:
1639                                 break;
1640
1641                    case LENERR:
1642                    case FMTERR:
1643                    default:
1644                                 break;
1645                 }
1646
1647                 break;
1648         }
1649
1650         fclose (in);
1651         return 0;
1652 }