collect.c revision 88150
1/*
2 * Copyright (c) 1980, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35#if 0
36static char sccsid[] = "@(#)collect.c	8.2 (Berkeley) 4/19/94";
37#endif
38static const char rcsid[] =
39  "$FreeBSD: head/usr.bin/mail/collect.c 88150 2001-12-18 20:52:09Z mikeh $";
40#endif /* not lint */
41
42/*
43 * Mail -- a mail program
44 *
45 * Collect input from standard input, handling
46 * ~ escapes.
47 */
48
49#include "rcv.h"
50#include "extern.h"
51
52/*
53 * Read a message from standard output and return a read file to it
54 * or NULL on error.
55 */
56
57/*
58 * The following hokiness with global variables is so that on
59 * receipt of an interrupt signal, the partial message can be salted
60 * away on dead.letter.
61 */
62
63static	sig_t	saveint;		/* Previous SIGINT value */
64static	sig_t	savehup;		/* Previous SIGHUP value */
65static	sig_t	savetstp;		/* Previous SIGTSTP value */
66static	sig_t	savettou;		/* Previous SIGTTOU value */
67static	sig_t	savettin;		/* Previous SIGTTIN value */
68static	FILE	*collf;			/* File for saving away */
69static	int	hadintr;		/* Have seen one SIGINT so far */
70
71static	jmp_buf	colljmp;		/* To get back to work */
72static	int	colljmp_p;		/* whether to long jump */
73static	jmp_buf	collabort;		/* To end collection with error */
74
75FILE *
76collect(hp, printheaders)
77	struct header *hp;
78	int printheaders;
79{
80	FILE *fbuf;
81	int lc, cc, escape, eofcount, fd, c, t;
82	char linebuf[LINESIZE], tempname[PATHSIZE], *cp, getsub;
83	sigset_t nset;
84	int longline, lastlong, rc;	/* So we don't make 2 or more lines
85					   out of a long input line. */
86
87	collf = NULL;
88	/*
89	 * Start catching signals from here, but we're still die on interrupts
90	 * until we're in the main loop.
91	 */
92	(void)sigemptyset(&nset);
93	(void)sigaddset(&nset, SIGINT);
94	(void)sigaddset(&nset, SIGHUP);
95	(void)sigprocmask(SIG_BLOCK, &nset, NULL);
96	if ((saveint = signal(SIGINT, SIG_IGN)) != SIG_IGN)
97		(void)signal(SIGINT, collint);
98	if ((savehup = signal(SIGHUP, SIG_IGN)) != SIG_IGN)
99		(void)signal(SIGHUP, collhup);
100	savetstp = signal(SIGTSTP, collstop);
101	savettou = signal(SIGTTOU, collstop);
102	savettin = signal(SIGTTIN, collstop);
103	if (setjmp(collabort) || setjmp(colljmp)) {
104		(void)rm(tempname);
105		goto err;
106	}
107	(void)sigprocmask(SIG_UNBLOCK, &nset, NULL);
108
109	noreset++;
110	(void)snprintf(tempname, sizeof(tempname),
111	    "%s/mail.RsXXXXXXXXXX", tmpdir);
112	if ((fd = mkstemp(tempname)) == -1 ||
113	    (collf = Fdopen(fd, "w+")) == NULL) {
114		warn("%s", tempname);
115		goto err;
116	}
117	(void)rm(tempname);
118
119	/*
120	 * If we are going to prompt for a subject,
121	 * refrain from printing a newline after
122	 * the headers (since some people mind).
123	 */
124	t = GTO|GSUBJECT|GCC|GNL;
125	getsub = 0;
126	if (hp->h_subject == NULL && value("interactive") != NULL &&
127	    (value("ask") != NULL || value("asksub") != NULL))
128		t &= ~GNL, getsub++;
129	if (printheaders) {
130		puthead(hp, stdout, t);
131		(void)fflush(stdout);
132	}
133	if ((cp = value("escape")) != NULL)
134		escape = *cp;
135	else
136		escape = ESCAPE;
137	eofcount = 0;
138	hadintr = 0;
139	lastlong = 0;
140	longline = 0;
141
142	if (!setjmp(colljmp)) {
143		if (getsub)
144			grabh(hp, GSUBJECT);
145	} else {
146		/*
147		 * Come here for printing the after-signal message.
148		 * Duplicate messages won't be printed because
149		 * the write is aborted if we get a SIGTTOU.
150		 */
151cont:
152		if (hadintr) {
153			(void)fflush(stdout);
154			fprintf(stderr,
155			"\n(Interrupt -- one more to kill letter)\n");
156		} else {
157			printf("(continue)\n");
158			(void)fflush(stdout);
159		}
160	}
161	for (;;) {
162		colljmp_p = 1;
163		c = readline(stdin, linebuf, LINESIZE);
164		colljmp_p = 0;
165		if (c < 0) {
166			if (value("interactive") != NULL &&
167			    value("ignoreeof") != NULL && ++eofcount < 25) {
168				printf("Use \".\" to terminate letter\n");
169				continue;
170			}
171			break;
172		}
173		lastlong = longline;
174		longline = c == LINESIZE - 1;
175		eofcount = 0;
176		hadintr = 0;
177		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
178		    value("interactive") != NULL && !lastlong &&
179		    (value("dot") != NULL || value("ignoreeof") != NULL))
180			break;
181		if (linebuf[0] != escape || value("interactive") == NULL ||
182		    lastlong) {
183			if (putline(collf, linebuf, !longline) < 0)
184				goto err;
185			continue;
186		}
187		c = linebuf[1];
188		switch (c) {
189		default:
190			/*
191			 * On double escape, just send the single one.
192			 * Otherwise, it's an error.
193			 */
194			if (c == escape) {
195				if (putline(collf, &linebuf[1], !longline) < 0)
196					goto err;
197				else
198					break;
199			}
200			printf("Unknown tilde escape.\n");
201			break;
202		case 'C':
203			/*
204			 * Dump core.
205			 */
206			core();
207			break;
208		case '!':
209			/*
210			 * Shell escape, send the balance of the
211			 * line to sh -c.
212			 */
213			shell(&linebuf[2]);
214			break;
215		case ':':
216			/*
217			 * Escape to command mode, but be nice!
218			 */
219			execute(&linebuf[2], 1);
220			goto cont;
221		case '.':
222			/*
223			 * Simulate end of file on input.
224			 */
225			goto out;
226		case 'q':
227			/*
228			 * Force a quit of sending mail.
229			 * Act like an interrupt happened.
230			 */
231			hadintr++;
232			collint(SIGINT);
233			exit(1);
234		case 'h':
235			/*
236			 * Grab a bunch of headers.
237			 */
238			grabh(hp, GTO|GSUBJECT|GCC|GBCC);
239			goto cont;
240		case 't':
241			/*
242			 * Add to the To list.
243			 */
244			hp->h_to = cat(hp->h_to, extract(&linebuf[2], GTO));
245			break;
246		case 's':
247			/*
248			 * Set the Subject line.
249			 */
250			cp = &linebuf[2];
251			while (isspace(*cp))
252				cp++;
253			hp->h_subject = savestr(cp);
254			break;
255		case 'R':
256			/*
257			 * Set the Reply-To line.
258			 */
259			cp = &linebuf[2];
260			while (isspace(*cp))
261				cp++;
262			hp->h_replyto = savestr(cp);
263			break;
264		case 'c':
265			/*
266			 * Add to the CC list.
267			 */
268			hp->h_cc = cat(hp->h_cc, extract(&linebuf[2], GCC));
269			break;
270		case 'b':
271			/*
272			 * Add stuff to blind carbon copies list.
273			 */
274			hp->h_bcc = cat(hp->h_bcc, extract(&linebuf[2], GBCC));
275			break;
276		case 'd':
277			if (strlcpy(linebuf + 2, getdeadletter(), sizeof(linebuf) - 2)
278			    >= sizeof(linebuf) - 2) {
279				printf("Line buffer overflow\n");
280				break;
281			}
282			/* fall into . . . */
283		case 'r':
284			/*
285			 * Invoke a file:
286			 * Search for the file name,
287			 * then open it and copy the contents to collf.
288			 */
289			cp = &linebuf[2];
290			while (isspace(*cp))
291				cp++;
292			if (*cp == '\0') {
293				printf("Interpolate what file?\n");
294				break;
295			}
296			cp = expand(cp);
297			if (cp == NULL)
298				break;
299			if (isdir(cp)) {
300				printf("%s: Directory\n", cp);
301				break;
302			}
303			if ((fbuf = Fopen(cp, "r")) == NULL) {
304				warn("%s", cp);
305				break;
306			}
307			printf("\"%s\" ", cp);
308			(void)fflush(stdout);
309			lc = 0;
310			cc = 0;
311			while ((rc = readline(fbuf, linebuf, LINESIZE)) >= 0) {
312				if (rc != LINESIZE - 1)
313					lc++;
314				if ((t = putline(collf, linebuf,
315					 rc != LINESIZE - 1)) < 0) {
316					(void)Fclose(fbuf);
317					goto err;
318				}
319				cc += t;
320			}
321			(void)Fclose(fbuf);
322			printf("%d/%d\n", lc, cc);
323			break;
324		case 'w':
325			/*
326			 * Write the message on a file.
327			 */
328			cp = &linebuf[2];
329			while (*cp == ' ' || *cp == '\t')
330				cp++;
331			if (*cp == '\0') {
332				fprintf(stderr, "Write what file!?\n");
333				break;
334			}
335			if ((cp = expand(cp)) == NULL)
336				break;
337			rewind(collf);
338			exwrite(cp, collf, 1);
339			break;
340		case 'm':
341		case 'M':
342		case 'f':
343		case 'F':
344			/*
345			 * Interpolate the named messages, if we
346			 * are in receiving mail mode.  Does the
347			 * standard list processing garbage.
348			 * If ~f is given, we don't shift over.
349			 */
350			if (forward(linebuf + 2, collf, tempname, c) < 0)
351				goto err;
352			goto cont;
353		case '?':
354			if ((fbuf = Fopen(_PATH_TILDE, "r")) == NULL) {
355				warn("%s", _PATH_TILDE);
356				break;
357			}
358			while ((t = getc(fbuf)) != EOF)
359				(void)putchar(t);
360			(void)Fclose(fbuf);
361			break;
362		case 'p':
363			/*
364			 * Print out the current state of the
365			 * message without altering anything.
366			 */
367			rewind(collf);
368			printf("-------\nMessage contains:\n");
369			puthead(hp, stdout, GTO|GSUBJECT|GCC|GBCC|GNL);
370			while ((t = getc(collf)) != EOF)
371				(void)putchar(t);
372			goto cont;
373		case '|':
374			/*
375			 * Pipe message through command.
376			 * Collect output as new message.
377			 */
378			rewind(collf);
379			mespipe(collf, &linebuf[2]);
380			goto cont;
381		case 'v':
382		case 'e':
383			/*
384			 * Edit the current message.
385			 * 'e' means to use EDITOR
386			 * 'v' means to use VISUAL
387			 */
388			rewind(collf);
389			mesedit(collf, c);
390			goto cont;
391		}
392	}
393	goto out;
394err:
395	if (collf != NULL) {
396		(void)Fclose(collf);
397		collf = NULL;
398	}
399out:
400	if (collf != NULL)
401		rewind(collf);
402	noreset--;
403	(void)sigprocmask(SIG_BLOCK, &nset, NULL);
404	(void)signal(SIGINT, saveint);
405	(void)signal(SIGHUP, savehup);
406	(void)signal(SIGTSTP, savetstp);
407	(void)signal(SIGTTOU, savettou);
408	(void)signal(SIGTTIN, savettin);
409	(void)sigprocmask(SIG_UNBLOCK, &nset, NULL);
410	return (collf);
411}
412
413/*
414 * Write a file, ex-like if f set.
415 */
416int
417exwrite(name, fp, f)
418	char name[];
419	FILE *fp;
420	int f;
421{
422	FILE *of;
423	int c, lc;
424	long cc;
425	struct stat junk;
426
427	if (f) {
428		printf("\"%s\" ", name);
429		(void)fflush(stdout);
430	}
431	if (stat(name, &junk) >= 0 && S_ISREG(junk.st_mode)) {
432		if (!f)
433			fprintf(stderr, "%s: ", name);
434		fprintf(stderr, "File exists\n");
435		return (-1);
436	}
437	if ((of = Fopen(name, "w")) == NULL) {
438		warn((char *)NULL);
439		return (-1);
440	}
441	lc = 0;
442	cc = 0;
443	while ((c = getc(fp)) != EOF) {
444		cc++;
445		if (c == '\n')
446			lc++;
447		(void)putc(c, of);
448		if (ferror(of)) {
449			warnx("%s", name);
450			(void)Fclose(of);
451			return (-1);
452		}
453	}
454	(void)Fclose(of);
455	printf("%d/%ld\n", lc, cc);
456	(void)fflush(stdout);
457	return (0);
458}
459
460/*
461 * Edit the message being collected on fp.
462 * On return, make the edit file the new temp file.
463 */
464void
465mesedit(fp, c)
466	FILE *fp;
467	int c;
468{
469	sig_t sigint = signal(SIGINT, SIG_IGN);
470	FILE *nf = run_editor(fp, (off_t)-1, c, 0);
471
472	if (nf != NULL) {
473		(void)fseeko(nf, (off_t)0, SEEK_END);
474		collf = nf;
475		(void)Fclose(fp);
476	}
477	(void)signal(SIGINT, sigint);
478}
479
480/*
481 * Pipe the message through the command.
482 * Old message is on stdin of command;
483 * New message collected from stdout.
484 * Sh -c must return 0 to accept the new message.
485 */
486void
487mespipe(fp, cmd)
488	FILE *fp;
489	char cmd[];
490{
491	FILE *nf;
492	int fd;
493	sig_t sigint = signal(SIGINT, SIG_IGN);
494	char *sh, tempname[PATHSIZE];
495
496	(void)snprintf(tempname, sizeof(tempname),
497	    "%s/mail.ReXXXXXXXXXX", tmpdir);
498	if ((fd = mkstemp(tempname)) == -1 ||
499	    (nf = Fdopen(fd, "w+")) == NULL) {
500		warn("%s", tempname);
501		goto out;
502	}
503	(void)rm(tempname);
504	/*
505	 * stdin = current message.
506	 * stdout = new message.
507	 */
508	if ((sh = value("SHELL")) == NULL)
509		sh = _PATH_CSHELL;
510	if (run_command(sh,
511	    0, fileno(fp), fileno(nf), "-c", cmd, NULL) < 0) {
512		(void)Fclose(nf);
513		goto out;
514	}
515	if (fsize(nf) == 0) {
516		fprintf(stderr, "No bytes from \"%s\" !?\n", cmd);
517		(void)Fclose(nf);
518		goto out;
519	}
520	/*
521	 * Take new files.
522	 */
523	(void)fseeko(nf, (off_t)0, SEEK_END);
524	collf = nf;
525	(void)Fclose(fp);
526out:
527	(void)signal(SIGINT, sigint);
528}
529
530/*
531 * Interpolate the named messages into the current
532 * message, preceding each line with a tab.
533 * Return a count of the number of characters now in
534 * the message, or -1 if an error is encountered writing
535 * the message temporary.  The flag argument is 'm' if we
536 * should shift over and 'f' if not.
537 */
538int
539forward(ms, fp, fn, f)
540	char ms[];
541	FILE *fp;
542	char *fn;
543	int f;
544{
545	int *msgvec;
546	struct ignoretab *ig;
547	char *tabst;
548
549	msgvec = (int *)salloc((msgCount+1) * sizeof(*msgvec));
550	if (msgvec == NULL)
551		return (0);
552	if (getmsglist(ms, msgvec, 0) < 0)
553		return (0);
554	if (*msgvec == 0) {
555		*msgvec = first(0, MMNORM);
556		if (*msgvec == 0) {
557			printf("No appropriate messages\n");
558			return (0);
559		}
560		msgvec[1] = 0;
561	}
562	if (f == 'f' || f == 'F')
563		tabst = NULL;
564	else if ((tabst = value("indentprefix")) == NULL)
565		tabst = "\t";
566	ig = isupper(f) ? NULL : ignore;
567	printf("Interpolating:");
568	for (; *msgvec != 0; msgvec++) {
569		struct message *mp = message + *msgvec - 1;
570
571		touch(mp);
572		printf(" %d", *msgvec);
573		if (sendmessage(mp, fp, ig, tabst) < 0) {
574			warnx("%s", fn);
575			return (-1);
576		}
577	}
578	printf("\n");
579	return (0);
580}
581
582/*
583 * Print (continue) when continued after ^Z.
584 */
585/*ARGSUSED*/
586void
587collstop(s)
588	int s;
589{
590	sig_t old_action = signal(s, SIG_DFL);
591	sigset_t nset;
592
593	(void)sigemptyset(&nset);
594	(void)sigaddset(&nset, s);
595	(void)sigprocmask(SIG_UNBLOCK, &nset, NULL);
596	(void)kill(0, s);
597	(void)sigprocmask(SIG_BLOCK, &nset, NULL);
598	(void)signal(s, old_action);
599	if (colljmp_p) {
600		colljmp_p = 0;
601		hadintr = 0;
602		longjmp(colljmp, 1);
603	}
604}
605
606/*
607 * On interrupt, come here to save the partial message in ~/dead.letter.
608 * Then jump out of the collection loop.
609 */
610/*ARGSUSED*/
611void
612collint(s)
613	int s;
614{
615	/*
616	 * the control flow is subtle, because we can be called from ~q.
617	 */
618	if (!hadintr) {
619		if (value("ignore") != NULL) {
620			printf("@");
621			(void)fflush(stdout);
622			clearerr(stdin);
623			return;
624		}
625		hadintr = 1;
626		longjmp(colljmp, 1);
627	}
628	rewind(collf);
629	if (value("nosave") == NULL)
630		savedeadletter(collf);
631	longjmp(collabort, 1);
632}
633
634/*ARGSUSED*/
635void
636collhup(s)
637	int s;
638{
639	rewind(collf);
640	savedeadletter(collf);
641	/*
642	 * Let's pretend nobody else wants to clean up,
643	 * a true statement at this time.
644	 */
645	exit(1);
646}
647
648void
649savedeadletter(fp)
650	FILE *fp;
651{
652	FILE *dbuf;
653	int c;
654	char *cp;
655
656	if (fsize(fp) == 0)
657		return;
658	cp = getdeadletter();
659	c = umask(077);
660	dbuf = Fopen(cp, "a");
661	(void)umask(c);
662	if (dbuf == NULL)
663		return;
664	while ((c = getc(fp)) != EOF)
665		(void)putc(c, dbuf);
666	(void)Fclose(dbuf);
667	rewind(fp);
668}
669