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
117 static struct Maildir_entry {
121 static int num_maildir_entries = 0;
122 static int snoop = 0;
125 extern char response[];
130 static int mbx_style = MMDF_FORMAT;
131 static int pd = NOTOK;
137 static char *packfile = NULL;
138 static FILE *pf = NULL;
140 /* This is an attempt to simplify things by putting all the
141 * privilege ops into macros.
142 * *GROUPPRIVS() is related to handling the setgid MAIL property,
143 * and only applies if MAILGROUP is defined.
144 * *USERPRIVS() is related to handling the setuid root property,
145 * and only applies if POP is defined [why does POP => setuid root?]
146 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
147 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
148 * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
149 * before DROPUSERPRIVS() is called [this is needed because setgid()
150 * sets both effective and real uids if euid is root.]
152 * There's probably a better implementation if we're allowed to use
153 * BSD-style setreuid() rather than using POSIX saved-ids.
154 * Anyway, if you're euid root it's a bit pointless to drop the group
157 * I'm pretty happy that the security is good provided we aren't setuid root.
158 * The only things we trust with group=mail privilege are lkfopen()
163 * For setting and returning to "mail" gid
166 static int return_gid;
168 /* easy case; we're not setuid root, so can drop group privs
171 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
172 #else /* POP ie we are setuid root */
173 #define TRYDROPGROUPPRIVS() \
174 if (geteuid() != 0) DROPGROUPPRIVS()
176 #define DROPGROUPPRIVS() setgid(getgid())
177 #define GETGROUPPRIVS() setgid(return_gid)
178 #define SAVEGROUPPRIVS() return_gid = getegid()
180 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
181 #define TRYDROPGROUPPRIVS()
182 #define DROPGROUPPRIVS()
183 #define GETGROUPPRIVS()
184 #define SAVEGROUPPRIVS()
185 #endif /* not MAILGROUP */
187 /* these variables have to be globals so that done() can correctly clean up the lockfile */
188 static int locked = 0;
189 static char *newmail;
195 char *map_name(char *);
197 static void inc_done(int) NORETURN;
199 static int pop_action(char *);
200 static int pop_pack(char *);
201 static int map_count(void);
205 maildir_srt(const void *va, const void *vb)
207 const struct Maildir_entry *a = va, *b = vb;
208 if (a->mtime > b->mtime)
210 else if (a->mtime < b->mtime)
217 main (int argc, char **argv)
219 int chgflag = 1, trnflag = 1;
220 int noisy = 1, width = 0;
221 int hghnum = 0, msgnum = 0;
223 int incerr = 0; /* <0 if inc hits an error which means it should not truncate mailspool */
224 char *cp, *maildir = NULL, *folder = NULL;
225 char *format = NULL, *form = NULL;
226 char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
227 char *audfile = NULL, *from = NULL, *saslmech = NULL;
228 char buf[BUFSIZ], **argp, *nfs, **arguments;
229 struct msgs *mp = NULL;
232 char b[MAXPATHLEN + 1];
233 char *maildir_copy = NULL; /* copy of mail directory because the static gets overwritten */
238 char *MAILHOST_env_variable;
243 /* absolutely the first thing we do is save our privileges,
244 * and drop them if we can.
250 setlocale(LC_ALL, "");
252 invo_name = r1bindex (argv[0], '/');
254 /* read user profile/context */
257 mts_init (invo_name);
258 arguments = getarguments (invo_name, argc, argv, 1);
264 * use MAILHOST environment variable if present,
266 * If that fails, use the default (if any)
267 * provided by mts.conf in mts_init()
269 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
270 pophost = MAILHOST_env_variable;
272 * If there is a valid "pophost" entry in mts.conf,
273 * then use it as the default host.
275 if (pophost && *pophost)
278 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
282 while ((cp = *argp++)) {
284 switch (smatch (++cp, switches)) {
286 ambigsw (cp, switches);
289 adios (NULL, "-%s unknown", cp);
292 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
293 print_help (buf, switches, 1);
296 print_version(invo_name);
300 if (!(cp = *argp++) || *cp == '-')
301 adios (NULL, "missing argument to %s", argp[-2]);
302 audfile = getcpy (m_maildir (cp));
316 * The flag `trnflag' has the value:
318 * 2 if -truncate is given
319 * 1 by default (truncating is default)
320 * 0 if -notruncate is given
330 if (!(cp = *argp++) || *cp == '-')
331 adios (NULL, "missing argument to %s", argp[-2]);
332 from = path (cp, TFILE);
335 * If the truncate file is in default state,
336 * change to not truncate.
350 if (!(form = *argp++) || *form == '-')
351 adios (NULL, "missing argument to %s", argp[-2]);
355 if (!(format = *argp++) || *format == '-')
356 adios (NULL, "missing argument to %s", argp[-2]);
361 if (!(cp = *argp++) || *cp == '-')
362 adios (NULL, "missing argument to %s", argp[-2]);
367 if (!(host = *argp++) || *host == '-')
368 adios (NULL, "missing argument to %s", argp[-2]);
372 if (!(host = *argp++) || *port == '-')
373 adios (NULL, "missing argument to %s", argp[-2]);
377 if (!(user = *argp++) || *user == '-')
378 adios (NULL, "missing argument to %s", argp[-2]);
383 if (!(cp = *argp++) || *cp == '-')
384 adios (NULL, "missing argument to %s", argp[-2]);
386 if (!(packfile = *argp++) || *packfile == '-')
387 adios (NULL, "missing argument to %s", argp[-2]);
405 if (!(saslmech = *argp++) || *saslmech == '-')
406 adios (NULL, "missing argument to %s", argp[-2]);
409 if (!(proxy = *argp++) || *proxy == '-')
410 adios (NULL, "missing argument to %s", argp[-2]);
414 if (*cp == '+' || *cp == '@') {
416 adios (NULL, "only one folder at a time!");
418 folder = pluspath (cp);
420 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
424 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
425 * not DROPGROUPPRIVS().
432 /* guarantee dropping group priveleges; we might not have done so earlier */
436 * Where are we getting the new mail?
449 * Are we getting the mail from
452 if (inc_type == INC_POP) {
454 user = getusername ();
456 pass = getusername ();
458 ruserpass (host, &user, &pass);
461 * initialize POP connection
463 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
465 adios (NULL, "%s", response);
467 /* Check if there are any messages */
468 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
469 adios (NULL, "%s", response);
473 adios (NULL, "no mail to incorporate");
479 * We will get the mail from a file
480 * (typically the standard maildrop)
483 if (inc_type == INC_FILE) {
486 else if ((newmail = getenv ("MAILDROP")) && *newmail)
487 newmail = m_mailpath (newmail);
488 else if ((newmail = context_find ("maildrop")) && *newmail)
489 newmail = m_mailpath (newmail);
491 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
493 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
494 adios (NULL, "no mail to incorporate");
495 if (s1.st_mode & S_IFDIR) {
501 cp = concat (newmail, "/new", NULL);
502 if ((md = opendir(cp)) == NULL)
503 adios (NULL, "unable to open %s", cp);
504 while ((de = readdir (md)) != NULL) {
505 if (de->d_name[0] == '.')
507 if (i >= num_maildir_entries) {
508 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
509 adios(NULL, "not enough memory for %d messages", 2*i+16);
510 num_maildir_entries = 2*i+16;
512 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
513 if (stat(Maildir[i].filename, &ms) != 0)
514 adios (Maildir[i].filename, "couldn't get delivery time");
515 Maildir[i].mtime = ms.st_mtime;
520 cp = concat (newmail, "/cur", NULL);
521 if ((md = opendir(cp)) == NULL)
522 adios (NULL, "unable to open %s", cp);
523 while ((de = readdir (md)) != NULL) {
524 if (de->d_name[0] == '.')
526 if (i >= num_maildir_entries) {
527 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
528 adios(NULL, "not enough memory for %d messages", 2*i+16);
529 num_maildir_entries = 2*i+16;
531 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
532 if (stat(Maildir[i].filename, &ms) != 0)
533 adios (Maildir[i].filename, "couldn't get delivery time");
534 Maildir[i].mtime = ms.st_mtime;
540 adios (NULL, "no mail to incorporate");
541 num_maildir_entries = i;
542 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
545 if ((cp = strdup(newmail)) == (char *)0)
546 adios (NULL, "error allocating memory to copy newmail");
552 /* skip the folder setup */
553 if ((inc_type == INC_POP) && packfile)
557 if (!context_find ("path"))
558 free (path ("./", TFOLDER));
560 folder = getfolder (0);
561 maildir = m_maildir (folder);
563 if ((maildir_copy = strdup(maildir)) == (char *)0)
564 adios (maildir, "error allocating memory to copy maildir");
566 if (!folder_exists(maildir)) {
567 /* If the folder doesn't exist, and we're given the -silent flag,
571 create_folder(maildir, 0, done);
576 if (chdir (maildir) == NOTOK)
577 adios (maildir, "unable to change directory to");
579 /* read folder and create message structure */
580 if (!(mp = folder_read (folder)))
581 adios (NULL, "unable to read folder %s", folder);
587 if (inc_type == INC_FILE && Maildir == NULL) {
588 if (access (newmail, W_OK) != NOTOK) {
591 SIGNAL (SIGHUP, SIG_IGN);
592 SIGNAL (SIGINT, SIG_IGN);
593 SIGNAL (SIGQUIT, SIG_IGN);
594 SIGNAL (SIGTERM, SIG_IGN);
597 GETGROUPPRIVS(); /* Reset gid to lock mail file */
598 in = lkfopen (newmail, "r");
601 adios (NULL, "unable to lock and fopen %s", newmail);
602 fstat (fileno(in), &s1);
605 if ((in = fopen (newmail, "r")) == NULL)
606 adios (newmail, "unable to read");
610 /* This shouldn't be necessary but it can't hurt. */
615 if ((i = stat (audfile, &st)) == NOTOK)
616 advise (NULL, "Creating Receive-Audit: %s", audfile);
617 if ((aud = fopen (audfile, "a")) == NULL)
618 adios (audfile, "unable to append to");
620 chmod (audfile, m_gmprot ());
623 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
624 : host ? "<<inc>> %s -host %s -user %s\n"
626 dtimenow (0), from ? from : host, user);
628 fprintf (aud, from ? "<<inc>> %s -ms %s\n" : "<<inc>> %s\n",
633 /* Get new format string */
634 nfs = new_fs (form, format, FORMAT);
637 printf ("Incorporating new mail into %s...\n\n", folder);
643 * Get the mail from a POP server
645 if (inc_type == INC_POP) {
648 packfile = path (packfile, TFILE);
649 if (stat (packfile, &st) == NOTOK) {
651 adios (packfile, "error on file");
652 cp = concat ("Create file \"", packfile, "\"? ", NULL);
653 if (noisy && !getanswer (cp))
657 msgnum = map_count ();
658 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
660 adios (packfile, "unable to open");
661 if ((pf = fdopen (pd, "w+")) == NULL)
662 adios (NULL, "unable to fdopen %s", packfile);
664 hghnum = msgnum = mp->hghmsg;
666 * Check if we have enough message space for all the new
667 * messages. If not, then realloc the folder and add enough
668 * space for all new messages plus 10 additional slots.
670 if (mp->hghmsg + nmsgs >= mp->hghoff
671 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
672 adios (NULL, "unable to allocate folder storage");
675 for (i = 1; i <= nmsgs; i++) {
678 fseek (pf, 0L, SEEK_CUR);
681 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
684 if (pop_retr (i, pop_pack) == NOTOK)
685 adios (NULL, "%s", response);
687 fseek (pf, 0L, SEEK_CUR);
690 adios (packfile, "write error on");
691 fseek (pf, start, SEEK_SET);
693 cp = getcpy (m_name (msgnum));
694 if ((pf = fopen (cp, "w+")) == NULL)
695 adios (cp, "unable to write");
696 chmod (cp, m_gmprot ());
699 if (pop_retr (i, pop_action) == NOTOK)
700 adios (NULL, "%s", response);
703 adios (cp, "write error on");
704 fseek (pf, 0L, SEEK_SET);
706 switch (incerr = scan (pf, msgnum, 0, nfs, width,
707 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
708 1, NULL, stop - start, noisy)) {
710 printf ("%*d empty\n", DMAXFOLDER, msgnum);
716 /* advise (cp, "unable to read"); already advised */
731 clear_msg_flags (mp, msgnum);
732 set_exists (mp, msgnum);
733 set_unseen (mp, msgnum);
734 mp->msgflags |= SEQMOD;
739 fseek (pf, stop, SEEK_SET);
740 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
741 if (fflush (pf) || ferror (pf)) {
745 adios (packfile, "write error on");
747 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
749 if (ferror(pf) || fclose (pf)) {
754 adios (cp, "write error on");
759 if (trnflag && pop_dele (i) == NOTOK)
760 adios (NULL, "%s", response);
763 if (pop_quit () == NOTOK)
764 adios (NULL, "%s", response);
766 mbx_close (packfile, pd);
773 * Get the mail from file (usually mail spool)
775 if (inc_type == INC_FILE && Maildir == NULL) {
776 m_unknown (in); /* the MAGIC invocation... */
777 hghnum = msgnum = mp->hghmsg;
780 * Check if we need to allocate more space for message status.
781 * If so, then add space for an additional 100 messages.
783 if (msgnum >= mp->hghoff
784 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
785 advise (NULL, "unable to allocate folder storage");
791 /* copy file from spool to tmp file */
792 tmpfilenam = m_scratch ("", invo_name);
793 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
794 adios (tmpfilenam, "unable to create");
795 chmod (tmpfilenam, m_gmprot ());
796 if (!(in2 = fdopen (fd, "r+")))
797 adios (tmpfilenam, "unable to access");
800 /* link message into folder */
801 newmsg = folder_addmsg(mp, tmpfilenam);
803 /* create scanline for new message */
804 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
805 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
812 fputs ("inc aborted!\n", aud);
813 advise (NULL, "aborted!"); /* doesn't clean up locks! */
817 advise (NULL, "BUG in %s, number out of range", invo_name);
821 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
827 * Run the external program hook on the message.
830 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
831 (void)ext_hook("add-hook", b, (char *)0);
841 if (mp->lowmsg == 0) mp->lowmsg = 1;
843 clear_msg_flags (mp, msgnum);
844 set_exists (mp, msgnum);
845 set_unseen (mp, msgnum);
846 mp->msgflags |= SEQMOD;
849 /* If we get here there was some sort of error from scan(),
850 * so stop processing anything more from the spool.
854 } else if (inc_type == INC_FILE) { /* Maildir inbox to process */
859 hghnum = msgnum = mp->hghmsg;
860 for (i = 0; i < num_maildir_entries; i++) {
863 * Check if we need to allocate more space for message status.
864 * If so, then add space for an additional 100 messages.
866 if (msgnum >= mp->hghoff
867 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
868 advise (NULL, "unable to allocate folder storage");
873 sp = Maildir[i].filename;
874 cp = getcpy (m_name (msgnum));
876 if (!trnflag || link(sp, cp) == -1) {
877 static char buf[65536];
880 if ((sf = fopen (sp, "r")) == NULL)
881 adios (sp, "unable to read for copy");
882 if ((pf = fopen (cp, "w+")) == NULL)
883 adios (cp, "unable to write for copy");
884 while ((nrd = fread(buf, 1, sizeof(buf), sf)) > 0)
885 if (fwrite(buf, 1, nrd, pf) != nrd)
887 if (ferror(sf) || fflush(pf) || ferror(pf)) {
889 fclose(pf); fclose(sf); unlink(cp);
891 adios(cp, "copy error %s -> %s", sp, cp);
896 if (pf == NULL && (pf = fopen (cp, "r")) == NULL)
897 adios (cp, "not available");
898 chmod (cp, m_gmprot ());
900 fseek (pf, 0L, SEEK_SET);
901 switch (incerr = scan (pf, msgnum, 0, nfs, width,
902 msgnum == mp->hghmsg + 1 && chgflag,
903 1, NULL, stop - start, noisy)) {
905 printf ("%*d empty\n", DMAXFOLDER, msgnum);
911 /* advise (cp, "unable to read"); already advised */
922 * Run the external program hook on the message.
925 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
926 (void)ext_hook("add-hook", b, (char *)0);
933 clear_msg_flags (mp, msgnum);
934 set_exists (mp, msgnum);
935 set_unseen (mp, msgnum);
936 mp->msgflags |= SEQMOD;
940 if (ferror(pf) || fclose (pf)) {
944 adios (cp, "write error on");
949 if (trnflag && unlink (sp) == NOTOK)
950 adios (sp, "couldn't unlink");
951 free (sp); /* Free Maildir[i]->filename */
953 free (Maildir); /* From now on Maildir is just a flag - don't dref! */
956 if (incerr < 0) { /* error */
958 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
959 (void) lkfclose (in, newmail); in = NULL;
960 DROPGROUPPRIVS(); /* And then return us to normal privileges */
962 fclose (in); in = NULL;
964 adios (NULL, "failed");
974 if ((inc_type == INC_POP) && packfile)
979 * truncate file we are incorporating from
981 if (inc_type == INC_FILE && Maildir == NULL) {
983 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
984 advise (NULL, "new messages have arrived!\007");
987 if ((newfd = creat (newmail, 0600)) != NOTOK)
990 admonish (newmail, "error zero'ing");
991 unlink(map_name(newmail));
995 printf ("%s not zero'd\n", newmail);
999 if (msgnum == hghnum) {
1000 admonish (NULL, "no messages incorporated");
1002 context_replace (pfolder, folder); /* update current folder */
1004 mp->curmsg = hghnum + 1;
1005 mp->hghmsg = msgnum;
1006 if (mp->lowmsg == 0)
1008 if (chgflag) /* sigh... */
1009 seq_setcur (mp, mp->curmsg);
1013 * unlock the mail spool
1015 if (inc_type == INC_FILE && Maildir == NULL) {
1017 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
1018 (void) lkfclose (in, newmail); in = NULL;
1019 DROPGROUPPRIVS(); /* And then return us to normal privileges */
1021 fclose (in); in = NULL;
1025 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
1026 seq_save (mp); /* synchronize sequences */
1027 context_save (); /* save the context file */
1036 * Copy message message from spool into
1037 * temporary file. Massage the "From " line
1041 cpymsg (FILE *in, FILE *out)
1044 char *tmpbuf, name[NAMESZ];
1047 state = m_getfld (state, name, tmpbuf, rlwidth, in);
1067 inc_done (int status)
1070 if (packfile && pd != NOTOK)
1071 mbx_close (packfile, pd);
1076 lkfclose(in, newmail);
1084 pop_action (char *s)
1086 fprintf (pf, "%s\n", s);
1087 stop += strlen (s) + 1;
1088 return 0; /* Is return value used? This was missing before 1999-07-15. */
1095 char buffer[BUFSIZ];
1097 snprintf (buffer, sizeof(buffer), "%s\n", s);
1098 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1100 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1103 size += strlen (buffer) + 1;
1104 return 0; /* Is return value used? This was missing before 1999-07-15. */
1115 if (stat (packfile, &st) == NOTOK)
1117 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1118 || map_chk (cp, md, &d, (long) st.st_size, 1)) {