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