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[MAXPATHLEN + 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 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
251 while ((cp = *argp++)) {
253 switch (smatch (++cp, switches)) {
255 ambigsw (cp, switches);
258 adios (NULL, "-%s unknown", cp);
261 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
262 print_help (buf, switches, 1);
265 print_version(invo_name);
269 if (!(cp = *argp++) || *cp == '-')
270 adios (NULL, "missing argument to %s", argp[-2]);
271 audfile = getcpy (m_maildir (cp));
285 * The flag `trnflag' has the value:
287 * 2 if -truncate is given
288 * 1 by default (truncating is default)
289 * 0 if -notruncate is given
299 if (!(cp = *argp++) || *cp == '-')
300 adios (NULL, "missing argument to %s", argp[-2]);
301 from = path (cp, TFILE);
304 * If the truncate file is in default state,
305 * change to not truncate.
319 if (!(form = *argp++) || *form == '-')
320 adios (NULL, "missing argument to %s", argp[-2]);
324 if (!(format = *argp++) || *format == '-')
325 adios (NULL, "missing argument to %s", argp[-2]);
330 if (!(cp = *argp++) || *cp == '-')
331 adios (NULL, "missing argument to %s", argp[-2]);
336 if (!(host = *argp++) || *host == '-')
337 adios (NULL, "missing argument to %s", argp[-2]);
341 if (!(host = *argp++) || *port == '-')
342 adios (NULL, "missing argument to %s", argp[-2]);
346 if (!(user = *argp++) || *user == '-')
347 adios (NULL, "missing argument to %s", argp[-2]);
351 if (!(packfile = *argp++) || *packfile == '-')
352 adios (NULL, "missing argument to %s", argp[-2]);
367 if (!(saslmech = *argp++) || *saslmech == '-')
368 adios (NULL, "missing argument to %s", argp[-2]);
371 if (!(proxy = *argp++) || *proxy == '-')
372 adios (NULL, "missing argument to %s", argp[-2]);
376 if (*cp == '+' || *cp == '@') {
378 adios (NULL, "only one folder at a time!");
380 folder = pluspath (cp);
382 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
386 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
387 * not DROPGROUPPRIVS().
392 /* guarantee dropping group priveleges; we might not have done so earlier */
396 * Where are we getting the new mail?
406 * Are we getting the mail from
409 if (inc_type == INC_POP) {
411 user = getusername ();
413 pass = getusername ();
415 ruserpass (host, &user, &pass);
418 * initialize POP connection
420 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
422 adios (NULL, "%s", response);
424 /* Check if there are any messages */
425 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
426 adios (NULL, "%s", response);
430 adios (NULL, "no mail to incorporate");
435 * We will get the mail from a file
436 * (typically the standard maildrop)
439 if (inc_type == INC_FILE) {
442 else if ((newmail = getenv ("MAILDROP")) && *newmail)
443 newmail = m_mailpath (newmail);
444 else if ((newmail = context_find ("maildrop")) && *newmail)
445 newmail = m_mailpath (newmail);
447 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
449 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
450 adios (NULL, "no mail to incorporate");
451 if (s1.st_mode & S_IFDIR) {
457 cp = concat (newmail, "/new", NULL);
458 if ((md = opendir(cp)) == NULL)
459 adios (NULL, "unable to open %s", cp);
460 while ((de = readdir (md)) != NULL) {
461 if (de->d_name[0] == '.')
463 if (i >= num_maildir_entries) {
464 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
465 adios(NULL, "not enough memory for %d messages", 2*i+16);
466 num_maildir_entries = 2*i+16;
468 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
469 if (stat(Maildir[i].filename, &ms) != 0)
470 adios (Maildir[i].filename, "couldn't get delivery time");
471 Maildir[i].mtime = ms.st_mtime;
476 cp = concat (newmail, "/cur", NULL);
477 if ((md = opendir(cp)) == NULL)
478 adios (NULL, "unable to open %s", cp);
479 while ((de = readdir (md)) != NULL) {
480 if (de->d_name[0] == '.')
482 if (i >= num_maildir_entries) {
483 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
484 adios(NULL, "not enough memory for %d messages", 2*i+16);
485 num_maildir_entries = 2*i+16;
487 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
488 if (stat(Maildir[i].filename, &ms) != 0)
489 adios (Maildir[i].filename, "couldn't get delivery time");
490 Maildir[i].mtime = ms.st_mtime;
496 adios (NULL, "no mail to incorporate");
497 num_maildir_entries = i;
498 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
501 if ((cp = strdup(newmail)) == (char *)0)
502 adios (NULL, "error allocating memory to copy newmail");
507 /* skip the folder setup */
508 if ((inc_type == INC_POP) && packfile)
511 if (!context_find ("path"))
512 free (path ("./", TFOLDER));
514 folder = getfolder (0);
515 maildir = m_maildir (folder);
517 if ((maildir_copy = strdup(maildir)) == (char *)0)
518 adios (maildir, "error allocating memory to copy maildir");
520 if (!folder_exists(maildir)) {
521 /* If the folder doesn't exist, and we're given the -silent flag,
525 create_folder(maildir, 0, done);
530 if (chdir (maildir) == NOTOK)
531 adios (maildir, "unable to change directory to");
533 /* read folder and create message structure */
534 if (!(mp = folder_read (folder)))
535 adios (NULL, "unable to read folder %s", folder);
539 if (inc_type == INC_FILE && Maildir == NULL) {
540 if (access (newmail, W_OK) != NOTOK) {
543 SIGNAL (SIGHUP, SIG_IGN);
544 SIGNAL (SIGINT, SIG_IGN);
545 SIGNAL (SIGQUIT, SIG_IGN);
546 SIGNAL (SIGTERM, SIG_IGN);
549 GETGROUPPRIVS(); /* Reset gid to lock mail file */
550 in = lkfopen (newmail, "r");
553 adios (NULL, "unable to lock and fopen %s", newmail);
554 fstat (fileno(in), &s1);
557 if ((in = fopen (newmail, "r")) == NULL)
558 adios (newmail, "unable to read");
562 /* This shouldn't be necessary but it can't hurt. */
567 if ((i = stat (audfile, &st)) == NOTOK)
568 advise (NULL, "Creating Receive-Audit: %s", audfile);
569 if ((aud = fopen (audfile, "a")) == NULL)
570 adios (audfile, "unable to append to");
572 chmod (audfile, m_gmprot ());
574 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
575 : host ? "<<inc>> %s -host %s -user %s\n"
577 dtimenow (0), from ? from : host, user);
580 /* Get new format string */
581 nfs = new_fs (form, format, FORMAT);
584 printf ("Incorporating new mail into %s...\n\n", folder);
589 * Get the mail from a POP server
591 if (inc_type == INC_POP) {
594 packfile = path (packfile, TFILE);
595 if (stat (packfile, &st) == NOTOK) {
597 adios (packfile, "error on file");
598 cp = concat ("Create file \"", packfile, "\"? ", NULL);
599 if (noisy && !getanswer (cp))
603 msgnum = map_count ();
604 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
606 adios (packfile, "unable to open");
607 if ((pf = fdopen (pd, "w+")) == NULL)
608 adios (NULL, "unable to fdopen %s", packfile);
610 hghnum = msgnum = mp->hghmsg;
612 * Check if we have enough message space for all the new
613 * messages. If not, then realloc the folder and add enough
614 * space for all new messages plus 10 additional slots.
616 if (mp->hghmsg + nmsgs >= mp->hghoff
617 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
618 adios (NULL, "unable to allocate folder storage");
621 for (i = 1; i <= nmsgs; i++) {
624 fseek (pf, 0L, SEEK_CUR);
627 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
630 if (pop_retr (i, pop_pack) == NOTOK)
631 adios (NULL, "%s", response);
633 fseek (pf, 0L, SEEK_CUR);
636 adios (packfile, "write error on");
637 fseek (pf, start, SEEK_SET);
639 cp = getcpy (m_name (msgnum));
640 if ((pf = fopen (cp, "w+")) == NULL)
641 adios (cp, "unable to write");
642 chmod (cp, m_gmprot ());
645 if (pop_retr (i, pop_action) == NOTOK)
646 adios (NULL, "%s", response);
649 adios (cp, "write error on");
650 fseek (pf, 0L, SEEK_SET);
652 switch (incerr = scan (pf, msgnum, 0, nfs, width,
653 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
654 1, NULL, stop - start, noisy)) {
656 printf ("%*d empty\n", DMAXFOLDER, msgnum);
662 /* advise (cp, "unable to read"); already advised */
677 clear_msg_flags (mp, msgnum);
678 set_exists (mp, msgnum);
679 set_unseen (mp, msgnum);
680 mp->msgflags |= SEQMOD;
685 fseek (pf, stop, SEEK_SET);
686 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
687 if (fflush (pf) || ferror (pf)) {
691 adios (packfile, "write error on");
693 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
695 if (ferror(pf) || fclose (pf)) {
700 adios (cp, "write error on");
705 if (trnflag && pop_dele (i) == NOTOK)
706 adios (NULL, "%s", response);
709 if (pop_quit () == NOTOK)
710 adios (NULL, "%s", response);
712 mbx_close (packfile, pd);
718 * Get the mail from file (usually mail spool)
720 if (inc_type == INC_FILE && Maildir == NULL) {
721 m_unknown (in); /* the MAGIC invocation... */
722 hghnum = msgnum = mp->hghmsg;
725 * Check if we need to allocate more space for message status.
726 * If so, then add space for an additional 100 messages.
728 if (msgnum >= mp->hghoff
729 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
730 advise (NULL, "unable to allocate folder storage");
736 /* copy file from spool to tmp file */
737 tmpfilenam = m_scratch ("", invo_name);
738 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
739 adios (tmpfilenam, "unable to create");
740 chmod (tmpfilenam, m_gmprot ());
741 if (!(in2 = fdopen (fd, "r+")))
742 adios (tmpfilenam, "unable to access");
745 /* link message into folder */
746 newmsg = folder_addmsg(mp, tmpfilenam);
748 /* create scanline for new message */
749 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
750 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
757 fputs ("inc aborted!\n", aud);
758 advise (NULL, "aborted!"); /* doesn't clean up locks! */
762 advise (NULL, "BUG in %s, number out of range", invo_name);
766 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
772 * Run the external program hook on the message.
775 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
776 (void)ext_hook("add-hook", b, (char *)0);
786 if (mp->lowmsg == 0) mp->lowmsg = 1;
788 clear_msg_flags (mp, msgnum);
789 set_exists (mp, msgnum);
790 set_unseen (mp, msgnum);
791 mp->msgflags |= SEQMOD;
794 /* If we get here there was some sort of error from scan(),
795 * so stop processing anything more from the spool.
799 } else if (inc_type == INC_FILE) { /* Maildir inbox to process */
804 hghnum = msgnum = mp->hghmsg;
805 for (i = 0; i < num_maildir_entries; i++) {
808 * Check if we need to allocate more space for message status.
809 * If so, then add space for an additional 100 messages.
811 if (msgnum >= mp->hghoff
812 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
813 advise (NULL, "unable to allocate folder storage");
818 sp = Maildir[i].filename;
819 cp = getcpy (m_name (msgnum));
821 if (!trnflag || link(sp, cp) == -1) {
822 static char buf[65536];
825 if ((sf = fopen (sp, "r")) == NULL)
826 adios (sp, "unable to read for copy");
827 if ((pf = fopen (cp, "w+")) == NULL)
828 adios (cp, "unable to write for copy");
829 while ((nrd = fread(buf, 1, sizeof(buf), sf)) > 0)
830 if (fwrite(buf, 1, nrd, pf) != nrd)
832 if (ferror(sf) || fflush(pf) || ferror(pf)) {
834 fclose(pf); fclose(sf); unlink(cp);
836 adios(cp, "copy error %s -> %s", sp, cp);
841 if (pf == NULL && (pf = fopen (cp, "r")) == NULL)
842 adios (cp, "not available");
843 chmod (cp, m_gmprot ());
845 fseek (pf, 0L, SEEK_SET);
846 switch (incerr = scan (pf, msgnum, 0, nfs, width,
847 msgnum == mp->hghmsg + 1 && chgflag,
848 1, NULL, stop - start, noisy)) {
850 printf ("%*d empty\n", DMAXFOLDER, msgnum);
856 /* advise (cp, "unable to read"); already advised */
867 * Run the external program hook on the message.
870 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
871 (void)ext_hook("add-hook", b, (char *)0);
878 clear_msg_flags (mp, msgnum);
879 set_exists (mp, msgnum);
880 set_unseen (mp, msgnum);
881 mp->msgflags |= SEQMOD;
885 if (ferror(pf) || fclose (pf)) {
889 adios (cp, "write error on");
894 if (trnflag && unlink (sp) == NOTOK)
895 adios (sp, "couldn't unlink");
896 free (sp); /* Free Maildir[i]->filename */
898 free (Maildir); /* From now on Maildir is just a flag - don't dref! */
901 if (incerr < 0) { /* error */
903 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
904 (void) lkfclose (in, newmail); in = NULL;
905 DROPGROUPPRIVS(); /* And then return us to normal privileges */
907 fclose (in); in = NULL;
909 adios (NULL, "failed");
918 if ((inc_type == INC_POP) && packfile)
922 * truncate file we are incorporating from
924 if (inc_type == INC_FILE && Maildir == NULL) {
926 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
927 advise (NULL, "new messages have arrived!\007");
930 if ((newfd = creat (newmail, 0600)) != NOTOK)
933 admonish (newmail, "error zero'ing");
934 unlink(map_name(newmail));
938 printf ("%s not zero'd\n", newmail);
942 if (msgnum == hghnum) {
943 admonish (NULL, "no messages incorporated");
945 context_replace (pfolder, folder); /* update current folder */
947 mp->curmsg = hghnum + 1;
951 if (chgflag) /* sigh... */
952 seq_setcur (mp, mp->curmsg);
956 * unlock the mail spool
958 if (inc_type == INC_FILE && Maildir == NULL) {
960 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
961 (void) lkfclose (in, newmail); in = NULL;
962 DROPGROUPPRIVS(); /* And then return us to normal privileges */
964 fclose (in); in = NULL;
968 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
969 seq_save (mp); /* synchronize sequences */
970 context_save (); /* save the context file */
979 * Copy message message from spool into
980 * temporary file. Massage the "From " line
984 cpymsg (FILE *in, FILE *out)
987 char *tmpbuf, name[NAMESZ];
990 state = m_getfld (state, name, tmpbuf, rlwidth, in);
1010 inc_done (int status)
1012 if (packfile && pd != NOTOK)
1013 mbx_close (packfile, pd);
1017 lkfclose(in, newmail);
1024 pop_action (char *s)
1026 fprintf (pf, "%s\n", s);
1027 stop += strlen (s) + 1;
1028 return 0; /* Is return value used? This was missing before 1999-07-15. */
1035 char buffer[BUFSIZ];
1037 snprintf (buffer, sizeof(buffer), "%s\n", s);
1038 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1040 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1043 size += strlen (buffer) + 1;
1044 return 0; /* Is return value used? This was missing before 1999-07-15. */
1055 if (stat (packfile, &st) == NOTOK)
1057 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1058 || map_chk (cp, md, &d, (long) st.st_size, 1)) {