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