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