3 * inc.c -- incorporate messages from a maildrop into a folder
9 /* Revised: Sat Apr 14 17:08:17 PDT 1990 (marvit@hplabs)
10 * Added hpux hacks to set and reset gid to be "mail" as needed. The reset
11 * is necessary so inc'ed mail is the group of the inc'er, rather than
12 * "mail". We setgid to egid only when [un]locking the mail file. This
13 * is also a major security precaution which will not be explained here.
15 * Fri Feb 7 16:04:57 PST 1992 John Romine <bug-mh@ics.uci.edu>
16 * NB: I'm not 100% sure that this setgid stuff is secure even now.
18 * See the *GROUPPRIVS() macros later. I'm reasonably happy with the setgid
19 * attribute. Running setuid root is probably not a terribly good idea, though.
20 * -- Peter Maydell <pmaydell@chiark.greenend.org.uk>, 04/1998
22 * Peter Maydell's patch slightly modified for nmh 0.28-pre2.
23 * Ruud de Rooij <ruud@debian.org> Wed, 22 Jul 1998 13:24:22 +0200
31 # include <h/dropsbr.h>
32 # include <h/popsbr.h>
39 #include <h/fmt_scan.h>
40 #include <h/scansbr.h>
41 #include <h/signals.h>
43 #include <zotnet/mts/mts.h>
48 # define POPminc(a) (a)
54 # define RPOPminc(a) (a)
56 # define RPOPminc(a) 0
60 # define APOPminc(a) (a)
62 # define APOPminc(a) 0
66 # define KPOPminc(a) (a)
68 # define KPOPminc(a) 0
71 static struct swit switches[] = {
73 { "audit audit-file", 0 },
83 { "form formatfile", 0 },
85 { "format string", 5 },
87 { "host hostname", POPminc (-4) },
89 { "user username", POPminc (-4) },
91 { "pack file", POPminc (-4) },
93 { "nopack", POPminc (-6) },
95 { "apop", APOPminc (-4) },
97 { "noapop", APOPminc (-6) },
99 { "rpop", RPOPminc (-4) },
101 { "norpop", RPOPminc (-6) },
111 { "width columns", 0 },
119 { "kpop", KPOPminc (-4) },
126 * flags for the mail source
132 static int snoop = 0;
135 extern char response[];
137 static char *packfile = NULL;
143 static int mbx_style = MMDF_FORMAT;
144 static int pd = NOTOK;
145 static FILE *pf = NULL;
148 /* This is an attempt to simplify things by putting all the
149 * privilege ops into macros.
150 * *GROUPPRIVS() is related to handling the setgid MAIL property,
151 * and only applies if MAILGROUP is defined.
152 * *USERPRIVS() is related to handling the setuid root property,
153 * and only applies if POP is defined [why does POP => setuid root?]
154 * Basically, SAVEGROUPPRIVS() is called right at the top of main()
155 * to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
156 * do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
157 * before DROPUSERPRIVS() is called [this is needed because setgid()
158 * sets both effective and real uids if euid is root.]
160 * There's probably a better implementation if we're allowed to use
161 * BSD-style setreuid() rather than using POSIX saved-ids.
162 * Anyway, if you're euid root it's a bit pointless to drop the group
165 * I'm pretty happy that the security is good provided we aren't setuid root.
166 * The only things we trust with group=mail privilege are lkfopen()
171 * For setting and returning to "mail" gid
174 static int return_gid;
176 /* easy case; we're not setuid root, so can drop group privs
179 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
180 #else /* POP ie we are setuid root */
181 #define TRYDROPGROUPPRIVS() \
182 if (geteuid() != 0) DROPGROUPPRIVS()
184 #define DROPGROUPPRIVS() setgid(getgid())
185 #define GETGROUPPRIVS() setgid(return_gid)
186 #define SAVEGROUPPRIVS() return_gid = getegid()
188 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
189 #define TRYDROPGROUPPRIVS()
190 #define DROPGROUPPRIVS()
191 #define GETGROUPPRIVS()
192 #define SAVEGROUPPRIVS()
193 #endif /* not MAILGROUP */
196 #define DROPUSERPRIVS() setuid(getuid())
198 #define DROPUSERPRIVS()
201 /* these variables have to be globals so that done() can correctly clean up the lockfile */
202 static int locked = 0;
203 static char *newmail;
209 char *map_name(char *);
213 static int pop_action(char *);
214 static int pop_pack(char *);
215 static int map_count(void);
220 main (int argc, char **argv)
222 int chgflag = 1, trnflag = 1;
223 int noisy = 1, width = 0;
224 int rpop, i, hghnum, msgnum;
226 char *cp, *maildir, *folder = NULL;
227 char *format = NULL, *form = NULL;
228 char *host = NULL, *user = NULL;
229 char *audfile = NULL, *from = NULL;
230 char buf[BUFSIZ], **argp, *nfs, **arguments;
236 int nmsgs, nbytes, p = 0;
245 struct hes_postoffice *po;
249 /* absolutely the first thing we do is save our privileges,
250 * and drop them if we can.
256 setlocale(LC_ALL, "");
258 invo_name = r1bindex (argv[0], '/');
260 /* read user profile/context */
263 mts_init (invo_name);
264 arguments = getarguments (invo_name, argc, argv, 1);
271 * use MAILHOST environment variable if present,
273 * If that fails, use the default (if any)
274 * provided by mts.conf in mts_init()
276 if ((tmphost = getenv("MAILHOST")) != NULL)
278 else if ((po = hes_getmailhost(getusername())) != NULL &&
279 strcmp(po->po_type, "POP") == 0)
280 pophost = po->po_host;
283 * If there is a valid "pophost" entry in mts.conf,
284 * then use it as the default host.
286 if (pophost && *pophost)
289 if ((cp = getenv ("MHPOPDEBUG")) && *cp)
295 while ((cp = *argp++)) {
297 switch (smatch (++cp, switches)) {
299 ambigsw (cp, switches);
302 adios (NULL, "-%s unknown", cp);
305 snprintf (buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
306 print_help (buf, switches, 1);
309 print_version(invo_name);
313 if (!(cp = *argp++) || *cp == '-')
314 adios (NULL, "missing argument to %s", argp[-2]);
315 audfile = getcpy (m_maildir (cp));
329 * The flag `trnflag' has the value:
331 * 2 if -truncate is given
332 * 1 by default (truncating is default)
333 * 0 if -notruncate is given
343 if (!(cp = *argp++) || *cp == '-')
344 adios (NULL, "missing argument to %s", argp[-2]);
345 from = path (cp, TFILE);
348 * If the truncate file is in default state,
349 * change to not truncate.
363 if (!(form = *argp++) || *form == '-')
364 adios (NULL, "missing argument to %s", argp[-2]);
368 if (!(format = *argp++) || *format == '-')
369 adios (NULL, "missing argument to %s", argp[-2]);
374 if (!(cp = *argp++) || *cp == '-')
375 adios (NULL, "missing argument to %s", argp[-2]);
380 if (!(host = *argp++) || *host == '-')
381 adios (NULL, "missing argument to %s", argp[-2]);
384 if (!(user = *argp++) || *user == '-')
385 adios (NULL, "missing argument to %s", argp[-2]);
390 if (!(cp = *argp++) || *cp == '-')
391 adios (NULL, "missing argument to %s", argp[-2]);
393 if (!(packfile = *argp++) || *packfile == '-')
394 adios (NULL, "missing argument to %s", argp[-2]);
426 if (*cp == '+' || *cp == '@') {
428 adios (NULL, "only one folder at a time!");
430 folder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
432 adios (NULL, "usage: %s [+folder] [switches]", invo_name);
436 /* NOTE: above this point you should use TRYDROPGROUPPRIVS(),
437 * not DROPGROUPPRIVS().
442 if (from || !host || rpop <= 0)
446 /* guarantee dropping group priveleges; we might not have done so earlier */
450 * Where are we getting the new mail?
463 * Are we getting the mail from
466 if (inc_type == INC_POP) {
468 user = getusername ();
469 if ( strcmp( POPSERVICE, "kpop" ) == 0 ) {
472 if (kpop || ( rpop > 0))
473 pass = getusername ();
475 ruserpass (host, &user, &pass);
478 * initialize POP connection
480 if (pop_init (host, user, pass, snoop, kpop ? 1 : rpop, kpop) == NOTOK)
481 adios (NULL, "%s", response);
483 /* Check if there are any messages */
484 if (pop_stat (&nmsgs, &nbytes) == NOTOK)
485 adios (NULL, "%s", response);
491 adios (NULL, "no mail to incorporate");
497 * We will get the mail from a file
498 * (typically the standard maildrop)
501 if (inc_type == INC_FILE) {
504 else if ((newmail = getenv ("MAILDROP")) && *newmail)
505 newmail = m_mailpath (newmail);
506 else if ((newmail = context_find ("maildrop")) && *newmail)
507 newmail = m_mailpath (newmail);
509 newmail = concat (MAILDIR, "/", MAILFIL, NULL);
511 if (stat (newmail, &s1) == NOTOK || s1.st_size == 0)
512 adios (NULL, "no mail to incorporate");
516 /* skip the folder setup */
517 if ((inc_type == INC_POP) && packfile)
521 if (!context_find ("path"))
522 free (path ("./", TFOLDER));
524 folder = getfolder (0);
525 maildir = m_maildir (folder);
527 if (stat (maildir, &st) == NOTOK) {
529 adios (maildir, "error on folder");
530 cp = concat ("Create folder \"", maildir, "\"? ", NULL);
531 if (noisy && !getanswer (cp))
534 if (!makedir (maildir))
535 adios (NULL, "unable to create folder %s", maildir);
538 if (chdir (maildir) == NOTOK)
539 adios (maildir, "unable to change directory to");
541 /* read folder and create message structure */
542 if (!(mp = folder_read (folder)))
543 adios (NULL, "unable to read folder %s", folder);
549 if (inc_type == INC_FILE) {
550 if (access (newmail, W_OK) != NOTOK) {
553 SIGNAL (SIGHUP, SIG_IGN);
554 SIGNAL (SIGINT, SIG_IGN);
555 SIGNAL (SIGQUIT, SIG_IGN);
556 SIGNAL (SIGTERM, SIG_IGN);
559 GETGROUPPRIVS(); /* Reset gid to lock mail file */
560 in = lkfopen (newmail, "r");
563 adios (NULL, "unable to lock and fopen %s", newmail);
564 fstat (fileno(in), &s1);
567 if ((in = fopen (newmail, "r")) == NULL)
568 adios (newmail, "unable to read");
572 /* This shouldn't be necessary but it can't hurt. */
576 if ((i = stat (audfile, &st)) == NOTOK)
577 advise (NULL, "Creating Receive-Audit: %s", audfile);
578 if ((aud = fopen (audfile, "a")) == NULL)
579 adios (audfile, "unable to append to");
581 chmod (audfile, m_gmprot ());
584 fprintf (aud, from ? "<<inc>> %s -ms %s\n"
585 : host ? "<<inc>> %s -host %s -user %s%s\n"
587 dtimenow (0), from ? from : host, user,
588 rpop < 0 ? " -apop" : rpop > 0 ? " -rpop" : "");
590 fprintf (aud, from ? "<<inc>> %s -ms %s\n" : "<<inc>> %s\n",
596 if (context_find ("mhe")) {
597 cp = concat (maildir, "/++", NULL);
599 if ((mhe = fopen (cp, "a")) == NULL)
600 admonish (cp, "unable to append to");
603 chmod (cp, m_gmprot ());
608 /* Get new format string */
609 nfs = new_fs (form, format, FORMAT);
612 printf ("Incorporating new mail into %s...\n\n", folder);
618 * Get the mail from a POP server
620 if (inc_type == INC_POP) {
622 packfile = path (packfile, TFILE);
623 if (stat (packfile, &st) == NOTOK) {
625 adios (packfile, "error on file");
626 cp = concat ("Create file \"", packfile, "\"? ", NULL);
627 if (noisy && !getanswer (cp))
631 msgnum = map_count ();
632 if ((pd = mbx_open (packfile, mbx_style, getuid(), getgid(), m_gmprot()))
634 adios (packfile, "unable to open");
635 if ((pf = fdopen (pd, "w+")) == NULL)
636 adios (NULL, "unable to fdopen %s", packfile);
638 hghnum = msgnum = mp->hghmsg;
640 * Check if we have enough message space for all the new
641 * messages. If not, then realloc the folder and add enough
642 * space for all new messages plus 10 additional slots.
644 if (mp->hghmsg + nmsgs >= mp->hghoff
645 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghmsg + nmsgs + 10)))
646 adios (NULL, "unable to allocate folder storage");
649 for (i = 1; i <= nmsgs; i++) {
652 fseek (pf, 0L, SEEK_CUR);
655 fwrite (mmdlm1, 1, strlen (mmdlm1), pf);
658 if (pop_retr (i, pop_pack) == NOTOK)
659 adios (NULL, "%s", response);
661 fseek (pf, 0L, SEEK_CUR);
664 adios (packfile, "write error on");
665 fseek (pf, start, SEEK_SET);
667 cp = getcpy (m_name (msgnum));
668 if ((pf = fopen (cp, "w+")) == NULL)
669 adios (cp, "unable to write");
670 chmod (cp, m_gmprot ());
673 if (pop_retr (i, pop_action) == NOTOK)
674 adios (NULL, "%s", response);
677 adios (cp, "write error on");
678 fseek (pf, 0L, SEEK_SET);
680 switch (p = scan (pf, msgnum, 0, nfs, width,
681 packfile ? 0 : msgnum == mp->hghmsg + 1 && chgflag,
682 1, NULL, stop - start, noisy)) {
684 printf ("%*d empty\n", DMAXFOLDER, msgnum);
690 /* advise (cp, "unable to read"); already advised */
709 clear_msg_flags (mp, msgnum);
710 set_exists (mp, msgnum);
711 set_unseen (mp, msgnum);
712 mp->msgflags |= SEQMOD;
717 fseek (pf, stop, SEEK_SET);
718 fwrite (mmdlm2, 1, strlen (mmdlm2), pf);
719 if (fflush (pf) || ferror (pf)) {
723 adios (packfile, "write error on");
725 map_write (packfile, pd, 0, 0L, start, stop, pos, size, noisy);
727 if (ferror(pf) || fclose (pf)) {
732 adios (cp, "write error on");
737 if (trnflag && pop_dele (i) == NOTOK)
738 adios (NULL, "%s", response);
741 if (pop_quit () == NOTOK)
742 adios (NULL, "%s", response);
744 mbx_close (packfile, pd);
751 * Get the mail from file (usually mail spool)
753 if (inc_type == INC_FILE) {
754 m_unknown (in); /* the MAGIC invocation... */
755 hghnum = msgnum = mp->hghmsg;
758 * Check if we need to allocate more space for message status.
759 * If so, then add space for an additional 100 messages.
761 if (msgnum >= mp->hghoff
762 && !(mp = folder_realloc (mp, mp->lowoff, mp->hghoff + 100))) {
763 advise (NULL, "unable to allocate folder storage");
769 /* copy file from spool to tmp file */
770 tmpfilenam = m_scratch ("", invo_name);
771 if ((fd = creat (tmpfilenam, m_gmprot ())) == NOTOK)
772 adios (tmpfilenam, "unable to create");
773 chmod (tmpfilenam, m_gmprot ());
774 if (!(in2 = fdopen (fd, "r+")))
775 adios (tmpfilenam, "unable to access");
778 /* link message into folder */
779 newmsg = folder_addmsg(mp, tmpfilenam);
782 /* create scanline for new message */
783 switch (i = scan (in, msgnum + 1, msgnum + 1, nfs, width,
784 msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
791 fputs ("inc aborted!\n", aud);
792 advise (NULL, "aborted!"); /* doesn't clean up locks! */
796 advise (NULL, "BUG in %s, number out of range", invo_name);
800 advise (NULL, "BUG in %s, scan() botch (%d)", invo_name, i);
816 clear_msg_flags (mp, msgnum);
817 set_exists (mp, msgnum);
818 set_unseen (mp, msgnum);
819 mp->msgflags |= SEQMOD;
827 if (p < 0) { /* error */
829 if (i < 0) { /* error */
832 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
833 (void) lkfclose (in, newmail); in = NULL;
834 DROPGROUPPRIVS(); /* And then return us to normal privileges */
836 fclose (in); in = NULL;
838 adios (NULL, "failed");
853 if ((inc_type == INC_POP) && packfile)
858 * truncate file we are incorporating from
860 if (inc_type == INC_FILE) {
862 if (stat (newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
863 advise (NULL, "new messages have arrived!\007");
865 if ((i = creat (newmail, 0600)) != NOTOK)
868 admonish (newmail, "error zero'ing");
869 unlink(map_name(newmail));
873 printf ("%s not zero'd\n", newmail);
877 if (msgnum == hghnum) {
878 admonish (NULL, "no messages incorporated");
880 context_replace (pfolder, folder); /* update current folder */
882 mp->curmsg = hghnum + 1;
886 if (chgflag) /* sigh... */
887 seq_setcur (mp, mp->curmsg);
891 * unlock the mail spool
893 if (inc_type == INC_FILE) {
895 GETGROUPPRIVS(); /* Be sure we can unlock mail file */
896 (void) lkfclose (in, newmail); in = NULL;
897 DROPGROUPPRIVS(); /* And then return us to normal privileges */
899 fclose (in); in = NULL;
903 seq_setunseen (mp, 0); /* set the Unseen-Sequence */
904 seq_save (mp); /* synchronize sequences */
905 context_save (); /* save the context file */
913 * Copy message message from spool into
914 * temporary file. Massage the "From " line
918 cpymsg (FILE *in, FILE *out)
921 char *tmpbuf, name[NAMESZ];
924 state = m_getfld (state, name, tmpbuf, rlwidth, in);
947 if (packfile && pd != NOTOK)
948 mbx_close (packfile, pd);
953 lkfclose(in, newmail);
957 return 1; /* dead code to satisfy the compiler */
964 fprintf (pf, "%s\n", s);
965 stop += strlen (s) + 1;
966 return 0; /* Is return value used? This was missing before 1999-07-15. */
975 snprintf (buffer, sizeof(buffer), "%s\n", s);
976 for (j = 0; (j = stringdex (mmdlm1, buffer)) >= 0; buffer[j]++)
978 for (j = 0; (j = stringdex (mmdlm2, buffer)) >= 0; buffer[j]++)
981 size += strlen (buffer) + 1;
982 return 0; /* Is return value used? This was missing before 1999-07-15. */
993 if (stat (packfile, &st) == NOTOK)
995 if ((md = open (cp = map_name (packfile), O_RDONLY)) == NOTOK
996 || map_chk (cp, md, &d, (long) st.st_size, 1)) {