Massive garbage collection. Remove functionality for APOP, RPOP,
[mmh] / uip / inc.c
1
2 /*
3  * inc.c -- incorporate messages from a maildrop into a folder
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #ifdef MAILGROUP
11 /* Revised: Sat Apr 14 17:08:17 PDT 1990 (marvit@hplabs)
12  *    Added hpux hacks to set and reset gid to be "mail" as needed. The reset
13  *    is necessary so inc'ed mail is the group of the inc'er, rather than
14  *    "mail". We setgid to egid only when [un]locking the mail file. This
15  *    is also a major security precaution which will not be explained here.
16  *
17  * Fri Feb  7 16:04:57 PST 1992         John Romine <bug-mh@ics.uci.edu>
18  *   NB: I'm not 100% sure that this setgid stuff is secure even now.
19  *
20  * See the *GROUPPRIVS() macros later. I'm reasonably happy with the setgid
21  * attribute. Running setuid root is probably not a terribly good idea, though.
22  *       -- Peter Maydell <pmaydell@chiark.greenend.org.uk>, 04/1998
23  *
24  * Peter Maydell's patch slightly modified for nmh 0.28-pre2.
25  * Ruud de Rooij <ruud@debian.org>  Wed, 22 Jul 1998 13:24:22 +0200
26  */
27 #endif
28
29 #include <h/mh.h>
30 #include <h/utils.h>
31 #include <fcntl.h>
32
33 #ifdef POP
34 # include <h/dropsbr.h>
35 # include <h/popsbr.h>
36 #endif
37
38 #include <h/fmt_scan.h>
39 #include <h/scansbr.h>
40 #include <h/signals.h>
41 #include <h/tws.h>
42 #include <h/mts.h>
43 #include <errno.h>
44 #include <signal.h>
45
46 #ifndef POP
47 # define POPminc(a) (a)
48 #else
49 # define POPminc(a)  0
50 #endif
51
52 #ifndef CYRUS_SASL
53 # define SASLminc(a) (a)
54 #else
55 # define SASLminc(a)  0
56 #endif
57
58 static struct swit switches[] = {
59 #define AUDSW                      0
60     { "audit audit-file", 0 },
61 #define NAUDSW                     1
62     { "noaudit", 0 },
63 #define CHGSW                      2
64     { "changecur", 0 },
65 #define NCHGSW                     3
66     { "nochangecur", 0 },
67 #define FILESW                     4
68     { "file name", 0 },
69 #define FORMSW                     5
70     { "form formatfile", 0 },
71 #define FMTSW                      6
72     { "format string", 5 },
73 #define HOSTSW                     7
74     { "host hostname", POPminc (-4) },
75 #define USERSW                     8
76     { "user username", POPminc (-4) },
77 #define PACKSW                     9
78     { "pack file", POPminc (-4) },
79 #define NPACKSW                   10
80     { "nopack", POPminc (-6) },
81 #define PORTSW                    13
82     { "port name/number", POPminc (-4) },
83 #define SILSW                     15
84     { "silent", 0 },
85 #define NSILSW                    16
86     { "nosilent", 0 },
87 #define TRNCSW                    17
88     { "truncate", 0 },
89 #define NTRNCSW                   18
90     { "notruncate", 0 },
91 #define WIDTHSW                   19
92     { "width columns", 0 },
93 #define VERSIONSW                 20
94     { "version", 0 },
95 #define HELPSW                    21
96     { "help", 0 },
97 #define SNOOPSW                   22
98     { "snoop", -5 },
99 #define SASLSW                    24
100     { "sasl", SASLminc(-4) },
101 #define SASLMECHSW                25
102     { "saslmech", SASLminc(-8) },
103 #define PROXYSW                   26
104     { "proxy command", POPminc(-5) },
105     { NULL, 0 }
106 };
107
108 /*
109  * flags for the mail source
110  */
111 #define INC_FILE  0
112 #define INC_POP   1
113
114 static int inc_type;
115 static int snoop = 0;
116
117 #ifdef POP
118 extern char response[];
119
120 static char *packfile = NULL;
121 static int size;
122 static long pos;
123 static long start;
124 static long stop;
125
126 static int mbx_style = MMDF_FORMAT;
127 static int pd = NOTOK;
128 static FILE *pf = NULL;
129 #endif /* POP */
130
131 /* This is an attempt to simplify things by putting all the
132  * privilege ops into macros.
133  * *GROUPPRIVS() is related to handling the setgid MAIL property,
134  * and only applies if MAILGROUP is defined.
135  * *USERPRIVS() is related to handling the setuid root property,
136  * and only applies if POP is defined [why does POP => setuid root?]
137  * Basically, SAVEGROUPPRIVS() is called right at the top of main()
138  * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
139  * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
140  * before DROPUSERPRIVS() is called [this is needed because setgid()
141  * sets both effective and real uids if euid is root.]
142  *
143  * There's probably a better implementation if we're allowed to use
144  * BSD-style setreuid() rather than using POSIX saved-ids.
145  * Anyway, if you're euid root it's a bit pointless to drop the group
146  * permissions...
147  *
148  * I'm pretty happy that the security is good provided we aren't setuid root.
149  * The only things we trust with group=mail privilege are lkfopen()
150  * and lkfclose().
151  */
152
153 /*
154  * For setting and returning to "mail" gid
155  */
156 #ifdef MAILGROUP
157 static int return_gid;
158 #ifndef POP
159 /* easy case; we're not setuid root, so can drop group privs
160  * immediately.
161  */
162 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
163 #else /* POP ie we are setuid root */
164 #define TRYDROPGROUPPRIVS() \
165 if (geteuid() != 0) DROPGROUPPRIVS()
166 #endif
167 #define DROPGROUPPRIVS() setgid(getgid())
168 #define GETGROUPPRIVS() setgid(return_gid)
169 #define SAVEGROUPPRIVS() return_gid = getegid()
170 #else
171 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
172 #define TRYDROPGROUPPRIVS()
173 #define DROPGROUPPRIVS()
174 #define GETGROUPPRIVS()
175 #define SAVEGROUPPRIVS()
176 #endif /* not MAILGROUP */
177
178 /* these variables have to be globals so that done() can correctly clean up the lockfile */
179 static int locked = 0;
180 static char *newmail;
181 static FILE *in;
182
183 /*
184  * prototypes
185  */
186 char *map_name(char *);
187
188 static void inc_done(int) NORETURN;
189 #ifdef POP
190 static int pop_action(char *);
191 static int pop_pack(char *);
192 static int map_count(void);
193 #endif
194
195
196 int
197 main (int argc, char **argv)
198 {
199     int chgflag = 1, trnflag = 1;
200     int noisy = 1, width = 0;
201     int i, hghnum = 0, msgnum = 0;
202     int sasl = 0;
203     char *cp, *maildir = NULL, *folder = NULL;
204     char *format = NULL, *form = NULL;
205     char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
206     char *audfile = NULL, *from = NULL, *saslmech = NULL;
207     char buf[BUFSIZ], **argp, *nfs, **arguments;
208     struct msgs *mp = NULL;
209     struct stat st, s1;
210     FILE *aud = NULL;
211     char b[MAXPATHLEN + 1];
212     char *maildir_copy = NULL;  /* copy of mail directory because the static gets overwritten */
213
214 #ifdef POP
215     int nmsgs, nbytes, p = 0;
216     char *pass = NULL;
217     char *MAILHOST_env_variable;
218 #endif
219
220 #ifdef MHE
221     FILE *mhe = NULL;
222 #endif
223
224     done=inc_done;
225
226 /* absolutely the first thing we do is save our privileges,
227  * and drop them if we can.
228  */
229     SAVEGROUPPRIVS();
230     TRYDROPGROUPPRIVS();
231
232 #ifdef LOCALE
233     setlocale(LC_ALL, "");
234 #endif
235     invo_name = r1bindex (argv[0], '/');
236
237     /* read user profile/context */
238     context_read();
239
240     mts_init (invo_name);
241     arguments = getarguments (invo_name, argc, argv, 1);
242     argp = arguments;
243
244 #ifdef POP
245     /*
246      * Scheme is:
247      *        use MAILHOST environment variable if present,
248      *  else try Hesiod.
249      *  If that fails, use the default (if any)
250      *  provided by mts.conf in mts_init()
251      */
252     if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
253         pophost = MAILHOST_env_variable;
254     /*
255      * If there is a valid "pophost" entry in mts.conf,
256      * then use it as the default host.
257      */
258     if (pophost && *pophost)
259         host = pophost;
260
261     if ((cp = getenv ("MHPOPDEBUG")) && *cp)
262         snoop++;
263 #endif /* POP */
264
265     while ((cp = *argp++)) {
266         if (*cp == '-') {
267             switch (smatch (++cp, switches)) {
268             case AMBIGSW: 
269                 ambigsw (cp, switches);
270                 done (1);
271             case UNKWNSW: 
272                 adios (NULL, "-%s unknown", cp);
273
274             case HELPSW: 
275                 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
276                 print_help (buf, switches, 1);
277                 done (1);
278             case VERSIONSW:
279                 print_version(invo_name);
280                 done (1);
281
282             case AUDSW: 
283                 if (!(cp = *argp++) || *cp == '-')
284                     adios (NULL, "missing argument to %s", argp[-2]);
285                 audfile = getcpy (m_maildir (cp));
286                 continue;
287             case NAUDSW: 
288                 audfile = NULL;
289                 continue;
290
291             case CHGSW: 
292                 chgflag++;
293                 continue;
294             case NCHGSW: 
295                 chgflag = 0;
296                 continue;
297
298             /*
299              * The flag `trnflag' has the value:
300              *
301              * 2 if -truncate is given
302              * 1 by default (truncating is default)
303              * 0 if -notruncate is given
304              */
305             case TRNCSW: 
306                 trnflag = 2;
307                 continue;
308             case NTRNCSW: 
309                 trnflag = 0;
310                 continue;
311
312             case FILESW: 
313                 if (!(cp = *argp++) || *cp == '-')
314                     adios (NULL, "missing argument to %s", argp[-2]);
315                 from = path (cp, TFILE);
316
317                 /*
318                  * If the truncate file is in default state,
319                  * change to not truncate.
320                  */
321                 if (trnflag == 1)
322                     trnflag = 0;
323                 continue;
324
325             case SILSW: 
326                 noisy = 0;
327                 continue;
328             case NSILSW: 
329                 noisy++;
330                 continue;
331
332             case FORMSW: 
333                 if (!(form = *argp++) || *form == '-')
334                     adios (NULL, "missing argument to %s", argp[-2]);
335                 format = NULL;
336                 continue;
337             case FMTSW: 
338                 if (!(format = *argp++) || *format == '-')
339                     adios (NULL, "missing argument to %s", argp[-2]);
340                 form = NULL;
341                 continue;
342
343             case WIDTHSW: 
344                 if (!(cp = *argp++) || *cp == '-')
345                     adios (NULL, "missing argument to %s", argp[-2]);
346                 width = atoi (cp);
347                 continue;
348
349             case HOSTSW:
350                 if (!(host = *argp++) || *host == '-')
351                     adios (NULL, "missing argument to %s", argp[-2]);
352                 continue;
353
354             case PORTSW:
355                 if (!(host = *argp++) || *port == '-')
356                     adios (NULL, "missing argument to %s", argp[-2]);
357                 continue;
358
359             case USERSW:
360                 if (!(user = *argp++) || *user == '-')
361                     adios (NULL, "missing argument to %s", argp[-2]);
362                 continue;
363
364             case PACKSW:
365 #ifndef POP
366                 if (!(cp = *argp++) || *cp == '-')
367                     adios (NULL, "missing argument to %s", argp[-2]);
368 #else /* POP */
369                 if (!(packfile = *argp++) || *packfile == '-')
370                     adios (NULL, "missing argument to %s", argp[-2]);
371 #endif /* POP */
372                 continue;
373             case NPACKSW:
374 #ifdef POP
375                 packfile = NULL;
376 #endif /* POP */
377                 continue;
378
379             case SNOOPSW:
380                 snoop++;
381                 continue;
382         
383             case SASLSW:
384                 sasl++;
385                 continue;
386         
387             case SASLMECHSW:
388                 if (!(saslmech = *argp++) || *saslmech == '-')
389                     adios (NULL, "missing argument to %s", argp[-2]);
390                 continue;
391             case PROXYSW:
392                 if (!(proxy = *argp++) || *proxy == '-')
393                     adios (NULL, "missing argument to %s", argp[-2]);
394                 continue;
395             }
396         }
397         if (*cp == '+' || *cp == '@') {
398             if (folder)
399                 adios (NULL, "only one folder at a time!");
400             else
401                 folder = pluspath (cp);
402         } else {
403             adios (NULL, "usage: %s [+folder] [switches]", invo_name);
404         }
405     }
406
407     /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
408      * not DROPGROUPPRIVS().
409      */
410 #ifdef POP
411     if (host && !*host)
412         host = NULL;
413 #endif /* POP */
414
415     /* guarantee dropping group priveleges; we might not have done so earlier */
416     DROPGROUPPRIVS();
417
418     /*
419      * Where are we getting the new mail?
420      */
421     if (from)
422         inc_type = INC_FILE;
423 #ifdef POP
424     else if (host)
425         inc_type = INC_POP;
426 #endif
427     else
428         inc_type = INC_FILE;
429
430 #ifdef POP
431     /*
432      * Are we getting the mail from
433      * a POP server?
434      */
435     if (inc_type == INC_POP) {
436         if (user == NULL)
437             user = getusername ();
438         if (sasl)
439             pass = getusername ();
440         else
441             ruserpass (host, &user, &pass);
442
443         /*
444          * initialize POP connection
445          */
446         if (pop_init (host, port, user, pass, proxy, snoop, sasl,
447                       saslmech) == NOTOK)
448             adios (NULL, "%s", response);
449
450         /* Check if there are any messages */
451         if (pop_stat (&nmsgs, &nbytes) == NOTOK)
452             adios (NULL, "%s", response);
453
454         if (nmsgs == 0) {
455             pop_quit();
456             adios (NULL, "no mail to incorporate");
457         }
458     }
459 #endif /* POP */
460
461     /*
462      * We will get the mail from a file
463      * (typically the standard maildrop)
464      */
465
466     if (inc_type == INC_FILE) {
467         if (from)
468             newmail = from;
469         else if ((newmail = getenv ("MAILDROP")) && *newmail)
470             newmail = m_mailpath (newmail);
471         else if ((newmail = context_find ("maildrop")) && *newmail)
472             newmail = m_mailpath (newmail);
473         else {
474             newmail = concat (MAILDIR, "/", MAILFIL, NULL);
475         }
476         if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
477             adios (NULL, "no mail to incorporate");
478
479         if ((cp = strdup(newmail)) == (char *)0)
480             adios (NULL, "error allocating memory to copy newmail");
481
482         newmail = cp;
483     }
484
485 #ifdef POP
486     /* skip the folder setup */
487     if ((inc_type == INC_POP) && packfile)
488         goto go_to_it;
489 #endif /* POP */
490
491     if (!context_find ("path"))
492         free (path ("./", TFOLDER));
493     if (!folder)
494         folder = getfolder (0);
495     maildir = m_maildir (folder);
496
497     if ((maildir_copy = strdup(maildir)) == (char *)0)
498         adios (maildir, "error allocating memory to copy maildir");
499
500     if (!folder_exists(maildir)) {
501         /* If the folder doesn't exist, and we're given the -silent flag,
502          * just fail.
503          */
504         if (noisy)
505             create_folder(maildir, 0, done);
506         else
507             done (1);
508     }
509
510     if (chdir (maildir) == NOTOK)
511         adios (maildir, "unable to change directory to");
512
513     /* read folder and create message structure */
514     if (!(mp = folder_read (folder)))
515         adios (NULL, "unable to read folder %s", folder);
516
517 #ifdef POP
518 go_to_it:
519 #endif /* POP */
520
521     if (inc_type == INC_FILE) {
522         if (access (newmail, W_OK) != NOTOK) {
523             locked++;
524             if (trnflag) {
525                 SIGNAL (SIGHUP, SIG_IGN);
526                 SIGNAL (SIGINT, SIG_IGN);
527                 SIGNAL (SIGQUIT, SIG_IGN);
528                 SIGNAL (SIGTERM, SIG_IGN);
529             }
530
531             GETGROUPPRIVS();       /* Reset gid to lock mail file */
532             in = lkfopen (newmail, "r");
533             DROPGROUPPRIVS();
534             if (in == NULL)
535                 adios (NULL, "unable to lock and fopen %s", newmail);
536             fstat (fileno(in), &s1);
537         } else {
538             trnflag = 0;
539             if ((in = fopen (newmail, "r")) == NULL)
540                 adios (newmail, "unable to read");
541         }
542     }
543
544     /* This shouldn't be necessary but it can't hurt. */
545     DROPGROUPPRIVS();
546
547     if (audfile) {
548         if ((i = stat (audfile, &st)) == NOTOK)
549             advise (NULL, "Creating Receive-Audit: %s", audfile);
550         if ((aud = fopen (audfile, "a")) == NULL)
551             adios (audfile, "unable to append to");
552         else if (i == NOTOK)
553             chmod (audfile, m_gmprot ());
554
555 #ifdef POP
556         fprintf (aud, from ? "<<inc>> %s -ms %s\n"
557                  : host ? "<<inc>> %s -host %s -user %s\n"
558                  : "<<inc>> %s\n",
559                  dtimenow (0), from ? from : host, user);
560 #else /* POP */
561         fprintf (aud, from ? "<<inc>> %s  -ms %s\n" : "<<inc>> %s\n",
562                  dtimenow (0), from);
563 #endif /* POP */
564     }
565
566 #ifdef MHE
567     if (context_find ("mhe")) {
568         cp = concat (maildir, "/++", NULL);
569         i = stat (cp, &st);
570         if ((mhe = fopen (cp, "a")) == NULL)
571             admonish (cp, "unable to append to");
572         else
573             if (i == NOTOK)
574                 chmod (cp, m_gmprot ());
575         free (cp);
576     }
577 #endif /* MHE */
578
579     /* Get new format string */
580     nfs = new_fs (form, format, FORMAT);
581
582     if (noisy) {
583         printf ("Incorporating new mail into %s...\n\n", folder);
584         fflush (stdout);
585     }
586
587 #ifdef POP
588     /*
589      * Get the mail from a POP server
590      */
591     if (inc_type == INC_POP) {
592         if (packfile) {
593             packfile = path (packfile, TFILE);
594             if (stat (packfile, &st) == NOTOK) {
595                 if (errno != ENOENT)
596                     adios (packfile, "error on file");
597                 cp = concat ("Create file \"", packfile, "\"? ", NULL);
598                 if (noisy && !getanswer (cp))
599                     done (1);
600                 free (cp);
601             }
602             msgnum = map_count ();
603             if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
604                 == NOTOK)
605                 adios (packfile, "unable to open");
606             if ((pf = fdopen (pd, "w+")) == NULL)
607                 adios (NULL, "unable to fdopen %s", packfile);
608         } else {
609             hghnum = msgnum = mp->hghmsg;
610             /*
611              * Check if we have enough message space for all the new
612              * messages.  If not, then realloc the folder and add enough
613              * space for all new messages plus 10 additional slots.
614              */
615             if (mp->hghmsg + nmsgs >= mp->hghoff
616                 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
617                 adios (NULL, "unable to allocate folder storage");
618         }
619
620         for (i = 1; i <= nmsgs; i++) {
621             msgnum++;
622             if (packfile) {
623                 fseek (pf, 0L, SEEK_CUR);
624                 pos = ftell (pf);
625                 size = 0;
626                 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
627                 start = ftell (pf);
628
629                 if (pop_retr (i, pop_pack) == NOTOK)
630                     adios (NULL, "%s", response);
631
632                 fseek (pf, 0L, SEEK_CUR);
633                 stop = ftell (pf);
634                 if (fflush (pf))
635                     adios (packfile, "write error on");
636                 fseek (pf, start, SEEK_SET);
637             } else {
638                 cp = getcpy (m_name (msgnum));
639                 if ((pf = fopen (cp, "w+")) == NULL)
640                     adios (cp, "unable to write");
641                 chmod (cp, m_gmprot ());
642                 start = stop = 0L;
643
644                 if (pop_retr (i, pop_action) == NOTOK)
645                     adios (NULL, "%s", response);
646
647                 if (fflush (pf))
648                     adios (cp, "write error on");
649                 fseek (pf, 0L, SEEK_SET);
650             }
651             switch (p = scan (pf, msgnum, 0, nfs, width,
652                               packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
653                               1, NULL, stop - start, noisy)) {
654             case SCNEOF: 
655                 printf ("%*d  empty\n", DMAXFOLDER, msgnum);
656                 break;
657
658             case SCNFAT:
659                 trnflag = 0;
660                 noisy++;
661                 /* advise (cp, "unable to read"); already advised */
662                 /* fall thru */
663
664             case SCNERR:
665             case SCNNUM: 
666                 break;
667
668             case SCNMSG: 
669             case SCNENC:
670             default: 
671                 if (aud)
672                     fputs (scanl, aud);
673 # ifdef MHE
674                 if (mhe)
675                     fputs (scanl, mhe);
676 # endif /* MHE */
677                 if (noisy)
678                     fflush (stdout);
679                 if (!packfile) {
680                     clear_msg_flags (mp, msgnum);
681                     set_exists (mp, msgnum);
682                     set_unseen (mp, msgnum);
683                     mp->msgflags |= SEQMOD;
684                 }
685                 break;
686             }
687             if (packfile) {
688                 fseek (pf, stop, SEEK_SET);
689                 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
690                 if (fflush (pf) || ferror (pf)) {
691                     int e = errno;
692                     pop_quit ();
693                     errno = e;
694                     adios (packfile, "write error on");
695                 }
696                 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
697             } else {
698                 if (ferror(pf) || fclose (pf)) {
699                     int e = errno;
700                     unlink (cp);
701                     pop_quit ();
702                     errno = e;
703                     adios (cp, "write error on");
704                 }
705                 free (cp);
706             }
707
708             if (trnflag && pop_dele (i) == NOTOK)
709                 adios (NULL, "%s", response);
710         }
711
712         if (pop_quit () == NOTOK)
713             adios (NULL, "%s", response);
714         if (packfile) {
715             mbx_close (packfile, pd);
716             pd = NOTOK;
717         }
718     }
719 #endif /* POP */
720
721     /*
722      * Get the mail from file (usually mail spool)
723      */
724     if (inc_type == INC_FILE) {
725         m_unknown (in);         /* the MAGIC invocation... */
726         hghnum = msgnum = mp->hghmsg;
727         for (i = 0;;) {
728             /*
729              * Check if we need to allocate more space for message status.
730              * If so, then add space for an additional 100 messages.
731              */
732             if (msgnum >= mp->hghoff
733                 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
734                 advise (NULL, "unable to allocate folder storage");
735                 i = NOTOK;
736                 break;
737             }
738
739 #if 0
740             /* copy file from spool to tmp file */
741             tmpfilenam = m_scratch ("", invo_name);
742             if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
743                 adios (tmpfilenam, "unable to create");
744             chmod (tmpfilenam, m_gmprot ());
745             if (!(in2 = fdopen (fd, "r+")))
746                 adios (tmpfilenam, "unable to access");
747             cpymsg (in, in2);
748
749             /* link message into folder */
750             newmsg = folder_addmsg(mp, tmpfilenam);
751 #endif
752             /* create scanline for new message */
753             switch (i = scan (in, msgnum + 1, msgnum + 1, nfs, width,
754                               msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
755             case SCNFAT:
756             case SCNEOF: 
757                 break;
758
759             case SCNERR:
760                 if (aud)
761                     fputs ("inc aborted!\n", aud);
762                 advise (NULL, "aborted!");      /* doesn't clean up locks! */
763                 break;
764
765             case SCNNUM: 
766                 advise (NULL, "BUG in %s, number out of range", invo_name);
767                 break;
768
769             default: 
770                 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, i);
771                 break;
772
773             case SCNMSG:
774             case SCNENC:
775                 /*
776                  *  Run the external program hook on the message.
777                  */
778
779                 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
780                 (void)ext_hook("add-hook", b, (char *)0);
781
782                 if (aud)
783                     fputs (scanl, aud);
784 #ifdef MHE
785                 if (mhe)
786                     fputs (scanl, mhe);
787 #endif /* MHE */
788                 if (noisy)
789                     fflush (stdout);
790
791                 msgnum++;
792                 mp->hghmsg++;
793                 mp->nummsg++;
794                 if (mp->lowmsg == 0) mp->lowmsg = 1;
795
796                 clear_msg_flags (mp, msgnum);
797                 set_exists (mp, msgnum);
798                 set_unseen (mp, msgnum);
799                 mp->msgflags |= SEQMOD;
800                 continue;
801             }
802             break;
803         }
804     }
805
806 #ifdef POP
807     if (p < 0) {                /* error */
808 #else
809     if (i < 0) {                /* error */
810 #endif
811         if (locked) {
812             GETGROUPPRIVS();      /* Be sure we can unlock mail file */
813             (void) lkfclose (in, newmail); in = NULL;
814             DROPGROUPPRIVS();    /* And then return us to normal privileges */
815         } else {
816             fclose (in); in = NULL;
817         }
818         adios (NULL, "failed");
819     }
820
821     if (aud)
822         fclose (aud);
823
824 #ifdef MHE
825     if (mhe)
826         fclose (mhe);
827 #endif /* MHE */
828
829     if (noisy)
830         fflush (stdout);
831
832 #ifdef POP
833     if ((inc_type == INC_POP) && packfile)
834         done (0);
835 #endif /* POP */
836
837     /*
838      * truncate file we are incorporating from
839      */
840     if (inc_type == INC_FILE) {
841         if (trnflag) {
842             if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
843                 advise (NULL, "new messages have arrived!\007");
844             else {
845                 if ((i = creat (newmail, 0600)) != NOTOK)
846                     close (i);
847                 else
848                     admonish (newmail, "error zero'ing");
849                 unlink(map_name(newmail));
850             }
851         } else {
852             if (noisy)
853                 printf ("%s not zero'd\n", newmail);
854         }
855     }
856
857     if (msgnum == hghnum) {
858         admonish (NULL, "no messages incorporated");
859     } else {
860         context_replace (pfolder, folder);      /* update current folder */
861         if (chgflag)
862             mp->curmsg = hghnum + 1;
863         mp->hghmsg = msgnum;
864         if (mp->lowmsg == 0)
865             mp->lowmsg = 1;
866         if (chgflag)            /* sigh... */
867             seq_setcur (mp, mp->curmsg);
868     }
869
870     /*
871      * unlock the mail spool
872      */
873     if (inc_type == INC_FILE) {
874         if (locked) {
875            GETGROUPPRIVS();        /* Be sure we can unlock mail file */
876            (void) lkfclose (in, newmail); in = NULL;
877            DROPGROUPPRIVS();       /* And then return us to normal privileges */
878         } else {
879             fclose (in); in = NULL;
880         }
881     }
882
883     seq_setunseen (mp, 0);      /* set the Unseen-Sequence */
884     seq_save (mp);              /* synchronize sequences   */
885     context_save ();            /* save the context file   */
886     done (0);
887     return 1;
888 }
889
890
891 #if 0
892
893 /*
894  * Copy message message from spool into
895  * temporary file.  Massage the "From " line
896  * while copying.
897  */
898
899 cpymsg (FILE *in, FILE *out)
900 {
901     int state;
902     char *tmpbuf, name[NAMESZ];
903
904     for (;;) {
905         state = m_getfld (state, name, tmpbuf, rlwidth, in);
906         switch (state) {
907         case FLD:
908         case FLDPLUS:
909             break;
910         case BODY:
911             break;
912         case LENERR:
913         case FMTERR:
914             break;
915         case FILEEOF:
916             break;
917         default:
918         }
919     }
920 }
921 #endif /* if 0 */
922
923
924 static void
925 inc_done (int status)
926 {
927 #ifdef POP
928     if (packfile && pd != NOTOK)
929         mbx_close (packfile, pd);
930 #endif /* POP */
931     if (locked)
932     {
933         GETGROUPPRIVS();
934         lkfclose(in, newmail);
935         DROPGROUPPRIVS();
936     }
937     exit (status);
938 }
939
940 #ifdef POP
941 static int
942 pop_action (char *s)
943 {
944     fprintf (pf, "%s\n", s);
945     stop += strlen (s) + 1;
946     return 0;  /* Is return value used?  This was missing before 1999-07-15. */
947 }
948
949 static int
950 pop_pack (char *s)
951 {
952     int j;
953     char buffer[BUFSIZ];
954
955     snprintf (buffer, sizeof(buffer), "%s\n", s);
956     for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
957         continue;
958     for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
959         continue;
960     fputs (buffer, pf);
961     size += strlen (buffer) + 1;
962     return 0;  /* Is return value used?  This was missing before 1999-07-15. */
963 }
964
965 static int
966 map_count (void)
967 {
968     int md;
969     char *cp;
970     struct drop d;
971     struct stat st;
972
973     if (stat (packfile, &st) == NOTOK)
974         return 0;
975     if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
976             || map_chk (cp, md, &d, (long) st.st_size, 1)) {
977         if (md != NOTOK)
978             close (md);
979         return 0;
980     }
981     close (md);
982     return (d.d_id);
983 }
984 #endif /* POP */