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
34#ifndef lint
35#if 0
36static char sccsid[] = "@(#)names.c	8.1 (Berkeley) 6/6/93";
37#endif
38__attribute__((__used__))
39static const char rcsid[] =
40  "$FreeBSD: src/usr.bin/mail/names.c,v 1.9 2004/02/29 20:44:44 mikeh Exp $";
41#endif /* not lint */
42
43#include <sys/cdefs.h>
44
45/*
46 * Mail -- a mail program
47 *
48 * Handle name lists.
49 */
50
51#include "rcv.h"
52#include <fcntl.h>
53#include "extern.h"
54
55/*
56 * Allocate a single element of a name list,
57 * initialize its name field to the passed
58 * name and return it.
59 */
60struct name *
61nalloc(str, ntype)
62	char str[];
63	int ntype;
64{
65	struct name *np;
66
67	np = (struct name *)salloc(sizeof(*np));
68	np->n_flink = NULL;
69	np->n_blink = NULL;
70	np->n_type = ntype;
71	np->n_name = savestr(str);
72	return (np);
73}
74
75/*
76 * Find the tail of a list and return it.
77 */
78struct name *
79tailof(name)
80	struct name *name;
81{
82	struct name *np;
83
84	np = name;
85	if (np == NULL)
86		return (NULL);
87	while (np->n_flink != NULL)
88		np = np->n_flink;
89	return (np);
90}
91
92/*
93 * Extract a list of names from a line,
94 * and make a list of names from it.
95 * Return the list or NULL if none found.
96 */
97struct name *
98extract(line, ntype)
99	char line[];
100	int ntype;
101{
102	char *cp, *nbuf;
103	struct name *top, *np, *t;
104
105	if (line == NULL || *line == '\0')
106		return (NULL);
107	if ((nbuf = malloc(strlen(line) + 1)) == NULL)
108		err(1, "Out of memory");
109	top = NULL;
110	np = NULL;
111	cp = line;
112	while ((cp = yankword(cp, nbuf)) != NULL) {
113		t = nalloc(nbuf, ntype);
114		if (top == NULL)
115			top = t;
116		else
117			np->n_flink = t;
118		t->n_blink = np;
119		np = t;
120	}
121	(void)free(nbuf);
122	return (top);
123}
124
125/*
126 * Turn a list of names into a string of the same names.
127 */
128char *
129detract(np, ntype)
130	struct name *np;
131	int ntype;
132{
133	int s, comma;
134	char *cp, *top;
135	struct name *p;
136
137	comma = ntype & GCOMMA;
138	if (np == NULL)
139		return (NULL);
140	ntype &= ~GCOMMA;
141	s = 0;
142	if (debug && comma)
143		fprintf(stderr, "detract asked to insert commas\n");
144	for (p = np; p != NULL; p = p->n_flink) {
145		if (ntype && (p->n_type & GMASK) != ntype)
146			continue;
147		s += strlen(p->n_name) + 1;
148		if (comma)
149			s++;
150	}
151	if (s == 0)
152		return (NULL);
153	s += 2;
154	top = salloc(s);
155	cp = top;
156	for (p = np; p != NULL; p = p->n_flink) {
157		if (ntype && (p->n_type & GMASK) != ntype)
158			continue;
159		cp += strlcpy(cp, p->n_name, strlen(p->n_name) + 1);
160		if (comma && p->n_flink != NULL)
161			*cp++ = ',';
162		*cp++ = ' ';
163	}
164	*--cp = '\0';
165	if (comma && *--cp == ',')
166		*cp = '\0';
167	return (top);
168}
169
170/*
171 * Grab a single word (liberal word)
172 * Throw away things between ()'s, and take anything between <>.
173 */
174char *
175yankword(ap, wbuf)
176	char *ap, wbuf[];
177{
178	char *cp, *cp2;
179
180	cp = ap;
181	for (;;) {
182		if (*cp == '\0')
183			return (NULL);
184		if (*cp == '(') {
185			int nesting = 0;
186
187			while (*cp != '\0') {
188				switch (*cp++) {
189				case '(':
190					nesting++;
191					break;
192				case ')':
193					--nesting;
194					break;
195				}
196				if (nesting <= 0)
197					break;
198			}
199		} else if (*cp == ' ' || *cp == '\t' || *cp == ',')
200			cp++;
201		else
202			break;
203	}
204	if (*cp ==  '<')
205		for (cp2 = wbuf; *cp && (*cp2++ = *cp++) != '>';)
206			;
207	else
208		for (cp2 = wbuf; *cp != '\0' && strchr(" \t,(", *cp) == NULL;
209		    *cp2++ = *cp++)
210			;
211	*cp2 = '\0';
212	return (cp);
213}
214
215/*
216 * Grab a single login name (liberal word)
217 * Throw away things between ()'s, take anything between <>,
218 * and look for words before metacharacters %, @, !.
219 */
220char *
221yanklogin(ap, wbuf)
222	char *ap, wbuf[];
223{
224	char *cp, *cp2, *cp_temp;
225	int n;
226
227	cp = ap;
228	for (;;) {
229		if (*cp == '\0')
230			return (NULL);
231		if (*cp == '(') {
232			int nesting = 0;
233
234			while (*cp != '\0') {
235				switch (*cp++) {
236				case '(':
237					nesting++;
238					break;
239				case ')':
240					--nesting;
241					break;
242				}
243				if (nesting <= 0)
244					break;
245			}
246		} else if (*cp == ' ' || *cp == '\t' || *cp == ',')
247			cp++;
248		else
249			break;
250	}
251
252	/*
253	 * Now, let's go forward till we meet the needed character,
254	 * and step one word back.
255	 */
256
257	/* First, remember current point. */
258	cp_temp = cp;
259	n = 0;
260
261	/*
262	 * Note that we look ahead in a cycle. This is safe, since
263	 * non-end of string is checked first.
264	 */
265	while(*cp != '\0' && strchr("@%!", *(cp + 1)) == NULL)
266		cp++;
267
268	/*
269	 * Now, start stepping back to the first non-word character,
270	 * while counting the number of symbols in a word.
271	 */
272	while(cp != cp_temp && strchr(" \t,<>", *(cp - 1)) == NULL) {
273		n++;
274		cp--;
275	}
276
277	/* Finally, grab the word forward. */
278	cp2 = wbuf;
279	while(n >= 0) {
280		*cp2++=*cp++;
281		n--;
282	}
283
284	*cp2 = '\0';
285	return (cp);
286}
287
288/*
289 * For each recipient in the passed name list with a /
290 * in the name, append the message to the end of the named file
291 * and remove him from the recipient list.
292 *
293 * Recipients whose name begins with | are piped through the given
294 * program and removed.
295 */
296struct name *
297outof(names, fo, hp)
298	struct name *names;
299	FILE *fo;
300	struct header *hp;
301{
302	int c, ispipe;
303	struct name *np, *top;
304	time_t now;
305	char *date, *fname;
306	FILE *fout, *fin;
307
308	top = names;
309	np = names;
310	(void)time(&now);
311	date = ctime(&now);
312	while (np != NULL) {
313		if (!isfileaddr(np->n_name) && np->n_name[0] != '|') {
314			np = np->n_flink;
315			continue;
316		}
317		ispipe = np->n_name[0] == '|';
318		if (ispipe)
319			fname = np->n_name+1;
320		else
321			fname = expand(np->n_name);
322
323		/*
324		 * See if we have copied the complete message out yet.
325		 * If not, do so.
326		 */
327
328		if (image < 0) {
329			int fd;
330			char tempname[PATHSIZE];
331
332			(void)snprintf(tempname, sizeof(tempname),
333			    "%s/mail.ReXXXXXXXXXX", tmpdir);
334			if ((fd = mkstemp(tempname)) == -1 ||
335			    (fout = Fdopen(fd, "a")) == NULL) {
336				warn("%s", tempname);
337				senderr++;
338				goto cant;
339			}
340			image = open(tempname, O_RDWR);
341			(void)rm(tempname);
342			if (image < 0) {
343				warn("%s", tempname);
344				senderr++;
345				(void)Fclose(fout);
346				goto cant;
347			}
348			(void)fcntl(image, F_SETFD, 1);
349			fprintf(fout, "From %s %s", myname, date);
350			puthead(hp, fout,
351			    GTO|GSUBJECT|GCC|GREPLYTO|GINREPLYTO|GNL);
352			while ((c = getc(fo)) != EOF)
353				(void)putc(c, fout);
354			rewind(fo);
355			fprintf(fout, "\n");
356			(void)fflush(fout);
357			if (ferror(fout)) {
358				warn("%s", tempname);
359				senderr++;
360				(void)Fclose(fout);
361				goto cant;
362			}
363			(void)Fclose(fout);
364		}
365
366		/*
367		 * Now either copy "image" to the desired file
368		 * or give it as the standard input to the desired
369		 * program as appropriate.
370		 */
371
372		if (ispipe) {
373			int pid;
374			char *sh;
375			sigset_t nset;
376
377			/*
378			 * XXX
379			 * We can't really reuse the same image file,
380			 * because multiple piped recipients will
381			 * share the same lseek location and trample
382			 * on one another.
383			 */
384			if ((sh = value("SHELL")) == NULL)
385				sh = _PATH_BSHELL;
386			(void)sigemptyset(&nset);
387			(void)sigaddset(&nset, SIGHUP);
388			(void)sigaddset(&nset, SIGINT);
389			(void)sigaddset(&nset, SIGQUIT);
390			pid = start_command(sh, &nset, image, -1, "-c", fname,
391			    NULL);
392			if (pid < 0) {
393				senderr++;
394				goto cant;
395			}
396			free_child(pid);
397		} else {
398			int f;
399			if ((fout = Fopen(fname, "a")) == NULL) {
400				warn("%s", fname);
401				senderr++;
402				goto cant;
403			}
404			if ((f = dup(image)) < 0) {
405				warn("dup");
406				fin = NULL;
407			} else
408				fin = Fdopen(f, "r");
409			if (fin == NULL) {
410				fprintf(stderr, "Can't reopen image\n");
411				(void)Fclose(fout);
412				senderr++;
413				goto cant;
414			}
415			rewind(fin);
416			while ((c = getc(fin)) != EOF)
417				(void)putc(c, fout);
418			if (ferror(fout)) {
419				warnx("%s", fname);
420				senderr++;
421				(void)Fclose(fout);
422				(void)Fclose(fin);
423				goto cant;
424			}
425			(void)Fclose(fout);
426			(void)Fclose(fin);
427		}
428cant:
429		/*
430		 * In days of old we removed the entry from the
431		 * the list; now for sake of header expansion
432		 * we leave it in and mark it as deleted.
433		 */
434		np->n_type |= GDEL;
435		np = np->n_flink;
436	}
437	if (image >= 0) {
438		(void)close(image);
439		image = -1;
440	}
441	return (top);
442}
443
444/*
445 * Determine if the passed address is a local "send to file" address.
446 * If any of the network metacharacters precedes any slashes, it can't
447 * be a filename.  We cheat with .'s to allow path names like ./...
448 */
449int
450isfileaddr(name)
451	char *name;
452{
453	char *cp;
454
455	if (*name == '+')
456		return (1);
457	for (cp = name; *cp != '\0'; cp++) {
458		if (*cp == '!' || *cp == '%' || *cp == '@')
459			return (0);
460		if (*cp == '/')
461			return (1);
462	}
463	return (0);
464}
465
466/*
467 * Map all of the aliased users in the invoker's mailrc
468 * file and insert them into the list.
469 * Changed after all these months of service to recursively
470 * expand names (2/14/80).
471 */
472
473struct name *
474usermap(names)
475	struct name *names;
476{
477	struct name *new, *np, *cp;
478	struct grouphead *gh;
479	int metoo;
480
481	new = NULL;
482	np = names;
483	metoo = (value("metoo") != NULL);
484	while (np != NULL) {
485		if (np->n_name[0] == '\\') {
486			cp = np->n_flink;
487			new = put(new, np);
488			np = cp;
489			continue;
490		}
491		gh = findgroup(np->n_name);
492		cp = np->n_flink;
493		if (gh != NULL)
494			new = gexpand(new, gh, metoo, np->n_type);
495		else
496			new = put(new, np);
497		np = cp;
498	}
499	return (new);
500}
501
502/*
503 * Recursively expand a group name.  We limit the expansion to some
504 * fixed level to keep things from going haywire.
505 * Direct recursion is not expanded for convenience.
506 */
507
508struct name *
509gexpand(nlist, gh, metoo, ntype)
510	struct name *nlist;
511	struct grouphead *gh;
512	int metoo, ntype;
513{
514	struct group *gp;
515	struct grouphead *ngh;
516	struct name *np;
517	static int depth;
518	char *cp;
519
520	if (depth > MAXEXP) {
521		printf("Expanding alias to depth larger than %d\n", MAXEXP);
522		return (nlist);
523	}
524	depth++;
525	for (gp = gh->g_list; gp != NULL; gp = gp->ge_link) {
526		cp = gp->ge_name;
527		if (*cp == '\\')
528			goto quote;
529		if (strcmp(cp, gh->g_name) == 0)
530			goto quote;
531		if ((ngh = findgroup(cp)) != NULL) {
532			nlist = gexpand(nlist, ngh, metoo, ntype);
533			continue;
534		}
535quote:
536		np = nalloc(cp, ntype);
537		/*
538		 * At this point should allow to expand
539		 * to self if only person in group
540		 */
541		if (gp == gh->g_list && gp->ge_link == NULL)
542			goto skip;
543		if (!metoo && strcmp(cp, myname) == 0)
544			np->n_type |= GDEL;
545skip:
546		nlist = put(nlist, np);
547	}
548	depth--;
549	return (nlist);
550}
551
552/*
553 * Concatenate the two passed name lists, return the result.
554 */
555struct name *
556cat(n1, n2)
557	struct name *n1, *n2;
558{
559	struct name *tail;
560
561	if (n1 == NULL)
562		return (n2);
563	if (n2 == NULL)
564		return (n1);
565	tail = tailof(n1);
566	tail->n_flink = n2;
567	n2->n_blink = tail;
568	return (n1);
569}
570
571/*
572 * Unpack the name list onto a vector of strings.
573 * Return an error if the name list won't fit.
574 */
575char **
576unpack(np)
577	struct name *np;
578{
579	char **ap, **top;
580	struct name *n;
581	int t, extra, metoo, verbose;
582
583	n = np;
584	if ((t = count(n)) == 0)
585		errx(1, "No names to unpack");
586	/*
587	 * Compute the number of extra arguments we will need.
588	 * We need at least two extra -- one for "mail" and one for
589	 * the terminating 0 pointer.  Additional spots may be needed
590	 * to pass along -f to the host mailer.
591	 */
592	extra = 2;
593	extra++;
594	metoo = value("metoo") != NULL;
595	if (metoo)
596		extra++;
597	verbose = value("verbose") != NULL;
598	if (verbose)
599		extra++;
600	top = (char **)salloc((t + extra) * sizeof(*top));
601	ap = top;
602	*ap++ = "send-mail";
603	*ap++ = "-i";
604	if (metoo)
605		*ap++ = "-m";
606	if (verbose)
607		*ap++ = "-v";
608	for (; n != NULL; n = n->n_flink)
609		if ((n->n_type & GDEL) == 0)
610			*ap++ = n->n_name;
611	*ap = NULL;
612	return (top);
613}
614
615/*
616 * Remove all of the duplicates from the passed name list by
617 * insertion sorting them, then checking for dups.
618 * Return the head of the new list.
619 */
620struct name *
621elide(names)
622	struct name *names;
623{
624	struct name *np, *t, *new;
625	struct name *x;
626
627	if (names == NULL)
628		return (NULL);
629	new = names;
630	np = names;
631	np = np->n_flink;
632	if (np != NULL)
633		np->n_blink = NULL;
634	new->n_flink = NULL;
635	while (np != NULL) {
636		t = new;
637		while (strcasecmp(t->n_name, np->n_name) < 0) {
638			if (t->n_flink == NULL)
639				break;
640			t = t->n_flink;
641		}
642
643		/*
644		 * If we ran out of t's, put the new entry after
645		 * the current value of t.
646		 */
647
648		if (strcasecmp(t->n_name, np->n_name) < 0) {
649			t->n_flink = np;
650			np->n_blink = t;
651			t = np;
652			np = np->n_flink;
653			t->n_flink = NULL;
654			continue;
655		}
656
657		/*
658		 * Otherwise, put the new entry in front of the
659		 * current t.  If at the front of the list,
660		 * the new guy becomes the new head of the list.
661		 */
662
663		if (t == new) {
664			t = np;
665			np = np->n_flink;
666			t->n_flink = new;
667			new->n_blink = t;
668			t->n_blink = NULL;
669			new = t;
670			continue;
671		}
672
673		/*
674		 * The normal case -- we are inserting into the
675		 * middle of the list.
676		 */
677
678		x = np;
679		np = np->n_flink;
680		x->n_flink = t;
681		x->n_blink = t->n_blink;
682		t->n_blink->n_flink = x;
683		t->n_blink = x;
684	}
685
686	/*
687	 * Now the list headed up by new is sorted.
688	 * Go through it and remove duplicates.
689	 */
690
691	np = new;
692	while (np != NULL) {
693		t = np;
694		while (t->n_flink != NULL &&
695		    strcasecmp(np->n_name, t->n_flink->n_name) == 0)
696			t = t->n_flink;
697		if (t == np || t == NULL) {
698			np = np->n_flink;
699			continue;
700		}
701
702		/*
703		 * Now t points to the last entry with the same name
704		 * as np.  Make np point beyond t.
705		 */
706
707		np->n_flink = t->n_flink;
708		if (t->n_flink != NULL)
709			t->n_flink->n_blink = np;
710		np = np->n_flink;
711	}
712	return (new);
713}
714
715/*
716 * Put another node onto a list of names and return
717 * the list.
718 */
719struct name *
720put(list, node)
721	struct name *list, *node;
722{
723	node->n_flink = list;
724	node->n_blink = NULL;
725	if (list != NULL)
726		list->n_blink = node;
727	return (node);
728}
729
730/*
731 * Determine the number of undeleted elements in
732 * a name list and return it.
733 */
734int
735count(np)
736	struct name *np;
737{
738	int c;
739
740	for (c = 0; np != NULL; np = np->n_flink)
741		if ((np->n_type & GDEL) == 0)
742			c++;
743	return (c);
744}
745
746/*
747 * Delete the given name from a namelist.
748 */
749struct name *
750delname(np, name)
751	struct name *np;
752	char name[];
753{
754	struct name *p;
755
756	for (p = np; p != NULL; p = p->n_flink)
757		if (strcasecmp(p->n_name, name) == 0) {
758			if (p->n_blink == NULL) {
759				if (p->n_flink != NULL)
760					p->n_flink->n_blink = NULL;
761				np = p->n_flink;
762				continue;
763			}
764			if (p->n_flink == NULL) {
765				if (p->n_blink != NULL)
766					p->n_blink->n_flink = NULL;
767				continue;
768			}
769			p->n_blink->n_flink = p->n_flink;
770			p->n_flink->n_blink = p->n_blink;
771		}
772	return (np);
773}
774
775/*
776 * Pretty print a name list
777 * Uncomment it if you need it.
778 */
779
780/*
781void
782prettyprint(name)
783	struct name *name;
784{
785	struct name *np;
786
787	np = name;
788	while (np != NULL) {
789		fprintf(stderr, "%s(%d) ", np->n_name, np->n_type);
790		np = np->n_flink;
791	}
792	fprintf(stderr, "\n");
793}
794*/
795