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