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