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