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