xref: /freebsd/usr.bin/mail/list.c (revision a2f733abcff64628b7771a47089628b7327a88bd)
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 #ifndef lint
33 #endif /* not lint */
34 #include <sys/cdefs.h>
35 #include "rcv.h"
36 #include <ctype.h>
37 #include "extern.h"
38 
39 /*
40  * Mail -- a mail program
41  *
42  * Message list handling.
43  */
44 
45 /*
46  * Convert the user string of message numbers and
47  * store the numbers into vector.
48  *
49  * Returns the count of messages picked up or -1 on error.
50  */
51 int
52 getmsglist(char *buf, int *vector, int flags)
53 {
54 	int *ip;
55 	struct message *mp;
56 
57 	if (msgCount == 0) {
58 		*vector = 0;
59 		return (0);
60 	}
61 	if (markall(buf, flags) < 0)
62 		return (-1);
63 	ip = vector;
64 	for (mp = &message[0]; mp < &message[msgCount]; mp++)
65 		if (mp->m_flag & MMARK)
66 			*ip++ = mp - &message[0] + 1;
67 	*ip = 0;
68 	return (ip - vector);
69 }
70 
71 /*
72  * Mark all messages that the user wanted from the command
73  * line in the message structure.  Return 0 on success, -1
74  * on error.
75  */
76 
77 /*
78  * Bit values for colon modifiers.
79  */
80 
81 #define	CMNEW		01		/* New messages */
82 #define	CMOLD		02		/* Old messages */
83 #define	CMUNREAD	04		/* Unread messages */
84 #define	CMDELETED	010		/* Deleted messages */
85 #define	CMREAD		020		/* Read messages */
86 
87 /*
88  * The following table describes the letters which can follow
89  * the colon and gives the corresponding modifier bit.
90  */
91 
92 static struct coltab {
93 	char	co_char;		/* What to find past : */
94 	int	co_bit;			/* Associated modifier bit */
95 	int	co_mask;		/* m_status bits to mask */
96 	int	co_equal;		/* ... must equal this */
97 } coltab[] = {
98 	{ 'n',		CMNEW,		MNEW,		MNEW	},
99 	{ 'o',		CMOLD,		MNEW,		0	},
100 	{ 'u',		CMUNREAD,	MREAD,		0	},
101 	{ 'd',		CMDELETED,	MDELETED,	MDELETED},
102 	{ 'r',		CMREAD,		MREAD,		MREAD	},
103 	{ 0,		0,		0,		0	}
104 };
105 
106 static	int	lastcolmod;
107 
108 int
109 markall(char buf[], int f)
110 {
111 	char **np;
112 	int i;
113 	struct message *mp;
114 	char *namelist[NMLSIZE], *bufp;
115 	int tok, beg, mc, star, other, valdot, colmod, colresult;
116 
117 	valdot = dot - &message[0] + 1;
118 	colmod = 0;
119 	for (i = 1; i <= msgCount; i++)
120 		unmark(i);
121 	bufp = buf;
122 	mc = 0;
123 	np = &namelist[0];
124 	scaninit();
125 	tok = scan(&bufp);
126 	star = 0;
127 	other = 0;
128 	beg = 0;
129 	while (tok != TEOL) {
130 		switch (tok) {
131 		case TNUMBER:
132 number:
133 			if (star) {
134 				printf("No numbers mixed with *\n");
135 				return (-1);
136 			}
137 			mc++;
138 			other++;
139 			if (beg != 0) {
140 				if (check(lexnumber, f))
141 					return (-1);
142 				for (i = beg; i <= lexnumber; i++)
143 					if (f == MDELETED || (message[i - 1].m_flag & MDELETED) == 0)
144 						mark(i);
145 				beg = 0;
146 				break;
147 			}
148 			beg = lexnumber;
149 			if (check(beg, f))
150 				return (-1);
151 			tok = scan(&bufp);
152 			regret(tok);
153 			if (tok != TDASH) {
154 				mark(beg);
155 				beg = 0;
156 			}
157 			break;
158 
159 		case TPLUS:
160 			if (beg != 0) {
161 				printf("Non-numeric second argument\n");
162 				return (-1);
163 			}
164 			i = valdot;
165 			do {
166 				i++;
167 				if (i > msgCount) {
168 					printf("Referencing beyond EOF\n");
169 					return (-1);
170 				}
171 			} while ((message[i - 1].m_flag & MDELETED) != f);
172 			mark(i);
173 			break;
174 
175 		case TDASH:
176 			if (beg == 0) {
177 				i = valdot;
178 				do {
179 					i--;
180 					if (i <= 0) {
181 						printf("Referencing before 1\n");
182 						return (-1);
183 					}
184 				} while ((message[i - 1].m_flag & MDELETED) != f);
185 				mark(i);
186 			}
187 			break;
188 
189 		case TSTRING:
190 			if (beg != 0) {
191 				printf("Non-numeric second argument\n");
192 				return (-1);
193 			}
194 			other++;
195 			if (lexstring[0] == ':') {
196 				colresult = evalcol(lexstring[1]);
197 				if (colresult == 0) {
198 					printf("Unknown colon modifier \"%s\"\n",
199 					    lexstring);
200 					return (-1);
201 				}
202 				colmod |= colresult;
203 			}
204 			else
205 				*np++ = savestr(lexstring);
206 			break;
207 
208 		case TDOLLAR:
209 		case TUP:
210 		case TDOT:
211 			lexnumber = metamess(lexstring[0], f);
212 			if (lexnumber == -1)
213 				return (-1);
214 			goto number;
215 
216 		case TSTAR:
217 			if (other) {
218 				printf("Can't mix \"*\" with anything\n");
219 				return (-1);
220 			}
221 			star++;
222 			break;
223 
224 		case TERROR:
225 			return (-1);
226 		}
227 		tok = scan(&bufp);
228 	}
229 	lastcolmod = colmod;
230 	*np = NULL;
231 	mc = 0;
232 	if (star) {
233 		for (i = 0; i < msgCount; i++)
234 			if ((message[i].m_flag & MDELETED) == f) {
235 				mark(i+1);
236 				mc++;
237 			}
238 		if (mc == 0) {
239 			printf("No applicable messages.\n");
240 			return (-1);
241 		}
242 		return (0);
243 	}
244 
245 	/*
246 	 * If no numbers were given, mark all of the messages,
247 	 * so that we can unmark any whose sender was not selected
248 	 * if any user names were given.
249 	 */
250 
251 	if ((np > namelist || colmod != 0) && mc == 0)
252 		for (i = 1; i <= msgCount; i++)
253 			if ((message[i-1].m_flag & MDELETED) == f)
254 				mark(i);
255 
256 	/*
257 	 * If any names were given, go through and eliminate any
258 	 * messages whose senders were not requested.
259 	 */
260 
261 	if (np > namelist) {
262 		for (i = 1; i <= msgCount; i++) {
263 			for (mc = 0, np = &namelist[0]; *np != NULL; np++)
264 				if (**np == '/') {
265 					if (matchfield(*np, i)) {
266 						mc++;
267 						break;
268 					}
269 				}
270 				else {
271 					if (matchsender(*np, i)) {
272 						mc++;
273 						break;
274 					}
275 				}
276 			if (mc == 0)
277 				unmark(i);
278 		}
279 
280 		/*
281 		 * Make sure we got some decent messages.
282 		 */
283 
284 		mc = 0;
285 		for (i = 1; i <= msgCount; i++)
286 			if (message[i-1].m_flag & MMARK) {
287 				mc++;
288 				break;
289 			}
290 		if (mc == 0) {
291 			printf("No applicable messages from {%s",
292 				namelist[0]);
293 			for (np = &namelist[1]; *np != NULL; np++)
294 				printf(", %s", *np);
295 			printf("}\n");
296 			return (-1);
297 		}
298 	}
299 
300 	/*
301 	 * If any colon modifiers were given, go through and
302 	 * unmark any messages which do not satisfy the modifiers.
303 	 */
304 
305 	if (colmod != 0) {
306 		for (i = 1; i <= msgCount; i++) {
307 			struct coltab *colp;
308 
309 			mp = &message[i - 1];
310 			for (colp = &coltab[0]; colp->co_char != '\0'; colp++)
311 				if (colp->co_bit & colmod)
312 					if ((mp->m_flag & colp->co_mask)
313 					    != colp->co_equal)
314 						unmark(i);
315 
316 		}
317 		for (mp = &message[0]; mp < &message[msgCount]; mp++)
318 			if (mp->m_flag & MMARK)
319 				break;
320 		if (mp >= &message[msgCount]) {
321 			struct coltab *colp;
322 
323 			printf("No messages satisfy");
324 			for (colp = &coltab[0]; colp->co_char != '\0'; colp++)
325 				if (colp->co_bit & colmod)
326 					printf(" :%c", colp->co_char);
327 			printf("\n");
328 			return (-1);
329 		}
330 	}
331 	return (0);
332 }
333 
334 /*
335  * Turn the character after a colon modifier into a bit
336  * value.
337  */
338 int
339 evalcol(int col)
340 {
341 	struct coltab *colp;
342 
343 	if (col == 0)
344 		return (lastcolmod);
345 	for (colp = &coltab[0]; colp->co_char != '\0'; colp++)
346 		if (colp->co_char == col)
347 			return (colp->co_bit);
348 	return (0);
349 }
350 
351 /*
352  * Check the passed message number for legality and proper flags.
353  * If f is MDELETED, then either kind will do.  Otherwise, the message
354  * has to be undeleted.
355  */
356 int
357 check(int mesg, int f)
358 {
359 	struct message *mp;
360 
361 	if (mesg < 1 || mesg > msgCount) {
362 		printf("%d: Invalid message number\n", mesg);
363 		return (-1);
364 	}
365 	mp = &message[mesg-1];
366 	if (f != MDELETED && (mp->m_flag & MDELETED) != 0) {
367 		printf("%d: Inappropriate message\n", mesg);
368 		return (-1);
369 	}
370 	return (0);
371 }
372 
373 /*
374  * Scan out the list of string arguments, shell style
375  * for a RAWLIST.
376  */
377 int
378 getrawlist(char line[], char **argv, int argc)
379 {
380 	char c, *cp, *cp2, quotec;
381 	int argn;
382 	char *linebuf;
383 	size_t linebufsize = BUFSIZ;
384 
385 	if ((linebuf = malloc(linebufsize)) == NULL)
386 		err(1, "Out of memory");
387 
388 	argn = 0;
389 	cp = line;
390 	for (;;) {
391 		for (; *cp == ' ' || *cp == '\t'; cp++)
392 			;
393 		if (*cp == '\0')
394 			break;
395 		if (argn >= argc - 1) {
396 			printf(
397 			"Too many elements in the list; excess discarded.\n");
398 			break;
399 		}
400 		cp2 = linebuf;
401 		quotec = '\0';
402 		while ((c = *cp) != '\0') {
403 			/* Allocate more space if necessary */
404 			if (cp2 - linebuf == linebufsize - 1) {
405 				linebufsize += BUFSIZ;
406 				if ((linebuf = realloc(linebuf, linebufsize)) == NULL)
407 					err(1, "Out of memory");
408 				cp2 = linebuf + linebufsize - BUFSIZ - 1;
409 			}
410 			cp++;
411 			if (quotec != '\0') {
412 				if (c == quotec)
413 					quotec = '\0';
414 				else if (c == '\\')
415 					switch (c = *cp++) {
416 					case '\0':
417 						*cp2++ = '\\';
418 						cp--;
419 						break;
420 					case '0': case '1': case '2': case '3':
421 					case '4': case '5': case '6': case '7':
422 						c -= '0';
423 						if (*cp >= '0' && *cp <= '7')
424 							c = c * 8 + *cp++ - '0';
425 						if (*cp >= '0' && *cp <= '7')
426 							c = c * 8 + *cp++ - '0';
427 						*cp2++ = c;
428 						break;
429 					case 'b':
430 						*cp2++ = '\b';
431 						break;
432 					case 'f':
433 						*cp2++ = '\f';
434 						break;
435 					case 'n':
436 						*cp2++ = '\n';
437 						break;
438 					case 'r':
439 						*cp2++ = '\r';
440 						break;
441 					case 't':
442 						*cp2++ = '\t';
443 						break;
444 					case 'v':
445 						*cp2++ = '\v';
446 						break;
447 					default:
448 						*cp2++ = c;
449 					}
450 				else if (c == '^') {
451 					c = *cp++;
452 					if (c == '?')
453 						*cp2++ = '\177';
454 					/* null doesn't show up anyway */
455 					else if ((c >= 'A' && c <= '_') ||
456 					    (c >= 'a' && c <= 'z'))
457 						*cp2++ = c & 037;
458 					else {
459 						*cp2++ = '^';
460 						cp--;
461 					}
462 				} else
463 					*cp2++ = c;
464 			} else if (c == '"' || c == '\'')
465 				quotec = c;
466 			else if (c == ' ' || c == '\t')
467 				break;
468 			else
469 				*cp2++ = c;
470 		}
471 		*cp2 = '\0';
472 		argv[argn++] = savestr(linebuf);
473 	}
474 	argv[argn] = NULL;
475 	(void)free(linebuf);
476 	return (argn);
477 }
478 
479 /*
480  * scan out a single lexical item and return its token number,
481  * updating the string pointer passed **p.  Also, store the value
482  * of the number or string scanned in lexnumber or lexstring as
483  * appropriate.  In any event, store the scanned `thing' in lexstring.
484  */
485 
486 static struct lex {
487 	char	l_char;
488 	char	l_token;
489 } singles[] = {
490 	{ '$',	TDOLLAR	},
491 	{ '.',	TDOT	},
492 	{ '^',	TUP 	},
493 	{ '*',	TSTAR 	},
494 	{ '-',	TDASH 	},
495 	{ '+',	TPLUS 	},
496 	{ '(',	TOPEN 	},
497 	{ ')',	TCLOSE 	},
498 	{ 0,	0 	}
499 };
500 
501 int
502 scan(char **sp)
503 {
504 	char *cp, *cp2;
505 	int c;
506 	struct lex *lp;
507 	int quotec;
508 
509 	if (regretp >= 0) {
510 		strcpy(lexstring, string_stack[regretp]);
511 		lexnumber = numberstack[regretp];
512 		return (regretstack[regretp--]);
513 	}
514 	cp = *sp;
515 	cp2 = lexstring;
516 	c = *cp++;
517 
518 	/*
519 	 * strip away leading white space.
520 	 */
521 
522 	while (c == ' ' || c == '\t')
523 		c = *cp++;
524 
525 	/*
526 	 * If no characters remain, we are at end of line,
527 	 * so report that.
528 	 */
529 
530 	if (c == '\0') {
531 		*sp = --cp;
532 		return (TEOL);
533 	}
534 
535 	/*
536 	 * If the leading character is a digit, scan
537 	 * the number and convert it on the fly.
538 	 * Return TNUMBER when done.
539 	 */
540 
541 	if (isdigit((unsigned char)c)) {
542 		lexnumber = 0;
543 		while (isdigit((unsigned char)c)) {
544 			lexnumber = lexnumber*10 + c - '0';
545 			*cp2++ = c;
546 			c = *cp++;
547 		}
548 		*cp2 = '\0';
549 		*sp = --cp;
550 		return (TNUMBER);
551 	}
552 
553 	/*
554 	 * Check for single character tokens; return such
555 	 * if found.
556 	 */
557 
558 	for (lp = &singles[0]; lp->l_char != '\0'; lp++)
559 		if (c == lp->l_char) {
560 			lexstring[0] = c;
561 			lexstring[1] = '\0';
562 			*sp = cp;
563 			return (lp->l_token);
564 		}
565 
566 	/*
567 	 * We've got a string!  Copy all the characters
568 	 * of the string into lexstring, until we see
569 	 * a null, space, or tab.
570 	 * If the lead character is a " or ', save it
571 	 * and scan until you get another.
572 	 */
573 
574 	quotec = 0;
575 	if (c == '\'' || c == '"') {
576 		quotec = c;
577 		c = *cp++;
578 	}
579 	while (c != '\0') {
580 		if (c == quotec) {
581 			cp++;
582 			break;
583 		}
584 		if (quotec == 0 && (c == ' ' || c == '\t'))
585 			break;
586 		if (cp2 - lexstring < STRINGLEN-1)
587 			*cp2++ = c;
588 		c = *cp++;
589 	}
590 	if (quotec && c == '\0') {
591 		fprintf(stderr, "Missing %c\n", quotec);
592 		return (TERROR);
593 	}
594 	*sp = --cp;
595 	*cp2 = '\0';
596 	return (TSTRING);
597 }
598 
599 /*
600  * Unscan the named token by pushing it onto the regret stack.
601  */
602 void
603 regret(int token)
604 {
605 	if (++regretp >= REGDEP)
606 		errx(1, "Too many regrets");
607 	regretstack[regretp] = token;
608 	lexstring[STRINGLEN-1] = '\0';
609 	string_stack[regretp] = savestr(lexstring);
610 	numberstack[regretp] = lexnumber;
611 }
612 
613 /*
614  * Reset all the scanner global variables.
615  */
616 void
617 scaninit(void)
618 {
619 	regretp = -1;
620 }
621 
622 /*
623  * Find the first message whose flags & m == f  and return
624  * its message number.
625  */
626 int
627 first(int f, int m)
628 {
629 	struct message *mp;
630 
631 	if (msgCount == 0)
632 		return (0);
633 	f &= MDELETED;
634 	m &= MDELETED;
635 	for (mp = dot; mp < &message[msgCount]; mp++)
636 		if ((mp->m_flag & m) == f)
637 			return (mp - message + 1);
638 	for (mp = dot-1; mp >= &message[0]; mp--)
639 		if ((mp->m_flag & m) == f)
640 			return (mp - message + 1);
641 	return (0);
642 }
643 
644 /*
645  * See if the passed name sent the passed message number.  Return true
646  * if so.
647  */
648 int
649 matchsender(char *str, int mesg)
650 {
651 	char *cp;
652 
653 	/* null string matches nothing instead of everything */
654 	if (*str == '\0')
655 		return (0);
656 
657 	cp = nameof(&message[mesg - 1], 0);
658 	return (strcasestr(cp, str) != NULL);
659 }
660 
661 /*
662  * See if the passed name received the passed message number.  Return true
663  * if so.
664  */
665 
666 static char *to_fields[] = { "to", "cc", "bcc", NULL };
667 
668 static int
669 matchto(char *str, int mesg)
670 {
671 	struct message *mp;
672 	char *cp, **to;
673 
674 	str++;
675 
676 	/* null string matches nothing instead of everything */
677 	if (*str == '\0')
678 		return (0);
679 
680 	mp = &message[mesg - 1];
681 
682 	for (to = to_fields; *to != NULL; to++) {
683 		cp = hfield(*to, mp);
684 		if (cp != NULL && strcasestr(cp, str) != NULL)
685 			return (1);
686 	}
687 	return (0);
688 }
689 
690 /*
691  * See if the given substring is contained within the specified field. If
692  * 'searchheaders' is set, then the form '/x:y' will be accepted and matches
693  * any message with the substring 'y' in field 'x'. If 'x' is omitted or
694  * 'searchheaders' is not set, then the search matches any messages
695  * with the substring 'y' in the 'Subject'. The search is case insensitive.
696  *
697  * The form '/to:y' is a special case, and will match all messages
698  * containing the substring 'y' in the 'To', 'Cc', or 'Bcc' header
699  * fields. The search for 'to' is case sensitive, so that '/To:y' can
700  * be used to limit the search to just the 'To' field.
701  */
702 
703 static char lastscan[STRINGLEN];
704 int
705 matchfield(char *str, int mesg)
706 {
707 	struct message *mp;
708 	char *cp, *cp2;
709 
710 	str++;
711 	if (*str == '\0')
712 		str = lastscan;
713 	else
714 		strlcpy(lastscan, str, sizeof(lastscan));
715 	mp = &message[mesg-1];
716 
717 	/*
718 	 * Now look, ignoring case, for the word in the string.
719 	 */
720 
721 	if (value("searchheaders") && (cp = strchr(str, ':')) != NULL) {
722 		/* Check for special case "/to:" */
723 		if (strncmp(str, "to:", 3) == 0)
724 			return (matchto(cp, mesg));
725 		*cp++ = '\0';
726 		cp2 = hfield(*str != '\0' ? str : "subject", mp);
727 		cp[-1] = ':';
728 		str = cp;
729 		cp = cp2;
730 	} else
731 		cp = hfield("subject", mp);
732 
733 	if (cp == NULL)
734 		return (0);
735 
736 	return (strcasestr(cp, str) != NULL);
737 }
738 
739 /*
740  * Mark the named message by setting its mark bit.
741  */
742 void
743 mark(int mesg)
744 {
745 	int i;
746 
747 	i = mesg;
748 	if (i < 1 || i > msgCount)
749 		errx(1, "Bad message number to mark");
750 	message[i-1].m_flag |= MMARK;
751 }
752 
753 /*
754  * Unmark the named message.
755  */
756 void
757 unmark(int mesg)
758 {
759 	int i;
760 
761 	i = mesg;
762 	if (i < 1 || i > msgCount)
763 		errx(1, "Bad message number to unmark");
764 	message[i-1].m_flag &= ~MMARK;
765 }
766 
767 /*
768  * Return the message number corresponding to the passed meta character.
769  */
770 int
771 metamess(int meta, int f)
772 {
773 	int c, m;
774 	struct message *mp;
775 
776 	c = meta;
777 	switch (c) {
778 	case '^':
779 		/*
780 		 * First 'good' message left.
781 		 */
782 		for (mp = &message[0]; mp < &message[msgCount]; mp++)
783 			if ((mp->m_flag & MDELETED) == f)
784 				return (mp - &message[0] + 1);
785 		printf("No applicable messages\n");
786 		return (-1);
787 
788 	case '$':
789 		/*
790 		 * Last 'good message left.
791 		 */
792 		for (mp = &message[msgCount-1]; mp >= &message[0]; mp--)
793 			if ((mp->m_flag & MDELETED) == f)
794 				return (mp - &message[0] + 1);
795 		printf("No applicable messages\n");
796 		return (-1);
797 
798 	case '.':
799 		/*
800 		 * Current message.
801 		 */
802 		m = dot - &message[0] + 1;
803 		if ((dot->m_flag & MDELETED) != f) {
804 			printf("%d: Inappropriate message\n", m);
805 			return (-1);
806 		}
807 		return (m);
808 
809 	default:
810 		printf("Unknown metachar (%c)\n", c);
811 		return (-1);
812 	}
813 }
814