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 struct Maildir_entry {
119 static int num_maildir_entries = 0;
120 static int snoop = 0;
123 extern char response[];
128 static int mbx_style = MMDF_FORMAT;
129 static int pd = NOTOK;
135 static char *packfile = NULL;
136 static FILE *pf = NULL;
138 /* This is an attempt to simplify things by putting all the
139 * privilege ops into macros.
140 * *GROUPPRIVS() is related to handling the setgid MAIL property,
141 * and only applies if MAILGROUP is defined.
142 * *USERPRIVS() is related to handling the setuid root property,
143 * and only applies if POP is defined [why does POP => setuid root?]
144 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
145 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
146 * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
147 * before DROPUSERPRIVS() is called [this is needed because setgid()
148 * sets both effective and real uids if euid is root.]
150 * There's probably a better implementation if we're allowed to use
151 * BSD-style setreuid() rather than using POSIX saved-ids.
152 * Anyway, if you're euid root it's a bit pointless to drop the group
155 * I'm pretty happy that the security is good provided we aren't setuid root.
156 * The only things we trust with group=mail privilege are lkfopen()
161 * For setting and returning to "mail" gid
164 static int return_gid;
166 /* easy case; we're not setuid root, so can drop group privs
169 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
170 #else /* POP ie we are setuid root */
171 #define TRYDROPGROUPPRIVS() \
172 if (geteuid() != 0) DROPGROUPPRIVS()
174 #define DROPGROUPPRIVS() setgid(getgid())
175 #define GETGROUPPRIVS() setgid(return_gid)
176 #define SAVEGROUPPRIVS() return_gid = getegid()
178 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
179 #define TRYDROPGROUPPRIVS()
180 #define DROPGROUPPRIVS()
181 #define GETGROUPPRIVS()
182 #define SAVEGROUPPRIVS()
183 #endif /* not MAILGROUP */
185 /* these variables have to be globals so that done() can correctly clean up the lockfile */
186 static int locked = 0;
187 static char *newmail;
193 char *map_name(char *);
195 static void inc_done(int) NORETURN;
197 static int pop_action(char *);
198 static int pop_pack(char *);
199 static int map_count(void);
203 maildir_srt(const void *va, const void *vb)
205 const struct Maildir_entry *a = va, *b = vb;
206 if (a->mtime > b->mtime)
208 else if (a->mtime < b->mtime)
215 main (int argc, char **argv)
217 int chgflag = 1, trnflag = 1;
218 int noisy = 1, width = 0;
219 int hghnum = 0, msgnum = 0;
221 int incerr = 0; /* <0 if inc hits an error which means it should not truncate mailspool */
222 char *cp, *maildir = NULL, *folder = NULL;
223 char *format = NULL, *form = NULL;
224 char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
225 char *audfile = NULL, *from = NULL, *saslmech = NULL;
226 char buf[BUFSIZ], **argp, *nfs, **arguments;
227 struct msgs *mp = NULL;
230 char b[MAXPATHLEN + 1];
231 char *maildir_copy = NULL; /* copy of mail directory because the static gets overwritten */
236 char *MAILHOST_env_variable;
241 /* absolutely the first thing we do is save our privileges,
242 * and drop them if we can.
248 setlocale(LC_ALL, "");
250 invo_name = r1bindex (argv[0], '/');
252 /* read user profile/context */
255 mts_init (invo_name);
256 arguments = getarguments (invo_name, argc, argv, 1);
262 * use MAILHOST environment variable if present,
264 * If that fails, use the default (if any)
265 * provided by mts.conf in mts_init()
267 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
268 pophost = MAILHOST_env_variable;
270 * If there is a valid "pophost" entry in mts.conf,
271 * then use it as the default host.
273 if (pophost && *pophost)
276 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
280 while ((cp = *argp++)) {
282 switch (smatch (++cp, switches)) {
284 ambigsw (cp, switches);
287 adios (NULL, "-%s unknown", cp);
290 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
291 print_help (buf, switches, 1);
294 print_version(invo_name);
298 if (!(cp = *argp++) || *cp == '-')
299 adios (NULL, "missing argument to %s", argp[-2]);
300 audfile = getcpy (m_maildir (cp));
314 * The flag `trnflag' has the value:
316 * 2 if -truncate is given
317 * 1 by default (truncating is default)
318 * 0 if -notruncate is given
328 if (!(cp = *argp++) || *cp == '-')
329 adios (NULL, "missing argument to %s", argp[-2]);
330 from = path (cp, TFILE);
333 * If the truncate file is in default state,
334 * change to not truncate.
348 if (!(form = *argp++) || *form == '-')
349 adios (NULL, "missing argument to %s", argp[-2]);
353 if (!(format = *argp++) || *format == '-')
354 adios (NULL, "missing argument to %s", argp[-2]);
359 if (!(cp = *argp++) || *cp == '-')
360 adios (NULL, "missing argument to %s", argp[-2]);
365 if (!(host = *argp++) || *host == '-')
366 adios (NULL, "missing argument to %s", argp[-2]);
370 if (!(host = *argp++) || *port == '-')
371 adios (NULL, "missing argument to %s", argp[-2]);
375 if (!(user = *argp++) || *user == '-')
376 adios (NULL, "missing argument to %s", argp[-2]);
381 if (!(cp = *argp++) || *cp == '-')
382 adios (NULL, "missing argument to %s", argp[-2]);
384 if (!(packfile = *argp++) || *packfile == '-')
385 adios (NULL, "missing argument to %s", argp[-2]);
403 if (!(saslmech = *argp++) || *saslmech == '-')
404 adios (NULL, "missing argument to %s", argp[-2]);
407 if (!(proxy = *argp++) || *proxy == '-')
408 adios (NULL, "missing argument to %s", argp[-2]);
412 if (*cp == '+' || *cp == '@') {
414 adios (NULL, "only one folder at a time!");
416 folder = pluspath (cp);
418 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
422 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
423 * not DROPGROUPPRIVS().
430 /* guarantee dropping group priveleges; we might not have done so earlier */
434 * Where are we getting the new mail?
447 * Are we getting the mail from
450 if (inc_type == INC_POP) {
452 user = getusername ();
454 pass = getusername ();
456 ruserpass (host, &user, &pass);
459 * initialize POP connection
461 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
463 adios (NULL, "%s", response);
465 /* Check if there are any messages */
466 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
467 adios (NULL, "%s", response);
471 adios (NULL, "no mail to incorporate");
477 * We will get the mail from a file
478 * (typically the standard maildrop)
481 if (inc_type == INC_FILE) {
484 else if ((newmail = getenv ("MAILDROP")) && *newmail)
485 newmail = m_mailpath (newmail);
486 else if ((newmail = context_find ("maildrop")) && *newmail)
487 newmail = m_mailpath (newmail);
489 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
491 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
492 adios (NULL, "no mail to incorporate");
493 if (s1.st_mode & S_IFDIR) {
499 cp = concat (newmail, "/new", NULL);
500 if ((md = opendir(cp)) == NULL)
501 adios (NULL, "unable to open %s", cp);
502 while ((de = readdir (md)) != NULL) {
503 if (de->d_name[0] == '.')
505 if (i >= num_maildir_entries) {
506 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
507 adios(NULL, "not enough memory for %d messages", 2*i+16);
508 num_maildir_entries = 2*i+16;
510 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
511 if (stat(Maildir[i].filename, &ms) != 0)
512 adios (Maildir[i].filename, "couldn't get delivery time");
513 Maildir[i].mtime = ms.st_mtime;
518 cp = concat (newmail, "/cur", NULL);
519 if ((md = opendir(cp)) == NULL)
520 adios (NULL, "unable to open %s", cp);
521 while ((de = readdir (md)) != NULL) {
522 if (de->d_name[0] == '.')
524 if (i >= num_maildir_entries) {
525 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
526 adios(NULL, "not enough memory for %d messages", 2*i+16);
527 num_maildir_entries = 2*i+16;
529 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
530 if (stat(Maildir[i].filename, &ms) != 0)
531 adios (Maildir[i].filename, "couldn't get delivery time");
532 Maildir[i].mtime = ms.st_mtime;
538 adios (NULL, "no mail to incorporate");
539 num_maildir_entries = i;
540 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
543 if ((cp = strdup(newmail)) == (char *)0)
544 adios (NULL, "error allocating memory to copy newmail");
550 /* skip the folder setup */
551 if ((inc_type == INC_POP) && packfile)
555 if (!context_find ("path"))
556 free (path ("./", TFOLDER));
558 folder = getfolder (0);
559 maildir = m_maildir (folder);
561 if ((maildir_copy = strdup(maildir)) == (char *)0)
562 adios (maildir, "error allocating memory to copy maildir");
564 if (!folder_exists(maildir)) {
565 /* If the folder doesn't exist, and we're given the -silent flag,
569 create_folder(maildir, 0, done);
574 if (chdir (maildir) == NOTOK)
575 adios (maildir, "unable to change directory to");
577 /* read folder and create message structure */
578 if (!(mp = folder_read (folder)))
579 adios (NULL, "unable to read folder %s", folder);
585 if (inc_type == INC_FILE && Maildir == NULL) {
586 if (access (newmail, W_OK) != NOTOK) {
589 SIGNAL (SIGHUP, SIG_IGN);
590 SIGNAL (SIGINT, SIG_IGN);
591 SIGNAL (SIGQUIT, SIG_IGN);
592 SIGNAL (SIGTERM, SIG_IGN);
595 GETGROUPPRIVS(); /* Reset gid to lock mail file */
596 in = lkfopen (newmail, "r");
599 adios (NULL, "unable to lock and fopen %s", newmail);
600 fstat (fileno(in), &s1);
603 if ((in = fopen (newmail, "r")) == NULL)
604 adios (newmail, "unable to read");
608 /* This shouldn't be necessary but it can't hurt. */
613 if ((i = stat (audfile, &st)) == NOTOK)
614 advise (NULL, "Creating Receive-Audit: %s", audfile);
615 if ((aud = fopen (audfile, "a")) == NULL)
616 adios (audfile, "unable to append to");
618 chmod (audfile, m_gmprot ());
621 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
622 : host ? "<<inc>> %s -host %s -user %s\n"
624 dtimenow (0), from ? from : host, user);
626 fprintf (aud, from ? "<<inc>> %s -ms %s\n" : "<<inc>> %s\n",
631 /* Get new format string */
632 nfs = new_fs (form, format, FORMAT);
635 printf ("Incorporating new mail into %s...\n\n", folder);
641 * Get the mail from a POP server
643 if (inc_type == INC_POP) {
646 packfile = path (packfile, TFILE);
647 if (stat (packfile, &st) == NOTOK) {
649 adios (packfile, "error on file");
650 cp = concat ("Create file \"", packfile, "\"? ", NULL);
651 if (noisy && !getanswer (cp))
655 msgnum = map_count ();
656 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
658 adios (packfile, "unable to open");
659 if ((pf = fdopen (pd, "w+")) == NULL)
660 adios (NULL, "unable to fdopen %s", packfile);
662 hghnum = msgnum = mp->hghmsg;
664 * Check if we have enough message space for all the new
665 * messages. If not, then realloc the folder and add enough
666 * space for all new messages plus 10 additional slots.
668 if (mp->hghmsg + nmsgs >= mp->hghoff
669 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
670 adios (NULL, "unable to allocate folder storage");
673 for (i = 1; i <= nmsgs; i++) {
676 fseek (pf, 0L, SEEK_CUR);
679 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
682 if (pop_retr (i, pop_pack) == NOTOK)
683 adios (NULL, "%s", response);
685 fseek (pf, 0L, SEEK_CUR);
688 adios (packfile, "write error on");
689 fseek (pf, start, SEEK_SET);
691 cp = getcpy (m_name (msgnum));
692 if ((pf = fopen (cp, "w+")) == NULL)
693 adios (cp, "unable to write");
694 chmod (cp, m_gmprot ());
697 if (pop_retr (i, pop_action) == NOTOK)
698 adios (NULL, "%s", response);
701 adios (cp, "write error on");
702 fseek (pf, 0L, SEEK_SET);
704 switch (incerr = scan (pf, msgnum, 0, nfs, width,
705 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
706 1, NULL, stop - start, noisy)) {
708 printf ("%*d empty\n", DMAXFOLDER, msgnum);
714 /* advise (cp, "unable to read"); already advised */
729 clear_msg_flags (mp, msgnum);
730 set_exists (mp, msgnum);
731 set_unseen (mp, msgnum);
732 mp->msgflags |= SEQMOD;
737 fseek (pf, stop, SEEK_SET);
738 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
739 if (fflush (pf) || ferror (pf)) {
743 adios (packfile, "write error on");
745 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
747 if (ferror(pf) || fclose (pf)) {
752 adios (cp, "write error on");
757 if (trnflag && pop_dele (i) == NOTOK)
758 adios (NULL, "%s", response);
761 if (pop_quit () == NOTOK)
762 adios (NULL, "%s", response);
764 mbx_close (packfile, pd);
771 * Get the mail from file (usually mail spool)
773 if (inc_type == INC_FILE && Maildir == NULL) {
774 m_unknown (in); /* the MAGIC invocation... */
775 hghnum = msgnum = mp->hghmsg;
778 * Check if we need to allocate more space for message status.
779 * If so, then add space for an additional 100 messages.
781 if (msgnum >= mp->hghoff
782 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
783 advise (NULL, "unable to allocate folder storage");
789 /* copy file from spool to tmp file */
790 tmpfilenam = m_scratch ("", invo_name);
791 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
792 adios (tmpfilenam, "unable to create");
793 chmod (tmpfilenam, m_gmprot ());
794 if (!(in2 = fdopen (fd, "r+")))
795 adios (tmpfilenam, "unable to access");
798 /* link message into folder */
799 newmsg = folder_addmsg(mp, tmpfilenam);
801 /* create scanline for new message */
802 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
803 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
810 fputs ("inc aborted!\n", aud);
811 advise (NULL, "aborted!"); /* doesn't clean up locks! */
815 advise (NULL, "BUG in %s, number out of range", invo_name);
819 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
825 * Run the external program hook on the message.
828 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
829 (void)ext_hook("add-hook", b, (char *)0);
839 if (mp->lowmsg == 0) mp->lowmsg = 1;
841 clear_msg_flags (mp, msgnum);
842 set_exists (mp, msgnum);
843 set_unseen (mp, msgnum);
844 mp->msgflags |= SEQMOD;
847 /* If we get here there was some sort of error from scan(),
848 * so stop processing anything more from the spool.
852 } else if (inc_type == INC_FILE) { /* Maildir inbox to process */
857 hghnum = msgnum = mp->hghmsg;
858 for (i = 0; i < num_maildir_entries; i++) {
861 * Check if we need to allocate more space for message status.
862 * If so, then add space for an additional 100 messages.
864 if (msgnum >= mp->hghoff
865 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
866 advise (NULL, "unable to allocate folder storage");
871 sp = Maildir[i].filename;
872 cp = getcpy (m_name (msgnum));
874 if (!trnflag || link(sp, cp) == -1) {
875 static char buf[65536];
878 if ((sf = fopen (sp, "r")) == NULL)
879 adios (sp, "unable to read for copy");
880 if ((pf = fopen (cp, "w+")) == NULL)
881 adios (cp, "unable to write for copy");
882 while ((nrd = fread(buf, 1, sizeof(buf), sf)) > 0)
883 if (fwrite(buf, 1, nrd, pf) != nrd)
885 if (ferror(sf) || fflush(pf) || ferror(pf)) {
887 fclose(pf); fclose(sf); unlink(cp);
889 adios(cp, "copy error %s -> %s", sp, cp);
894 if (pf == NULL && (pf = fopen (cp, "r")) == NULL)
895 adios (cp, "not available");
896 chmod (cp, m_gmprot ());
898 fseek (pf, 0L, SEEK_SET);
899 switch (incerr = scan (pf, msgnum, 0, nfs, width,
900 msgnum == mp->hghmsg + 1 && chgflag,
901 1, NULL, stop - start, noisy)) {
903 printf ("%*d empty\n", DMAXFOLDER, msgnum);
909 /* advise (cp, "unable to read"); already advised */
920 * Run the external program hook on the message.
923 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
924 (void)ext_hook("add-hook", b, (char *)0);
931 clear_msg_flags (mp, msgnum);
932 set_exists (mp, msgnum);
933 set_unseen (mp, msgnum);
934 mp->msgflags |= SEQMOD;
938 if (ferror(pf) || fclose (pf)) {
942 adios (cp, "write error on");
947 if (trnflag && unlink (sp) == NOTOK)
948 adios (sp, "couldn't unlink");
949 free (sp); /* Free Maildir[i]->filename */
951 free (Maildir); /* From now on Maildir is just a flag - don't dref! */
954 if (incerr < 0) { /* error */
956 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
957 (void) lkfclose (in, newmail); in = NULL;
958 DROPGROUPPRIVS(); /* And then return us to normal privileges */
960 fclose (in); in = NULL;
962 adios (NULL, "failed");
972 if ((inc_type == INC_POP) && packfile)
977 * truncate file we are incorporating from
979 if (inc_type == INC_FILE && Maildir == NULL) {
981 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
982 advise (NULL, "new messages have arrived!\007");
985 if ((newfd = creat (newmail, 0600)) != NOTOK)
988 admonish (newmail, "error zero'ing");
989 unlink(map_name(newmail));
993 printf ("%s not zero'd\n", newmail);
997 if (msgnum == hghnum) {
998 admonish (NULL, "no messages incorporated");
1000 context_replace (pfolder, folder); /* update current folder */
1002 mp->curmsg = hghnum + 1;
1003 mp->hghmsg = msgnum;
1004 if (mp->lowmsg == 0)
1006 if (chgflag) /* sigh... */
1007 seq_setcur (mp, mp->curmsg);
1011 * unlock the mail spool
1013 if (inc_type == INC_FILE && Maildir == NULL) {
1015 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
1016 (void) lkfclose (in, newmail); in = NULL;
1017 DROPGROUPPRIVS(); /* And then return us to normal privileges */
1019 fclose (in); in = NULL;
1023 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
1024 seq_save (mp); /* synchronize sequences */
1025 context_save (); /* save the context file */
1034 * Copy message message from spool into
1035 * temporary file. Massage the "From " line
1039 cpymsg (FILE *in, FILE *out)
1042 char *tmpbuf, name[NAMESZ];
1045 state = m_getfld (state, name, tmpbuf, rlwidth, in);
1065 inc_done (int status)
1068 if (packfile && pd != NOTOK)
1069 mbx_close (packfile, pd);
1074 lkfclose(in, newmail);
1082 pop_action (char *s)
1084 fprintf (pf, "%s\n", s);
1085 stop += strlen (s) + 1;
1086 return 0; /* Is return value used? This was missing before 1999-07-15. */
1093 char buffer[BUFSIZ];
1095 snprintf (buffer, sizeof(buffer), "%s\n", s);
1096 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1098 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1101 size += strlen (buffer) + 1;
1102 return 0; /* Is return value used? This was missing before 1999-07-15. */
1113 if (stat (packfile, &st) == NOTOK)
1115 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1116 || map_chk (cp, md, &d, (long) st.st_size, 1)) {