xref: /freebsd/usr.bin/write/write.c (revision 56e53cb8ef000c3ef72337a4095987a932cdedef)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Jef Poskanzer and Craig Leres of the Lawrence Berkeley Laboratory.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)write.c	8.1 (Berkeley) 6/6/93";
44 #endif
45 #endif
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/capsicum.h>
52 #include <sys/filio.h>
53 #include <sys/signal.h>
54 #include <sys/stat.h>
55 #include <sys/time.h>
56 
57 #include <capsicum_helpers.h>
58 #include <ctype.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <locale.h>
62 #include <paths.h>
63 #include <pwd.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <utmpx.h>
69 #include <wchar.h>
70 #include <wctype.h>
71 
72 void done(int);
73 void do_write(int, char *, char *, const char *);
74 static void usage(void);
75 int term_chk(int, char *, int *, time_t *, int);
76 void wr_fputs(wchar_t *s);
77 void search_utmp(int, char *, char *, char *, uid_t);
78 int utmp_chk(char *, char *);
79 
80 int
81 main(int argc, char **argv)
82 {
83 	unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ, FIODGNAME };
84 	cap_rights_t rights;
85 	struct passwd *pwd;
86 	time_t atime;
87 	uid_t myuid;
88 	int msgsok, myttyfd;
89 	char tty[MAXPATHLEN], *mytty;
90 	const char *login;
91 	int devfd;
92 
93 	(void)setlocale(LC_CTYPE, "");
94 
95 	devfd = open(_PATH_DEV, O_RDONLY);
96 	if (devfd < 0)
97 		err(1, "open(/dev)");
98 	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_LOOKUP,
99 	    CAP_PWRITE);
100 	if (cap_rights_limit(devfd, &rights) < 0 && errno != ENOSYS)
101 		err(1, "can't limit devfd rights");
102 
103 	/*
104 	 * Can't use capsicum helpers here because we need the additional
105 	 * FIODGNAME ioctl.
106 	 */
107 	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_READ,
108 	    CAP_WRITE);
109 	if ((cap_rights_limit(STDIN_FILENO, &rights) < 0 && errno != ENOSYS) ||
110 	    (cap_rights_limit(STDOUT_FILENO, &rights) < 0 && errno != ENOSYS) ||
111 	    (cap_rights_limit(STDERR_FILENO, &rights) < 0 && errno != ENOSYS) ||
112 	    (cap_ioctls_limit(STDIN_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
113 	    (cap_ioctls_limit(STDOUT_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
114 	    (cap_ioctls_limit(STDERR_FILENO, cmds, nitems(cmds)) < 0 && errno != ENOSYS) ||
115 	    (cap_fcntls_limit(STDIN_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) ||
116 	    (cap_fcntls_limit(STDOUT_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) ||
117 	    (cap_fcntls_limit(STDERR_FILENO, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS))
118 		err(1, "can't limit stdio rights");
119 
120 	caph_cache_catpages();
121 	caph_cache_tzdata();
122 
123 	/*
124 	 * Cache UTX database fds.
125 	 */
126 	setutxent();
127 
128 	/*
129 	 * Determine our login name before we reopen() stdout
130 	 * and before entering capability sandbox.
131 	 */
132 	myuid = getuid();
133 	if ((login = getlogin()) == NULL) {
134 		if ((pwd = getpwuid(myuid)))
135 			login = pwd->pw_name;
136 		else
137 			login = "???";
138 	}
139 
140 	if (cap_enter() < 0 && errno != ENOSYS)
141 		err(1, "cap_enter");
142 
143 	while (getopt(argc, argv, "") != -1)
144 		usage();
145 	argc -= optind;
146 	argv += optind;
147 
148 	/* check that sender has write enabled */
149 	if (isatty(fileno(stdin)))
150 		myttyfd = fileno(stdin);
151 	else if (isatty(fileno(stdout)))
152 		myttyfd = fileno(stdout);
153 	else if (isatty(fileno(stderr)))
154 		myttyfd = fileno(stderr);
155 	else
156 		errx(1, "can't find your tty");
157 	if (!(mytty = ttyname(myttyfd)))
158 		errx(1, "can't find your tty's name");
159 	if (!strncmp(mytty, _PATH_DEV, strlen(_PATH_DEV)))
160 		mytty += strlen(_PATH_DEV);
161 	if (term_chk(devfd, mytty, &msgsok, &atime, 1))
162 		exit(1);
163 	if (!msgsok)
164 		errx(1, "you have write permission turned off");
165 
166 	/* check args */
167 	switch (argc) {
168 	case 1:
169 		search_utmp(devfd, argv[0], tty, mytty, myuid);
170 		do_write(devfd, tty, mytty, login);
171 		break;
172 	case 2:
173 		if (!strncmp(argv[1], _PATH_DEV, strlen(_PATH_DEV)))
174 			argv[1] += strlen(_PATH_DEV);
175 		if (utmp_chk(argv[0], argv[1]))
176 			errx(1, "%s is not logged in on %s", argv[0], argv[1]);
177 		if (term_chk(devfd, argv[1], &msgsok, &atime, 1))
178 			exit(1);
179 		if (myuid && !msgsok)
180 			errx(1, "%s has messages disabled on %s", argv[0], argv[1]);
181 		do_write(devfd, argv[1], mytty, login);
182 		break;
183 	default:
184 		usage();
185 	}
186 	done(0);
187 	return (0);
188 }
189 
190 static void
191 usage(void)
192 {
193 	(void)fprintf(stderr, "usage: write user [tty]\n");
194 	exit(1);
195 }
196 
197 /*
198  * utmp_chk - checks that the given user is actually logged in on
199  *     the given tty
200  */
201 int
202 utmp_chk(char *user, char *tty)
203 {
204 	struct utmpx lu, *u;
205 
206 	strncpy(lu.ut_line, tty, sizeof lu.ut_line);
207 	setutxent();
208 	while ((u = getutxline(&lu)) != NULL)
209 		if (u->ut_type == USER_PROCESS &&
210 		    strcmp(user, u->ut_user) == 0) {
211 			endutxent();
212 			return(0);
213 		}
214 	endutxent();
215 	return(1);
216 }
217 
218 /*
219  * search_utmp - search utmp for the "best" terminal to write to
220  *
221  * Ignores terminals with messages disabled, and of the rest, returns
222  * the one with the most recent access time.  Returns as value the number
223  * of the user's terminals with messages enabled, or -1 if the user is
224  * not logged in at all.
225  *
226  * Special case for writing to yourself - ignore the terminal you're
227  * writing from, unless that's the only terminal with messages enabled.
228  */
229 void
230 search_utmp(int devfd, char *user, char *tty, char *mytty, uid_t myuid)
231 {
232 	struct utmpx *u;
233 	time_t bestatime, atime;
234 	int nloggedttys, nttys, msgsok, user_is_me;
235 
236 	nloggedttys = nttys = 0;
237 	bestatime = 0;
238 	user_is_me = 0;
239 
240 	setutxent();
241 	while ((u = getutxent()) != NULL)
242 		if (u->ut_type == USER_PROCESS &&
243 		    strcmp(user, u->ut_user) == 0) {
244 			++nloggedttys;
245 			if (term_chk(devfd, u->ut_line, &msgsok, &atime, 0))
246 				continue;	/* bad term? skip */
247 			if (myuid && !msgsok)
248 				continue;	/* skip ttys with msgs off */
249 			if (strcmp(u->ut_line, mytty) == 0) {
250 				user_is_me = 1;
251 				continue;	/* don't write to yourself */
252 			}
253 			++nttys;
254 			if (atime > bestatime) {
255 				bestatime = atime;
256 				(void)strlcpy(tty, u->ut_line, MAXPATHLEN);
257 			}
258 		}
259 	endutxent();
260 
261 	if (nloggedttys == 0)
262 		errx(1, "%s is not logged in", user);
263 	if (nttys == 0) {
264 		if (user_is_me) {		/* ok, so write to yourself! */
265 			(void)strlcpy(tty, mytty, MAXPATHLEN);
266 			return;
267 		}
268 		errx(1, "%s has messages disabled", user);
269 	} else if (nttys > 1) {
270 		warnx("%s is logged in more than once; writing to %s", user, tty);
271 	}
272 }
273 
274 /*
275  * term_chk - check that a terminal exists, and get the message bit
276  *     and the access time
277  */
278 int
279 term_chk(int devfd, char *tty, int *msgsokP, time_t *atimeP, int showerror)
280 {
281 	struct stat s;
282 
283 	if (fstatat(devfd, tty, &s, 0) < 0) {
284 		if (showerror)
285 			warn("%s%s", _PATH_DEV, tty);
286 		return(1);
287 	}
288 	*msgsokP = (s.st_mode & (S_IWRITE >> 3)) != 0;	/* group write bit */
289 	*atimeP = s.st_atime;
290 	return(0);
291 }
292 
293 /*
294  * do_write - actually make the connection
295  */
296 void
297 do_write(int devfd, char *tty, char *mytty, const char *login)
298 {
299 	char *nows;
300 	time_t now;
301 	char host[MAXHOSTNAMELEN];
302 	wchar_t line[512];
303 	int fd;
304 
305 	fd = openat(devfd, tty, O_WRONLY);
306 	if (fd < 0)
307 		err(1, "openat(%s%s)", _PATH_DEV, tty);
308 	fclose(stdout);
309 	stdout = fdopen(fd, "w");
310 	if (stdout == NULL)
311 		err(1, "%s%s", _PATH_DEV, tty);
312 
313 	(void)signal(SIGINT, done);
314 	(void)signal(SIGHUP, done);
315 
316 	/* print greeting */
317 	if (gethostname(host, sizeof(host)) < 0)
318 		(void)strcpy(host, "???");
319 	now = time((time_t *)NULL);
320 	nows = ctime(&now);
321 	nows[16] = '\0';
322 	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
323 	    login, host, mytty, nows + 11);
324 
325 	while (fgetws(line, sizeof(line)/sizeof(wchar_t), stdin) != NULL)
326 		wr_fputs(line);
327 }
328 
329 /*
330  * done - cleanup and exit
331  */
332 void
333 done(int n __unused)
334 {
335 	(void)printf("EOF\r\n");
336 	exit(0);
337 }
338 
339 /*
340  * wr_fputs - like fputs(), but makes control characters visible and
341  *     turns \n into \r\n
342  */
343 void
344 wr_fputs(wchar_t *s)
345 {
346 
347 #define	PUTC(c)	if (putwchar(c) == WEOF) err(1, NULL);
348 
349 	for (; *s != L'\0'; ++s) {
350 		if (*s == L'\n') {
351 			PUTC(L'\r');
352 			PUTC(L'\n');
353 		} else if (iswprint(*s) || iswspace(*s)) {
354 			PUTC(*s);
355 		} else {
356 			wprintf(L"<0x%X>", *s);
357 		}
358 	}
359 	return;
360 #undef PUTC
361 }
362