write.c revision 92922
1277323Sdim/*
2277323Sdim * Copyright (c) 1989, 1993
3277323Sdim *	The Regents of the University of California.  All rights reserved.
4277323Sdim *
5277323Sdim * This code is derived from software contributed to Berkeley by
6277323Sdim * Jef Poskanzer and Craig Leres of the Lawrence Berkeley Laboratory.
7277323Sdim *
8277323Sdim * Redistribution and use in source and binary forms, with or without
9277323Sdim * modification, are permitted provided that the following conditions
10277323Sdim * are met:
11277323Sdim * 1. Redistributions of source code must retain the above copyright
12277323Sdim *    notice, this list of conditions and the following disclaimer.
13277323Sdim * 2. Redistributions in binary form must reproduce the above copyright
14277323Sdim *    notice, this list of conditions and the following disclaimer in the
15277323Sdim *    documentation and/or other materials provided with the distribution.
16277323Sdim * 3. All advertising materials mentioning features or use of this software
17277323Sdim *    must display the following acknowledgement:
18277323Sdim *	This product includes software developed by the University of
19277323Sdim *	California, Berkeley and its contributors.
20277323Sdim * 4. Neither the name of the University nor the names of its contributors
21277323Sdim *    may be used to endorse or promote products derived from this software
22277323Sdim *    without specific prior written permission.
23277323Sdim *
24277323Sdim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25277323Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26277323Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27277323Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28277323Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29277323Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30277323Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31277323Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32277323Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33277323Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34277323Sdim * SUCH DAMAGE.
35277323Sdim */
36277323Sdim
37277323Sdim#ifndef lint
38277323Sdimstatic const char copyright[] =
39277323Sdim"@(#) Copyright (c) 1989, 1993\n\
40277323Sdim	The Regents of the University of California.  All rights reserved.\n";
41277323Sdim#endif
42277323Sdim
43277323Sdim#if 0
44277323Sdim#ifndef lint
45277323Sdimstatic char sccsid[] = "@(#)write.c	8.1 (Berkeley) 6/6/93";
46277323Sdim#endif
47277323Sdim#endif
48277323Sdim
49277323Sdim#include <sys/cdefs.h>
50277323Sdim__FBSDID("$FreeBSD: head/usr.bin/write/write.c 92922 2002-03-22 01:42:45Z imp $");
51277323Sdim
52277323Sdim#include <sys/param.h>
53277323Sdim#include <sys/signal.h>
54277323Sdim#include <sys/stat.h>
55277323Sdim#include <sys/file.h>
56277323Sdim#include <sys/time.h>
57277323Sdim#include <ctype.h>
58277323Sdim#include <err.h>
59277323Sdim#include <locale.h>
60277323Sdim#include <paths.h>
61277323Sdim#include <pwd.h>
62277323Sdim#include <stdio.h>
63277323Sdim#include <stdlib.h>
64277323Sdim#include <string.h>
65277323Sdim#include <unistd.h>
66277323Sdim#include <utmp.h>
67277323Sdim
68277323Sdimvoid done(int);
69277323Sdimvoid do_write(char *, char *, uid_t);
70277323Sdimstatic void usage(void);
71277323Sdimint term_chk(char *, int *, time_t *, int);
72277323Sdimvoid wr_fputs(unsigned char *s);
73277323Sdimvoid search_utmp(char *, char *, char *, uid_t);
74277323Sdimint utmp_chk(char *, char *);
75277323Sdim
76277323Sdimint
77277323Sdimmain(argc, argv)
78277323Sdim	int argc;
79277323Sdim	char **argv;
80277323Sdim{
81277323Sdim	register char *cp;
82277323Sdim	time_t atime;
83277323Sdim	uid_t myuid;
84277323Sdim	int msgsok, myttyfd;
85277323Sdim	char tty[MAXPATHLEN], *mytty;
86277323Sdim
87277323Sdim	(void)setlocale(LC_CTYPE, "");
88277323Sdim
89277323Sdim	/* check that sender has write enabled */
90277323Sdim	if (isatty(fileno(stdin)))
91277323Sdim		myttyfd = fileno(stdin);
92277323Sdim	else if (isatty(fileno(stdout)))
93288943Sdim		myttyfd = fileno(stdout);
94288943Sdim	else if (isatty(fileno(stderr)))
95288943Sdim		myttyfd = fileno(stderr);
96288943Sdim	else
97288943Sdim		errx(1, "can't find your tty");
98288943Sdim	if (!(mytty = ttyname(myttyfd)))
99288943Sdim		errx(1, "can't find your tty's name");
100288943Sdim	if ((cp = rindex(mytty, '/')))
101		mytty = cp + 1;
102	if (term_chk(mytty, &msgsok, &atime, 1))
103		exit(1);
104	if (!msgsok)
105		errx(1, "you have write permission turned off");
106
107	myuid = getuid();
108
109	/* check args */
110	switch (argc) {
111	case 2:
112		search_utmp(argv[1], tty, mytty, myuid);
113		do_write(tty, mytty, myuid);
114		break;
115	case 3:
116		if (!strncmp(argv[2], _PATH_DEV, strlen(_PATH_DEV)))
117			argv[2] += strlen(_PATH_DEV);
118		if (utmp_chk(argv[1], argv[2]))
119			errx(1, "%s is not logged in on %s", argv[1], argv[2]);
120		if (term_chk(argv[2], &msgsok, &atime, 1))
121			exit(1);
122		if (myuid && !msgsok)
123			errx(1, "%s has messages disabled on %s", argv[1], argv[2]);
124		do_write(argv[2], mytty, myuid);
125		break;
126	default:
127		usage();
128	}
129	done(0);
130	return (0);
131}
132
133static void
134usage()
135{
136	(void)fprintf(stderr, "usage: write user [tty]\n");
137	exit(1);
138}
139
140/*
141 * utmp_chk - checks that the given user is actually logged in on
142 *     the given tty
143 */
144int
145utmp_chk(user, tty)
146	char *user, *tty;
147{
148	struct utmp u;
149	int ufd;
150
151	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
152		return(0);	/* ignore error, shouldn't happen anyway */
153
154	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
155		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0 &&
156		    strncmp(tty, u.ut_line, sizeof(u.ut_line)) == 0) {
157			(void)close(ufd);
158			return(0);
159		}
160
161	(void)close(ufd);
162	return(1);
163}
164
165/*
166 * search_utmp - search utmp for the "best" terminal to write to
167 *
168 * Ignores terminals with messages disabled, and of the rest, returns
169 * the one with the most recent access time.  Returns as value the number
170 * of the user's terminals with messages enabled, or -1 if the user is
171 * not logged in at all.
172 *
173 * Special case for writing to yourself - ignore the terminal you're
174 * writing from, unless that's the only terminal with messages enabled.
175 */
176void
177search_utmp(user, tty, mytty, myuid)
178	char *user, *tty, *mytty;
179	uid_t myuid;
180{
181	struct utmp u;
182	time_t bestatime, atime;
183	int ufd, nloggedttys, nttys, msgsok, user_is_me;
184	char atty[UT_LINESIZE + 1];
185
186	if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
187		err(1, "utmp");
188
189	nloggedttys = nttys = 0;
190	bestatime = 0;
191	user_is_me = 0;
192	while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
193		if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0) {
194			++nloggedttys;
195			(void)strncpy(atty, u.ut_line, UT_LINESIZE);
196			atty[UT_LINESIZE] = '\0';
197			if (term_chk(atty, &msgsok, &atime, 0))
198				continue;	/* bad term? skip */
199			if (myuid && !msgsok)
200				continue;	/* skip ttys with msgs off */
201			if (strcmp(atty, mytty) == 0) {
202				user_is_me = 1;
203				continue;	/* don't write to yourself */
204			}
205			++nttys;
206			if (atime > bestatime) {
207				bestatime = atime;
208				(void)strcpy(tty, atty);
209			}
210		}
211
212	(void)close(ufd);
213	if (nloggedttys == 0)
214		errx(1, "%s is not logged in", user);
215	if (nttys == 0) {
216		if (user_is_me) {		/* ok, so write to yourself! */
217			(void)strcpy(tty, mytty);
218			return;
219		}
220		errx(1, "%s has messages disabled", user);
221	} else if (nttys > 1) {
222		warnx("%s is logged in more than once; writing to %s", user, tty);
223	}
224}
225
226/*
227 * term_chk - check that a terminal exists, and get the message bit
228 *     and the access time
229 */
230int
231term_chk(tty, msgsokP, atimeP, showerror)
232	char *tty;
233	int *msgsokP, showerror;
234	time_t *atimeP;
235{
236	struct stat s;
237	char path[MAXPATHLEN];
238
239	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
240	if (stat(path, &s) < 0) {
241		if (showerror)
242			warn("%s", path);
243		return(1);
244	}
245	*msgsokP = (s.st_mode & (S_IWRITE >> 3)) != 0;	/* group write bit */
246	*atimeP = s.st_atime;
247	return(0);
248}
249
250/*
251 * do_write - actually make the connection
252 */
253void
254do_write(tty, mytty, myuid)
255	char *tty, *mytty;
256	uid_t myuid;
257{
258	const char *login;
259	char *nows;
260	struct passwd *pwd;
261	time_t now;
262	char path[MAXPATHLEN], host[MAXHOSTNAMELEN], line[512];
263
264	/* Determine our login name before the we reopen() stdout */
265	if ((login = getlogin()) == NULL) {
266		if ((pwd = getpwuid(myuid)))
267			login = pwd->pw_name;
268		else
269			login = "???";
270	}
271
272	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
273	if ((freopen(path, "w", stdout)) == NULL)
274		err(1, "%s", path);
275
276	(void)signal(SIGINT, done);
277	(void)signal(SIGHUP, done);
278
279	/* print greeting */
280	if (gethostname(host, sizeof(host)) < 0)
281		(void)strcpy(host, "???");
282	now = time((time_t *)NULL);
283	nows = ctime(&now);
284	nows[16] = '\0';
285	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
286	    login, host, mytty, nows + 11);
287
288	while (fgets(line, sizeof(line), stdin) != NULL)
289		wr_fputs(line);
290}
291
292/*
293 * done - cleanup and exit
294 */
295void
296done(n)
297	int n __unused;
298{
299	(void)printf("EOF\r\n");
300	exit(0);
301}
302
303/*
304 * wr_fputs - like fputs(), but makes control characters visible and
305 *     turns \n into \r\n
306 */
307void
308wr_fputs(s)
309	unsigned char *s;
310{
311
312#define	PUTC(c)	if (putchar(c) == EOF) err(1, NULL);
313
314	for (; *s != '\0'; ++s) {
315		if (*s == '\n') {
316			PUTC('\r');
317		} else if (((*s & 0x80) && *s < 0xA0) ||
318			   /* disable upper controls */
319			   (!isprint(*s) && !isspace(*s) &&
320			    *s != '\a' && *s != '\b')
321			  ) {
322			if (*s & 0x80) {
323				*s &= ~0x80;
324				PUTC('M');
325				PUTC('-');
326			}
327			if (iscntrl(*s)) {
328				*s ^= 0x40;
329				PUTC('^');
330			}
331		}
332		PUTC(*s);
333	}
334	return;
335#undef PUTC
336}
337