3 * inc.c -- incorporate messages from a maildrop into a folder
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.
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.
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.
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
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
34 # include <h/dropsbr.h>
35 # include <h/popsbr.h>
38 #include <h/fmt_scan.h>
39 #include <h/scansbr.h>
40 #include <h/signals.h>
47 # define POPminc(a) (a)
53 # define SASLminc(a) (a)
55 # define SASLminc(a) 0
58 static struct swit switches[] = {
60 { "audit audit-file", 0 },
70 { "form formatfile", 0 },
72 { "format string", 5 },
74 { "host hostname", POPminc (-4) },
76 { "user username", POPminc (-4) },
78 { "pack file", POPminc (-4) },
80 { "nopack", POPminc (-6) },
82 { "port name/number", POPminc (-4) },
92 { "width columns", 0 },
100 { "sasl", SASLminc(-4) },
101 #define SASLMECHSW 21
102 { "saslmech", SASLminc(-8) },
104 { "proxy command", POPminc(-5) },
109 * flags for the mail source
115 static int snoop = 0;
118 extern char response[];
120 static char *packfile = NULL;
126 static int mbx_style = MMDF_FORMAT;
127 static int pd = NOTOK;
128 static FILE *pf = NULL;
131 /* This is an attempt to simplify things by putting all the
132 * privilege ops into macros.
133 * *GROUPPRIVS() is related to handling the setgid MAIL property,
134 * and only applies if MAILGROUP is defined.
135 * *USERPRIVS() is related to handling the setuid root property,
136 * and only applies if POP is defined [why does POP => setuid root?]
137 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
138 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
139 * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
140 * before DROPUSERPRIVS() is called [this is needed because setgid()
141 * sets both effective and real uids if euid is root.]
143 * There's probably a better implementation if we're allowed to use
144 * BSD-style setreuid() rather than using POSIX saved-ids.
145 * Anyway, if you're euid root it's a bit pointless to drop the group
148 * I'm pretty happy that the security is good provided we aren't setuid root.
149 * The only things we trust with group=mail privilege are lkfopen()
154 * For setting and returning to "mail" gid
157 static int return_gid;
159 /* easy case; we're not setuid root, so can drop group privs
162 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
163 #else /* POP ie we are setuid root */
164 #define TRYDROPGROUPPRIVS() \
165 if (geteuid() != 0) DROPGROUPPRIVS()
167 #define DROPGROUPPRIVS() setgid(getgid())
168 #define GETGROUPPRIVS() setgid(return_gid)
169 #define SAVEGROUPPRIVS() return_gid = getegid()
171 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
172 #define TRYDROPGROUPPRIVS()
173 #define DROPGROUPPRIVS()
174 #define GETGROUPPRIVS()
175 #define SAVEGROUPPRIVS()
176 #endif /* not MAILGROUP */
178 /* these variables have to be globals so that done() can correctly clean up the lockfile */
179 static int locked = 0;
180 static char *newmail;
186 char *map_name(char *);
188 static void inc_done(int) NORETURN;
190 static int pop_action(char *);
191 static int pop_pack(char *);
192 static int map_count(void);
197 main (int argc, char **argv)
199 int chgflag = 1, trnflag = 1;
200 int noisy = 1, width = 0;
201 int hghnum = 0, msgnum = 0;
203 int incerr = 0; /* <0 if inc hits an error which means it should not truncate mailspool */
204 char *cp, *maildir = NULL, *folder = NULL;
205 char *format = NULL, *form = NULL;
206 char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
207 char *audfile = NULL, *from = NULL, *saslmech = NULL;
208 char buf[BUFSIZ], **argp, *nfs, **arguments;
209 struct msgs *mp = NULL;
212 char b[MAXPATHLEN + 1];
213 char *maildir_copy = NULL; /* copy of mail directory because the static gets overwritten */
218 char *MAILHOST_env_variable;
227 /* absolutely the first thing we do is save our privileges,
228 * and drop them if we can.
234 setlocale(LC_ALL, "");
236 invo_name = r1bindex (argv[0], '/');
238 /* read user profile/context */
241 mts_init (invo_name);
242 arguments = getarguments (invo_name, argc, argv, 1);
248 * use MAILHOST environment variable if present,
250 * If that fails, use the default (if any)
251 * provided by mts.conf in mts_init()
253 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
254 pophost = MAILHOST_env_variable;
256 * If there is a valid "pophost" entry in mts.conf,
257 * then use it as the default host.
259 if (pophost && *pophost)
262 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
266 while ((cp = *argp++)) {
268 switch (smatch (++cp, switches)) {
270 ambigsw (cp, switches);
273 adios (NULL, "-%s unknown", cp);
276 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
277 print_help (buf, switches, 1);
280 print_version(invo_name);
284 if (!(cp = *argp++) || *cp == '-')
285 adios (NULL, "missing argument to %s", argp[-2]);
286 audfile = getcpy (m_maildir (cp));
300 * The flag `trnflag' has the value:
302 * 2 if -truncate is given
303 * 1 by default (truncating is default)
304 * 0 if -notruncate is given
314 if (!(cp = *argp++) || *cp == '-')
315 adios (NULL, "missing argument to %s", argp[-2]);
316 from = path (cp, TFILE);
319 * If the truncate file is in default state,
320 * change to not truncate.
334 if (!(form = *argp++) || *form == '-')
335 adios (NULL, "missing argument to %s", argp[-2]);
339 if (!(format = *argp++) || *format == '-')
340 adios (NULL, "missing argument to %s", argp[-2]);
345 if (!(cp = *argp++) || *cp == '-')
346 adios (NULL, "missing argument to %s", argp[-2]);
351 if (!(host = *argp++) || *host == '-')
352 adios (NULL, "missing argument to %s", argp[-2]);
356 if (!(host = *argp++) || *port == '-')
357 adios (NULL, "missing argument to %s", argp[-2]);
361 if (!(user = *argp++) || *user == '-')
362 adios (NULL, "missing argument to %s", argp[-2]);
367 if (!(cp = *argp++) || *cp == '-')
368 adios (NULL, "missing argument to %s", argp[-2]);
370 if (!(packfile = *argp++) || *packfile == '-')
371 adios (NULL, "missing argument to %s", argp[-2]);
389 if (!(saslmech = *argp++) || *saslmech == '-')
390 adios (NULL, "missing argument to %s", argp[-2]);
393 if (!(proxy = *argp++) || *proxy == '-')
394 adios (NULL, "missing argument to %s", argp[-2]);
398 if (*cp == '+' || *cp == '@') {
400 adios (NULL, "only one folder at a time!");
402 folder = pluspath (cp);
404 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
408 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
409 * not DROPGROUPPRIVS().
416 /* guarantee dropping group priveleges; we might not have done so earlier */
420 * Where are we getting the new mail?
433 * Are we getting the mail from
436 if (inc_type == INC_POP) {
438 user = getusername ();
440 pass = getusername ();
442 ruserpass (host, &user, &pass);
445 * initialize POP connection
447 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
449 adios (NULL, "%s", response);
451 /* Check if there are any messages */
452 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
453 adios (NULL, "%s", response);
457 adios (NULL, "no mail to incorporate");
463 * We will get the mail from a file
464 * (typically the standard maildrop)
467 if (inc_type == INC_FILE) {
470 else if ((newmail = getenv ("MAILDROP")) && *newmail)
471 newmail = m_mailpath (newmail);
472 else if ((newmail = context_find ("maildrop")) && *newmail)
473 newmail = m_mailpath (newmail);
475 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
477 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
478 adios (NULL, "no mail to incorporate");
480 if ((cp = strdup(newmail)) == (char *)0)
481 adios (NULL, "error allocating memory to copy newmail");
487 /* skip the folder setup */
488 if ((inc_type == INC_POP) && packfile)
492 if (!context_find ("path"))
493 free (path ("./", TFOLDER));
495 folder = getfolder (0);
496 maildir = m_maildir (folder);
498 if ((maildir_copy = strdup(maildir)) == (char *)0)
499 adios (maildir, "error allocating memory to copy maildir");
501 if (!folder_exists(maildir)) {
502 /* If the folder doesn't exist, and we're given the -silent flag,
506 create_folder(maildir, 0, done);
511 if (chdir (maildir) == NOTOK)
512 adios (maildir, "unable to change directory to");
514 /* read folder and create message structure */
515 if (!(mp = folder_read (folder)))
516 adios (NULL, "unable to read folder %s", folder);
522 if (inc_type == INC_FILE) {
523 if (access (newmail, W_OK) != NOTOK) {
526 SIGNAL (SIGHUP, SIG_IGN);
527 SIGNAL (SIGINT, SIG_IGN);
528 SIGNAL (SIGQUIT, SIG_IGN);
529 SIGNAL (SIGTERM, SIG_IGN);
532 GETGROUPPRIVS(); /* Reset gid to lock mail file */
533 in = lkfopen (newmail, "r");
536 adios (NULL, "unable to lock and fopen %s", newmail);
537 fstat (fileno(in), &s1);
540 if ((in = fopen (newmail, "r")) == NULL)
541 adios (newmail, "unable to read");
545 /* This shouldn't be necessary but it can't hurt. */
550 if ((i = stat (audfile, &st)) == NOTOK)
551 advise (NULL, "Creating Receive-Audit: %s", audfile);
552 if ((aud = fopen (audfile, "a")) == NULL)
553 adios (audfile, "unable to append to");
555 chmod (audfile, m_gmprot ());
558 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
559 : host ? "<<inc>> %s -host %s -user %s\n"
561 dtimenow (0), from ? from : host, user);
563 fprintf (aud, from ? "<<inc>> %s -ms %s\n" : "<<inc>> %s\n",
569 if (context_find ("mhe")) {
571 cp = concat (maildir, "/++", NULL);
573 if ((mhe = fopen (cp, "a")) == NULL)
574 admonish (cp, "unable to append to");
577 chmod (cp, m_gmprot ());
582 /* Get new format string */
583 nfs = new_fs (form, format, FORMAT);
586 printf ("Incorporating new mail into %s...\n\n", folder);
592 * Get the mail from a POP server
594 if (inc_type == INC_POP) {
597 packfile = path (packfile, TFILE);
598 if (stat (packfile, &st) == NOTOK) {
600 adios (packfile, "error on file");
601 cp = concat ("Create file \"", packfile, "\"? ", NULL);
602 if (noisy && !getanswer (cp))
606 msgnum = map_count ();
607 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
609 adios (packfile, "unable to open");
610 if ((pf = fdopen (pd, "w+")) == NULL)
611 adios (NULL, "unable to fdopen %s", packfile);
613 hghnum = msgnum = mp->hghmsg;
615 * Check if we have enough message space for all the new
616 * messages. If not, then realloc the folder and add enough
617 * space for all new messages plus 10 additional slots.
619 if (mp->hghmsg + nmsgs >= mp->hghoff
620 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
621 adios (NULL, "unable to allocate folder storage");
624 for (i = 1; i <= nmsgs; i++) {
627 fseek (pf, 0L, SEEK_CUR);
630 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
633 if (pop_retr (i, pop_pack) == NOTOK)
634 adios (NULL, "%s", response);
636 fseek (pf, 0L, SEEK_CUR);
639 adios (packfile, "write error on");
640 fseek (pf, start, SEEK_SET);
642 cp = getcpy (m_name (msgnum));
643 if ((pf = fopen (cp, "w+")) == NULL)
644 adios (cp, "unable to write");
645 chmod (cp, m_gmprot ());
648 if (pop_retr (i, pop_action) == NOTOK)
649 adios (NULL, "%s", response);
652 adios (cp, "write error on");
653 fseek (pf, 0L, SEEK_SET);
655 switch (incerr = scan (pf, msgnum, 0, nfs, width,
656 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
657 1, NULL, stop - start, noisy)) {
659 printf ("%*d empty\n", DMAXFOLDER, msgnum);
665 /* advise (cp, "unable to read"); already advised */
684 clear_msg_flags (mp, msgnum);
685 set_exists (mp, msgnum);
686 set_unseen (mp, msgnum);
687 mp->msgflags |= SEQMOD;
692 fseek (pf, stop, SEEK_SET);
693 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
694 if (fflush (pf) || ferror (pf)) {
698 adios (packfile, "write error on");
700 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
702 if (ferror(pf) || fclose (pf)) {
707 adios (cp, "write error on");
712 if (trnflag && pop_dele (i) == NOTOK)
713 adios (NULL, "%s", response);
716 if (pop_quit () == NOTOK)
717 adios (NULL, "%s", response);
719 mbx_close (packfile, pd);
726 * Get the mail from file (usually mail spool)
728 if (inc_type == INC_FILE) {
729 m_unknown (in); /* the MAGIC invocation... */
730 hghnum = msgnum = mp->hghmsg;
733 * Check if we need to allocate more space for message status.
734 * If so, then add space for an additional 100 messages.
736 if (msgnum >= mp->hghoff
737 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
738 advise (NULL, "unable to allocate folder storage");
744 /* copy file from spool to tmp file */
745 tmpfilenam = m_scratch ("", invo_name);
746 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
747 adios (tmpfilenam, "unable to create");
748 chmod (tmpfilenam, m_gmprot ());
749 if (!(in2 = fdopen (fd, "r+")))
750 adios (tmpfilenam, "unable to access");
753 /* link message into folder */
754 newmsg = folder_addmsg(mp, tmpfilenam);
756 /* create scanline for new message */
757 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
758 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
765 fputs ("inc aborted!\n", aud);
766 advise (NULL, "aborted!"); /* doesn't clean up locks! */
770 advise (NULL, "BUG in %s, number out of range", invo_name);
774 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
780 * Run the external program hook on the message.
783 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
784 (void)ext_hook("add-hook", b, (char *)0);
798 if (mp->lowmsg == 0) mp->lowmsg = 1;
800 clear_msg_flags (mp, msgnum);
801 set_exists (mp, msgnum);
802 set_unseen (mp, msgnum);
803 mp->msgflags |= SEQMOD;
806 /* If we get here there was some sort of error from scan(),
807 * so stop processing anything more from the spool.
813 if (incerr < 0) { /* error */
815 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
816 (void) lkfclose (in, newmail); in = NULL;
817 DROPGROUPPRIVS(); /* And then return us to normal privileges */
819 fclose (in); in = NULL;
821 adios (NULL, "failed");
836 if ((inc_type == INC_POP) && packfile)
841 * truncate file we are incorporating from
843 if (inc_type == INC_FILE) {
845 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
846 advise (NULL, "new messages have arrived!\007");
849 if ((newfd = creat (newmail, 0600)) != NOTOK)
852 admonish (newmail, "error zero'ing");
853 unlink(map_name(newmail));
857 printf ("%s not zero'd\n", newmail);
861 if (msgnum == hghnum) {
862 admonish (NULL, "no messages incorporated");
864 context_replace (pfolder, folder); /* update current folder */
866 mp->curmsg = hghnum + 1;
870 if (chgflag) /* sigh... */
871 seq_setcur (mp, mp->curmsg);
875 * unlock the mail spool
877 if (inc_type == INC_FILE) {
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 */
883 fclose (in); in = NULL;
887 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
888 seq_save (mp); /* synchronize sequences */
889 context_save (); /* save the context file */
898 * Copy message message from spool into
899 * temporary file. Massage the "From " line
903 cpymsg (FILE *in, FILE *out)
906 char *tmpbuf, name[NAMESZ];
909 state = m_getfld (state, name, tmpbuf, rlwidth, in);
929 inc_done (int status)
932 if (packfile && pd != NOTOK)
933 mbx_close (packfile, pd);
938 lkfclose(in, newmail);
948 fprintf (pf, "%s\n", s);
949 stop += strlen (s) + 1;
950 return 0; /* Is return value used? This was missing before 1999-07-15. */
959 snprintf (buffer, sizeof(buffer), "%s\n", s);
960 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
962 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
965 size += strlen (buffer) + 1;
966 return 0; /* Is return value used? This was missing before 1999-07-15. */
977 if (stat (packfile, &st) == NOTOK)
979 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
980 || map_chk (cp, md, &d, (long) st.st_size, 1)) {