0cb2a5e0083186c5643560e6c6f872f6374c46de
[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++) || *cp == '-')
229                                         adios(EX_USAGE, NULL, "missing argument to %s",
230                                                         argp[-2]);
231                                 from = 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 priveleges; we might not have done so earlier */
278         DROPGROUPPRIVS();
279
280         /*
281         ** We will get the mail from a file
282         ** (typically the standard maildrop)
283         */
284         if (from)
285                 newmail = from;
286         else if ((newmail = getenv("MAILDROP")) && *newmail)
287                 newmail = toabsdir(newmail);
288         else if ((newmail = context_find("maildrop")) && *newmail)
289                 newmail = toabsdir(newmail);
290         else {
291                 newmail = concat(mailspool, "/", getusername(), NULL);
292         }
293         if (stat(newmail, &s1) == NOTOK || s1.st_size == 0)
294                 adios(EX_DATAERR, NULL, "no mail to incorporate");
295
296         if ((cp = strdup(newmail)) == NULL)
297                 adios(EX_OSERR, NULL, "error allocating memory to copy newmail");
298
299         newmail = cp;
300
301         if (!folder)
302                 folder = getdeffol();
303         maildir = toabsdir(folder);
304
305         if ((maildir_copy = strdup(maildir)) == NULL)
306                 adios(EX_OSERR, maildir, "error allocating memory to copy maildir");
307
308         create_folder(maildir, noisy ? 0 : 1, exit);
309
310         if (chdir(maildir) == NOTOK)
311                 adios(EX_OSERR, maildir, "unable to change directory to");
312
313         if (!(mp = folder_read(folder)))
314                 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
315
316         if (access(newmail, W_OK) != NOTOK) {
317                 locked++;
318                 if (trnflag) {
319                         SIGNAL(SIGHUP, SIG_IGN);
320                         SIGNAL(SIGINT, SIG_IGN);
321                         SIGNAL(SIGQUIT, SIG_IGN);
322                         SIGNAL(SIGTERM, SIG_IGN);
323                 }
324
325                 GETGROUPPRIVS();  /* Reset gid to lock mail file */
326                 in = lkfopen(newmail, "r");
327                 DROPGROUPPRIVS();
328                 if (in == NULL)
329                         adios(EX_IOERR, NULL, "unable to lock and fopen %s", newmail);
330                 fstat(fileno(in), &s1);
331         } else {
332                 trnflag = 0;
333                 if ((in = fopen(newmail, "r")) == NULL)
334                         adios(EX_IOERR, newmail, "unable to read");
335         }
336
337         /* This shouldn't be necessary but it can't hurt. */
338         DROPGROUPPRIVS();
339
340         if (audfile) {
341                 int i;
342                 if ((i = stat(audfile, &st)) == NOTOK)
343                         advise(NULL, "Creating Receive-Audit: %s", audfile);
344                 if ((aud = fopen(audfile, "a")) == NULL)
345                         adios(EX_IOERR, audfile, "unable to append to");
346                 else if (i == NOTOK)
347                         chmod(audfile, m_gmprot());
348
349                 fprintf(aud, from ? "<<inc>> %s  -ms %s\n" : "<<inc>> %s\n",
350                          dtimenow(), from);
351         }
352
353         /* Set format string */
354         fmtstr = new_fs(form, scanformat);
355
356         if (noisy) {
357                 printf("Incorporating new mail into %s...\n\n", folder);
358                 fflush(stdout);
359         }
360
361         /* check if readable and nonempty */
362         if (!fgets(buf, sizeof(buf), in)) {
363                 if (ferror(in)) {
364                         advise("read", "unable to");
365                         incerr = SCNFAT;
366                 } else {
367                         incerr = SCNEOF;
368                 }
369                 goto giveup;
370         }
371         if (strncmp("From ", buf, 5)!=0) {
372                 advise(NULL, "not in mbox format");
373                 incerr = SCNFAT;
374                 goto giveup;
375         }
376
377         /*
378         ** Get the mail from file (usually mail spool)
379         */
380         hghnum = msgnum = mp->hghmsg;
381         for (;;) {
382                 /*
383                 ** Check if we need to allocate more space for message status.
384                 ** If so, then add space for an additional 100 messages.
385                 */
386                 if (msgnum >= mp->hghoff && !(mp = folder_realloc(mp, mp->lowoff, mp->hghoff + 100))) {
387                         advise(NULL, "unable to allocate folder storage");
388                         incerr = NOTOK;
389                         break;
390                 }
391
392                 /* create scanline for new message */
393                 switch (incerr = scan(in, msgnum + 1, msgnum + 1,
394                                 noisy ? fmtstr : NULL, width,
395                                 msgnum == hghnum && chgflag, 1)) {
396                 case SCNFAT:
397                 case SCNEOF:
398                         break;
399
400                 case SCNERR:
401                         if (aud)
402                                 fputs("inc aborted!\n", aud);
403                         /* doesn't clean up locks! */
404                         advise(NULL, "aborted!");
405                         break;
406
407                 case SCNNUM:
408                         advise(NULL, "BUG in %s, number out of range",
409                                         invo_name);
410                         break;
411
412                 default:
413                         advise(NULL, "BUG in %s, scan() botch (%d)",
414                                         invo_name, incerr);
415                         break;
416
417                 case SCNMSG:
418                         /*
419                         **  Run the external program hook on the message.
420                         */
421
422                         snprintf(b, sizeof (b), "%s/%d", maildir_copy,
423                                         msgnum + 1);
424                         ext_hook("add-hook", b, NULL);
425
426                         if (aud)
427                                 fputs(scanl, aud);
428                         if (noisy)
429                                 fflush(stdout);
430                         msgnum++;
431                         mp->hghmsg++;
432                         mp->nummsg++;
433                         if (mp->lowmsg == 0)
434                                 mp->lowmsg = 1;
435                         clear_msg_flags(mp, msgnum);
436                         set_exists(mp, msgnum);
437                         set_unseen(mp, msgnum);
438                         mp->msgflags |= SEQMOD;
439                         continue;
440                 }
441                 /*
442                 ** If we get here there was some sort of error from scan(),
443                 ** so stop processing anything more from the spool.
444                 */
445                 break;
446         }
447 giveup:;
448         mh_free0(&maildir_copy);
449
450         if (incerr < 0) {  /* error */
451                 if (locked) {
452                         GETGROUPPRIVS();  /* Be sure we can unlock mail file */
453                         lkfclose(in, newmail); in = NULL;
454                         DROPGROUPPRIVS();  /*
455                                         ** And then return us to normal
456                                         ** privileges
457                                         */
458                 } else {
459                         fclose(in); in = NULL;
460                 }
461                 adios(EX_SOFTWARE, NULL, "failed");
462         }
463
464         if (aud)
465                 fclose(aud);
466
467         if (noisy)
468                 fflush(stdout);
469
470         /*
471         ** truncate file we are incorporating from
472         */
473         if (trnflag) {
474                 if (stat(newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
475                         advise(NULL, "new messages have arrived!\007");
476                 else {
477                         int newfd;
478                         if ((newfd = creat(newmail, 0600)) != NOTOK)
479                                 close(newfd);
480                         else
481                                 admonish(newmail, "error zero'ing");
482                 }
483         } else if (noisy) {
484                 printf("%s not zero'd\n", newmail);
485         }
486
487         if (msgnum == hghnum) {
488                 admonish(NULL, "no messages incorporated");
489         } else {
490                 context_replace(curfolder, folder); /* update current folder */
491                 if (chgflag)
492                         mp->curmsg = hghnum + 1;
493                 mp->hghmsg = msgnum;
494                 if (mp->lowmsg == 0)
495                         mp->lowmsg = 1;
496                 if (chgflag)  /* sigh... */
497                         seq_setcur(mp, mp->curmsg);
498         }
499
500         /*
501         ** unlock the mail spool
502         */
503         if (locked) {
504                 GETGROUPPRIVS();  /* Be sure we can unlock mail file */
505                 lkfclose(in, newmail); in = NULL;
506                 DROPGROUPPRIVS();  /* And then return us to normal privileges */
507         } else {
508                 fclose(in); in = NULL;
509         }
510
511         seq_setunseen(mp, 1);
512         seq_save(mp);
513         context_save();
514         return 0;
515 }
516
517 void
518 inc_done()
519 {
520         if (locked) {
521                 GETGROUPPRIVS();
522                 lkfclose(in, newmail);
523                 DROPGROUPPRIVS();
524         }
525 }