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