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 { "nosasl", SASLminc(-6) },
95 { "saslmech", SASLminc(-8) },
97 { "proxy command", 0 },
102 * flags for the mail source
108 static struct Maildir_entry {
112 static int num_maildir_entries = 0;
113 static int snoop = 0;
115 extern char response[];
120 static int mbx_style = MMDF_FORMAT;
121 static int pd = NOTOK;
126 static char *packfile = NULL;
127 static FILE *pf = NULL;
129 /* This is an attempt to simplify things by putting all the
130 * privilege ops into macros.
131 * *GROUPPRIVS() is related to handling the setgid MAIL property,
132 * and only applies if MAILGROUP is defined.
133 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
134 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
135 * do the obvious thing.
137 * There's probably a better implementation if we're allowed to use
138 * BSD-style setreuid() rather than using POSIX saved-ids.
139 * Anyway, if you're euid root it's a bit pointless to drop the group
142 * I'm pretty happy that the security is good provided we aren't setuid root.
143 * The only things we trust with group=mail privilege are lkfopen()
148 * For setting and returning to "mail" gid
151 static int return_gid;
152 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
153 #define DROPGROUPPRIVS() setgid(getgid())
154 #define GETGROUPPRIVS() setgid(return_gid)
155 #define SAVEGROUPPRIVS() return_gid = getegid()
157 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
158 #define TRYDROPGROUPPRIVS()
159 #define DROPGROUPPRIVS()
160 #define GETGROUPPRIVS()
161 #define SAVEGROUPPRIVS()
162 #endif /* not MAILGROUP */
164 /* these variables have to be globals so that done() can correctly clean up the lockfile */
165 static int locked = 0;
166 static char *newmail;
172 char *map_name(char *);
174 static void inc_done(int) NORETURN;
175 static int pop_action(char *);
176 static int pop_pack(char *);
177 static int map_count(void);
180 maildir_srt(const void *va, const void *vb)
182 const struct Maildir_entry *a = va, *b = vb;
183 if (a->mtime > b->mtime)
185 else if (a->mtime < b->mtime)
192 main (int argc, char **argv)
194 int chgflag = 1, trnflag = 1;
195 int noisy = 1, width = 0;
196 int hghnum = 0, msgnum = 0;
198 int incerr = 0; /* <0 if inc hits an error which means it should not truncate mailspool */
199 char *cp, *maildir = NULL, *folder = NULL;
200 char *format = NULL, *form = NULL;
201 char *host = NULL, *port = NULL, *user = NULL, *proxy = NULL;
202 char *audfile = NULL, *from = NULL, *saslmech = NULL;
203 char buf[BUFSIZ], **argp, *nfs, **arguments;
204 struct msgs *mp = NULL;
207 char b[PATH_MAX + 1];
208 char *maildir_copy = NULL; /* copy of mail directory because the static gets overwritten */
212 char *MAILHOST_env_variable;
216 /* absolutely the first thing we do is save our privileges,
217 * and drop them if we can.
223 setlocale(LC_ALL, "");
225 invo_name = r1bindex (argv[0], '/');
227 /* read user profile/context */
230 mts_init (invo_name);
231 arguments = getarguments (invo_name, argc, argv, 1);
236 * use MAILHOST environment variable if present,
238 * If that fails, use the default (if any)
239 * provided by mts.conf in mts_init()
241 if ((MAILHOST_env_variable = getenv("MAILHOST")) != NULL)
242 pophost = MAILHOST_env_variable;
244 * If there is a valid "pophost" entry in mts.conf,
245 * then use it as the default host.
247 if (pophost && *pophost)
250 while ((cp = *argp++)) {
252 switch (smatch (++cp, switches)) {
254 ambigsw (cp, switches);
257 adios (NULL, "-%s unknown", cp);
260 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
261 print_help (buf, switches, 1);
264 print_version(invo_name);
268 if (!(cp = *argp++) || *cp == '-')
269 adios (NULL, "missing argument to %s", argp[-2]);
270 audfile = getcpy (m_maildir (cp));
284 * The flag `trnflag' has the value:
286 * 2 if -truncate is given
287 * 1 by default (truncating is default)
288 * 0 if -notruncate is given
298 if (!(cp = *argp++) || *cp == '-')
299 adios (NULL, "missing argument to %s", argp[-2]);
300 from = path (cp, TFILE);
303 * If the truncate file is in default state,
304 * change to not truncate.
318 if (!(form = *argp++) || *form == '-')
319 adios (NULL, "missing argument to %s", argp[-2]);
323 if (!(format = *argp++) || *format == '-')
324 adios (NULL, "missing argument to %s", argp[-2]);
329 if (!(cp = *argp++) || *cp == '-')
330 adios (NULL, "missing argument to %s", argp[-2]);
335 if (!(host = *argp++) || *host == '-')
336 adios (NULL, "missing argument to %s", argp[-2]);
340 if (!(port = *argp++) || *port == '-')
341 adios (NULL, "missing argument to %s", argp[-2]);
345 if (!(user = *argp++) || *user == '-')
346 adios (NULL, "missing argument to %s", argp[-2]);
350 if (!(packfile = *argp++) || *packfile == '-')
351 adios (NULL, "missing argument to %s", argp[-2]);
369 if (!(saslmech = *argp++) || *saslmech == '-')
370 adios (NULL, "missing argument to %s", argp[-2]);
373 if (!(proxy = *argp++) || *proxy == '-')
374 adios (NULL, "missing argument to %s", argp[-2]);
378 if (*cp == '+' || *cp == '@') {
380 adios (NULL, "only one folder at a time!");
382 folder = pluspath (cp);
384 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
388 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
389 * not DROPGROUPPRIVS().
394 /* guarantee dropping group priveleges; we might not have done so earlier */
398 * Where are we getting the new mail?
408 * Are we getting the mail from
411 if (inc_type == INC_POP) {
413 user = getusername ();
415 pass = getusername ();
417 ruserpass (host, &user, &pass);
420 * initialize POP connection
422 if (pop_init (host, port, user, pass, proxy, snoop, sasl,
424 adios (NULL, "%s", response);
426 /* Check if there are any messages */
427 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
428 adios (NULL, "%s", response);
432 adios (NULL, "no mail to incorporate");
437 * We will get the mail from a file
438 * (typically the standard maildrop)
441 if (inc_type == INC_FILE) {
444 else if ((newmail = getenv ("MAILDROP")) && *newmail)
445 newmail = m_mailpath (newmail);
446 else if ((newmail = context_find ("maildrop")) && *newmail)
447 newmail = m_mailpath (newmail);
449 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
451 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
452 adios (NULL, "no mail to incorporate");
453 if (s1.st_mode & S_IFDIR) {
459 cp = concat (newmail, "/new", NULL);
460 if ((md = opendir(cp)) == NULL)
461 adios (NULL, "unable to open %s", cp);
462 while ((de = readdir (md)) != NULL) {
463 if (de->d_name[0] == '.')
465 if (i >= num_maildir_entries) {
466 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
467 adios(NULL, "not enough memory for %d messages", 2*i+16);
468 num_maildir_entries = 2*i+16;
470 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
471 if (stat(Maildir[i].filename, &ms) != 0)
472 adios (Maildir[i].filename, "couldn't get delivery time");
473 Maildir[i].mtime = ms.st_mtime;
478 cp = concat (newmail, "/cur", NULL);
479 if ((md = opendir(cp)) == NULL)
480 adios (NULL, "unable to open %s", cp);
481 while ((de = readdir (md)) != NULL) {
482 if (de->d_name[0] == '.')
484 if (i >= num_maildir_entries) {
485 if ((Maildir = realloc(Maildir, sizeof(*Maildir) * (2*i+16))) == NULL)
486 adios(NULL, "not enough memory for %d messages", 2*i+16);
487 num_maildir_entries = 2*i+16;
489 Maildir[i].filename = concat (cp, "/", de->d_name, NULL);
490 if (stat(Maildir[i].filename, &ms) != 0)
491 adios (Maildir[i].filename, "couldn't get delivery time");
492 Maildir[i].mtime = ms.st_mtime;
498 adios (NULL, "no mail to incorporate");
499 num_maildir_entries = i;
500 qsort (Maildir, num_maildir_entries, sizeof(*Maildir), maildir_srt);
503 if ((cp = strdup(newmail)) == (char *)0)
504 adios (NULL, "error allocating memory to copy newmail");
509 /* skip the folder setup */
510 if ((inc_type == INC_POP) && packfile)
513 if (!context_find ("path"))
514 free (path ("./", TFOLDER));
516 folder = getfolder (0);
517 maildir = m_maildir (folder);
519 if ((maildir_copy = strdup(maildir)) == (char *)0)
520 adios (maildir, "error allocating memory to copy maildir");
522 if (!folder_exists(maildir)) {
523 /* If the folder doesn't exist, and we're given the -silent flag,
527 create_folder(maildir, 0, done);
532 if (chdir (maildir) == NOTOK)
533 adios (maildir, "unable to change directory to");
535 /* read folder and create message structure */
536 if (!(mp = folder_read (folder)))
537 adios (NULL, "unable to read folder %s", folder);
541 if (inc_type == INC_FILE && Maildir == NULL) {
542 if (access (newmail, W_OK) != NOTOK) {
545 SIGNAL (SIGHUP, SIG_IGN);
546 SIGNAL (SIGINT, SIG_IGN);
547 SIGNAL (SIGQUIT, SIG_IGN);
548 SIGNAL (SIGTERM, SIG_IGN);
551 GETGROUPPRIVS(); /* Reset gid to lock mail file */
552 in = lkfopen (newmail, "r");
555 adios (NULL, "unable to lock and fopen %s", newmail);
556 fstat (fileno(in), &s1);
559 if ((in = fopen (newmail, "r")) == NULL)
560 adios (newmail, "unable to read");
564 /* This shouldn't be necessary but it can't hurt. */
569 if ((i = stat (audfile, &st)) == NOTOK)
570 advise (NULL, "Creating Receive-Audit: %s", audfile);
571 if ((aud = fopen (audfile, "a")) == NULL)
572 adios (audfile, "unable to append to");
574 chmod (audfile, m_gmprot ());
576 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
577 : host ? "<<inc>> %s -host %s -user %s\n"
579 dtimenow (0), from ? from : host, user);
582 /* Get new format string */
583 nfs = new_fs (form, format, FORMAT);
586 printf ("Incorporating new mail into %s...\n\n", folder);
591 * Get the mail from a POP server
593 if (inc_type == INC_POP) {
596 packfile = path (packfile, TFILE);
597 if (stat (packfile, &st) == NOTOK) {
599 adios (packfile, "error on file");
600 cp = concat ("Create file \"", packfile, "\"? ", NULL);
601 if (noisy && !getanswer (cp))
605 msgnum = map_count ();
606 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
608 adios (packfile, "unable to open");
609 if ((pf = fdopen (pd, "w+")) == NULL)
610 adios (NULL, "unable to fdopen %s", packfile);
612 hghnum = msgnum = mp->hghmsg;
614 * Check if we have enough message space for all the new
615 * messages. If not, then realloc the folder and add enough
616 * space for all new messages plus 10 additional slots.
618 if (mp->hghmsg + nmsgs >= mp->hghoff
619 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
620 adios (NULL, "unable to allocate folder storage");
623 for (i = 1; i <= nmsgs; i++) {
626 fseek (pf, 0L, SEEK_CUR);
629 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
632 if (pop_retr (i, pop_pack) == NOTOK)
633 adios (NULL, "%s", response);
635 fseek (pf, 0L, SEEK_CUR);
638 adios (packfile, "write error on");
639 fseek (pf, start, SEEK_SET);
641 cp = getcpy (m_name (msgnum));
642 if ((pf = fopen (cp, "w+")) == NULL)
643 adios (cp, "unable to write");
644 chmod (cp, m_gmprot ());
647 if (pop_retr (i, pop_action) == NOTOK)
648 adios (NULL, "%s", response);
651 adios (cp, "write error on");
652 fseek (pf, 0L, SEEK_SET);
654 switch (incerr = scan (pf, msgnum, 0, nfs, width,
655 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
656 1, NULL, stop - start, noisy)) {
658 printf ("%*d empty\n", DMAXFOLDER, msgnum);
664 /* advise (cp, "unable to read"); already advised */
679 clear_msg_flags (mp, msgnum);
680 set_exists (mp, msgnum);
681 set_unseen (mp, msgnum);
682 mp->msgflags |= SEQMOD;
687 fseek (pf, stop, SEEK_SET);
688 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
689 if (fflush (pf) || ferror (pf)) {
693 adios (packfile, "write error on");
695 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
697 if (ferror(pf) || fclose (pf)) {
702 adios (cp, "write error on");
707 if (trnflag && pop_dele (i) == NOTOK)
708 adios (NULL, "%s", response);
711 if (pop_quit () == NOTOK)
712 adios (NULL, "%s", response);
714 mbx_close (packfile, pd);
720 * Get the mail from file (usually mail spool)
722 if (inc_type == INC_FILE && Maildir == NULL) {
723 m_unknown (in); /* the MAGIC invocation... */
724 hghnum = msgnum = mp->hghmsg;
727 * Check if we need to allocate more space for message status.
728 * If so, then add space for an additional 100 messages.
730 if (msgnum >= mp->hghoff
731 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
732 advise (NULL, "unable to allocate folder storage");
738 /* copy file from spool to tmp file */
739 tmpfilenam = m_scratch ("", invo_name);
740 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
741 adios (tmpfilenam, "unable to create");
742 chmod (tmpfilenam, m_gmprot ());
743 if (!(in2 = fdopen (fd, "r+")))
744 adios (tmpfilenam, "unable to access");
747 /* link message into folder */
748 newmsg = folder_addmsg(mp, tmpfilenam);
750 /* create scanline for new message */
751 switch (incerr = scan (in, msgnum + 1, msgnum + 1, nfs, width,
752 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
759 fputs ("inc aborted!\n", aud);
760 advise (NULL, "aborted!"); /* doesn't clean up locks! */
764 advise (NULL, "BUG in %s, number out of range", invo_name);
768 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, incerr);
774 * Run the external program hook on the message.
777 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
778 (void)ext_hook("add-hook", b, (char *)0);
788 if (mp->lowmsg == 0) mp->lowmsg = 1;
790 clear_msg_flags (mp, msgnum);
791 set_exists (mp, msgnum);
792 set_unseen (mp, msgnum);
793 mp->msgflags |= SEQMOD;
796 /* If we get here there was some sort of error from scan(),
797 * so stop processing anything more from the spool.
801 } else if (inc_type == INC_FILE) { /* Maildir inbox to process */
806 hghnum = msgnum = mp->hghmsg;
807 for (i = 0; i < num_maildir_entries; i++) {
810 * Check if we need to allocate more space for message status.
811 * If so, then add space for an additional 100 messages.
813 if (msgnum >= mp->hghoff
814 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
815 advise (NULL, "unable to allocate folder storage");
820 sp = Maildir[i].filename;
821 cp = getcpy (m_name (msgnum));
823 if (!trnflag || link(sp, cp) == -1) {
824 static char buf[65536];
827 if ((sf = fopen (sp, "r")) == NULL)
828 adios (sp, "unable to read for copy");
829 if ((pf = fopen (cp, "w+")) == NULL)
830 adios (cp, "unable to write for copy");
831 while ((nrd = fread(buf, 1, sizeof(buf), sf)) > 0)
832 if (fwrite(buf, 1, nrd, pf) != nrd)
834 if (ferror(sf) || fflush(pf) || ferror(pf)) {
836 fclose(pf); fclose(sf); unlink(cp);
838 adios(cp, "copy error %s -> %s", sp, cp);
843 if (pf == NULL && (pf = fopen (cp, "r")) == NULL)
844 adios (cp, "not available");
845 chmod (cp, m_gmprot ());
847 fseek (pf, 0L, SEEK_SET);
848 switch (incerr = scan (pf, msgnum, 0, nfs, width,
849 msgnum == mp->hghmsg + 1 && chgflag,
850 1, NULL, stop - start, noisy)) {
852 printf ("%*d empty\n", DMAXFOLDER, msgnum);
858 /* advise (cp, "unable to read"); already advised */
869 * Run the external program hook on the message.
872 (void)snprintf(b, sizeof (b), "%s/%d", maildir_copy, msgnum + 1);
873 (void)ext_hook("add-hook", b, (char *)0);
880 clear_msg_flags (mp, msgnum);
881 set_exists (mp, msgnum);
882 set_unseen (mp, msgnum);
883 mp->msgflags |= SEQMOD;
887 if (ferror(pf) || fclose (pf)) {
891 adios (cp, "write error on");
896 if (trnflag && unlink (sp) == NOTOK)
897 adios (sp, "couldn't unlink");
898 free (sp); /* Free Maildir[i]->filename */
900 free (Maildir); /* From now on Maildir is just a flag - don't dref! */
903 if (incerr < 0) { /* error */
905 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
906 (void) lkfclose (in, newmail); in = NULL;
907 DROPGROUPPRIVS(); /* And then return us to normal privileges */
909 fclose (in); in = NULL;
911 adios (NULL, "failed");
920 if ((inc_type == INC_POP) && packfile)
924 * truncate file we are incorporating from
926 if (inc_type == INC_FILE && Maildir == NULL) {
928 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
929 advise (NULL, "new messages have arrived!\007");
932 if ((newfd = creat (newmail, 0600)) != NOTOK)
935 admonish (newmail, "error zero'ing");
936 unlink(map_name(newmail));
940 printf ("%s not zero'd\n", newmail);
944 if (msgnum == hghnum) {
945 admonish (NULL, "no messages incorporated");
947 context_replace (pfolder, folder); /* update current folder */
949 mp->curmsg = hghnum + 1;
953 if (chgflag) /* sigh... */
954 seq_setcur (mp, mp->curmsg);
958 * unlock the mail spool
960 if (inc_type == INC_FILE && Maildir == NULL) {
962 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
963 (void) lkfclose (in, newmail); in = NULL;
964 DROPGROUPPRIVS(); /* And then return us to normal privileges */
966 fclose (in); in = NULL;
970 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
971 seq_save (mp); /* synchronize sequences */
972 context_save (); /* save the context file */
981 * Copy message message from spool into
982 * temporary file. Massage the "From " line
986 cpymsg (FILE *in, FILE *out)
989 char *tmpbuf, name[NAMESZ];
992 state = m_getfld (state, name, tmpbuf, rlwidth, in);
1012 inc_done (int status)
1014 if (packfile && pd != NOTOK)
1015 mbx_close (packfile, pd);
1019 lkfclose(in, newmail);
1026 pop_action (char *s)
1028 fprintf (pf, "%s\n", s);
1029 stop += strlen (s) + 1;
1030 return 0; /* Is return value used? This was missing before 1999-07-15. */
1037 char buffer[BUFSIZ];
1039 snprintf (buffer, sizeof(buffer), "%s\n", s);
1040 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
1042 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
1045 size += strlen (buffer) + 1;
1046 return 0; /* Is return value used? This was missing before 1999-07-15. */
1057 if (stat (packfile, &st) == NOTOK)
1059 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
1060 || map_chk (cp, md, &d, (long) st.st_size, 1)) {