write.c revision 92922
1/*
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Jef Poskanzer and Craig Leres of the Lawrence Berkeley Laboratory.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 *    must display the following acknowledgement:
18 *	This product includes software developed by the University of
19 *	California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 *    may be used to endorse or promote products derived from this software
22 *    without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1989, 1993\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif
42
43#if 0
44#ifndef lint
45static char sccsid[] = "@(#)write.c	8.1 (Berkeley) 6/6/93";
46#endif
47#endif
48
49#include <sys/cdefs.h>
50__FBSDID("$FreeBSD: head/usr.bin/write/write.c 92922 2002-03-22 01:42:45Z imp $");
51
52#include <sys/param.h>
53#include <sys/signal.h>
54#include <sys/stat.h>
55#include <sys/file.h>
56#include <sys/time.h>
57#include <ctype.h>
58#include <err.h>
59#include <locale.h>
60#include <paths.h>
61#include <pwd.h>
62#include <stdio.h>
63#include <stdlib.h>
64#include <string.h>
65#include <unistd.h>
66#include <utmp.h>
67
68void done(int);
69void do_write(char *, char *, uid_t);
70static void usage(void);
71int term_chk(char *, int *, time_t *, int);
72void wr_fputs(unsigned char *s);
73void search_utmp(char *, char *, char *, uid_t);
74int utmp_chk(char *, char *);
75
76int
77main(argc, argv)
78	int argc;
79	char **argv;
80{
81	register char *cp;
82	time_t atime;
83	uid_t myuid;
84	int msgsok, myttyfd;
85	char tty[MAXPATHLEN], *mytty;
86
87	(void)setlocale(LC_CTYPE, "");
88
89	/* check that sender has write enabled */
90	if (isatty(fileno(stdin)))
91		myttyfd = fileno(stdin);
92	else if (isatty(fileno(stdout)))
93		myttyfd = fileno(stdout);
94	else if (isatty(fileno(stderr)))
95		myttyfd = fileno(stderr);
96	else
97		errx(1, "can't find your tty");
98	if (!(mytty = ttyname(myttyfd)))
99		errx(1, "can't find your tty's name");
100	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