collect.c revision 74769
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 74769 2001-03-25 04:57:05Z 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;
82	register int c, t;
83	char linebuf[LINESIZE], tempname[PATHSIZE], *cp;
84	char getsub;
85	int omask;
86	void collint(), collhup(), collstop();
87
88	collf = NULL;
89	/*
90	 * Start catching signals from here, but we're still die on interrupts
91	 * until we're in the main loop.
92	 */
93	omask = sigblock(sigmask(SIGINT) | sigmask(SIGHUP));
94	if ((saveint = signal(SIGINT, SIG_IGN)) != SIG_IGN)
95		signal(SIGINT, collint);
96	if ((savehup = signal(SIGHUP, SIG_IGN)) != SIG_IGN)
97		signal(SIGHUP, collhup);
98	savetstp = signal(SIGTSTP, collstop);
99	savettou = signal(SIGTTOU, collstop);
100	savettin = signal(SIGTTIN, collstop);
101	if (setjmp(collabort) || setjmp(colljmp)) {
102		rm(tempname);
103		goto err;
104	}
105	sigsetmask(omask & ~(sigmask(SIGINT) | sigmask(SIGHUP)));
106
107	noreset++;
108	snprintf(tempname, sizeof(tempname), "%s/mail.RsXXXXXXXXXX", tmpdir);
109	if ((fd = mkstemp(tempname)) == -1 ||
110	    (collf = Fdopen(fd, "w+")) == NULL) {
111		warn("%s", tempname);
112		goto err;
113	}
114	rm(tempname);
115
116	/*
117	 * If we are going to prompt for a subject,
118	 * refrain from printing a newline after
119	 * the headers (since some people mind).
120	 */
121	t = GTO|GSUBJECT|GCC|GNL;
122	getsub = 0;
123	if (hp->h_subject == NOSTR && value("interactive") != NOSTR &&
124	    (value("ask") != NOSTR || value("asksub") != NOSTR))
125		t &= ~GNL, getsub++;
126	if (printheaders) {
127		puthead(hp, stdout, t);
128		fflush(stdout);
129	}
130	if ((cp = value("escape")) != NOSTR)
131		escape = *cp;
132	else
133		escape = ESCAPE;
134	eofcount = 0;
135	hadintr = 0;
136
137	if (!setjmp(colljmp)) {
138		if (getsub)
139			grabh(hp, GSUBJECT);
140	} else {
141		/*
142		 * Come here for printing the after-signal message.
143		 * Duplicate messages won't be printed because
144		 * the write is aborted if we get a SIGTTOU.
145		 */
146cont:
147		if (hadintr) {
148			fflush(stdout);
149			fprintf(stderr,
150			"\n(Interrupt -- one more to kill letter)\n");
151		} else {
152			printf("(continue)\n");
153			fflush(stdout);
154		}
155	}
156	for (;;) {
157		colljmp_p = 1;
158		c = readline(stdin, linebuf, LINESIZE);
159		colljmp_p = 0;
160		if (c < 0) {
161			if (value("interactive") != NOSTR &&
162			    value("ignoreeof") != NOSTR && ++eofcount < 25) {
163				printf("Use \".\" to terminate letter\n");
164				continue;
165			}
166			break;
167		}
168		eofcount = 0;
169		hadintr = 0;
170		if (linebuf[0] == '.' && linebuf[1] == '\0' &&
171		    value("interactive") != NOSTR &&
172		    (value("dot") != NOSTR || value("ignoreeof") != NOSTR))
173			break;
174		if (linebuf[0] != escape || value("interactive") == NOSTR) {
175			if (putline(collf, linebuf) < 0)
176				goto err;
177			continue;
178		}
179		c = linebuf[1];
180		switch (c) {
181		default:
182			/*
183			 * On double escape, just send the single one.
184			 * Otherwise, it's an error.
185			 */
186			if (c == escape) {
187				if (putline(collf, &linebuf[1]) < 0)
188					goto err;
189				else
190					break;
191			}
192			printf("Unknown tilde escape.\n");
193			break;
194		case 'C':
195			/*
196			 * Dump core.
197			 */
198			core();
199			break;
200		case '!':
201			/*
202			 * Shell escape, send the balance of the
203			 * line to sh -c.
204			 */
205			shell(&linebuf[2]);
206			break;
207		case ':':
208			/*
209			 * Escape to command mode, but be nice!
210			 */
211			execute(&linebuf[2], 1);
212			goto cont;
213		case '.':
214			/*
215			 * Simulate end of file on input.
216			 */
217			goto out;
218		case 'q':
219			/*
220			 * Force a quit of sending mail.
221			 * Act like an interrupt happened.
222			 */
223			hadintr++;
224			collint(SIGINT);
225			exit(1);
226		case 'h':
227			/*
228			 * Grab a bunch of headers.
229			 */
230			grabh(hp, GTO|GSUBJECT|GCC|GBCC);
231			goto cont;
232		case 't':
233			/*
234			 * Add to the To list.
235			 */
236			hp->h_to = cat(hp->h_to, extract(&linebuf[2], GTO));
237			break;
238		case 's':
239			/*
240			 * Set the Subject line.
241			 */
242			cp = &linebuf[2];
243			while (isspace(*cp))
244				cp++;
245			hp->h_subject = savestr(cp);
246			break;
247		case 'R':
248			/*
249			 * Set the Reply-To line.
250			 */
251			cp = &linebuf[2];
252			while (isspace(*cp))
253				cp++;
254			hp->h_replyto = savestr(cp);
255			break;
256		case 'c':
257			/*
258			 * Add to the CC list.
259			 */
260			hp->h_cc = cat(hp->h_cc, extract(&linebuf[2], GCC));
261			break;
262		case 'b':
263			/*
264			 * Add stuff to blind carbon copies list.
265			 */
266			hp->h_bcc = cat(hp->h_bcc, extract(&linebuf[2], GBCC));
267			break;
268		case 'd':
269			if (strlcpy(linebuf + 2, getdeadletter(), sizeof(linebuf) - 2)
270			    >= sizeof(linebuf) - 2) {
271				printf("Line buffer overflow\n");
272				break;
273			}
274			/* fall into . . . */
275		case 'r':
276			/*
277			 * Invoke a file:
278			 * Search for the file name,
279			 * then open it and copy the contents to collf.
280			 */
281			cp = &linebuf[2];
282			while (isspace(*cp))
283				cp++;
284			if (*cp == '\0') {
285				printf("Interpolate what file?\n");
286				break;
287			}
288			cp = expand(cp);
289			if (cp == NOSTR)
290				break;
291			if (isdir(cp)) {
292				printf("%s: Directory\n", cp);
293				break;
294			}
295			if ((fbuf = Fopen(cp, "r")) == NULL) {
296				warn("%s", cp);
297				break;
298			}
299			printf("\"%s\" ", cp);
300			fflush(stdout);
301			lc = 0;
302			cc = 0;
303			while (readline(fbuf, linebuf, LINESIZE) >= 0) {
304				lc++;
305				if ((t = putline(collf, linebuf)) < 0) {
306					Fclose(fbuf);
307					goto err;
308				}
309				cc += t;
310			}
311			Fclose(fbuf);
312			printf("%d/%d\n", lc, cc);
313			break;
314		case 'w':
315			/*
316			 * Write the message on a file.
317			 */
318			cp = &linebuf[2];
319			while (*cp == ' ' || *cp == '\t')
320				cp++;
321			if (*cp == '\0') {
322				fprintf(stderr, "Write what file!?\n");
323				break;
324			}
325			if ((cp = expand(cp)) == NOSTR)
326				break;
327			rewind(collf);
328			exwrite(cp, collf, 1);
329			break;
330		case 'm':
331		case 'M':
332		case 'f':
333		case 'F':
334			/*
335			 * Interpolate the named messages, if we
336			 * are in receiving mail mode.  Does the
337			 * standard list processing garbage.
338			 * If ~f is given, we don't shift over.
339			 */
340			if (forward(linebuf + 2, collf, tempname, c) < 0)
341				goto err;
342			goto cont;
343		case '?':
344			if ((fbuf = Fopen(_PATH_TILDE, "r")) == NULL) {
345				warn("%s", _PATH_TILDE);
346				break;
347			}
348			while ((t = getc(fbuf)) != EOF)
349				(void) putchar(t);
350			Fclose(fbuf);
351			break;
352		case 'p':
353			/*
354			 * Print out the current state of the
355			 * message without altering anything.
356			 */
357			rewind(collf);
358			printf("-------\nMessage contains:\n");
359			puthead(hp, stdout, GTO|GSUBJECT|GCC|GBCC|GNL);
360			while ((t = getc(collf)) != EOF)
361				(void) putchar(t);
362			goto cont;
363		case '|':
364			/*
365			 * Pipe message through command.
366			 * Collect output as new message.
367			 */
368			rewind(collf);
369			mespipe(collf, &linebuf[2]);
370			goto cont;
371		case 'v':
372		case 'e':
373			/*
374			 * Edit the current message.
375			 * 'e' means to use EDITOR
376			 * 'v' means to use VISUAL
377			 */
378			rewind(collf);
379			mesedit(collf, c);
380			goto cont;
381		}
382	}
383	goto out;
384err:
385	if (collf != NULL) {
386		Fclose(collf);
387		collf = NULL;
388	}
389out:
390	if (collf != NULL)
391		rewind(collf);
392	noreset--;
393	sigblock(sigmask(SIGINT) | sigmask(SIGHUP));
394	signal(SIGINT, saveint);
395	signal(SIGHUP, savehup);
396	signal(SIGTSTP, savetstp);
397	signal(SIGTTOU, savettou);
398	signal(SIGTTIN, savettin);
399	sigsetmask(omask);
400	return collf;
401}
402
403/*
404 * Write a file, ex-like if f set.
405 */
406int
407exwrite(name, fp, f)
408	char name[];
409	FILE *fp;
410	int f;
411{
412	register FILE *of;
413	register int c;
414	long cc;
415	int lc;
416	struct stat junk;
417
418	if (f) {
419		printf("\"%s\" ", name);
420		fflush(stdout);
421	}
422	if (stat(name, &junk) >= 0 && S_ISREG(junk.st_mode)) {
423		if (!f)
424			fprintf(stderr, "%s: ", name);
425		fprintf(stderr, "File exists\n");
426		return(-1);
427	}
428	if ((of = Fopen(name, "w")) == NULL) {
429		warn(NOSTR);
430		return(-1);
431	}
432	lc = 0;
433	cc = 0;
434	while ((c = getc(fp)) != EOF) {
435		cc++;
436		if (c == '\n')
437			lc++;
438		(void) putc(c, of);
439		if (ferror(of)) {
440			warnx("%s", name);
441			Fclose(of);
442			return(-1);
443		}
444	}
445	Fclose(of);
446	printf("%d/%ld\n", lc, cc);
447	fflush(stdout);
448	return(0);
449}
450
451/*
452 * Edit the message being collected on fp.
453 * On return, make the edit file the new temp file.
454 */
455void
456mesedit(fp, c)
457	FILE *fp;
458	int c;
459{
460	sig_t sigint = signal(SIGINT, SIG_IGN);
461	FILE *nf = run_editor(fp, (off_t)-1, c, 0);
462
463	if (nf != NULL) {
464		fseek(nf, 0L, 2);
465		collf = nf;
466		Fclose(fp);
467	}
468	(void) signal(SIGINT, sigint);
469}
470
471/*
472 * Pipe the message through the command.
473 * Old message is on stdin of command;
474 * New message collected from stdout.
475 * Sh -c must return 0 to accept the new message.
476 */
477void
478mespipe(fp, cmd)
479	FILE *fp;
480	char cmd[];
481{
482	FILE *nf;
483	int fd;
484	sig_t sigint = signal(SIGINT, SIG_IGN);
485	char *shell, tempname[PATHSIZE];
486
487	snprintf(tempname, sizeof(tempname), "%s/mail.ReXXXXXXXXXX", tmpdir);
488	if ((fd = mkstemp(tempname)) == -1 ||
489	    (nf = Fdopen(fd, "w+")) == NULL) {
490		warn("%s", tempname);
491		goto out;
492	}
493	(void) rm(tempname);
494	/*
495	 * stdin = current message.
496	 * stdout = new message.
497	 */
498	if ((shell = value("SHELL")) == NOSTR)
499		shell = _PATH_CSHELL;
500	if (run_command(shell,
501	    0, fileno(fp), fileno(nf), "-c", cmd, NOSTR) < 0) {
502		(void) Fclose(nf);
503		goto out;
504	}
505	if (fsize(nf) == 0) {
506		fprintf(stderr, "No bytes from \"%s\" !?\n", cmd);
507		(void) Fclose(nf);
508		goto out;
509	}
510	/*
511	 * Take new files.
512	 */
513	(void) fseek(nf, 0L, 2);
514	collf = nf;
515	(void) Fclose(fp);
516out:
517	(void) signal(SIGINT, sigint);
518}
519
520/*
521 * Interpolate the named messages into the current
522 * message, preceding each line with a tab.
523 * Return a count of the number of characters now in
524 * the message, or -1 if an error is encountered writing
525 * the message temporary.  The flag argument is 'm' if we
526 * should shift over and 'f' if not.
527 */
528int
529forward(ms, fp, fn, f)
530	char ms[];
531	FILE *fp;
532	char *fn;
533	int f;
534{
535	register int *msgvec;
536	struct ignoretab *ig;
537	char *tabst;
538
539	msgvec = (int *) salloc((msgCount+1) * sizeof *msgvec);
540	if (msgvec == (int *) NOSTR)
541		return(0);
542	if (getmsglist(ms, msgvec, 0) < 0)
543		return(0);
544	if (*msgvec == 0) {
545		*msgvec = first(0, MMNORM);
546		if (*msgvec == 0) {
547			printf("No appropriate messages\n");
548			return(0);
549		}
550		msgvec[1] = 0;
551	}
552	if (f == 'f' || f == 'F')
553		tabst = NOSTR;
554	else if ((tabst = value("indentprefix")) == NOSTR)
555		tabst = "\t";
556	ig = isupper(f) ? NULL : ignore;
557	printf("Interpolating:");
558	for (; *msgvec != 0; msgvec++) {
559		struct message *mp = message + *msgvec - 1;
560
561		touch(mp);
562		printf(" %d", *msgvec);
563		if (sendmessage(mp, fp, ig, tabst) < 0) {
564			warnx("%s", fn);
565			return(-1);
566		}
567	}
568	printf("\n");
569	return(0);
570}
571
572/*
573 * Print (continue) when continued after ^Z.
574 */
575/*ARGSUSED*/
576void
577collstop(s)
578	int s;
579{
580	sig_t old_action = signal(s, SIG_DFL);
581
582	sigsetmask(sigblock(0) & ~sigmask(s));
583	kill(0, s);
584	sigblock(sigmask(s));
585	signal(s, old_action);
586	if (colljmp_p) {
587		colljmp_p = 0;
588		hadintr = 0;
589		longjmp(colljmp, 1);
590	}
591}
592
593/*
594 * On interrupt, come here to save the partial message in ~/dead.letter.
595 * Then jump out of the collection loop.
596 */
597/*ARGSUSED*/
598void
599collint(s)
600	int s;
601{
602	/*
603	 * the control flow is subtle, because we can be called from ~q.
604	 */
605	if (!hadintr) {
606		if (value("ignore") != NOSTR) {
607			puts("@");
608			fflush(stdout);
609			clearerr(stdin);
610			return;
611		}
612		hadintr = 1;
613		longjmp(colljmp, 1);
614	}
615	rewind(collf);
616	if (value("nosave") == NOSTR)
617		savedeadletter(collf);
618	longjmp(collabort, 1);
619}
620
621/*ARGSUSED*/
622void
623collhup(s)
624	int s;
625{
626	rewind(collf);
627	savedeadletter(collf);
628	/*
629	 * Let's pretend nobody else wants to clean up,
630	 * a true statement at this time.
631	 */
632	exit(1);
633}
634
635void
636savedeadletter(fp)
637	register FILE *fp;
638{
639	register FILE *dbuf;
640	register int c;
641	char *cp;
642
643	if (fsize(fp) == 0)
644		return;
645	cp = getdeadletter();
646	c = umask(077);
647	dbuf = Fopen(cp, "a");
648	(void) umask(c);
649	if (dbuf == NULL)
650		return;
651	while ((c = getc(fp)) != EOF)
652		(void) putc(c, dbuf);
653	Fclose(dbuf);
654	rewind(fp);
655}
656