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