xref: /titanic_41/usr/src/ucbcmd/from/from.c (revision cde2885fdf538266ee2a3b08dee2d5075ce8fa2b)
1 /*
2  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*
7  * Copyright (c) 1980 Regents of the University of California.
8  * All rights reserved.  The Berkeley software License Agreement
9  * specifies the terms and conditions for redistribution.
10  */
11 
12 #pragma ident	"%Z%%M%	%I%	%E% SMI"
13 
14 #include <stdio.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17 #include <stdlib.h>
18 #include <ctype.h>
19 #include <pwd.h>
20 #include <sys/param.h>
21 #include <string.h>
22 
23 static int match(char *, char *);
24 
25 int
26 main(int argc, char **argv)
27 {
28 	char lbuf[BUFSIZ];
29 	char lbuf2[BUFSIZ];
30 	struct passwd *pp;
31 	int stashed = 0;
32 	char *name;
33 	char *sender = NULL;
34 	char mailbox[MAXPATHLEN];
35 	char *tmp_mailbox;
36 	extern char *optarg;
37 	extern int optind;
38 	extern int opterr;
39 	int c;
40 	int errflg = 0;
41 
42 	opterr = 0;
43 	while ((c = getopt(argc, argv, "s:")) != EOF)
44 		switch (c) {
45 		case 's':
46 			sender = optarg;
47 			for (name = sender; *name; name++)
48 				if (isupper(*name))
49 					*name = tolower(*name);
50 			break;
51 		case '?':
52 			errflg++;
53 			break;
54 		}
55 	if (errflg) {
56 		(void) fprintf(stderr,
57 			    "Usage: from [-s sender] [user]\n");
58 		exit(1);
59 	}
60 
61 	if (optind < argc) {
62 		(void) sprintf(mailbox, "/var/mail/%s", argv[optind]);
63 	} else {
64 		if (tmp_mailbox = getenv("MAIL")) {
65 			(void) strcpy(mailbox, tmp_mailbox);
66 		} else {
67 			name = getlogin();
68 			if (name == NULL || strlen(name) == 0) {
69 				pp = getpwuid(getuid());
70 				if (pp == NULL) {
71 					(void) fprintf(stderr,
72 					    "Who are you?\n");
73 					exit(1);
74 				}
75 				name = pp->pw_name;
76 			}
77 			(void) sprintf(mailbox, "/var/mail/%s", name);
78 		}
79 	}
80 	if (freopen(mailbox, "r", stdin) == NULL) {
81 		(void) fprintf(stderr, "Can't open %s\n", mailbox);
82 		exit(0);
83 	}
84 	while (fgets(lbuf, sizeof (lbuf), stdin) != NULL)
85 		if (lbuf[0] == '\n' && stashed) {
86 			stashed = 0;
87 			(void) printf("%s", lbuf2);
88 		} else if (strncmp(lbuf, "From ", 5) == 0 &&
89 		    (sender == NULL || match(&lbuf[4], sender))) {
90 			(void) strcpy(lbuf2, lbuf);
91 			stashed = 1;
92 		}
93 	if (stashed)
94 		(void) printf("%s", lbuf2);
95 	return (0);
96 }
97 
98 static int
99 match(char *line, char *str)
100 {
101 	char ch;
102 
103 	while (*line == ' ' || *line == '\t')
104 		++line;
105 	if (*line == '\n')
106 		return (0);
107 	while (*str && *line != ' ' && *line != '\t' && *line != '\n') {
108 		ch = isupper(*line) ? tolower(*line) : *line;
109 		if (ch != *str++)
110 			return (0);
111 		line++;
112 	}
113 	return (*str == '\0');
114 }
115