Add %(unmailto) format function for List-Post headers
[mmh] / uip / inc.c
1 /*
2 ** inc.c -- incorporate messages from a maildrop into a folder
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #ifdef MAILGROUP
10 /*
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.
16 **
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.
19 **
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
23 **
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
26 */
27 #endif
28
29 #include <h/mh.h>
30 #include <h/utils.h>
31 #include <fcntl.h>
32 #include <h/fmt_scan.h>
33 #include <h/scansbr.h>
34 #include <h/signals.h>
35 #include <h/tws.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <unistd.h>
39 #include <sys/stat.h>
40 #include <locale.h>
41 #include <sysexits.h>
42
43 #ifdef HAVE_SYS_PARAM_H
44 # include <sys/param.h>
45 #endif
46
47 static struct swit switches[] = {
48 #define AUDSW  0
49         { "audit audit-file", 0 },
50 #define NAUDSW  1
51         { "noaudit", 2 },
52 #define CHGSW  2
53         { "changecur", 0 },
54 #define NCHGSW  3
55         { "nochangecur", 2 },
56 #define FILESW  4
57         { "file name", 0 },
58 #define FORMSW  5
59         { "form formatfile", 0 },
60 #define SILSW  6
61         { "silent", 0 },
62 #define NSILSW  7
63         { "nosilent", 2 },
64 #define TRNCSW  8
65         { "truncate", 0 },
66 #define NTRNCSW  9
67         { "notruncate", 2 },
68 #define WIDTHSW  10
69         { "width columns", 0 },
70 #define VERSIONSW  11
71         { "Version", 0 },
72 #define HELPSW  12
73         { "help", 0 },
74         { NULL, 0 },
75 };
76
77 /*
78 ** This is an attempt to simplify things by putting all the
79 ** privilege ops into macros.
80 ** *GROUPPRIVS() is related to handling the setgid MAIL property,
81 ** and only applies if MAILGROUP is defined.
82 ** Basically, SAVEGROUPPRIVS() is called right at the top of main()
83 ** to initialise things, and then DROPGROUPPRIVS() and GETGROUPPRIVS()
84 ** do the obvious thing. TRYDROPGROUPPRIVS() has to be safe to call
85 ** before DROPUSERPRIVS() is called [this is needed because setgid()
86 ** sets both effective and real uids if euid is root.]
87 **
88 ** There's probably a better implementation if we're allowed to use
89 ** BSD-style setreuid() rather than using POSIX saved-ids.
90 ** Anyway, if you're euid root it's a bit pointless to drop the group
91 ** permissions...
92 **
93 ** I'm pretty happy that the security is good provided we aren't setuid root.
94 ** The only things we trust with group=mail privilege are lkfopen()
95 ** and lkfclose().
96 */
97
98 /*
99 ** For setting and returning to "mail" gid
100 */
101 #ifdef MAILGROUP
102 static int return_gid;
103 /*
104 ** easy case; we're not setuid root, so can drop group privs immediately.
105 */
106 #define TRYDROPGROUPPRIVS() DROPGROUPPRIVS()
107 #define DROPGROUPPRIVS() \
108     if (setegid(getgid()) != 0) { \
109         advise ("setegid", "unable to set group to %ld", (long) getgid()); \
110                 _exit (EX_OSERR); \
111     }
112 #define GETGROUPPRIVS() \
113     if (setegid(return_gid) != 0) { \
114         advise ("setegid", "unable to set group to %ld", (long) return_gid); \
115                 _exit (EX_OSERR); \
116     }
117 #define SAVEGROUPPRIVS() return_gid = getegid()
118 #else
119 /* define *GROUPPRIVS() as null; this avoids having lots of "#ifdef MAILGROUP"s */
120 #define TRYDROPGROUPPRIVS()
121 #define DROPGROUPPRIVS()
122 #define GETGROUPPRIVS()
123 #define SAVEGROUPPRIVS()
124 #endif /* not MAILGROUP */
125
126 /*
127 ** these variables have to be globals so that done() can correctly clean
128 ** up the lockfile
129 */
130 static int locked = 0;
131 static char *newmail;
132 static FILE *in;
133
134 /*
135 ** prototypes
136 */
137 void inc_done();
138
139
140 int
141 main(int argc, char **argv)
142 {
143         int chgflag = 1, trnflag = 1;
144         int noisy = 1, width = 0;
145         int hghnum = 0, msgnum = 0;
146         int incerr = 0;  /*
147                         ** <0 if inc hits an error which means it should
148                         ** not truncate mailspool
149                         */
150         char *cp, *maildir = NULL, *folder = NULL;
151         char *form = NULL;
152         char *audfile = NULL, *from = NULL;
153         char buf[BUFSIZ], **argp, *fmtstr, **arguments;
154         struct msgs *mp = NULL;
155         struct stat st, s1;
156         FILE *aud = NULL;
157         char b[MAXPATHLEN + 1];
158         /* copy of mail directory because the static gets overwritten */
159         char *maildir_copy = NULL;
160
161         if (atexit(inc_done) != 0) {
162                 adios(EX_OSERR, NULL, "atexit failed");
163         }
164
165         /*
166         ** absolutely the first thing we do is save our privileges,
167         ** and drop them if we can.
168         */
169         SAVEGROUPPRIVS();
170         TRYDROPGROUPPRIVS();
171
172         setlocale(LC_ALL, "");
173         invo_name = mhbasename(argv[0]);
174
175         context_read();
176
177         arguments = getarguments(invo_name, argc, argv, 1);
178         argp = arguments;
179
180         while ((cp = *argp++)) {
181                 if (*cp == '-') {
182                         switch (smatch(++cp, switches)) {
183                         case AMBIGSW:
184                                 ambigsw(cp, switches);
185                                 exit(EX_USAGE);
186                         case UNKWNSW:
187                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
188
189                         case HELPSW:
190                                 snprintf(buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
191                                 print_help(buf, switches, 1);
192                                 exit(argc == 2 ? EX_OK : EX_USAGE);
193                         case VERSIONSW:
194                                 print_version(invo_name);
195                                 exit(argc == 2 ? EX_OK : EX_USAGE);
196
197                         case AUDSW:
198                                 if (!(cp = *argp++) || *cp == '-')
199                                         adios(EX_USAGE, NULL, "missing argument to %s", argp[-2]);
200                                 audfile = mh_xstrdup(expanddir(cp));
201                                 continue;
202                         case NAUDSW:
203                                 audfile = NULL;
204                                 continue;
205
206                         case CHGSW:
207                                 chgflag++;
208                                 continue;
209                         case NCHGSW:
210                                 chgflag = 0;
211                                 continue;
212
213                         /*
214                         ** The flag `trnflag' has the value:
215                         **
216                         ** 2 if -truncate is given
217                         ** 1 by default (truncating is default)
218                         ** 0 if -notruncate is given
219                         */
220                         case TRNCSW:
221                                 trnflag = 2;
222                                 continue;
223                         case NTRNCSW:
224                                 trnflag = 0;
225                                 continue;
226
227                         case FILESW:
228                                 if (!(cp = *argp++))
229                                         adios(EX_USAGE, NULL, "missing argument to %s",
230                                                         argp[-2]);
231                                 from = (strcmp(cp, "-")==0) ? "-" : mh_xstrdup(expanddir(cp));
232
233                                 /*
234                                 ** If the truncate file is in default state,
235                                 ** change to not truncate.
236                                 */
237                                 if (trnflag == 1)
238                                         trnflag = 0;
239                                 continue;
240
241                         case SILSW:
242                                 noisy = 0;
243                                 continue;
244                         case NSILSW:
245                                 noisy++;
246                                 continue;
247
248                         case FORMSW:
249                                 if (!(form = *argp++) || *form == '-')
250                                         adios(EX_USAGE, NULL, "missing argument to %s",
251                                                         argp[-2]);
252                                 continue;
253
254                         case WIDTHSW:
255                                 if (!(cp = *argp++) || *cp == '-')
256                                         adios(EX_USAGE, NULL, "missing argument to %s",
257                                                         argp[-2]);
258                                 width = atoi(cp);
259                                 continue;
260                         }
261                 }
262                 if (*cp == '+' || *cp == '@') {
263                         if (folder)
264                                 adios(EX_USAGE, NULL, "only one folder at a time!");
265                         else
266                                 folder = mh_xstrdup(expandfol(cp));
267                 } else {
268                         adios(EX_USAGE, NULL, "usage: %s [+folder] [switches]",
269                                         invo_name);
270                 }
271         }
272
273         /*
274         ** NOTE: above this point you should use TRYDROPGROUPPRIVS(),
275         ** not DROPGROUPPRIVS().
276         */
277         /* guarantee dropping group privileges; we might not have done so earlier */
278         DROPGROUPPRIVS();
279
280         if (from && strcmp(from, "-")==0) {
281                 /* We'll read mail from stdin. */
282                 newmail = NULL;
283         } else {
284                 /* We'll read mail from a file. */
285                 if (from)
286                         newmail = from;
287                 else if ((newmail = getenv("MAILDROP")) && *newmail)
288                         newmail = toabsdir(newmail);
289                 else if ((newmail = context_find("maildrop")) && *newmail)
290                         newmail = toabsdir(newmail);
291                 else {
292                         newmail = concat(mailspool, "/", getusername(), NULL);
293                 }
294                 if (stat(newmail, &s1) == NOTOK || s1.st_size == 0)
295                         adios(EX_DATAERR, NULL, "no mail to incorporate");
296
297                 if ((cp = strdup(newmail)) == NULL)
298                         adios(EX_OSERR, NULL, "error allocating memory to copy newmail");
299
300                 newmail = cp;
301         }
302
303         if (!folder)
304                 folder = getdeffol();
305         maildir = toabsdir(folder);
306
307         if ((maildir_copy = strdup(maildir)) == NULL)
308                 adios(EX_OSERR, maildir, "error allocating memory to copy maildir");
309
310         create_folder(maildir, noisy ? 0 : 1, exit);
311
312         if (chdir(maildir) == NOTOK)
313                 adios(EX_OSERR, maildir, "unable to change directory to");
314
315         if (!(mp = folder_read(folder)))
316                 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
317
318         if (!newmail) {
319                 trnflag = 0;
320                 in = stdin;
321         } else if (access(newmail, W_OK) != NOTOK) {
322                 locked++;
323                 if (trnflag) {
324                         SIGNAL(SIGHUP, SIG_IGN);
325                         SIGNAL(SIGINT, SIG_IGN);
326                         SIGNAL(SIGQUIT, SIG_IGN);
327                         SIGNAL(SIGTERM, SIG_IGN);
328                 }
329
330                 GETGROUPPRIVS();  /* Reset gid to lock mail file */
331                 in = lkfopen(newmail, "r");
332                 DROPGROUPPRIVS();
333                 if (in == NULL)
334                         adios(EX_IOERR, NULL, "unable to lock and fopen %s", newmail);
335                 fstat(fileno(in), &s1);
336         } else {
337                 trnflag = 0;
338                 if ((in = fopen(newmail, "r")) == NULL)
339                         adios(EX_IOERR, newmail, "unable to read");
340         }
341
342         /* This shouldn't be necessary but it can't hurt. */
343         DROPGROUPPRIVS();
344
345         if (audfile) {
346                 int i;
347                 if ((i = stat(audfile, &st)) == NOTOK)
348                         advise(NULL, "Creating Receive-Audit: %s", audfile);
349                 if ((aud = fopen(audfile, "a")) == NULL)
350                         adios(EX_IOERR, audfile, "unable to append to");
351                 else if (i == NOTOK)
352                         chmod(audfile, m_gmprot());
353
354                 fprintf(aud, from ? "<<inc>> %s  -ms %s\n" : "<<inc>> %s\n",
355                          dtimenow(), from);
356         }
357
358         /* Set format string */
359         fmtstr = new_fs(form, scanformat);
360
361         if (noisy) {
362                 printf("Incorporating new mail into %s...\n\n", folder);
363                 fflush(stdout);
364         }
365
366         /* check if readable and nonempty */
367         if (!fgets(buf, sizeof(buf), in)) {
368                 if (ferror(in)) {
369                         advise("read", "unable to");
370                         incerr = SCNFAT;
371                 } else {
372                         incerr = SCNEOF;
373                 }
374                 goto giveup;
375         }
376         if (strncmp("From ", buf, 5)!=0) {
377                 advise(NULL, "not in mbox format");
378                 incerr = SCNFAT;
379                 goto giveup;
380         }
381
382         /*
383         ** Get the mail from file (usually mail spool)
384         */
385         hghnum = msgnum = mp->hghmsg;
386         for (;;) {
387                 /*
388                 ** Check if we need to allocate more space for message status.
389                 ** If so, then add space for an additional 100 messages.
390                 */
391                 if (msgnum >= mp->hghoff && !(mp = folder_realloc(mp, mp->lowoff, mp->hghoff + 100))) {
392                         advise(NULL, "unable to allocate folder storage");
393                         incerr = NOTOK;
394                         break;
395                 }
396
397                 /* create scanline for new message */
398                 switch (incerr = scan(in, msgnum + 1, msgnum + 1,
399                                 noisy ? fmtstr : NULL, width,
400                                 msgnum == hghnum && chgflag, 1)) {
401                 case SCNFAT:
402                 case SCNEOF:
403                         break;
404
405                 case SCNERR:
406                         if (aud)
407                                 fputs("inc aborted!\n", aud);
408                         /* doesn't clean up locks! */
409                         advise(NULL, "aborted!");
410                         break;
411
412                 case SCNNUM:
413                         advise(NULL, "BUG in %s, number out of range",
414                                         invo_name);
415                         break;
416
417                 default:
418                         advise(NULL, "BUG in %s, scan() botch (%d)",
419                                         invo_name, incerr);
420                         break;
421
422                 case SCNMSG:
423                         /*
424                         **  Run the external program hook on the message.
425                         */
426
427                         snprintf(b, sizeof (b), "%s/%d", maildir_copy,
428                                         msgnum + 1);
429                         ext_hook("add-hook", b, NULL);
430
431                         if (aud)
432                                 fputs(scanl, aud);
433                         if (noisy)
434                                 fflush(stdout);
435                         msgnum++;
436                         mp->hghmsg++;
437                         mp->nummsg++;
438                         if (mp->lowmsg == 0)
439                                 mp->lowmsg = 1;
440                         clear_msg_flags(mp, msgnum);
441                         set_exists(mp, msgnum);
442                         set_unseen(mp, msgnum);
443                         mp->msgflags |= SEQMOD;
444                         continue;
445                 }
446                 /*
447                 ** If we get here there was some sort of error from scan(),
448                 ** so stop processing anything more from the spool.
449                 */
450                 break;
451         }
452 giveup:;
453         mh_free0(&maildir_copy);
454
455         if (incerr < 0) {  /* error */
456                 if (locked) {
457                         GETGROUPPRIVS();  /* Be sure we can unlock mail file */
458                         lkfclose(in, newmail); in = NULL;
459                         DROPGROUPPRIVS();  /*
460                                         ** And then return us to normal
461                                         ** privileges
462                                         */
463                 } else {
464                         fclose(in); in = NULL;
465                 }
466                 adios(EX_SOFTWARE, NULL, "failed");
467         }
468
469         if (aud)
470                 fclose(aud);
471
472         if (noisy)
473                 fflush(stdout);
474
475         /*
476         ** truncate file we are incorporating from
477         */
478         if (trnflag) {
479                 if (stat(newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
480                         advise(NULL, "new messages have arrived!\007");
481                 else {
482                         int newfd;
483                         if ((newfd = creat(newmail, 0600)) != NOTOK)
484                                 close(newfd);
485                         else
486                                 admonish(newmail, "error zero'ing");
487                 }
488         } else if (noisy && newmail) {
489                 printf("%s not zero'd\n", newmail);
490         }
491
492         if (msgnum == hghnum) {
493                 admonish(NULL, "no messages incorporated");
494         } else {
495                 context_replace(curfolder, folder); /* update current folder */
496                 if (chgflag)
497                         mp->curmsg = hghnum + 1;
498                 mp->hghmsg = msgnum;
499                 if (mp->lowmsg == 0)
500                         mp->lowmsg = 1;
501                 if (chgflag)  /* sigh... */
502                         seq_setcur(mp, mp->curmsg);
503         }
504
505         /*
506         ** unlock the mail spool
507         */
508         if (locked) {
509                 GETGROUPPRIVS();  /* Be sure we can unlock mail file */
510                 lkfclose(in, newmail); in = NULL;
511                 DROPGROUPPRIVS();  /* And then return us to normal privileges */
512         } else {
513                 fclose(in); in = NULL;
514         }
515
516         seq_setunseen(mp, 1);
517         seq_save(mp);
518         context_save();
519         return 0;
520 }
521
522 void
523 inc_done()
524 {
525         if (locked) {
526                 GETGROUPPRIVS();
527                 lkfclose(in, newmail);
528                 DROPGROUPPRIVS();
529         }
530 }