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