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 * 4. Neither the name of the University nor the names of its contributors
17 *    may be used to endorse or promote products derived from this software
18 *    without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#ifndef lint
34static const char copyright[] =
35"@(#) Copyright (c) 1989, 1993\n\
36	The Regents of the University of California.  All rights reserved.\n";
37#endif
38
39#if 0
40#ifndef lint
41static char sccsid[] = "@(#)write.c	8.1 (Berkeley) 6/6/93";
42#endif
43#endif
44
45#include <sys/cdefs.h>
46__FBSDID("$FreeBSD$");
47
48#include <sys/param.h>
49#include <sys/signal.h>
50#include <sys/stat.h>
51#include <sys/file.h>
52#include <sys/time.h>
53#include <ctype.h>
54#include <err.h>
55#include <locale.h>
56#include <paths.h>
57#include <pwd.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62#include <utmpx.h>
63#include <wchar.h>
64#include <wctype.h>
65
66void done(int);
67void do_write(char *, char *, uid_t);
68static void usage(void);
69int term_chk(char *, int *, time_t *, int);
70void wr_fputs(wchar_t *s);
71void search_utmp(char *, char *, char *, uid_t);
72int utmp_chk(char *, char *);
73
74int
75main(int argc, char **argv)
76{
77	time_t atime;
78	uid_t myuid;
79	int msgsok, myttyfd;
80	char tty[MAXPATHLEN], *mytty;
81
82	(void)setlocale(LC_CTYPE, "");
83
84	while (getopt(argc, argv, "") != -1)
85		usage();
86	argc -= optind;
87	argv += optind;
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 (!strncmp(mytty, _PATH_DEV, strlen(_PATH_DEV)))
101		mytty += strlen(_PATH_DEV);
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 1:
112		search_utmp(argv[0], tty, mytty, myuid);
113		do_write(tty, mytty, myuid);
114		break;
115	case 2:
116		if (!strncmp(argv[1], _PATH_DEV, strlen(_PATH_DEV)))
117			argv[1] += strlen(_PATH_DEV);
118		if (utmp_chk(argv[0], argv[1]))
119			errx(1, "%s is not logged in on %s", argv[0], argv[1]);
120		if (term_chk(argv[1], &msgsok, &atime, 1))
121			exit(1);
122		if (myuid && !msgsok)
123			errx(1, "%s has messages disabled on %s", argv[0], argv[1]);
124		do_write(argv[1], mytty, myuid);
125		break;
126	default:
127		usage();
128	}
129	done(0);
130	return (0);
131}
132
133static void
134usage(void)
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(char *user, char *tty)
146{
147	struct utmpx lu, *u;
148
149	strncpy(lu.ut_line, tty, sizeof lu.ut_line);
150	setutxent();
151	while ((u = getutxline(&lu)) != NULL)
152		if (u->ut_type == USER_PROCESS &&
153		    strcmp(user, u->ut_user) == 0) {
154			endutxent();
155			return(0);
156		}
157	endutxent();
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 */
172void
173search_utmp(char *user, char *tty, char *mytty, uid_t myuid)
174{
175	struct utmpx *u;
176	time_t bestatime, atime;
177	int nloggedttys, nttys, msgsok, user_is_me;
178
179	nloggedttys = nttys = 0;
180	bestatime = 0;
181	user_is_me = 0;
182
183	setutxent();
184	while ((u = getutxent()) != NULL)
185		if (u->ut_type == USER_PROCESS &&
186		    strcmp(user, u->ut_user) == 0) {
187			++nloggedttys;
188			if (term_chk(u->ut_line, &msgsok, &atime, 0))
189				continue;	/* bad term? skip */
190			if (myuid && !msgsok)
191				continue;	/* skip ttys with msgs off */
192			if (strcmp(u->ut_line, mytty) == 0) {
193				user_is_me = 1;
194				continue;	/* don't write to yourself */
195			}
196			++nttys;
197			if (atime > bestatime) {
198				bestatime = atime;
199				(void)strlcpy(tty, u->ut_line, MAXPATHLEN);
200			}
201		}
202	endutxent();
203
204	if (nloggedttys == 0)
205		errx(1, "%s is not logged in", user);
206	if (nttys == 0) {
207		if (user_is_me) {		/* ok, so write to yourself! */
208			(void)strlcpy(tty, mytty, MAXPATHLEN);
209			return;
210		}
211		errx(1, "%s has messages disabled", user);
212	} else if (nttys > 1) {
213		warnx("%s is logged in more than once; writing to %s", user, tty);
214	}
215}
216
217/*
218 * term_chk - check that a terminal exists, and get the message bit
219 *     and the access time
220 */
221int
222term_chk(char *tty, int *msgsokP, time_t *atimeP, int showerror)
223{
224	struct stat s;
225	char path[MAXPATHLEN];
226
227	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
228	if (stat(path, &s) < 0) {
229		if (showerror)
230			warn("%s", path);
231		return(1);
232	}
233	*msgsokP = (s.st_mode & (S_IWRITE >> 3)) != 0;	/* group write bit */
234	*atimeP = s.st_atime;
235	return(0);
236}
237
238/*
239 * do_write - actually make the connection
240 */
241void
242do_write(char *tty, char *mytty, uid_t myuid)
243{
244	const char *login;
245	char *nows;
246	struct passwd *pwd;
247	time_t now;
248	char path[MAXPATHLEN], host[MAXHOSTNAMELEN];
249	wchar_t line[512];
250
251	/* Determine our login name before we reopen() stdout */
252	if ((login = getlogin()) == NULL) {
253		if ((pwd = getpwuid(myuid)))
254			login = pwd->pw_name;
255		else
256			login = "???";
257	}
258
259	(void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
260	if ((freopen(path, "w", stdout)) == NULL)
261		err(1, "%s", path);
262
263	(void)signal(SIGINT, done);
264	(void)signal(SIGHUP, done);
265
266	/* print greeting */
267	if (gethostname(host, sizeof(host)) < 0)
268		(void)strcpy(host, "???");
269	now = time((time_t *)NULL);
270	nows = ctime(&now);
271	nows[16] = '\0';
272	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
273	    login, host, mytty, nows + 11);
274
275	while (fgetws(line, sizeof(line)/sizeof(wchar_t), stdin) != NULL)
276		wr_fputs(line);
277}
278
279/*
280 * done - cleanup and exit
281 */
282void
283done(int n __unused)
284{
285	(void)printf("EOF\r\n");
286	exit(0);
287}
288
289/*
290 * wr_fputs - like fputs(), but makes control characters visible and
291 *     turns \n into \r\n
292 */
293void
294wr_fputs(wchar_t *s)
295{
296
297#define	PUTC(c)	if (putwchar(c) == WEOF) err(1, NULL);
298
299	for (; *s != L'\0'; ++s) {
300		if (*s == L'\n') {
301			PUTC(L'\r');
302			PUTC(L'\n');
303		} else if (iswprint(*s) || iswspace(*s)) {
304			PUTC(*s);
305		} else {
306			wprintf(L"<0x%X>", *s);
307		}
308	}
309	return;
310#undef PUTC
311}
312