e3199c048e4355c6028d89a1134ef1c7c5c27517
[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 static void inc_done(int) NORETURN;
125
126
127 int
128 main(int argc, char **argv)
129 {
130         int chgflag = 1, trnflag = 1;
131         int noisy = 1, width = 0;
132         int hghnum = 0, msgnum = 0;
133         int incerr = 0;  /*
134                         ** <0 if inc hits an error which means it should
135                         ** not truncate mailspool
136                         */
137         char *cp, *maildir = NULL, *folder = NULL;
138         char *format = NULL, *form = NULL;
139         char *audfile = NULL, *from = NULL;
140         char buf[BUFSIZ], **argp, *nfs, **arguments;
141         struct msgs *mp = NULL;
142         struct stat st, s1;
143         FILE *aud = NULL;
144         char b[MAXPATHLEN + 1];
145         /* copy of mail directory because the static gets overwritten */
146         char *maildir_copy = NULL;
147
148 #ifdef MHE
149         FILE *mhe = NULL;
150 #endif
151
152         done=inc_done;
153
154 /*
155 ** absolutely the first thing we do is save our privileges,
156 ** and drop them if we can.
157 */
158         SAVEGROUPPRIVS();
159         TRYDROPGROUPPRIVS();
160
161 #ifdef LOCALE
162         setlocale(LC_ALL, "");
163 #endif
164         invo_name = mhbasename(argv[0]);
165
166         /* read user profile/context */
167         context_read();
168
169         mts_init(invo_name);
170         arguments = getarguments(invo_name, argc, argv, 1);
171         argp = arguments;
172
173         while ((cp = *argp++)) {
174                 if (*cp == '-') {
175                         switch (smatch(++cp, switches)) {
176                         case AMBIGSW:
177                                 ambigsw(cp, switches);
178                                 done(1);
179                         case UNKWNSW:
180                                 adios(NULL, "-%s unknown", cp);
181
182                         case HELPSW:
183                                 snprintf(buf, sizeof(buf), "%s [+folder] [switches]", invo_name);
184                                 print_help(buf, switches, 1);
185                                 done(1);
186                         case VERSIONSW:
187                                 print_version(invo_name);
188                                 done(1);
189
190                         case AUDSW:
191                                 if (!(cp = *argp++) || *cp == '-')
192                                         adios(NULL, "missing argument to %s", argp[-2]);
193                                 audfile = getcpy(expanddir(cp));
194                                 continue;
195                         case NAUDSW:
196                                 audfile = NULL;
197                                 continue;
198
199                         case CHGSW:
200                                 chgflag++;
201                                 continue;
202                         case NCHGSW:
203                                 chgflag = 0;
204                                 continue;
205
206                         /*
207                         ** The flag `trnflag' has the value:
208                         **
209                         ** 2 if -truncate is given
210                         ** 1 by default (truncating is default)
211                         ** 0 if -notruncate is given
212                         */
213                         case TRNCSW:
214                                 trnflag = 2;
215                                 continue;
216                         case NTRNCSW:
217                                 trnflag = 0;
218                                 continue;
219
220                         case FILESW:
221                                 if (!(cp = *argp++) || *cp == '-')
222                                         adios(NULL, "missing argument to %s",
223                                                         argp[-2]);
224                                 from = getcpy(expanddir(cp));
225
226                                 /*
227                                 ** If the truncate file is in default state,
228                                 ** change to not truncate.
229                                 */
230                                 if (trnflag == 1)
231                                         trnflag = 0;
232                                 continue;
233
234                         case SILSW:
235                                 noisy = 0;
236                                 continue;
237                         case NSILSW:
238                                 noisy++;
239                                 continue;
240
241                         case FORMSW:
242                                 if (!(form = *argp++) || *form == '-')
243                                         adios(NULL, "missing argument to %s",
244                                                         argp[-2]);
245                                 format = NULL;
246                                 continue;
247                         case FMTSW:
248                                 if (!(format = *argp++) || *format == '-')
249                                         adios(NULL, "missing argument to %s",
250                                                         argp[-2]);
251                                 form = NULL;
252                                 continue;
253
254                         case WIDTHSW:
255                                 if (!(cp = *argp++) || *cp == '-')
256                                         adios(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(NULL, "only one folder at a time!");
265                         else
266                                 folder = getcpy(expandfol(cp));
267                 } else {
268                         adios(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(MAILDIR, "/", MAILFIL, NULL);
292         }
293         if (stat(newmail, &s1) == NOTOK || s1.st_size == 0)
294                 adios(NULL, "no mail to incorporate");
295
296         if ((cp = strdup(newmail)) == NULL)
297                 adios(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(maildir, "error allocating memory to copy maildir");
307
308         if (!folder_exists(maildir)) {
309                 /*
310                 ** If the folder doesn't exist, and we're given the -silent
311                 ** flag, just fail.
312                 */
313                 if (noisy)
314                         create_folder(maildir, 0, done);
315                 else
316                         done(1);
317         }
318
319         if (chdir(maildir) == NOTOK)
320                 adios(maildir, "unable to change directory to");
321
322         /* read folder and create message structure */
323         if (!(mp = folder_read(folder)))
324                 adios(NULL, "unable to read folder %s", folder);
325
326         if (access(newmail, W_OK) != NOTOK) {
327                 locked++;
328                 if (trnflag) {
329                         SIGNAL(SIGHUP, SIG_IGN);
330                         SIGNAL(SIGINT, SIG_IGN);
331                         SIGNAL(SIGQUIT, SIG_IGN);
332                         SIGNAL(SIGTERM, SIG_IGN);
333                 }
334
335                 GETGROUPPRIVS();  /* Reset gid to lock mail file */
336                 in = lkfopen(newmail, "r");
337                 DROPGROUPPRIVS();
338                 if (in == NULL)
339                         adios(NULL, "unable to lock and fopen %s", newmail);
340                 fstat(fileno(in), &s1);
341         } else {
342                 trnflag = 0;
343                 if ((in = fopen(newmail, "r")) == NULL)
344                         adios(newmail, "unable to read");
345         }
346
347         /* This shouldn't be necessary but it can't hurt. */
348         DROPGROUPPRIVS();
349
350         if (audfile) {
351                 int i;
352                 if ((i = stat(audfile, &st)) == NOTOK)
353                         advise(NULL, "Creating Receive-Audit: %s", audfile);
354                 if ((aud = fopen(audfile, "a")) == NULL)
355                         adios(audfile, "unable to append to");
356                 else if (i == NOTOK)
357                         chmod(audfile, m_gmprot());
358
359                 fprintf(aud, from ? "<<inc>> %s  -ms %s\n" : "<<inc>> %s\n",
360                          dtimenow(0), from);
361         }
362
363 #ifdef MHE
364         if (context_find("mhe")) {
365                 int i;
366                 cp = concat(maildir, "/++", NULL);
367                 i = stat(cp, &st);
368                 if ((mhe = fopen(cp, "a")) == NULL)
369                         admonish(cp, "unable to append to");
370                 else
371                         if (i == NOTOK)
372                                 chmod(cp, m_gmprot());
373                 free(cp);
374         }
375 #endif /* MHE */
376
377         /* Get new format string */
378         nfs = new_fs(form, format, FORMAT);
379
380         if (noisy) {
381                 printf("Incorporating new mail into %s...\n\n", folder);
382                 fflush(stdout);
383         }
384
385         /*
386         ** Get the mail from file (usually mail spool)
387         */
388         m_unknown(in);  /* the MAGIC invocation... */
389         hghnum = msgnum = mp->hghmsg;
390         for (;;) {
391                 /*
392                 ** Check if we need to allocate more space for message status.
393                 ** If so, then add space for an additional 100 messages.
394                 */
395                 if (msgnum >= mp->hghoff && !(mp = folder_realloc(mp, mp->lowoff, mp->hghoff + 100))) {
396                         advise(NULL, "unable to allocate folder storage");
397                         incerr = NOTOK;
398                         break;
399                 }
400
401                 /* create scanline for new message */
402                 switch (incerr = scan(in, msgnum + 1, msgnum + 1, nfs, width,
403                         msgnum == hghnum && chgflag, 1, NULL, 0L, noisy)) {
404                 case SCNFAT:
405                 case SCNEOF:
406                         break;
407
408                 case SCNERR:
409                         if (aud)
410                                 fputs("inc aborted!\n", aud);
411                         /* doesn't clean up locks! */
412                         advise(NULL, "aborted!");
413                         break;
414
415                 case SCNNUM:
416                         advise(NULL, "BUG in %s, number out of range",
417                                         invo_name);
418                         break;
419
420                 default:
421                         advise(NULL, "BUG in %s, scan() botch (%d)",
422                                         invo_name, incerr);
423                         break;
424
425                 case SCNMSG:
426                 case SCNENC:
427                         /*
428                         **  Run the external program hook on the message.
429                         */
430
431                         snprintf(b, sizeof (b), "%s/%d", maildir_copy,
432                                         msgnum + 1);
433                         ext_hook("add-hook", b, NULL);
434
435                         if (aud)
436                                 fputs(scanl, aud);
437 #ifdef MHE
438                         if (mhe)
439                                 fputs(scanl, mhe);
440 #endif /* MHE */
441                         if (noisy)
442                                 fflush(stdout);
443                         msgnum++;
444                         mp->hghmsg++;
445                         mp->nummsg++;
446                         if (mp->lowmsg == 0)
447                                 mp->lowmsg = 1;
448                         clear_msg_flags(mp, msgnum);
449                         set_exists(mp, msgnum);
450                         set_unseen(mp, msgnum);
451                         mp->msgflags |= SEQMOD;
452                         continue;
453                 }
454                 /*
455                 ** If we get here there was some sort of error from scan(),
456                 ** so stop processing anything more from the spool.
457                 */
458                 break;
459         }
460
461         if (incerr < 0) {  /* error */
462                 if (locked) {
463                         GETGROUPPRIVS();  /* Be sure we can unlock mail file */
464                         lkfclose(in, newmail); in = NULL;
465                         DROPGROUPPRIVS();  /*
466                                         ** And then return us to normal
467                                         ** privileges
468                                         */
469                 } else {
470                         fclose(in); in = NULL;
471                 }
472                 adios(NULL, "failed");
473         }
474
475         if (aud)
476                 fclose(aud);
477
478 #ifdef MHE
479         if (mhe)
480                 fclose(mhe);
481 #endif /* MHE */
482
483         if (noisy)
484                 fflush(stdout);
485
486         /*
487         ** truncate file we are incorporating from
488         */
489         if (trnflag) {
490                 if (stat(newmail, &st) != NOTOK && s1.st_mtime != st.st_mtime)
491                         advise(NULL, "new messages have arrived!\007");
492                 else {
493                         int newfd;
494                         if ((newfd = creat(newmail, 0600)) != NOTOK)
495                                 close(newfd);
496                         else
497                                 admonish(newmail, "error zero'ing");
498                 }
499         } else if (noisy) {
500                 printf("%s not zero'd\n", newmail);
501         }
502
503         if (msgnum == hghnum) {
504                 admonish(NULL, "no messages incorporated");
505         } else {
506                 context_replace(curfolder, folder); /* update current folder */
507                 if (chgflag)
508                         mp->curmsg = hghnum + 1;
509                 mp->hghmsg = msgnum;
510                 if (mp->lowmsg == 0)
511                         mp->lowmsg = 1;
512                 if (chgflag)  /* sigh... */
513                         seq_setcur(mp, mp->curmsg);
514         }
515
516         /*
517         ** unlock the mail spool
518         */
519         if (locked) {
520                 GETGROUPPRIVS();  /* Be sure we can unlock mail file */
521                 lkfclose(in, newmail); in = NULL;
522                 DROPGROUPPRIVS();  /* And then return us to normal privileges */
523         } else {
524                 fclose(in); in = NULL;
525         }
526
527         seq_setunseen(mp, 1);  /* add new msgs to unseen sequences */
528         seq_save(mp);  /* synchronize sequences   */
529         context_save();  /* save the context file   */
530         done(0);
531         return 1;
532 }
533
534 static void
535 inc_done(int status)
536 {
537         if (locked) {
538                 GETGROUPPRIVS();
539                 lkfclose(in, newmail);
540                 DROPGROUPPRIVS();
541         }
542         exit(status);
543 }