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
33 #include <h/dropsbr.h>
35 #include <h/fmt_scan.h>
36 #include <h/scansbr.h>
37 #include <h/signals.h>
44 # define SASLminc(a) (a)
46 # define SASLminc(a) 0
49 static struct swit switches[] = {
51 { "audit audit-file", 0 },
61 { "form formatfile", 0 },
63 { "format string", 5 },
65 { "host hostname", 0 },
67 { "user username", 0 },
73 { "port name/number", 0 },
83 { "width columns", 0 },
91 { "sasl", SASLminc(-4) },
93 { "saslmech", SASLminc(-8) },
95 { "proxy command", 0 },
100 * flags for the mail source
106 static struct Maildir_entry {
110 static int num_maildir_entries = 0;
111 static int snoop = 0;
113 extern char response[];
118 static int mbx_style = MMDF_FORMAT;
119 static int pd = NOTOK;
124 static char *packfile = NULL;
125 static FILE *pf = NULL;
127 /* This is an attempt to simplify things by putting all the
128 * privilege ops into macros.
129 * *GROUPPRIVS() is related to handling the setgid MAIL property,
130 * and only applies if MAILGROUP is defined.
131 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
132 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
133 * do the obvious thing.
135 * There's probably a better implementation if we're allowed to use
136 * BSD-style setreuid() rather than using POSIX saved-ids.
137 * Anyway, if you're euid root it's a bit pointless to drop the group
140 * I'm pretty happy that the security is good provided we aren't setuid root.
141 * The only things we trust with group=mail privilege are lkfopen()
146 * For setting and returning to "mail" gid
149 static int return_gid;
150 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
151 #define DROPGROUPPRIVS() setgid(getgid())
152 #define GETGROUPPRIVS() setgid(return_gid)
153 #define SAVEGROUPPRIVS() return_gid = getegid()
155 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
156 #define TRYDROPGROUPPRIVS()
157 #define DROPGROUPPRIVS()
158 #define GETGROUPPRIVS()
159 #define SAVEGROUPPRIVS()
160 #endif /* not MAILGROUP */
162 /* these variables have to be globals so that done() can correctly clean up the lockfile */
163 static int locked = 0;
164 static char *newmail;
170 char *map_name(char *);
172 static void inc_done(int) NORETURN;
173 static int pop_action(char *);
174 static int pop_pack(char *);
175 static int map_count(void);
178 maildir_srt(const void *va, const void *vb)
180 const struct Maildir_entry *a = va, *b = vb;
181 if (a->mtime > b->mtime)
183 else if (a->mtime < b->mtime)
190 main (int argc, char **argv)
192 int chgflag = 1, trnflag = 1;
193 int noisy = 1, width = 0;
194 int hghnum = 0, msgnum = 0;
196 int incerr = 0; /* <0 if inc hits an error which means it should not truncate mailspool */
197 char *cp, *maildir = NULL, *folder = NULL;
198 char *format = NULL, *form = NULL;
199 char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
200 char *audfile = NULL, *from = NULL, *saslmech = NULL;
201 char buf[BUFSIZ], **argp, *nfs, **arguments;
202 struct msgs *mp = NULL;
205 char b[PATH_MAX + 1];
206 char *maildir_copy = NULL; /* copy of mail directory because the static gets overwritten */
210 char *MAILHOST_env_variable;
214 /* absolutely the first thing we do is save our privileges,
215 * and drop them if we can.
221 setlocale(LC_ALL, "");
223 invo_name = r1bindex (argv[0], '/');
225 /* read user profile/context */
228 mts_init (invo_name);
229 arguments = getarguments (invo_name, argc, argv, 1);
234 * use MAILHOST environment variable if present,
236 * If that fails, use the default (if any)
237 * provided by mts.conf in mts_init()
239 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
240 pophost = MAILHOST_env_variable;
242 * If there is a valid "pophost" entry in mts.conf,
243 * then use it as the default host.
245 if (pophost && *pophost)
248 while ((cp = *argp++)) {
250 switch (smatch (++cp, switches)) {
252 ambigsw (cp, switches);
255 adios (NULL, "-%s unknown", cp);
258 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
259 print_help (buf, switches, 1);
262 print_version(invo_name);
266 if (!(cp = *argp++) || *cp == '-')
267 adios (NULL, "missing argument to %s", argp[-2]);
268 audfile = getcpy (m_maildir (cp));
282 * The flag `trnflag' has the value:
284 * 2 if -truncate is given
285 * 1 by default (truncating is default)
286 * 0 if -notruncate is given
296 if (!(cp = *argp++) || *cp == '-')
297 adios (NULL, "missing argument to %s", argp[-2]);
298 from = path (cp, TFILE);
301 * If the truncate file is in default state,
302 * change to not truncate.
316 if (!(form = *argp++) || *form == '-')
317 adios (NULL, "missing argument to %s", argp[-2]);
321 if (!(format = *argp++) || *format == '-')
322 adios (NULL, "missing argument to %s", argp[-2]);
327 if (!(cp = *argp++) || *cp == '-')
328 adios (NULL, "missing argument to %s", argp[-2]);
333 if (!(host = *argp++) || *host == '-')
334 adios (NULL, "missing argument to %s", argp[-2]);
338 if (!(host = *argp++) || *port == '-')
339 adios (NULL, "missing argument to %s", argp[-2]);
343 if (!(user = *argp++) || *user == '-')
344 adios (NULL, "missing argument to %s", argp[-2]);
348 if (!(packfile = *argp++) || *packfile == '-')
349 adios (NULL, "missing argument to %s", argp[-2]);
364 if (!(saslmech = *argp++) || *saslmech == '-')
365 adios (NULL, "missing argument to %s", argp[-2]);
368 if (!(proxy = *argp++) || *proxy == '-')
369 adios (NULL, "missing argument to %s", argp[-2]);
373 if (*cp == '+' || *cp == '@') {
375 adios (NULL, "only one folder at a time!");
377 folder = pluspath (cp);
379 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
383 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
384 * not DROPGROUPPRIVS().
389 /* guarantee dropping group priveleges; we might not have done so earlier */
393 * Where are we getting the new mail?
403 * Are we getting the mail from
406 if (inc_type == INC_POP) {
408 user = getusername ();
410 pass = getusername ();
412 ruserpass (host, &user, &pass);
415 * initialize POP connection
417 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
419 adios (NULL, "%s", response);
421 /* Check if there are any messages */
422 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
423 adios (NULL, "%s", response);
427 adios (NULL, "no mail to incorporate");
432 * We will get the mail from a file
433 * (typically the standard maildrop)
436 if (inc_type == INC_FILE) {
439 else if ((newmail = getenv ("MAILDROP")) && *newmail)
440 newmail = m_mailpath (newmail);
441 else if ((newmail = context_find ("maildrop")) && *newmail)
442 newmail = m_mailpath (newmail);
444 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
446 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
447 adios (NULL, "no mail to incorporate");
448 if (s1.st_mode & S_IFDIR) {
454 cp = concat (newmail, "/new", NULL);
455 if ((md = opendir(cp)) == NULL)
456 adios (NULL, "unable to open %s", cp);
457 while ((de = readdir (md)) != NULL) {
458 if (de->d_name[0] == '.')
460 if (i >= num_maildir_entries) {
461 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
462 adios(NULL, "not enough memory for %d messages", 2*i+16);
463 num_maildir_entries = 2*i+16;
465 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
466 if (stat(Maildir[i].filename, &ms) != 0)
467 adios (Maildir[i].filename, "couldn't get delivery time");
468 Maildir[i].mtime = ms.st_mtime;
473 cp = concat (newmail, "/cur", NULL);
474 if ((md = opendir(cp)) == NULL)
475 adios (NULL, "unable to open %s", cp);
476 while ((de = readdir (md)) != NULL) {
477 if (de->d_name[0] == '.')
479 if (i >= num_maildir_entries) {
480 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
481 adios(NULL, "not enough memory for %d messages", 2*i+16);
482 num_maildir_entries = 2*i+16;
484 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
485 if (stat(Maildir[i].filename, &ms) != 0)
486 adios (Maildir[i].filename, "couldn't get delivery time");
487 Maildir[i].mtime = ms.st_mtime;
493 adios (NULL, "no mail to incorporate");
494 num_maildir_entries = i;
495 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
498 if ((cp = strdup(newmail)) == (char *)0)
499 adios (NULL, "error allocating memory to copy newmail");
504 /* skip the folder setup */
505 if ((inc_type == INC_POP) && packfile)
508 if (!context_find ("path"))
509 free (path ("./", TFOLDER));
511 folder = getfolder (0);
512 maildir = m_maildir (folder);
514 if ((maildir_copy = strdup(maildir)) == (char *)0)
515 adios (maildir, "error allocating memory to copy maildir");
517 if (!folder_exists(maildir)) {
518 /* If the folder doesn't exist, and we're given the -silent flag,
522 create_folder(maildir, 0, done);
527 if (chdir (maildir) == NOTOK)
528 adios (maildir, "unable to change directory to");
530 /* read folder and create message structure */
531 if (!(mp = folder_read (folder)))
532 adios (NULL, "unable to read folder %s", folder);
536 if (inc_type == INC_FILE && Maildir == NULL) {
537 if (access (newmail, W_OK) != NOTOK) {
540 SIGNAL (SIGHUP, SIG_IGN);
541 SIGNAL (SIGINT, SIG_IGN);
542 SIGNAL (SIGQUIT, SIG_IGN);
543 SIGNAL (SIGTERM, SIG_IGN);
546 GETGROUPPRIVS(); /* Reset gid to lock mail file */
547 in = lkfopen (newmail, "r");
550 adios (NULL, "unable to lock and fopen %s", newmail);
551 fstat (fileno(in), &s1);
554 if ((in = fopen (newmail, "r")) == NULL)
555 adios (newmail, "unable to read");
559 /* This shouldn't be necessary but it can't hurt. */
564 if ((i = stat (audfile, &st)) == NOTOK)
565 advise (NULL, "Creating Receive-Audit: %s", audfile);
566 if ((aud = fopen (audfile, "a")) == NULL)
567 adios (audfile, "unable to append to");
569 chmod (audfile, m_gmprot ());
571 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
572 : host ? "<<inc>> %s -host %s -user %s\n"
574 dtimenow (0), from ? from : host, user);
577 /* Get new format string */
578 nfs = new_fs (form, format, FORMAT);
581 printf ("Incorporating new mail into %s...\n\n", folder);
586 * Get the mail from a POP server
588 if (inc_type == INC_POP) {
591 packfile = path (packfile, TFILE);
592 if (stat (packfile, &st) == NOTOK) {
594 adios (packfile, "error on file");
595 cp = concat ("Create file \"", packfile, "\"? ", NULL);
596 if (noisy && !getanswer (cp))
600 msgnum = map_count ();
601 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
603 adios (packfile, "unable to open");
604 if ((pf = fdopen (pd, "w+")) == NULL)
605 adios (NULL, "unable to fdopen %s", packfile);
607 hghnum = msgnum = mp->hghmsg;
609 * Check if we have enough message space for all the new
610 * messages. If not, then realloc the folder and add enough
611 * space for all new messages plus 10 additional slots.
613 if (mp->hghmsg + nmsgs >= mp->hghoff
614 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
615 adios (NULL, "unable to allocate folder storage");
618 for (i = 1; i <= nmsgs; i++) {
621 fseek (pf, 0L, SEEK_CUR);
624 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
627 if (pop_retr (i, pop_pack) == NOTOK)
628 adios (NULL, "%s", response);
630 fseek (pf, 0L, SEEK_CUR);
633 adios (packfile, "write error on");
634 fseek (pf, start, SEEK_SET);
636 cp = getcpy (m_name (msgnum));
637 if ((pf = fopen (cp, "w+")) == NULL)
638 adios (cp, "unable to write");
639 chmod (cp, m_gmprot ());
642 if (pop_retr (i, pop_action) == NOTOK)
643 adios (NULL, "%s", response);
646 adios (cp, "write error on");
647 fseek (pf, 0L, SEEK_SET);
649 switch (incerr = scan (pf, msgnum, 0, nfs, width,
650 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
651 1, NULL, stop - start, noisy)) {
653 printf ("%*d empty\n", DMAXFOLDER, msgnum);
659 /* advise (cp, "unable to read"); already advised */
674 clear_msg_flags (mp, msgnum);
675 set_exists (mp, msgnum);
676 set_unseen (mp, msgnum);
677 mp->msgflags |= SEQMOD;
682 fseek (pf, stop, SEEK_SET);
683 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
684 if (fflush (pf) || ferror (pf)) {
688 adios (packfile, "write error on");
690 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
692 if (ferror(pf) || fclose (pf)) {
697 adios (cp, "write error on");
702 if (trnflag && pop_dele (i) == NOTOK)
703 adios (NULL, "%s", response);
706 if (pop_quit () == NOTOK)
707 adios (NULL, "%s", response);
709 mbx_close (packfile, pd);
715 * Get the mail from file (usually mail spool)
717 if (inc_type == INC_FILE && Maildir == NULL) {
718 m_unknown (in); /* the MAGIC invocation... */
719 hghnum = msgnum = mp->hghmsg;
722 * Check if we need to allocate more space for message status.
723 * If so, then add space for an additional 100 messages.
725 if (msgnum >= mp->hghoff
726 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
727 advise (NULL, "unable to allocate folder storage");
733 /* copy file from spool to tmp file */
734 tmpfilenam = m_scratch ("", invo_name);
735 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
736 adios (tmpfilenam, "unable to create");
737 chmod (tmpfilenam, m_gmprot ());
738 if (!(in2 = fdopen (fd, "r+")))
739 adios (tmpfilenam, "unable to access");
742 /* link message into folder */
743 newmsg = folder_addmsg(mp, tmpfilenam);
745 /* create scanline for new message */
746 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
747 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
754 fputs ("inc aborted!\n", aud);
755 advise (NULL, "aborted!"); /* doesn't clean up locks! */
759 advise (NULL, "BUG in %s, number out of range", invo_name);
763 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
769 * Run the external program hook on the message.
772 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
773 (void)ext_hook("add-hook", b, (char *)0);
783 if (mp->lowmsg == 0) mp->lowmsg = 1;
785 clear_msg_flags (mp, msgnum);
786 set_exists (mp, msgnum);
787 set_unseen (mp, msgnum);
788 mp->msgflags |= SEQMOD;
791 /* If we get here there was some sort of error from scan(),
792 * so stop processing anything more from the spool.
796 } else if (inc_type == INC_FILE) { /* Maildir inbox to process */
801 hghnum = msgnum = mp->hghmsg;
802 for (i = 0; i < num_maildir_entries; i++) {
805 * Check if we need to allocate more space for message status.
806 * If so, then add space for an additional 100 messages.
808 if (msgnum >= mp->hghoff
809 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
810 advise (NULL, "unable to allocate folder storage");
815 sp = Maildir[i].filename;
816 cp = getcpy (m_name (msgnum));
818 if (!trnflag || link(sp, cp) == -1) {
819 static char buf[65536];
822 if ((sf = fopen (sp, "r")) == NULL)
823 adios (sp, "unable to read for copy");
824 if ((pf = fopen (cp, "w+")) == NULL)
825 adios (cp, "unable to write for copy");
826 while ((nrd = fread(buf, 1, sizeof(buf), sf)) > 0)
827 if (fwrite(buf, 1, nrd, pf) != nrd)
829 if (ferror(sf) || fflush(pf) || ferror(pf)) {
831 fclose(pf); fclose(sf); unlink(cp);
833 adios(cp, "copy error %s -> %s", sp, cp);
838 if (pf == NULL && (pf = fopen (cp, "r")) == NULL)
839 adios (cp, "not available");
840 chmod (cp, m_gmprot ());
842 fseek (pf, 0L, SEEK_SET);
843 switch (incerr = scan (pf, msgnum, 0, nfs, width,
844 msgnum == mp->hghmsg + 1 && chgflag,
845 1, NULL, stop - start, noisy)) {
847 printf ("%*d empty\n", DMAXFOLDER, msgnum);
853 /* advise (cp, "unable to read"); already advised */
864 * Run the external program hook on the message.
867 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
868 (void)ext_hook("add-hook", b, (char *)0);
875 clear_msg_flags (mp, msgnum);
876 set_exists (mp, msgnum);
877 set_unseen (mp, msgnum);
878 mp->msgflags |= SEQMOD;
882 if (ferror(pf) || fclose (pf)) {
886 adios (cp, "write error on");
891 if (trnflag && unlink (sp) == NOTOK)
892 adios (sp, "couldn't unlink");
893 free (sp); /* Free Maildir[i]->filename */
895 free (Maildir); /* From now on Maildir is just a flag - don't dref! */
898 if (incerr < 0) { /* error */
900 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
901 (void) lkfclose (in, newmail); in = NULL;
902 DROPGROUPPRIVS(); /* And then return us to normal privileges */
904 fclose (in); in = NULL;
906 adios (NULL, "failed");
915 if ((inc_type == INC_POP) && packfile)
919 * truncate file we are incorporating from
921 if (inc_type == INC_FILE && Maildir == NULL) {
923 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
924 advise (NULL, "new messages have arrived!\007");
927 if ((newfd = creat (newmail, 0600)) != NOTOK)
930 admonish (newmail, "error zero'ing");
931 unlink(map_name(newmail));
935 printf ("%s not zero'd\n", newmail);
939 if (msgnum == hghnum) {
940 admonish (NULL, "no messages incorporated");
942 context_replace (pfolder, folder); /* update current folder */
944 mp->curmsg = hghnum + 1;
948 if (chgflag) /* sigh... */
949 seq_setcur (mp, mp->curmsg);
953 * unlock the mail spool
955 if (inc_type == INC_FILE && Maildir == NULL) {
957 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
958 (void) lkfclose (in, newmail); in = NULL;
959 DROPGROUPPRIVS(); /* And then return us to normal privileges */
961 fclose (in); in = NULL;
965 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
966 seq_save (mp); /* synchronize sequences */
967 context_save (); /* save the context file */
976 * Copy message message from spool into
977 * temporary file. Massage the "From " line
981 cpymsg (FILE *in, FILE *out)
984 char *tmpbuf, name[NAMESZ];
987 state = m_getfld (state, name, tmpbuf, rlwidth, in);
1007 inc_done (int status)
1009 if (packfile && pd != NOTOK)
1010 mbx_close (packfile, pd);
1014 lkfclose(in, newmail);
1021 pop_action (char *s)
1023 fprintf (pf, "%s\n", s);
1024 stop += strlen (s) + 1;
1025 return 0; /* Is return value used? This was missing before 1999-07-15. */
1032 char buffer[BUFSIZ];
1034 snprintf (buffer, sizeof(buffer), "%s\n", s);
1035 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1037 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1040 size += strlen (buffer) + 1;
1041 return 0; /* Is return value used? This was missing before 1999-07-15. */
1052 if (stat (packfile, &st) == NOTOK)
1054 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1055 || map_chk (cp, md, &d, (long) st.st_size, 1)) {