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