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