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