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