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