3 * inc.c -- incorporate messages from a maildrop into a folder
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.
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.
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.
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
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
35 # include <h/dropsbr.h>
36 # include <h/popsbr.h>
43 #include <h/fmt_scan.h>
44 #include <h/scansbr.h>
45 #include <h/signals.h>
52 # define POPminc(a) (a)
58 # define RPOPminc(a) (a)
60 # define RPOPminc(a) 0
64 # define APOPminc(a) (a)
66 # define APOPminc(a) 0
70 # define KPOPminc(a) (a)
72 # define KPOPminc(a) 0
76 # define SASLminc(a) (a)
78 # define SASLminc(a) 0
81 static struct swit switches[] = {
83 { "audit audit-file", 0 },
93 { "form formatfile", 0 },
95 { "format string", 5 },
97 { "host hostname", POPminc (-4) },
99 { "user username", POPminc (-4) },
101 { "pack file", POPminc (-4) },
103 { "nopack", POPminc (-6) },
105 { "apop", APOPminc (-4) },
107 { "noapop", APOPminc (-6) },
109 { "rpop", RPOPminc (-4) },
111 { "norpop", RPOPminc (-6) },
121 { "width columns", 0 },
129 { "kpop", KPOPminc (-4) },
131 { "sasl", SASLminc(-4) },
132 #define SASLMECHSW 25
133 { "saslmech", SASLminc(-8) },
138 * flags for the mail source
144 static int snoop = 0;
147 extern char response[];
149 static char *packfile = NULL;
155 static int mbx_style = MMDF_FORMAT;
156 static int pd = NOTOK;
157 static FILE *pf = NULL;
160 /* This is an attempt to simplify things by putting all the
161 * privilege ops into macros.
162 * *GROUPPRIVS() is related to handling the setgid MAIL property,
163 * and only applies if MAILGROUP is defined.
164 * *USERPRIVS() is related to handling the setuid root property,
165 * and only applies if POP is defined [why does POP => setuid root?]
166 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
167 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
168 * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
169 * before DROPUSERPRIVS() is called [this is needed because setgid()
170 * sets both effective and real uids if euid is root.]
172 * There's probably a better implementation if we're allowed to use
173 * BSD-style setreuid() rather than using POSIX saved-ids.
174 * Anyway, if you're euid root it's a bit pointless to drop the group
177 * I'm pretty happy that the security is good provided we aren't setuid root.
178 * The only things we trust with group=mail privilege are lkfopen()
183 * For setting and returning to "mail" gid
186 static int return_gid;
188 /* easy case; we're not setuid root, so can drop group privs
191 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
192 #else /* POP ie we are setuid root */
193 #define TRYDROPGROUPPRIVS() \
194 if (geteuid() != 0) DROPGROUPPRIVS()
196 #define DROPGROUPPRIVS() setgid(getgid())
197 #define GETGROUPPRIVS() setgid(return_gid)
198 #define SAVEGROUPPRIVS() return_gid = getegid()
200 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
201 #define TRYDROPGROUPPRIVS()
202 #define DROPGROUPPRIVS()
203 #define GETGROUPPRIVS()
204 #define SAVEGROUPPRIVS()
205 #endif /* not MAILGROUP */
208 #define DROPUSERPRIVS() setuid(getuid())
210 #define DROPUSERPRIVS()
213 /* these variables have to be globals so that done() can correctly clean up the lockfile */
214 static int locked = 0;
215 static char *newmail;
221 char *map_name(char *);
225 static int pop_action(char *);
226 static int pop_pack(char *);
227 static int map_count(void);
232 main (int argc, char **argv)
234 int chgflag = 1, trnflag = 1;
235 int noisy = 1, width = 0;
236 int rpop, i, hghnum, msgnum;
237 int kpop = 0, sasl = 0;
238 char *cp, *maildir, *folder = NULL;
239 char *format = NULL, *form = NULL;
240 char *host = NULL, *user = NULL;
241 char *audfile = NULL, *from = NULL, *saslmech = NULL;
242 char buf[BUFSIZ], **argp, *nfs, **arguments;
246 char b[MAXPATHLEN + 1];
247 char *maildir_copy; /* copy of mail directory because the static gets overwritten */
250 int nmsgs, nbytes, p = 0;
252 char *MAILHOST_env_variable;
260 struct hes_postoffice *po;
263 /* absolutely the first thing we do is save our privileges,
264 * and drop them if we can.
270 setlocale(LC_ALL, "");
272 invo_name = r1bindex (argv[0], '/');
274 /* read user profile/context */
277 mts_init (invo_name);
278 arguments = getarguments (invo_name, argc, argv, 1);
284 * use MAILHOST environment variable if present,
286 * If that fails, use the default (if any)
287 * provided by mts.conf in mts_init()
289 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
290 pophost = MAILHOST_env_variable;
292 else if ((po = hes_getmailhost(getusername())) != NULL &&
293 strcmp(po->po_type, "POP") == 0)
294 pophost = po->po_host;
297 * If there is a valid "pophost" entry in mts.conf,
298 * then use it as the default host.
300 if (pophost && *pophost)
303 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
309 while ((cp = *argp++)) {
311 switch (smatch (++cp, switches)) {
313 ambigsw (cp, switches);
316 adios (NULL, "-%s unknown", cp);
319 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
320 print_help (buf, switches, 1);
323 print_version(invo_name);
327 if (!(cp = *argp++) || *cp == '-')
328 adios (NULL, "missing argument to %s", argp[-2]);
329 audfile = getcpy (m_maildir (cp));
343 * The flag `trnflag' has the value:
345 * 2 if -truncate is given
346 * 1 by default (truncating is default)
347 * 0 if -notruncate is given
357 if (!(cp = *argp++) || *cp == '-')
358 adios (NULL, "missing argument to %s", argp[-2]);
359 from = path (cp, TFILE);
362 * If the truncate file is in default state,
363 * change to not truncate.
377 if (!(form = *argp++) || *form == '-')
378 adios (NULL, "missing argument to %s", argp[-2]);
382 if (!(format = *argp++) || *format == '-')
383 adios (NULL, "missing argument to %s", argp[-2]);
388 if (!(cp = *argp++) || *cp == '-')
389 adios (NULL, "missing argument to %s", argp[-2]);
394 if (!(host = *argp++) || *host == '-')
395 adios (NULL, "missing argument to %s", argp[-2]);
398 if (!(user = *argp++) || *user == '-')
399 adios (NULL, "missing argument to %s", argp[-2]);
404 if (!(cp = *argp++) || *cp == '-')
405 adios (NULL, "missing argument to %s", argp[-2]);
407 if (!(packfile = *argp++) || *packfile == '-')
408 adios (NULL, "missing argument to %s", argp[-2]);
444 if (!(saslmech = *argp++) || *saslmech == '-')
445 adios (NULL, "missing argument to %s", argp[-2]);
449 if (*cp == '+' || *cp == '@') {
451 adios (NULL, "only one folder at a time!");
453 folder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
455 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
459 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
460 * not DROPGROUPPRIVS().
465 if (from || !host || rpop <= 0)
469 /* guarantee dropping group priveleges; we might not have done so earlier */
473 * Where are we getting the new mail?
486 * Are we getting the mail from
489 if (inc_type == INC_POP) {
491 user = getusername ();
492 if ( strcmp( POPSERVICE, "kpop" ) == 0 ) {
495 if (kpop || sasl || ( rpop > 0))
496 pass = getusername ();
498 ruserpass (host, &user, &pass);
501 * initialize POP connection
503 if (pop_init (host, user, pass, snoop, kpop ? 1 : rpop, kpop,
504 sasl, saslmech) == NOTOK)
505 adios (NULL, "%s", response);
507 /* Check if there are any messages */
508 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
509 adios (NULL, "%s", response);
515 adios (NULL, "no mail to incorporate");
521 * We will get the mail from a file
522 * (typically the standard maildrop)
525 if (inc_type == INC_FILE) {
528 else if ((newmail = getenv ("MAILDROP")) && *newmail)
529 newmail = m_mailpath (newmail);
530 else if ((newmail = context_find ("maildrop")) && *newmail)
531 newmail = m_mailpath (newmail);
533 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
535 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
536 adios (NULL, "no mail to incorporate");
540 /* skip the folder setup */
541 if ((inc_type == INC_POP) && packfile)
545 if (!context_find ("path"))
546 free (path ("./", TFOLDER));
548 folder = getfolder (0);
549 maildir = m_maildir (folder);
551 if ((maildir_copy = strdup(maildir)) == (char *)0)
552 adios (maildir, "error allocating memory to copy maildir");
554 if (stat (maildir, &st) == NOTOK) {
556 adios (maildir, "error on folder");
557 cp = concat ("Create folder \"", maildir, "\"? ", NULL);
558 if (noisy && !getanswer (cp))
561 if (!makedir (maildir))
562 adios (NULL, "unable to create folder %s", maildir);
565 if (chdir (maildir) == NOTOK)
566 adios (maildir, "unable to change directory to");
568 /* read folder and create message structure */
569 if (!(mp = folder_read (folder)))
570 adios (NULL, "unable to read folder %s", folder);
576 if (inc_type == INC_FILE) {
577 if (access (newmail, W_OK) != NOTOK) {
580 SIGNAL (SIGHUP, SIG_IGN);
581 SIGNAL (SIGINT, SIG_IGN);
582 SIGNAL (SIGQUIT, SIG_IGN);
583 SIGNAL (SIGTERM, SIG_IGN);
586 GETGROUPPRIVS(); /* Reset gid to lock mail file */
587 in = lkfopen (newmail, "r");
590 adios (NULL, "unable to lock and fopen %s", newmail);
591 fstat (fileno(in), &s1);
594 if ((in = fopen (newmail, "r")) == NULL)
595 adios (newmail, "unable to read");
599 /* This shouldn't be necessary but it can't hurt. */
603 if ((i = stat (audfile, &st)) == NOTOK)
604 advise (NULL, "Creating Receive-Audit: %s", audfile);
605 if ((aud = fopen (audfile, "a")) == NULL)
606 adios (audfile, "unable to append to");
608 chmod (audfile, m_gmprot ());
611 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
612 : host ? "<<inc>> %s -host %s -user %s%s\n"
614 dtimenow (0), from ? from : host, user,
615 rpop < 0 ? " -apop" : rpop > 0 ? " -rpop" : "");
617 fprintf (aud, from ? "<<inc>> %s -ms %s\n" : "<<inc>> %s\n",
623 if (context_find ("mhe")) {
624 cp = concat (maildir, "/++", NULL);
626 if ((mhe = fopen (cp, "a")) == NULL)
627 admonish (cp, "unable to append to");
630 chmod (cp, m_gmprot ());
635 /* Get new format string */
636 nfs = new_fs (form, format, FORMAT);
639 printf ("Incorporating new mail into %s...\n\n", folder);
645 * Get the mail from a POP server
647 if (inc_type == INC_POP) {
649 packfile = path (packfile, TFILE);
650 if (stat (packfile, &st) == NOTOK) {
652 adios (packfile, "error on file");
653 cp = concat ("Create file \"", packfile, "\"? ", NULL);
654 if (noisy && !getanswer (cp))
658 msgnum = map_count ();
659 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
661 adios (packfile, "unable to open");
662 if ((pf = fdopen (pd, "w+")) == NULL)
663 adios (NULL, "unable to fdopen %s", packfile);
665 hghnum = msgnum = mp->hghmsg;
667 * Check if we have enough message space for all the new
668 * messages. If not, then realloc the folder and add enough
669 * space for all new messages plus 10 additional slots.
671 if (mp->hghmsg + nmsgs >= mp->hghoff
672 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
673 adios (NULL, "unable to allocate folder storage");
676 for (i = 1; i <= nmsgs; i++) {
679 fseek (pf, 0L, SEEK_CUR);
682 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
685 if (pop_retr (i, pop_pack) == NOTOK)
686 adios (NULL, "%s", response);
688 fseek (pf, 0L, SEEK_CUR);
691 adios (packfile, "write error on");
692 fseek (pf, start, SEEK_SET);
694 cp = getcpy (m_name (msgnum));
695 if ((pf = fopen (cp, "w+")) == NULL)
696 adios (cp, "unable to write");
697 chmod (cp, m_gmprot ());
700 if (pop_retr (i, pop_action) == NOTOK)
701 adios (NULL, "%s", response);
704 adios (cp, "write error on");
705 fseek (pf, 0L, SEEK_SET);
707 switch (p = scan (pf, msgnum, 0, nfs, width,
708 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
709 1, NULL, stop - start, noisy)) {
711 printf ("%*d empty\n", DMAXFOLDER, msgnum);
717 /* advise (cp, "unable to read"); already advised */
736 clear_msg_flags (mp, msgnum);
737 set_exists (mp, msgnum);
738 set_unseen (mp, msgnum);
739 mp->msgflags |= SEQMOD;
744 fseek (pf, stop, SEEK_SET);
745 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
746 if (fflush (pf) || ferror (pf)) {
750 adios (packfile, "write error on");
752 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
754 if (ferror(pf) || fclose (pf)) {
759 adios (cp, "write error on");
764 if (trnflag && pop_dele (i) == NOTOK)
765 adios (NULL, "%s", response);
768 if (pop_quit () == NOTOK)
769 adios (NULL, "%s", response);
771 mbx_close (packfile, pd);
778 * Get the mail from file (usually mail spool)
780 if (inc_type == INC_FILE) {
781 m_unknown (in); /* the MAGIC invocation... */
782 hghnum = msgnum = mp->hghmsg;
785 * Check if we need to allocate more space for message status.
786 * If so, then add space for an additional 100 messages.
788 if (msgnum >= mp->hghoff
789 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
790 advise (NULL, "unable to allocate folder storage");
796 /* copy file from spool to tmp file */
797 tmpfilenam = m_scratch ("", invo_name);
798 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
799 adios (tmpfilenam, "unable to create");
800 chmod (tmpfilenam, m_gmprot ());
801 if (!(in2 = fdopen (fd, "r+")))
802 adios (tmpfilenam, "unable to access");
805 /* link message into folder */
806 newmsg = folder_addmsg(mp, tmpfilenam);
808 /* create scanline for new message */
809 switch (i = scan (in, msgnum + 1, msgnum + 1, nfs, width,
810 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
817 fputs ("inc aborted!\n", aud);
818 advise (NULL, "aborted!"); /* doesn't clean up locks! */
822 advise (NULL, "BUG in %s, number out of range", invo_name);
826 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, i);
832 * Run the external program hook on the message.
835 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
836 (void)ext_hook("add-hook", b, (char *)0);
850 if (mp->lowmsg == 0) mp->lowmsg = 1;
852 clear_msg_flags (mp, msgnum);
853 set_exists (mp, msgnum);
854 set_unseen (mp, msgnum);
855 mp->msgflags |= SEQMOD;
863 if (p < 0) { /* error */
865 if (i < 0) { /* error */
868 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
869 (void) lkfclose (in, newmail); in = NULL;
870 DROPGROUPPRIVS(); /* And then return us to normal privileges */
872 fclose (in); in = NULL;
874 adios (NULL, "failed");
889 if ((inc_type == INC_POP) && packfile)
894 * truncate file we are incorporating from
896 if (inc_type == INC_FILE) {
898 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
899 advise (NULL, "new messages have arrived!\007");
901 if ((i = creat (newmail, 0600)) != NOTOK)
904 admonish (newmail, "error zero'ing");
905 unlink(map_name(newmail));
909 printf ("%s not zero'd\n", newmail);
913 if (msgnum == hghnum) {
914 admonish (NULL, "no messages incorporated");
916 context_replace (pfolder, folder); /* update current folder */
918 mp->curmsg = hghnum + 1;
922 if (chgflag) /* sigh... */
923 seq_setcur (mp, mp->curmsg);
927 * unlock the mail spool
929 if (inc_type == INC_FILE) {
931 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
932 (void) lkfclose (in, newmail); in = NULL;
933 DROPGROUPPRIVS(); /* And then return us to normal privileges */
935 fclose (in); in = NULL;
939 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
940 seq_save (mp); /* synchronize sequences */
941 context_save (); /* save the context file */
949 * Copy message message from spool into
950 * temporary file. Massage the "From " line
954 cpymsg (FILE *in, FILE *out)
957 char *tmpbuf, name[NAMESZ];
960 state = m_getfld (state, name, tmpbuf, rlwidth, in);
983 if (packfile && pd != NOTOK)
984 mbx_close (packfile, pd);
989 lkfclose(in, newmail);
993 return 1; /* dead code to satisfy the compiler */
1000 fprintf (pf, "%s\n", s);
1001 stop += strlen (s) + 1;
1002 return 0; /* Is return value used? This was missing before 1999-07-15. */
1009 char buffer[BUFSIZ];
1011 snprintf (buffer, sizeof(buffer), "%s\n", s);
1012 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1014 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1017 size += strlen (buffer) + 1;
1018 return 0; /* Is return value used? This was missing before 1999-07-15. */
1029 if (stat (packfile, &st) == NOTOK)
1031 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1032 || map_chk (cp, md, &d, (long) st.st_size, 1)) {