Remove RCS keywords, since they no longer work after git migration.
[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 #ifdef HESIOD
39 # include <hesiod.h>
40 #endif
41
42 #include <h/fmt_scan.h>
43 #include <h/scansbr.h>
44 #include <h/signals.h>
45 #include <h/tws.h>
46 #include <h/mts.h>
47 #include <errno.h>
48 #include <signal.h>
49
50 #ifndef POP
51 # define POPminc(a) (a)
52 #else
53 # define POPminc(a)  0
54 #endif
55
56 #ifndef RPOP
57 # define RPOPminc(a) (a)
58 #else
59 # define RPOPminc(a)  0
60 #endif
61
62 #ifndef APOP
63 # define APOPminc(a) (a)
64 #else
65 # define APOPminc(a)  0
66 #endif
67
68 #ifndef KPOP
69 # define KPOPminc(a) (a)
70 #else
71 # define KPOPminc(a)  0
72 #endif
73
74 #ifndef CYRUS_SASL
75 # define SASLminc(a) (a)
76 #else
77 # define SASLminc(a)  0
78 #endif
79
80 static struct swit switches[] = {
81 #define AUDSW                      0
82     { "audit audit-file", 0 },
83 #define NAUDSW                     1
84     { "noaudit", 0 },
85 #define CHGSW                      2
86     { "changecur", 0 },
87 #define NCHGSW                     3
88     { "nochangecur", 0 },
89 #define FILESW                     4
90     { "file name", 0 },
91 #define FORMSW                     5
92     { "form formatfile", 0 },
93 #define FMTSW                      6
94     { "format string", 5 },
95 #define HOSTSW                     7
96     { "host hostname", POPminc (-4) },
97 #define USERSW                     8
98     { "user username", POPminc (-4) },
99 #define PACKSW                     9
100     { "pack file", POPminc (-4) },
101 #define NPACKSW                   10
102     { "nopack", POPminc (-6) },
103 #define APOPSW                    11
104     { "apop", APOPminc (-4) },
105 #define NAPOPSW                   12
106     { "noapop", APOPminc (-6) },
107 #define RPOPSW                    13
108     { "rpop", RPOPminc (-4) },
109 #define NRPOPSW                   14
110     { "norpop", RPOPminc (-6) },
111 #define SILSW                     15
112     { "silent", 0 },
113 #define NSILSW                    16
114     { "nosilent", 0 },
115 #define TRNCSW                    17
116     { "truncate", 0 },
117 #define NTRNCSW                   18
118     { "notruncate", 0 },
119 #define WIDTHSW                   19
120     { "width columns", 0 },
121 #define VERSIONSW                 20
122     { "version", 0 },
123 #define HELPSW                    21
124     { "help", 0 },
125 #define SNOOPSW                   22
126     { "snoop", -5 },
127 #define KPOPSW                    23
128     { "kpop", KPOPminc (-4) },
129 #define SASLSW                    24
130     { "sasl", SASLminc(-4) },
131 #define SASLMECHSW                25
132     { "saslmech", SASLminc(-8) },
133 #define PROXYSW                   26
134     { "proxy command", POPminc(-5) },
135     { NULL, 0 }
136 };
137
138 /*
139  * flags for the mail source
140  */
141 #define INC_FILE  0
142 #define INC_POP   1
143
144 static int inc_type;
145 static int snoop = 0;
146
147 #ifdef POP
148 extern char response[];
149
150 static char *packfile = NULL;
151 static int size;
152 static long pos;
153 static long start;
154 static long stop;
155
156 static int mbx_style = MMDF_FORMAT;
157 static int pd = NOTOK;
158 static FILE *pf = NULL;
159 #endif /* POP */
160
161 /* This is an attempt to simplify things by putting all the
162  * privilege ops into macros.
163  * *GROUPPRIVS() is related to handling the setgid MAIL property,
164  * and only applies if MAILGROUP is defined.
165  * *USERPRIVS() is related to handling the setuid root property,
166  * and only applies if POP is defined [why does POP => setuid root?]
167  * Basically, SAVEGROUPPRIVS() is called right at the top of main()
168  * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
169  * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
170  * before DROPUSERPRIVS() is called [this is needed because setgid()
171  * sets both effective and real uids if euid is root.]
172  *
173  * There's probably a better implementation if we're allowed to use
174  * BSD-style setreuid() rather than using POSIX saved-ids.
175  * Anyway, if you're euid root it's a bit pointless to drop the group
176  * permissions...
177  *
178  * I'm pretty happy that the security is good provided we aren't setuid root.
179  * The only things we trust with group=mail privilege are lkfopen()
180  * and lkfclose().
181  */
182
183 /*
184  * For setting and returning to "mail" gid
185  */
186 #ifdef MAILGROUP
187 static int return_gid;
188 #ifndef POP
189 /* easy case; we're not setuid root, so can drop group privs
190  * immediately.
191  */
192 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
193 #else /* POP ie we are setuid root */
194 #define TRYDROPGROUPPRIVS() \
195 if (geteuid() != 0) DROPGROUPPRIVS()
196 #endif
197 #define DROPGROUPPRIVS() setgid(getgid())
198 #define GETGROUPPRIVS() setgid(return_gid)
199 #define SAVEGROUPPRIVS() return_gid = getegid()
200 #else
201 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
202 #define TRYDROPGROUPPRIVS()
203 #define DROPGROUPPRIVS()
204 #define GETGROUPPRIVS()
205 #define SAVEGROUPPRIVS()
206 #endif /* not MAILGROUP */
207
208 #ifdef POP
209 #define DROPUSERPRIVS() setuid(getuid())
210 #else
211 #define DROPUSERPRIVS()
212 #endif
213
214 /* these variables have to be globals so that done() can correctly clean up the lockfile */
215 static int locked = 0;
216 static char *newmail;
217 static FILE *in;
218
219 /*
220  * prototypes
221  */
222 char *map_name(char *);
223
224 static void inc_done(int) NORETURN;
225 #ifdef POP
226 static int pop_action(char *);
227 static int pop_pack(char *);
228 static int map_count(void);
229 #endif
230
231
232 int
233 main (int argc, char **argv)
234 {
235     int chgflag = 1, trnflag = 1;
236     int noisy = 1, width = 0;
237     int rpop, i, hghnum = 0, msgnum = 0;
238     int kpop = 0, sasl = 0;
239     char *cp, *maildir = NULL, *folder = NULL;
240     char *format = NULL, *form = NULL;
241     char *host = NULL, *user = NULL, *proxy = NULL;
242     char *audfile = NULL, *from = NULL, *saslmech = NULL;
243     char buf[BUFSIZ], **argp, *nfs, **arguments;
244     struct msgs *mp = NULL;
245     struct stat st, s1;
246     FILE *aud = NULL;
247     char b[MAXPATHLEN + 1];
248     char *maildir_copy = NULL;  /* copy of mail directory because the static gets overwritten */
249
250 #ifdef POP
251     int nmsgs, nbytes, p = 0;
252     char *pass = NULL;
253     char *MAILHOST_env_variable;
254 #endif
255
256 #ifdef MHE
257     FILE *mhe = NULL;
258 #endif
259
260 #ifdef HESIOD
261     struct hes_postoffice *po;
262 #endif
263
264     done=inc_done;
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 = pluspath (cp);
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 (NULL, "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 (!folder_exists(maildir)) {
567         /* If the folder doesn't exist, and we're given the -silent flag,
568          * just fail.
569          */
570         if (noisy)
571             create_folder(maildir, 0, done);
572         else
573             done (1);
574     }
575
576     if (chdir (maildir) == NOTOK)
577         adios (maildir, "unable to change directory to");
578
579     /* read folder and create message structure */
580     if (!(mp = folder_read (folder)))
581         adios (NULL, "unable to read folder %s", folder);
582
583 #ifdef POP
584 go_to_it:
585 #endif /* POP */
586
587     if (inc_type == INC_FILE) {
588         if (access (newmail, W_OK) != NOTOK) {
589             locked++;
590             if (trnflag) {
591                 SIGNAL (SIGHUP, SIG_IGN);
592                 SIGNAL (SIGINT, SIG_IGN);
593                 SIGNAL (SIGQUIT, SIG_IGN);
594                 SIGNAL (SIGTERM, SIG_IGN);
595             }
596
597             GETGROUPPRIVS();       /* Reset gid to lock mail file */
598             in = lkfopen (newmail, "r");
599             DROPGROUPPRIVS();
600             if (in == NULL)
601                 adios (NULL, "unable to lock and fopen %s", newmail);
602             fstat (fileno(in), &s1);
603         } else {
604             trnflag = 0;
605             if ((in = fopen (newmail, "r")) == NULL)
606                 adios (newmail, "unable to read");
607         }
608     }
609
610     /* This shouldn't be necessary but it can't hurt. */
611     DROPGROUPPRIVS();
612
613     if (audfile) {
614         if ((i = stat (audfile, &st)) == NOTOK)
615             advise (NULL, "Creating Receive-Audit: %s", audfile);
616         if ((aud = fopen (audfile, "a")) == NULL)
617             adios (audfile, "unable to append to");
618         else if (i == NOTOK)
619             chmod (audfile, m_gmprot ());
620
621 #ifdef POP
622         fprintf (aud, from ? "<<inc>> %s -ms %s\n"
623                  : host ? "<<inc>> %s -host %s -user %s%s\n"
624                  : "<<inc>> %s\n",
625                  dtimenow (0), from ? from : host, user,
626                  rpop < 0 ? " -apop" : rpop > 0 ? " -rpop" : "");
627 #else /* POP */
628         fprintf (aud, from ? "<<inc>> %s  -ms %s\n" : "<<inc>> %s\n",
629                  dtimenow (0), from);
630 #endif /* POP */
631     }
632
633 #ifdef MHE
634     if (context_find ("mhe")) {
635         cp = concat (maildir, "/++", NULL);
636         i = stat (cp, &st);
637         if ((mhe = fopen (cp, "a")) == NULL)
638             admonish (cp, "unable to append to");
639         else
640             if (i == NOTOK)
641                 chmod (cp, m_gmprot ());
642         free (cp);
643     }
644 #endif /* MHE */
645
646     /* Get new format string */
647     nfs = new_fs (form, format, FORMAT);
648
649     if (noisy) {
650         printf ("Incorporating new mail into %s...\n\n", folder);
651         fflush (stdout);
652     }
653
654 #ifdef POP
655     /*
656      * Get the mail from a POP server
657      */
658     if (inc_type == INC_POP) {
659         if (packfile) {
660             packfile = path (packfile, TFILE);
661             if (stat (packfile, &st) == NOTOK) {
662                 if (errno != ENOENT)
663                     adios (packfile, "error on file");
664                 cp = concat ("Create file \"", packfile, "\"? ", NULL);
665                 if (noisy && !getanswer (cp))
666                     done (1);
667                 free (cp);
668             }
669             msgnum = map_count ();
670             if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
671                 == NOTOK)
672                 adios (packfile, "unable to open");
673             if ((pf = fdopen (pd, "w+")) == NULL)
674                 adios (NULL, "unable to fdopen %s", packfile);
675         } else {
676             hghnum = msgnum = mp->hghmsg;
677             /*
678              * Check if we have enough message space for all the new
679              * messages.  If not, then realloc the folder and add enough
680              * space for all new messages plus 10 additional slots.
681              */
682             if (mp->hghmsg + nmsgs >= mp->hghoff
683                 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
684                 adios (NULL, "unable to allocate folder storage");
685         }
686
687         for (i = 1; i <= nmsgs; i++) {
688             msgnum++;
689             if (packfile) {
690                 fseek (pf, 0L, SEEK_CUR);
691                 pos = ftell (pf);
692                 size = 0;
693                 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
694                 start = ftell (pf);
695
696                 if (pop_retr (i, pop_pack) == NOTOK)
697                     adios (NULL, "%s", response);
698
699                 fseek (pf, 0L, SEEK_CUR);
700                 stop = ftell (pf);
701                 if (fflush (pf))
702                     adios (packfile, "write error on");
703                 fseek (pf, start, SEEK_SET);
704             } else {
705                 cp = getcpy (m_name (msgnum));
706                 if ((pf = fopen (cp, "w+")) == NULL)
707                     adios (cp, "unable to write");
708                 chmod (cp, m_gmprot ());
709                 start = stop = 0L;
710
711                 if (pop_retr (i, pop_action) == NOTOK)
712                     adios (NULL, "%s", response);
713
714                 if (fflush (pf))
715                     adios (cp, "write error on");
716                 fseek (pf, 0L, SEEK_SET);
717             }
718             switch (p = scan (pf, msgnum, 0, nfs, width,
719                               packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
720                               1, NULL, stop - start, noisy)) {
721             case SCNEOF: 
722                 printf ("%*d  empty\n", DMAXFOLDER, msgnum);
723                 break;
724
725             case SCNFAT:
726                 trnflag = 0;
727                 noisy++;
728                 /* advise (cp, "unable to read"); already advised */
729                 /* fall thru */
730
731             case SCNERR:
732             case SCNNUM: 
733                 break;
734
735             case SCNMSG: 
736             case SCNENC:
737             default: 
738                 if (aud)
739                     fputs (scanl, aud);
740 # ifdef MHE
741                 if (mhe)
742                     fputs (scanl, mhe);
743 # endif /* MHE */
744                 if (noisy)
745                     fflush (stdout);
746                 if (!packfile) {
747                     clear_msg_flags (mp, msgnum);
748                     set_exists (mp, msgnum);
749                     set_unseen (mp, msgnum);
750                     mp->msgflags |= SEQMOD;
751                 }
752                 break;
753             }
754             if (packfile) {
755                 fseek (pf, stop, SEEK_SET);
756                 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
757                 if (fflush (pf) || ferror (pf)) {
758                     int e = errno;
759                     pop_quit ();
760                     errno = e;
761                     adios (packfile, "write error on");
762                 }
763                 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
764             } else {
765                 if (ferror(pf) || fclose (pf)) {
766                     int e = errno;
767                     unlink (cp);
768                     pop_quit ();
769                     errno = e;
770                     adios (cp, "write error on");
771                 }
772                 free (cp);
773             }
774
775             if (trnflag && pop_dele (i) == NOTOK)
776                 adios (NULL, "%s", response);
777         }
778
779         if (pop_quit () == NOTOK)
780             adios (NULL, "%s", response);
781         if (packfile) {
782             mbx_close (packfile, pd);
783             pd = NOTOK;
784         }
785     }
786 #endif /* POP */
787
788     /*
789      * Get the mail from file (usually mail spool)
790      */
791     if (inc_type == INC_FILE) {
792         m_unknown (in);         /* the MAGIC invocation... */
793         hghnum = msgnum = mp->hghmsg;
794         for (i = 0;;) {
795             /*
796              * Check if we need to allocate more space for message status.
797              * If so, then add space for an additional 100 messages.
798              */
799             if (msgnum >= mp->hghoff
800                 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
801                 advise (NULL, "unable to allocate folder storage");
802                 i = NOTOK;
803                 break;
804             }
805
806 #if 0
807             /* copy file from spool to tmp file */
808             tmpfilenam = m_scratch ("", invo_name);
809             if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
810                 adios (tmpfilenam, "unable to create");
811             chmod (tmpfilenam, m_gmprot ());
812             if (!(in2 = fdopen (fd, "r+")))
813                 adios (tmpfilenam, "unable to access");
814             cpymsg (in, in2);
815
816             /* link message into folder */
817             newmsg = folder_addmsg(mp, tmpfilenam);
818 #endif
819             /* create scanline for new message */
820             switch (i = scan (in, msgnum + 1, msgnum + 1, nfs, width,
821                               msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
822             case SCNFAT:
823             case SCNEOF: 
824                 break;
825
826             case SCNERR:
827                 if (aud)
828                     fputs ("inc aborted!\n", aud);
829                 advise (NULL, "aborted!");      /* doesn't clean up locks! */
830                 break;
831
832             case SCNNUM: 
833                 advise (NULL, "BUG in %s, number out of range", invo_name);
834                 break;
835
836             default: 
837                 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, i);
838                 break;
839
840             case SCNMSG:
841             case SCNENC:
842                 /*
843                  *  Run the external program hook on the message.
844                  */
845
846                 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
847                 (void)ext_hook("add-hook", b, (char *)0);
848
849                 if (aud)
850                     fputs (scanl, aud);
851 #ifdef MHE
852                 if (mhe)
853                     fputs (scanl, mhe);
854 #endif /* MHE */
855                 if (noisy)
856                     fflush (stdout);
857
858                 msgnum++;
859                 mp->hghmsg++;
860                 mp->nummsg++;
861                 if (mp->lowmsg == 0) mp->lowmsg = 1;
862
863                 clear_msg_flags (mp, msgnum);
864                 set_exists (mp, msgnum);
865                 set_unseen (mp, msgnum);
866                 mp->msgflags |= SEQMOD;
867                 continue;
868             }
869             break;
870         }
871     }
872
873 #ifdef POP
874     if (p < 0) {                /* error */
875 #else
876     if (i < 0) {                /* error */
877 #endif
878         if (locked) {
879             GETGROUPPRIVS();      /* Be sure we can unlock mail file */
880             (void) lkfclose (in, newmail); in = NULL;
881             DROPGROUPPRIVS();    /* And then return us to normal privileges */
882         } else {
883             fclose (in); in = NULL;
884         }
885         adios (NULL, "failed");
886     }
887
888     if (aud)
889         fclose (aud);
890
891 #ifdef MHE
892     if (mhe)
893         fclose (mhe);
894 #endif /* MHE */
895
896     if (noisy)
897         fflush (stdout);
898
899 #ifdef POP
900     if ((inc_type == INC_POP) && packfile)
901         done (0);
902 #endif /* POP */
903
904     /*
905      * truncate file we are incorporating from
906      */
907     if (inc_type == INC_FILE) {
908         if (trnflag) {
909             if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
910                 advise (NULL, "new messages have arrived!\007");
911             else {
912                 if ((i = creat (newmail, 0600)) != NOTOK)
913                     close (i);
914                 else
915                     admonish (newmail, "error zero'ing");
916                 unlink(map_name(newmail));
917             }
918         } else {
919             if (noisy)
920                 printf ("%s not zero'd\n", newmail);
921         }
922     }
923
924     if (msgnum == hghnum) {
925         admonish (NULL, "no messages incorporated");
926     } else {
927         context_replace (pfolder, folder);      /* update current folder */
928         if (chgflag)
929             mp->curmsg = hghnum + 1;
930         mp->hghmsg = msgnum;
931         if (mp->lowmsg == 0)
932             mp->lowmsg = 1;
933         if (chgflag)            /* sigh... */
934             seq_setcur (mp, mp->curmsg);
935     }
936
937     /*
938      * unlock the mail spool
939      */
940     if (inc_type == INC_FILE) {
941         if (locked) {
942            GETGROUPPRIVS();        /* Be sure we can unlock mail file */
943            (void) lkfclose (in, newmail); in = NULL;
944            DROPGROUPPRIVS();       /* And then return us to normal privileges */
945         } else {
946             fclose (in); in = NULL;
947         }
948     }
949
950     seq_setunseen (mp, 0);      /* set the Unseen-Sequence */
951     seq_save (mp);              /* synchronize sequences   */
952     context_save ();            /* save the context file   */
953     done (0);
954     return 1;
955 }
956
957
958 #if 0
959
960 /*
961  * Copy message message from spool into
962  * temporary file.  Massage the "From " line
963  * while copying.
964  */
965
966 cpymsg (FILE *in, FILE *out)
967 {
968     int state;
969     char *tmpbuf, name[NAMESZ];
970
971     for (;;) {
972         state = m_getfld (state, name, tmpbuf, rlwidth, in);
973         switch (state) {
974         case FLD:
975         case FLDPLUS:
976             break;
977         case BODY:
978             break;
979         case LENERR:
980         case FMTERR:
981             break;
982         case FILEEOF:
983             break;
984         default:
985         }
986     }
987 }
988 #endif /* if 0 */
989
990
991 static void
992 inc_done (int status)
993 {
994 #ifdef POP
995     if (packfile && pd != NOTOK)
996         mbx_close (packfile, pd);
997 #endif /* POP */
998     if (locked)
999     {
1000         GETGROUPPRIVS();
1001         lkfclose(in, newmail);
1002         DROPGROUPPRIVS();
1003     }
1004     exit (status);
1005 }
1006
1007 #ifdef POP
1008 static int
1009 pop_action (char *s)
1010 {
1011     fprintf (pf, "%s\n", s);
1012     stop += strlen (s) + 1;
1013     return 0;  /* Is return value used?  This was missing before 1999-07-15. */
1014 }
1015
1016 static int
1017 pop_pack (char *s)
1018 {
1019     int j;
1020     char buffer[BUFSIZ];
1021
1022     snprintf (buffer, sizeof(buffer), "%s\n", s);
1023     for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1024         continue;
1025     for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1026         continue;
1027     fputs (buffer, pf);
1028     size += strlen (buffer) + 1;
1029     return 0;  /* Is return value used?  This was missing before 1999-07-15. */
1030 }
1031
1032 static int
1033 map_count (void)
1034 {
1035     int md;
1036     char *cp;
1037     struct drop d;
1038     struct stat st;
1039
1040     if (stat (packfile, &st) == NOTOK)
1041         return 0;
1042     if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1043             || map_chk (cp, md, &d, (long) st.st_size, 1)) {
1044         if (md != NOTOK)
1045             close (md);
1046         return 0;
1047     }
1048     close (md);
1049     return (d.d_id);
1050 }
1051 #endif /* POP */