xref: /openbsd-src/usr.bin/write/write.c (revision ce7e0fc6a9d74d25b78fb6ad846387717f5172b6)
1 /*	$OpenBSD: write.c,v 1.16 2002/02/21 07:32:55 fgsch 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.16 2002/02/21 07:32:55 fgsch 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(argc, argv)
78 	int argc;
79 	char **argv;
80 {
81 	char *cp;
82 	time_t atime;
83 	uid_t myuid;
84 	int msgsok, myttyfd;
85 	char tty[MAXPATHLEN], *mytty;
86 
87 	/* check that sender has write enabled */
88 	if (isatty(fileno(stdin)))
89 		myttyfd = fileno(stdin);
90 	else if (isatty(fileno(stdout)))
91 		myttyfd = fileno(stdout);
92 	else if (isatty(fileno(stderr)))
93 		myttyfd = fileno(stderr);
94 	else
95 		errx(1, "can't find your tty");
96 	if (!(mytty = ttyname(myttyfd)))
97 		errx(1, "can't find your tty's name");
98 	if ((cp = strrchr(mytty, '/')))
99 		mytty = cp + 1;
100 	if (term_chk(mytty, &msgsok, &atime, 1))
101 		exit(1);
102 	if (!msgsok)
103 		warnx("you have write permission turned off");
104 
105 	myuid = getuid();
106 
107 	/* check args */
108 	switch (argc) {
109 	case 2:
110 		search_utmp(argv[1], tty, mytty, myuid);
111 		do_write(tty, mytty, myuid);
112 		break;
113 	case 3:
114 		if (!strncmp(argv[2], _PATH_DEV, sizeof(_PATH_DEV) - 1))
115 			argv[2] += sizeof(_PATH_DEV) - 1;
116 		if (utmp_chk(argv[1], argv[2]))
117 			errx(1, "%s is not logged in on %s",
118 			    argv[1], argv[2]);
119 		if (term_chk(argv[2], &msgsok, &atime, 1))
120 			exit(1);
121 		if (myuid && !msgsok)
122 			errx(1, "%s has messages disabled on %s",
123 			    argv[1], argv[2]);
124 		do_write(argv[2], mytty, myuid);
125 		break;
126 	default:
127 		(void)fprintf(stderr, "usage: write user [tty]\n");
128 		exit(1);
129 	}
130 	done(0);
131 
132 	/* NOTREACHED */
133 	return (0);
134 }
135 
136 /*
137  * utmp_chk - checks that the given user is actually logged in on
138  *     the given tty
139  */
140 int
141 utmp_chk(user, tty)
142 	char *user, *tty;
143 {
144 	struct utmp u;
145 	int ufd;
146 
147 	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
148 		return(0);	/* ignore error, shouldn't happen anyway */
149 
150 	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
151 		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0 &&
152 		    strncmp(tty, u.ut_line, sizeof(u.ut_line)) == 0) {
153 			(void)close(ufd);
154 			return(0);
155 		}
156 
157 	(void)close(ufd);
158 	return(1);
159 }
160 
161 /*
162  * search_utmp - search utmp for the "best" terminal to write to
163  *
164  * Ignores terminals with messages disabled, and of the rest, returns
165  * the one with the most recent access time.  Returns as value the number
166  * of the user's terminals with messages enabled, or -1 if the user is
167  * not logged in at all.
168  *
169  * Special case for writing to yourself - ignore the terminal you're
170  * writing from, unless that's the only terminal with messages enabled.
171  */
172 void
173 search_utmp(user, tty, mytty, myuid)
174 	char *user, *tty, *mytty;
175 	uid_t myuid;
176 {
177 	struct utmp u;
178 	time_t bestatime, atime;
179 	int ufd, nloggedttys, nttys, msgsok, user_is_me;
180 	char atty[UT_LINESIZE + 1];
181 
182 	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
183 		err(1, "%s", _PATH_UTMP);
184 
185 	nloggedttys = nttys = 0;
186 	bestatime = 0;
187 	user_is_me = 0;
188 	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
189 		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0) {
190 			++nloggedttys;
191 			(void)strncpy(atty, u.ut_line, UT_LINESIZE);
192 			atty[UT_LINESIZE] = '\0';
193 			if (term_chk(atty, &msgsok, &atime, 0))
194 				continue;	/* bad term? skip */
195 			if (myuid && !msgsok)
196 				continue;	/* skip ttys with msgs off */
197 			if (strcmp(atty, mytty) == 0) {
198 				user_is_me = 1;
199 				continue;	/* don't write to yourself */
200 			}
201 			++nttys;
202 			if (atime > bestatime) {
203 				bestatime = atime;
204 				(void)strcpy(tty, atty);
205 			}
206 		}
207 
208 	(void)close(ufd);
209 	if (nloggedttys == 0)
210 		errx(1, "%s is not logged in", user);
211 	if (nttys == 0) {
212 		if (user_is_me) {		/* ok, so write to yourself! */
213 			(void)strcpy(tty, mytty);
214 			return;
215 		}
216 		errx(1, "%s has messages disabled", user);
217 	} else if (nttys > 1)
218 		warnx("%s is logged in more than once; writing to %s",
219 		    user, tty);
220 }
221 
222 /*
223  * term_chk - check that a terminal exists, and get the message bit
224  *     and the access time
225  */
226 int
227 term_chk(tty, msgsokP, atimeP, showerror)
228 	char *tty;
229 	int *msgsokP, showerror;
230 	time_t *atimeP;
231 {
232 	struct stat s;
233 	char path[MAXPATHLEN];
234 
235 	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
236 	if (stat(path, &s) < 0) {
237 		if (showerror)
238 			warn("%s", path);
239 		return(1);
240 	}
241 	*msgsokP = (s.st_mode & S_IWGRP) != 0;	/* group write bit */
242 	*atimeP = s.st_atime;
243 	return(0);
244 }
245 
246 /*
247  * do_write - actually make the connection
248  */
249 void
250 do_write(tty, mytty, myuid)
251 	char *tty, *mytty;
252 	uid_t myuid;
253 {
254 	char *login, *nows;
255 	struct passwd *pwd;
256 	time_t now;
257 	char path[MAXPATHLEN], host[MAXHOSTNAMELEN], line[512];
258 
259 	/* Determine our login name before the we reopen() stdout */
260 	if ((login = getlogin()) == NULL) {
261 		if ((pwd = getpwuid(myuid)))
262 			login = pwd->pw_name;
263 		else
264 			login = "???";
265 	}
266 
267 	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
268 	if ((freopen(path, "w", stdout)) == NULL)
269 		err(1, "%s", path);
270 
271 	(void)signal(SIGINT, done);
272 	(void)signal(SIGHUP, done);
273 
274 	/* print greeting */
275 	if (gethostname(host, sizeof(host)) < 0)
276 		(void)strcpy(host, "???");
277 	now = time((time_t *)NULL);
278 	nows = ctime(&now);
279 	nows[16] = '\0';
280 	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
281 	    login, host, mytty, nows + 11);
282 
283 	while (fgets(line, sizeof(line), stdin) != NULL)
284 		wr_fputs(line);
285 }
286 
287 /*
288  * done - cleanup and exit
289  */
290 void
291 done(int sig)
292 {
293 	(void)write(STDOUT_FILENO, "EOF\r\n", 5);
294 	if (sig)
295 		_exit(0);
296 	else
297 		exit(0);
298 }
299 
300 /*
301  * wr_fputs - like fputs(), but makes control characters visible and
302  *     turns \n into \r\n
303  */
304 void
305 wr_fputs(s)
306 	char *s;
307 {
308 	u_char c;
309 	char visout[5], *s2;
310 
311 #define	PUTC(c)	if (putchar(c) == EOF) goto err;
312 
313 	for (; *s != '\0'; ++s) {
314 		c = toascii(*s);
315 		if (c == '\n') {
316 			PUTC('\r');
317 			PUTC('\n');
318 			continue;
319 		}
320 		vis(visout, c, VIS_SAFE|VIS_NOSLASH, s[1]);
321 		for (s2 = visout; *s2; s2++)
322 			PUTC(*s2);
323 	}
324 	return;
325 
326 err:	err(1, NULL);
327 #undef PUTC
328 }
329