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 #include <stdio.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 #include <stdlib.h>
16 #include <ctype.h>
17 #include <pwd.h>
18 #include <sys/param.h>
19 #include <string.h>
20
21 static int match(char *, char *);
22
23 int
main(int argc,char ** argv)24 main(int argc, char **argv)
25 {
26 char lbuf[BUFSIZ];
27 char lbuf2[BUFSIZ];
28 struct passwd *pp;
29 int stashed = 0;
30 char *name;
31 char *sender = NULL;
32 char mailbox[MAXPATHLEN];
33 char *tmp_mailbox;
34 extern char *optarg;
35 extern int optind;
36 extern int opterr;
37 int c;
38 int errflg = 0;
39
40 opterr = 0;
41 while ((c = getopt(argc, argv, "s:")) != EOF)
42 switch (c) {
43 case 's':
44 sender = optarg;
45 for (name = sender; *name; name++)
46 if (isupper(*name))
47 *name = tolower(*name);
48 break;
49 case '?':
50 errflg++;
51 break;
52 }
53 if (errflg) {
54 (void) fprintf(stderr,
55 "Usage: from [-s sender] [user]\n");
56 exit(1);
57 }
58
59 if (optind < argc) {
60 (void) sprintf(mailbox, "/var/mail/%s", argv[optind]);
61 } else {
62 if (tmp_mailbox = getenv("MAIL")) {
63 (void) strcpy(mailbox, tmp_mailbox);
64 } else {
65 name = getlogin();
66 if (name == NULL || strlen(name) == 0) {
67 pp = getpwuid(getuid());
68 if (pp == NULL) {
69 (void) fprintf(stderr,
70 "Who are you?\n");
71 exit(1);
72 }
73 name = pp->pw_name;
74 }
75 (void) sprintf(mailbox, "/var/mail/%s", name);
76 }
77 }
78 if (freopen(mailbox, "r", stdin) == NULL) {
79 (void) fprintf(stderr, "Can't open %s\n", mailbox);
80 exit(0);
81 }
82 while (fgets(lbuf, sizeof (lbuf), stdin) != NULL)
83 if (lbuf[0] == '\n' && stashed) {
84 stashed = 0;
85 (void) printf("%s", lbuf2);
86 } else if (strncmp(lbuf, "From ", 5) == 0 &&
87 (sender == NULL || match(&lbuf[4], sender))) {
88 (void) strcpy(lbuf2, lbuf);
89 stashed = 1;
90 }
91 if (stashed)
92 (void) printf("%s", lbuf2);
93 return (0);
94 }
95
96 static int
match(char * line,char * str)97 match(char *line, char *str)
98 {
99 char ch;
100
101 while (*line == ' ' || *line == '\t')
102 ++line;
103 if (*line == '\n')
104 return (0);
105 while (*str && *line != ' ' && *line != '\t' && *line != '\n') {
106 ch = isupper(*line) ? tolower(*line) : *line;
107 if (ch != *str++)
108 return (0);
109 line++;
110 }
111 return (*str == '\0');
112 }
113