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