xref: /freebsd/usr.bin/mail/lex.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
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 const char	*prompt = "& ";
56 
57 extern const struct cmd cmdtab[];
58 extern const char *version;
59 
60 /*
61  * Set up editing on the given file name.
62  * If the first character of name is %, we are considered to be
63  * editing the file, otherwise we are reading our mail which has
64  * signficance for mbox and so forth.
65  */
66 int
67 setfile(name)
68 	char *name;
69 {
70 	FILE *ibuf;
71 	int i, fd;
72 	struct stat stb;
73 	char isedit = *name != '%';
74 	char *who = name[1] ? name + 1 : myname;
75 	char tempname[PATHSIZE];
76 	static int shudclob;
77 
78 	if ((name = expand(name)) == NULL)
79 		return (-1);
80 
81 	if ((ibuf = Fopen(name, "r")) == NULL) {
82 		if (!isedit && errno == ENOENT)
83 			goto nomail;
84 		warn("%s", name);
85 		return (-1);
86 	}
87 
88 	if (fstat(fileno(ibuf), &stb) < 0) {
89 		warn("fstat");
90 		(void)Fclose(ibuf);
91 		return (-1);
92 	}
93 
94 	if (S_ISDIR(stb.st_mode) || !S_ISREG(stb.st_mode)) {
95 		(void)Fclose(ibuf);
96 		errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
97 		warn("%s", name);
98 		return (-1);
99 	}
100 
101 	/*
102 	 * Looks like all will be well.  We must now relinquish our
103 	 * hold on the current set of stuff.  Must hold signals
104 	 * while we are reading the new file, else we will ruin
105 	 * the message[] data structure.
106 	 */
107 
108 	holdsigs();
109 	if (shudclob)
110 		quit();
111 
112 	/*
113 	 * Copy the messages into /tmp
114 	 * and set pointers.
115 	 */
116 
117 	readonly = 0;
118 	if ((i = open(name, 1)) < 0)
119 		readonly++;
120 	else
121 		(void)close(i);
122 	if (shudclob) {
123 		(void)fclose(itf);
124 		(void)fclose(otf);
125 	}
126 	shudclob = 1;
127 	edit = isedit;
128 	strlcpy(prevfile, mailname, sizeof(prevfile));
129 	if (name != mailname)
130 		strlcpy(mailname, name, sizeof(mailname));
131 	mailsize = fsize(ibuf);
132 	(void)snprintf(tempname, sizeof(tempname),
133 	    "%s/mail.RxXXXXXXXXXX", tmpdir);
134 	if ((fd = mkstemp(tempname)) == -1 || (otf = fdopen(fd, "w")) == NULL)
135 		err(1, "%s", tempname);
136 	(void)fcntl(fileno(otf), F_SETFD, 1);
137 	if ((itf = fopen(tempname, "r")) == NULL)
138 		err(1, "%s", tempname);
139 	(void)fcntl(fileno(itf), F_SETFD, 1);
140 	(void)rm(tempname);
141 	setptr(ibuf);
142 	setmsize(msgCount);
143 	(void)Fclose(ibuf);
144 	relsesigs();
145 	sawcom = 0;
146 	if (!edit && msgCount == 0) {
147 nomail:
148 		fprintf(stderr, "No mail for %s\n", who);
149 		return (-1);
150 	}
151 	return (0);
152 }
153 
154 int	*msgvec;
155 int	reset_on_stop;			/* do a reset() if stopped */
156 
157 /*
158  * Interpret user commands one by one.  If standard input is not a tty,
159  * print no prompt.
160  */
161 void
162 commands()
163 {
164 	int n, eofloop = 0;
165 	char linebuf[LINESIZE];
166 
167 	if (!sourcing) {
168 		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
169 			(void)signal(SIGINT, intr);
170 		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
171 			(void)signal(SIGHUP, hangup);
172 		(void)signal(SIGTSTP, stop);
173 		(void)signal(SIGTTOU, stop);
174 		(void)signal(SIGTTIN, stop);
175 	}
176 	setexit();
177 	for (;;) {
178 		/*
179 		 * Print the prompt, if needed.  Clear out
180 		 * string space, and flush the output.
181 		 */
182 		if (!sourcing && value("interactive") != NULL) {
183 			reset_on_stop = 1;
184 			printf("%s", prompt);
185 		}
186 		(void)fflush(stdout);
187 		sreset();
188 		/*
189 		 * Read a line of commands from the current input
190 		 * and handle end of file specially.
191 		 */
192 		n = 0;
193 		for (;;) {
194 			if (readline(input, &linebuf[n], LINESIZE - n) < 0) {
195 				if (n == 0)
196 					n = -1;
197 				break;
198 			}
199 			if ((n = strlen(linebuf)) == 0)
200 				break;
201 			n--;
202 			if (linebuf[n] != '\\')
203 				break;
204 			linebuf[n++] = ' ';
205 		}
206 		reset_on_stop = 0;
207 		if (n < 0) {
208 				/* eof */
209 			if (loading)
210 				break;
211 			if (sourcing) {
212 				unstack();
213 				continue;
214 			}
215 			if (value("interactive") != NULL &&
216 			    value("ignoreeof") != NULL &&
217 			    ++eofloop < 25) {
218 				printf("Use \"quit\" to quit.\n");
219 				continue;
220 			}
221 			break;
222 		}
223 		eofloop = 0;
224 		if (execute(linebuf, 0))
225 			break;
226 	}
227 }
228 
229 /*
230  * Execute a single command.
231  * Command functions return 0 for success, 1 for error, and -1
232  * for abort.  A 1 or -1 aborts a load or source.  A -1 aborts
233  * the interactive command loop.
234  * Contxt is non-zero if called while composing mail.
235  */
236 int
237 execute(linebuf, contxt)
238 	char linebuf[];
239 	int contxt;
240 {
241 	char word[LINESIZE];
242 	char *arglist[MAXARGC];
243 	const struct cmd *com;
244 	char *cp, *cp2;
245 	int c, muvec[2];
246 	int e = 1;
247 
248 	/*
249 	 * Strip the white space away from the beginning
250 	 * of the command, then scan out a word, which
251 	 * consists of anything except digits and white space.
252 	 *
253 	 * Handle ! escapes differently to get the correct
254 	 * lexical conventions.
255 	 */
256 
257 	for (cp = linebuf; isspace(*cp); cp++)
258 		;
259 	if (*cp == '!') {
260 		if (sourcing) {
261 			printf("Can't \"!\" while sourcing\n");
262 			goto out;
263 		}
264 		shell(cp+1);
265 		return (0);
266 	}
267 	cp2 = word;
268 	while (*cp != '\0' && strchr(" \t0123456789$^.:/-+*'\"", *cp) == NULL)
269 		*cp2++ = *cp++;
270 	*cp2 = '\0';
271 
272 	/*
273 	 * Look up the command; if not found, bitch.
274 	 * Normally, a blank command would map to the
275 	 * first command in the table; while sourcing,
276 	 * however, we ignore blank lines to eliminate
277 	 * confusion.
278 	 */
279 
280 	if (sourcing && *word == '\0')
281 		return (0);
282 	com = lex(word);
283 	if (com == NULL) {
284 		printf("Unknown command: \"%s\"\n", word);
285 		goto out;
286 	}
287 
288 	/*
289 	 * See if we should execute the command -- if a conditional
290 	 * we always execute it, otherwise, check the state of cond.
291 	 */
292 
293 	if ((com->c_argtype & F) == 0)
294 		if ((cond == CRCV && !rcvmode) || (cond == CSEND && rcvmode))
295 			return (0);
296 
297 	/*
298 	 * Process the arguments to the command, depending
299 	 * on the type he expects.  Default to an error.
300 	 * If we are sourcing an interactive command, it's
301 	 * an error.
302 	 */
303 
304 	if (!rcvmode && (com->c_argtype & M) == 0) {
305 		printf("May not execute \"%s\" while sending\n",
306 		    com->c_name);
307 		goto out;
308 	}
309 	if (sourcing && com->c_argtype & I) {
310 		printf("May not execute \"%s\" while sourcing\n",
311 		    com->c_name);
312 		goto out;
313 	}
314 	if (readonly && com->c_argtype & W) {
315 		printf("May not execute \"%s\" -- message file is read only\n",
316 		   com->c_name);
317 		goto out;
318 	}
319 	if (contxt && com->c_argtype & R) {
320 		printf("Cannot recursively invoke \"%s\"\n", com->c_name);
321 		goto out;
322 	}
323 	switch (com->c_argtype & ~(F|P|I|M|T|W|R)) {
324 	case MSGLIST:
325 		/*
326 		 * A message list defaulting to nearest forward
327 		 * legal message.
328 		 */
329 		if (msgvec == 0) {
330 			printf("Illegal use of \"message list\"\n");
331 			break;
332 		}
333 		if ((c = getmsglist(cp, msgvec, com->c_msgflag)) < 0)
334 			break;
335 		if (c  == 0) {
336 			*msgvec = first(com->c_msgflag, 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") != NULL && 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 		(void)free(msgvec);
438 	msgvec = 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 __const struct cmd *
447 lex(word)
448 	char word[];
449 {
450 	const struct cmd *cp;
451 
452 	/*
453 	 * ignore trailing chars after `#'
454 	 *
455 	 * lines with beginning `#' are comments
456 	 * spaces before `#' are ignored in execute()
457 	 */
458 
459 	if (*word == '#')
460 	    *(word+1) = '\0';
461 
462 
463 	for (cp = &cmdtab[0]; cp->c_name != NULL; cp++)
464 		if (isprefix(word, cp->c_name))
465 			return (cp);
466 	return (NULL);
467 }
468 
469 /*
470  * Determine if as1 is a valid prefix of as2.
471  * Return true if yep.
472  */
473 int
474 isprefix(as1, as2)
475 	const char *as1, *as2;
476 {
477 	const char *s1, *s2;
478 
479 	s1 = as1;
480 	s2 = as2;
481 	while (*s1++ == *s2)
482 		if (*s2++ == '\0')
483 			return (1);
484 	return (*--s1 == '\0');
485 }
486 
487 /*
488  * The following gets called on receipt of an interrupt.  This is
489  * to abort printout of a command, mainly.
490  * Dispatching here when command() is inactive crashes rcv.
491  * Close all open files except 0, 1, 2, and the temporary.
492  * Also, unstack all source files.
493  */
494 
495 int	inithdr;			/* am printing startup headers */
496 
497 /*ARGSUSED*/
498 void
499 intr(s)
500 	int s;
501 {
502 
503 	noreset = 0;
504 	if (!inithdr)
505 		sawcom++;
506 	inithdr = 0;
507 	while (sourcing)
508 		unstack();
509 
510 	close_all_files();
511 
512 	if (image >= 0) {
513 		(void)close(image);
514 		image = -1;
515 	}
516 	fprintf(stderr, "Interrupt\n");
517 	reset(0);
518 }
519 
520 /*
521  * When we wake up after ^Z, reprint the prompt.
522  */
523 void
524 stop(s)
525 	int s;
526 {
527 	sig_t old_action = signal(s, SIG_DFL);
528 
529 	(void)sigsetmask(sigblock(0) & ~sigmask(s));
530 	(void)kill(0, s);
531 	(void)sigblock(sigmask(s));
532 	(void)signal(s, old_action);
533 	if (reset_on_stop) {
534 		reset_on_stop = 0;
535 		reset(0);
536 	}
537 }
538 
539 /*
540  * Branch here on hangup signal and simulate "exit".
541  */
542 /*ARGSUSED*/
543 void
544 hangup(s)
545 	int s;
546 {
547 
548 	/* nothing to do? */
549 	exit(1);
550 }
551 
552 /*
553  * Announce the presence of the current Mail version,
554  * give the message count, and print a header listing.
555  */
556 void
557 announce()
558 {
559 	int vec[2], mdot;
560 
561 	mdot = newfileinfo();
562 	vec[0] = mdot;
563 	vec[1] = 0;
564 	dot = &message[mdot - 1];
565 	if (msgCount > 0 && value("noheader") == NULL) {
566 		inithdr++;
567 		headers(vec);
568 		inithdr = 0;
569 	}
570 }
571 
572 /*
573  * Announce information about the file we are editing.
574  * Return a likely place to set dot.
575  */
576 int
577 newfileinfo()
578 {
579 	struct message *mp;
580 	int u, n, mdot, d, s;
581 	char fname[PATHSIZE+1], zname[PATHSIZE+1], *ename;
582 
583 	for (mp = &message[0]; mp < &message[msgCount]; mp++)
584 		if (mp->m_flag & MNEW)
585 			break;
586 	if (mp >= &message[msgCount])
587 		for (mp = &message[0]; mp < &message[msgCount]; mp++)
588 			if ((mp->m_flag & MREAD) == 0)
589 				break;
590 	if (mp < &message[msgCount])
591 		mdot = mp - &message[0] + 1;
592 	else
593 		mdot = 1;
594 	s = d = 0;
595 	for (mp = &message[0], n = 0, u = 0; mp < &message[msgCount]; mp++) {
596 		if (mp->m_flag & MNEW)
597 			n++;
598 		if ((mp->m_flag & MREAD) == 0)
599 			u++;
600 		if (mp->m_flag & MDELETED)
601 			d++;
602 		if (mp->m_flag & MSAVED)
603 			s++;
604 	}
605 	ename = mailname;
606 	if (getfold(fname, sizeof(fname) - 1) >= 0) {
607 		strcat(fname, "/");
608 		if (strncmp(fname, mailname, strlen(fname)) == 0) {
609 			(void)snprintf(zname, sizeof(zname), "+%s",
610 			    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 
643 	printf("Version %s\n", version);
644 	return (0);
645 }
646 
647 /*
648  * Load a file of user definitions.
649  */
650 void
651 load(name)
652 	char *name;
653 {
654 	FILE *in, *oldin;
655 
656 	if ((in = Fopen(name, "r")) == NULL)
657 		return;
658 	oldin = input;
659 	input = in;
660 	loading = 1;
661 	sourcing = 1;
662 	commands();
663 	loading = 0;
664 	sourcing = 0;
665 	input = oldin;
666 	(void)Fclose(in);
667 }
668