xref: /openbsd-src/usr.bin/write/write.c (revision 47911bd667ac77dc523b8a13ef40b012dbffa741)
1 /*	$OpenBSD: write.c,v 1.17 2002/08/04 01:26:40 deraadt Exp $	*/
2 /*	$NetBSD: write.c,v 1.5 1995/08/31 21:48:32 jtc Exp $	*/
3 
4 /*
5  * Copyright (c) 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Jef Poskanzer and Craig Leres of the Lawrence Berkeley Laboratory.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 #ifndef lint
41 static char copyright[] =
42 "@(#) Copyright (c) 1989, 1993\n\
43 	The Regents of the University of California.  All rights reserved.\n";
44 #endif /* not lint */
45 
46 #ifndef lint
47 #if 0
48 static char sccsid[] = "@(#)write.c	8.2 (Berkeley) 4/27/95";
49 #endif
50 static char *rcsid = "$OpenBSD: write.c,v 1.17 2002/08/04 01:26:40 deraadt Exp $";
51 #endif /* not lint */
52 
53 #include <sys/types.h>
54 #include <sys/param.h>
55 #include <sys/stat.h>
56 #include <ctype.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <signal.h>
60 #include <time.h>
61 #include <fcntl.h>
62 #include <paths.h>
63 #include <pwd.h>
64 #include <unistd.h>
65 #include <utmp.h>
66 #include <err.h>
67 #include <vis.h>
68 
69 void done(int sig);
70 void do_write(char *, char *, uid_t);
71 void wr_fputs(char *);
72 void search_utmp(char *, char *, char *, uid_t);
73 int term_chk(char *, int *, time_t *, int);
74 int utmp_chk(char *, char *);
75 
76 int
77 main(int argc, char **argv)
78 {
79 	char tty[MAXPATHLEN], *mytty, *cp;
80 	int msgsok, myttyfd;
81 	time_t atime;
82 	uid_t myuid;
83 
84 	/* check that sender has write enabled */
85 	if (isatty(fileno(stdin)))
86 		myttyfd = fileno(stdin);
87 	else if (isatty(fileno(stdout)))
88 		myttyfd = fileno(stdout);
89 	else if (isatty(fileno(stderr)))
90 		myttyfd = fileno(stderr);
91 	else
92 		errx(1, "can't find your tty");
93 	if (!(mytty = ttyname(myttyfd)))
94 		errx(1, "can't find your tty's name");
95 	if ((cp = strrchr(mytty, '/')))
96 		mytty = cp + 1;
97 	if (term_chk(mytty, &msgsok, &atime, 1))
98 		exit(1);
99 	if (!msgsok)
100 		warnx("you have write permission turned off");
101 
102 	myuid = getuid();
103 
104 	/* check args */
105 	switch (argc) {
106 	case 2:
107 		search_utmp(argv[1], tty, mytty, myuid);
108 		do_write(tty, mytty, myuid);
109 		break;
110 	case 3:
111 		if (!strncmp(argv[2], _PATH_DEV, sizeof(_PATH_DEV) - 1))
112 			argv[2] += sizeof(_PATH_DEV) - 1;
113 		if (utmp_chk(argv[1], argv[2]))
114 			errx(1, "%s is not logged in on %s",
115 			    argv[1], argv[2]);
116 		if (term_chk(argv[2], &msgsok, &atime, 1))
117 			exit(1);
118 		if (myuid && !msgsok)
119 			errx(1, "%s has messages disabled on %s",
120 			    argv[1], argv[2]);
121 		do_write(argv[2], mytty, myuid);
122 		break;
123 	default:
124 		(void)fprintf(stderr, "usage: write user [tty]\n");
125 		exit(1);
126 	}
127 	done(0);
128 
129 	/* NOTREACHED */
130 	return (0);
131 }
132 
133 /*
134  * utmp_chk - checks that the given user is actually logged in on
135  *     the given tty
136  */
137 int
138 utmp_chk(char *user, char *tty)
139 {
140 	struct utmp u;
141 	int ufd;
142 
143 	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
144 		return(0);	/* ignore error, shouldn't happen anyway */
145 
146 	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
147 		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0 &&
148 		    strncmp(tty, u.ut_line, sizeof(u.ut_line)) == 0) {
149 			(void)close(ufd);
150 			return(0);
151 		}
152 
153 	(void)close(ufd);
154 	return(1);
155 }
156 
157 /*
158  * search_utmp - search utmp for the "best" terminal to write to
159  *
160  * Ignores terminals with messages disabled, and of the rest, returns
161  * the one with the most recent access time.  Returns as value the number
162  * of the user's terminals with messages enabled, or -1 if the user is
163  * not logged in at all.
164  *
165  * Special case for writing to yourself - ignore the terminal you're
166  * writing from, unless that's the only terminal with messages enabled.
167  */
168 void
169 search_utmp(char *user, char *tty, char *mytty, uid_t myuid)
170 {
171 	struct utmp u;
172 	time_t bestatime, atime;
173 	int ufd, nloggedttys, nttys, msgsok, user_is_me;
174 	char atty[UT_LINESIZE + 1];
175 
176 	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
177 		err(1, "%s", _PATH_UTMP);
178 
179 	nloggedttys = nttys = 0;
180 	bestatime = 0;
181 	user_is_me = 0;
182 	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
183 		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0) {
184 			++nloggedttys;
185 			(void)strncpy(atty, u.ut_line, UT_LINESIZE);
186 			atty[UT_LINESIZE] = '\0';
187 			if (term_chk(atty, &msgsok, &atime, 0))
188 				continue;	/* bad term? skip */
189 			if (myuid && !msgsok)
190 				continue;	/* skip ttys with msgs off */
191 			if (strcmp(atty, mytty) == 0) {
192 				user_is_me = 1;
193 				continue;	/* don't write to yourself */
194 			}
195 			++nttys;
196 			if (atime > bestatime) {
197 				bestatime = atime;
198 				(void)strcpy(tty, atty);
199 			}
200 		}
201 
202 	(void)close(ufd);
203 	if (nloggedttys == 0)
204 		errx(1, "%s is not logged in", user);
205 	if (nttys == 0) {
206 		if (user_is_me) {		/* ok, so write to yourself! */
207 			(void)strcpy(tty, mytty);
208 			return;
209 		}
210 		errx(1, "%s has messages disabled", user);
211 	} else if (nttys > 1)
212 		warnx("%s is logged in more than once; writing to %s",
213 		    user, tty);
214 }
215 
216 /*
217  * term_chk - check that a terminal exists, and get the message bit
218  *     and the access time
219  */
220 int
221 term_chk(char *tty, int *msgsokP, time_t *atimeP, int showerror)
222 {
223 	struct stat s;
224 	char path[MAXPATHLEN];
225 
226 	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
227 	if (stat(path, &s) < 0) {
228 		if (showerror)
229 			warn("%s", path);
230 		return(1);
231 	}
232 	*msgsokP = (s.st_mode & S_IWGRP) != 0;	/* group write bit */
233 	*atimeP = s.st_atime;
234 	return(0);
235 }
236 
237 /*
238  * do_write - actually make the connection
239  */
240 void
241 do_write(char *tty, char *mytty, uid_t myuid)
242 {
243 	char *login, *nows;
244 	struct passwd *pwd;
245 	time_t now;
246 	char path[MAXPATHLEN], host[MAXHOSTNAMELEN], line[512];
247 
248 	/* Determine our login name before the we reopen() stdout */
249 	if ((login = getlogin()) == NULL) {
250 		if ((pwd = getpwuid(myuid)))
251 			login = pwd->pw_name;
252 		else
253 			login = "???";
254 	}
255 
256 	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
257 	if ((freopen(path, "w", stdout)) == NULL)
258 		err(1, "%s", path);
259 
260 	/* revoke privs, now that we have opened the tty */
261 	setegid(getgid());
262 	setgid(getgid());
263 
264 	(void)signal(SIGINT, done);
265 	(void)signal(SIGHUP, done);
266 
267 	/* print greeting */
268 	if (gethostname(host, sizeof(host)) < 0)
269 		(void)strcpy(host, "???");
270 	now = time((time_t *)NULL);
271 	nows = ctime(&now);
272 	nows[16] = '\0';
273 	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
274 	    login, host, mytty, nows + 11);
275 
276 	while (fgets(line, sizeof(line), stdin) != NULL)
277 		wr_fputs(line);
278 }
279 
280 /*
281  * done - cleanup and exit
282  */
283 void
284 done(int sig)
285 {
286 	(void)write(STDOUT_FILENO, "EOF\r\n", 5);
287 	if (sig)
288 		_exit(0);
289 	else
290 		exit(0);
291 }
292 
293 /*
294  * wr_fputs - like fputs(), but makes control characters visible and
295  *     turns \n into \r\n
296  */
297 void
298 wr_fputs(char *s)
299 {
300 	u_char c;
301 	char visout[5], *s2;
302 
303 #define	PUTC(c)	if (putchar(c) == EOF) goto err;
304 
305 	for (; *s != '\0'; ++s) {
306 		c = toascii(*s);
307 		if (c == '\n') {
308 			PUTC('\r');
309 			PUTC('\n');
310 			continue;
311 		}
312 		vis(visout, c, VIS_SAFE|VIS_NOSLASH, s[1]);
313 		for (s2 = visout; *s2; s2++)
314 			PUTC(*s2);
315 	}
316 	return;
317 
318 err:	err(1, NULL);
319 #undef PUTC
320 }
321