xref: /freebsd/usr.bin/mail/lex.c (revision ce4946daa5ce852d28008dac492029500ab2ee95)
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  * $FreeBSD$
34  */
35 
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)lex.c	8.1 (Berkeley) 6/6/93";
39 #endif
40 static const char rcsid[] =
41   "$FreeBSD$";
42 #endif /* not lint */
43 
44 #include "rcv.h"
45 #include <errno.h>
46 #include <fcntl.h>
47 #include "extern.h"
48 
49 /*
50  * Mail -- a mail program
51  *
52  * Lexical processing of commands.
53  */
54 
55 char	*prompt = "& ";
56 
57 /*
58  * Set up editing on the given file name.
59  * If the first character of name is %, we are considered to be
60  * editing the file, otherwise we are reading our mail which has
61  * signficance for mbox and so forth.
62  */
63 int
64 setfile(name)
65 	char *name;
66 {
67 	FILE *ibuf;
68 	int i, fd;
69 	struct stat stb;
70 	char isedit = *name != '%';
71 	char *who = name[1] ? name + 1 : myname;
72 	char tempname[PATHSIZE];
73 	static int shudclob;
74 
75 	if ((name = expand(name)) == NOSTR)
76 		return -1;
77 
78 	if ((ibuf = Fopen(name, "r")) == NULL) {
79 		if (!isedit && errno == ENOENT)
80 			goto nomail;
81 		warn("%s", name);
82 		return(-1);
83 	}
84 
85 	if (fstat(fileno(ibuf), &stb) < 0) {
86 		warn("fstat");
87 		Fclose(ibuf);
88 		return (-1);
89 	}
90 
91 	if (S_ISDIR(stb.st_mode) || !S_ISREG(stb.st_mode)) {
92 		Fclose(ibuf);
93 		errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
94 		warn("%s", name);
95 		return (-1);
96 	}
97 
98 	/*
99 	 * Looks like all will be well.  We must now relinquish our
100 	 * hold on the current set of stuff.  Must hold signals
101 	 * while we are reading the new file, else we will ruin
102 	 * the message[] data structure.
103 	 */
104 
105 	holdsigs();
106 	if (shudclob)
107 		quit();
108 
109 	/*
110 	 * Copy the messages into /tmp
111 	 * and set pointers.
112 	 */
113 
114 	readonly = 0;
115 	if ((i = open(name, 1)) < 0)
116 		readonly++;
117 	else
118 		close(i);
119 	if (shudclob) {
120 		fclose(itf);
121 		fclose(otf);
122 	}
123 	shudclob = 1;
124 	edit = isedit;
125 	strlcpy(prevfile, mailname, sizeof(prevfile));
126 	if (name != mailname)
127 		strlcpy(mailname, name, sizeof(mailname));
128 	mailsize = fsize(ibuf);
129 	snprintf(tempname, sizeof(tempname), "%s/mail.RxXXXXXXXXXX", tmpdir);
130 	if ((fd = mkstemp(tempname)) == -1 || (otf = fdopen(fd, "w")) == NULL)
131 		err(1, "%s", tempname);
132 	(void) fcntl(fileno(otf), F_SETFD, 1);
133 	if ((itf = fopen(tempname, "r")) == NULL)
134 		err(1, "%s", tempname);
135 	(void) fcntl(fileno(itf), F_SETFD, 1);
136 	rm(tempname);
137 	setptr(ibuf);
138 	setmsize(msgCount);
139 	Fclose(ibuf);
140 	relsesigs();
141 	sawcom = 0;
142 	if (!edit && msgCount == 0) {
143 nomail:
144 		fprintf(stderr, "No mail for %s\n", who);
145 		return -1;
146 	}
147 	return(0);
148 }
149 
150 int	*msgvec;
151 int	reset_on_stop;			/* do a reset() if stopped */
152 
153 /*
154  * Interpret user commands one by one.  If standard input is not a tty,
155  * print no prompt.
156  */
157 void
158 commands()
159 {
160 	int eofloop = 0;
161 	register int n;
162 	char linebuf[LINESIZE];
163 	void intr(), stop(), hangup();
164 
165 	if (!sourcing) {
166 		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
167 			signal(SIGINT, intr);
168 		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
169 			signal(SIGHUP, hangup);
170 		signal(SIGTSTP, stop);
171 		signal(SIGTTOU, stop);
172 		signal(SIGTTIN, stop);
173 	}
174 	setexit();
175 	for (;;) {
176 		/*
177 		 * Print the prompt, if needed.  Clear out
178 		 * string space, and flush the output.
179 		 */
180 		if (!sourcing && value("interactive") != NOSTR) {
181 			reset_on_stop = 1;
182 			printf("%s", prompt);
183 		}
184 		fflush(stdout);
185 		sreset();
186 		/*
187 		 * Read a line of commands from the current input
188 		 * and handle end of file specially.
189 		 */
190 		n = 0;
191 		for (;;) {
192 			if (readline(input, &linebuf[n], LINESIZE - n) < 0) {
193 				if (n == 0)
194 					n = -1;
195 				break;
196 			}
197 			if ((n = strlen(linebuf)) == 0)
198 				break;
199 			n--;
200 			if (linebuf[n] != '\\')
201 				break;
202 			linebuf[n++] = ' ';
203 		}
204 		reset_on_stop = 0;
205 		if (n < 0) {
206 				/* eof */
207 			if (loading)
208 				break;
209 			if (sourcing) {
210 				unstack();
211 				continue;
212 			}
213 			if (value("interactive") != NOSTR &&
214 			    value("ignoreeof") != NOSTR &&
215 			    ++eofloop < 25) {
216 				printf("Use \"quit\" to quit.\n");
217 				continue;
218 			}
219 			break;
220 		}
221 		eofloop = 0;
222 		if (execute(linebuf, 0))
223 			break;
224 	}
225 }
226 
227 /*
228  * Execute a single command.
229  * Command functions return 0 for success, 1 for error, and -1
230  * for abort.  A 1 or -1 aborts a load or source.  A -1 aborts
231  * the interactive command loop.
232  * Contxt is non-zero if called while composing mail.
233  */
234 int
235 execute(linebuf, contxt)
236 	char linebuf[];
237 	int contxt;
238 {
239 	char word[LINESIZE];
240 	char *arglist[MAXARGC];
241 	struct cmd *com;
242 	register char *cp, *cp2;
243 	register int c;
244 	int muvec[2];
245 	int e = 1;
246 
247 	/*
248 	 * Strip the white space away from the beginning
249 	 * of the command, then scan out a word, which
250 	 * consists of anything except digits and white space.
251 	 *
252 	 * Handle ! escapes differently to get the correct
253 	 * lexical conventions.
254 	 */
255 
256 	for (cp = linebuf; isspace(*cp); cp++)
257 		;
258 	if (*cp == '!') {
259 		if (sourcing) {
260 			printf("Can't \"!\" while sourcing\n");
261 			goto out;
262 		}
263 		shell(cp+1);
264 		return(0);
265 	}
266 	cp2 = word;
267 	while (*cp && strchr(" \t0123456789$^.:/-+*'\"", *cp) == NOSTR)
268 		*cp2++ = *cp++;
269 	*cp2 = '\0';
270 
271 	/*
272 	 * Look up the command; if not found, bitch.
273 	 * Normally, a blank command would map to the
274 	 * first command in the table; while sourcing,
275 	 * however, we ignore blank lines to eliminate
276 	 * confusion.
277 	 */
278 
279 	if (sourcing && *word == '\0')
280 		return(0);
281 	com = lex(word);
282 	if (com == NONE) {
283 		printf("Unknown command: \"%s\"\n", word);
284 		goto out;
285 	}
286 
287 	/*
288 	 * See if we should execute the command -- if a conditional
289 	 * we always execute it, otherwise, check the state of cond.
290 	 */
291 
292 	if ((com->c_argtype & F) == 0)
293 		if (cond == CRCV && !rcvmode || cond == CSEND && rcvmode)
294 			return(0);
295 
296 	/*
297 	 * Process the arguments to the command, depending
298 	 * on the type he expects.  Default to an error.
299 	 * If we are sourcing an interactive command, it's
300 	 * an error.
301 	 */
302 
303 	if (!rcvmode && (com->c_argtype & M) == 0) {
304 		printf("May not execute \"%s\" while sending\n",
305 		    com->c_name);
306 		goto out;
307 	}
308 	if (sourcing && com->c_argtype & I) {
309 		printf("May not execute \"%s\" while sourcing\n",
310 		    com->c_name);
311 		goto out;
312 	}
313 	if (readonly && com->c_argtype & W) {
314 		printf("May not execute \"%s\" -- message file is read only\n",
315 		   com->c_name);
316 		goto out;
317 	}
318 	if (contxt && com->c_argtype & R) {
319 		printf("Cannot recursively invoke \"%s\"\n", com->c_name);
320 		goto out;
321 	}
322 	switch (com->c_argtype & ~(F|P|I|M|T|W|R)) {
323 	case MSGLIST:
324 		/*
325 		 * A message list defaulting to nearest forward
326 		 * legal message.
327 		 */
328 		if (msgvec == 0) {
329 			printf("Illegal use of \"message list\"\n");
330 			break;
331 		}
332 		if ((c = getmsglist(cp, msgvec, com->c_msgflag)) < 0)
333 			break;
334 		if (c  == 0) {
335 			*msgvec = first(com->c_msgflag,
336 				com->c_msgmask);
337 			msgvec[1] = 0;
338 		}
339 		if (*msgvec == 0) {
340 			printf("No applicable messages\n");
341 			break;
342 		}
343 		e = (*com->c_func)(msgvec);
344 		break;
345 
346 	case NDMLIST:
347 		/*
348 		 * A message list with no defaults, but no error
349 		 * if none exist.
350 		 */
351 		if (msgvec == 0) {
352 			printf("Illegal use of \"message list\"\n");
353 			break;
354 		}
355 		if (getmsglist(cp, msgvec, com->c_msgflag) < 0)
356 			break;
357 		e = (*com->c_func)(msgvec);
358 		break;
359 
360 	case STRLIST:
361 		/*
362 		 * Just the straight string, with
363 		 * leading blanks removed.
364 		 */
365 		while (isspace(*cp))
366 			cp++;
367 		e = (*com->c_func)(cp);
368 		break;
369 
370 	case RAWLIST:
371 		/*
372 		 * A vector of strings, in shell style.
373 		 */
374 		if ((c = getrawlist(cp, arglist,
375 				sizeof arglist / sizeof *arglist)) < 0)
376 			break;
377 		if (c < com->c_minargs) {
378 			printf("%s requires at least %d arg(s)\n",
379 				com->c_name, com->c_minargs);
380 			break;
381 		}
382 		if (c > com->c_maxargs) {
383 			printf("%s takes no more than %d arg(s)\n",
384 				com->c_name, com->c_maxargs);
385 			break;
386 		}
387 		e = (*com->c_func)(arglist);
388 		break;
389 
390 	case NOLIST:
391 		/*
392 		 * Just the constant zero, for exiting,
393 		 * eg.
394 		 */
395 		e = (*com->c_func)(0);
396 		break;
397 
398 	default:
399 		errx(1, "Unknown argtype");
400 	}
401 
402 out:
403 	/*
404 	 * Exit the current source file on
405 	 * error.
406 	 */
407 	if (e) {
408 		if (e < 0)
409 			return 1;
410 		if (loading)
411 			return 1;
412 		if (sourcing)
413 			unstack();
414 		return 0;
415 	}
416 	if (value("autoprint") != NOSTR && com->c_argtype & P)
417 		if ((dot->m_flag & MDELETED) == 0) {
418 			muvec[0] = dot - &message[0] + 1;
419 			muvec[1] = 0;
420 			type(muvec);
421 		}
422 	if (!sourcing && (com->c_argtype & T) == 0)
423 		sawcom = 1;
424 	return(0);
425 }
426 
427 /*
428  * Set the size of the message vector used to construct argument
429  * lists to message list functions.
430  */
431 void
432 setmsize(sz)
433 	int sz;
434 {
435 
436 	if (msgvec != 0)
437 		free((char *) msgvec);
438 	msgvec = (int *) calloc((unsigned) (sz + 1), sizeof *msgvec);
439 }
440 
441 /*
442  * Find the correct command in the command table corresponding
443  * to the passed command "word"
444  */
445 
446 struct cmd *
447 lex(word)
448 	char word[];
449 {
450 	register struct cmd *cp;
451 	extern struct cmd cmdtab[];
452 
453 	/*
454 	 * ignore trailing chars after `#'
455 	 *
456 	 * lines with beginning `#' are comments
457 	 * spaces before `#' are ignored in execute()
458 	 */
459 
460 	if (*word == '#')
461 	    *(word+1) = '\0';
462 
463 
464 	for (cp = &cmdtab[0]; cp->c_name != NOSTR; cp++)
465 		if (isprefix(word, cp->c_name))
466 			return(cp);
467 	return(NONE);
468 }
469 
470 /*
471  * Determine if as1 is a valid prefix of as2.
472  * Return true if yep.
473  */
474 int
475 isprefix(as1, as2)
476 	char *as1, *as2;
477 {
478 	register char *s1, *s2;
479 
480 	s1 = as1;
481 	s2 = as2;
482 	while (*s1++ == *s2)
483 		if (*s2++ == '\0')
484 			return(1);
485 	return(*--s1 == '\0');
486 }
487 
488 /*
489  * The following gets called on receipt of an interrupt.  This is
490  * to abort printout of a command, mainly.
491  * Dispatching here when command() is inactive crashes rcv.
492  * Close all open files except 0, 1, 2, and the temporary.
493  * Also, unstack all source files.
494  */
495 
496 int	inithdr;			/* am printing startup headers */
497 
498 /*ARGSUSED*/
499 void
500 intr(s)
501 	int s;
502 {
503 
504 	noreset = 0;
505 	if (!inithdr)
506 		sawcom++;
507 	inithdr = 0;
508 	while (sourcing)
509 		unstack();
510 
511 	close_all_files();
512 
513 	if (image >= 0) {
514 		close(image);
515 		image = -1;
516 	}
517 	fprintf(stderr, "Interrupt\n");
518 	reset(0);
519 }
520 
521 /*
522  * When we wake up after ^Z, reprint the prompt.
523  */
524 void
525 stop(s)
526 	int s;
527 {
528 	sig_t old_action = signal(s, SIG_DFL);
529 
530 	sigsetmask(sigblock(0) & ~sigmask(s));
531 	kill(0, s);
532 	sigblock(sigmask(s));
533 	signal(s, old_action);
534 	if (reset_on_stop) {
535 		reset_on_stop = 0;
536 		reset(0);
537 	}
538 }
539 
540 /*
541  * Branch here on hangup signal and simulate "exit".
542  */
543 /*ARGSUSED*/
544 void
545 hangup(s)
546 	int s;
547 {
548 
549 	/* nothing to do? */
550 	exit(1);
551 }
552 
553 /*
554  * Announce the presence of the current Mail version,
555  * give the message count, and print a header listing.
556  */
557 void
558 announce()
559 {
560 	int vec[2], mdot;
561 
562 	mdot = newfileinfo();
563 	vec[0] = mdot;
564 	vec[1] = 0;
565 	dot = &message[mdot - 1];
566 	if (msgCount > 0 && value("noheader") == NOSTR) {
567 		inithdr++;
568 		headers(vec);
569 		inithdr = 0;
570 	}
571 }
572 
573 /*
574  * Announce information about the file we are editing.
575  * Return a likely place to set dot.
576  */
577 int
578 newfileinfo()
579 {
580 	register struct message *mp;
581 	register int u, n, mdot, d, s;
582 	char fname[PATHSIZE+1], zname[PATHSIZE+1], *ename;
583 
584 	for (mp = &message[0]; mp < &message[msgCount]; mp++)
585 		if (mp->m_flag & MNEW)
586 			break;
587 	if (mp >= &message[msgCount])
588 		for (mp = &message[0]; mp < &message[msgCount]; mp++)
589 			if ((mp->m_flag & MREAD) == 0)
590 				break;
591 	if (mp < &message[msgCount])
592 		mdot = mp - &message[0] + 1;
593 	else
594 		mdot = 1;
595 	s = d = 0;
596 	for (mp = &message[0], n = 0, u = 0; mp < &message[msgCount]; mp++) {
597 		if (mp->m_flag & MNEW)
598 			n++;
599 		if ((mp->m_flag & MREAD) == 0)
600 			u++;
601 		if (mp->m_flag & MDELETED)
602 			d++;
603 		if (mp->m_flag & MSAVED)
604 			s++;
605 	}
606 	ename = mailname;
607 	if (getfold(fname, sizeof(fname) - 1) >= 0) {
608 		strcat(fname, "/");
609 		if (strncmp(fname, mailname, strlen(fname)) == 0) {
610 			snprintf(zname, sizeof(zname), "+%s", mailname + strlen(fname));
611 			ename = zname;
612 		}
613 	}
614 	printf("\"%s\": ", ename);
615 	if (msgCount == 1)
616 		printf("1 message");
617 	else
618 		printf("%d messages", msgCount);
619 	if (n > 0)
620 		printf(" %d new", n);
621 	if (u-n > 0)
622 		printf(" %d unread", u);
623 	if (d > 0)
624 		printf(" %d deleted", d);
625 	if (s > 0)
626 		printf(" %d saved", s);
627 	if (readonly)
628 		printf(" [Read only]");
629 	printf("\n");
630 	return(mdot);
631 }
632 
633 /*
634  * Print the current version number.
635  */
636 
637 /*ARGSUSED*/
638 int
639 pversion(e)
640 	int e;
641 {
642 	extern char *version;
643 
644 	printf("Version %s\n", version);
645 	return(0);
646 }
647 
648 /*
649  * Load a file of user definitions.
650  */
651 void
652 load(name)
653 	char *name;
654 {
655 	register FILE *in, *oldin;
656 
657 	if ((in = Fopen(name, "r")) == NULL)
658 		return;
659 	oldin = input;
660 	input = in;
661 	loading = 1;
662 	sourcing = 1;
663 	commands();
664 	loading = 0;
665 	sourcing = 0;
666 	input = oldin;
667 	Fclose(in);
668 }
669