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