xref: /freebsd/usr.bin/write/write.c (revision 315ee00f)
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 #include <sys/param.h>
49 #include <sys/capsicum.h>
50 #include <sys/filio.h>
51 #include <sys/signal.h>
52 #include <sys/stat.h>
53 #include <sys/time.h>
54 
55 #include <capsicum_helpers.h>
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.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 <utmpx.h>
67 #include <wchar.h>
68 #include <wctype.h>
69 
70 void done(int);
71 void do_write(int, char *, char *, const char *);
72 static void usage(void) __dead2;
73 int term_chk(int, char *, int *, time_t *, int);
74 void wr_fputs(wchar_t *s);
75 void search_utmp(int, char *, char *, char *, uid_t);
76 int utmp_chk(char *, char *);
77 
78 int
79 main(int argc, char **argv)
80 {
81 	unsigned long cmds[] = { TIOCGETA, TIOCGWINSZ, FIODGNAME };
82 	cap_rights_t rights;
83 	struct passwd *pwd;
84 	time_t atime;
85 	uid_t myuid;
86 	int msgsok, myttyfd;
87 	char tty[MAXPATHLEN], *mytty;
88 	const char *login;
89 	int devfd;
90 
91 	(void)setlocale(LC_CTYPE, "");
92 
93 	devfd = open(_PATH_DEV, O_RDONLY);
94 	if (devfd < 0)
95 		err(1, "open(/dev)");
96 	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_LOOKUP,
97 	    CAP_PWRITE);
98 	if (caph_rights_limit(devfd, &rights) < 0)
99 		err(1, "can't limit devfd rights");
100 
101 	/*
102 	 * Can't use capsicum helpers here because we need the additional
103 	 * FIODGNAME ioctl.
104 	 */
105 	cap_rights_init(&rights, CAP_FCNTL, CAP_FSTAT, CAP_IOCTL, CAP_READ,
106 	    CAP_WRITE);
107 	if (caph_rights_limit(STDIN_FILENO, &rights) < 0 ||
108 	    caph_rights_limit(STDOUT_FILENO, &rights) < 0 ||
109 	    caph_rights_limit(STDERR_FILENO, &rights) < 0 ||
110 	    caph_ioctls_limit(STDIN_FILENO, cmds, nitems(cmds)) < 0 ||
111 	    caph_ioctls_limit(STDOUT_FILENO, cmds, nitems(cmds)) < 0 ||
112 	    caph_ioctls_limit(STDERR_FILENO, cmds, nitems(cmds)) < 0 ||
113 	    caph_fcntls_limit(STDIN_FILENO, CAP_FCNTL_GETFL) < 0 ||
114 	    caph_fcntls_limit(STDOUT_FILENO, CAP_FCNTL_GETFL) < 0 ||
115 	    caph_fcntls_limit(STDERR_FILENO, CAP_FCNTL_GETFL) < 0)
116 		err(1, "can't limit stdio rights");
117 
118 	caph_cache_catpages();
119 	caph_cache_tzdata();
120 
121 	/*
122 	 * Cache UTX database fds.
123 	 */
124 	setutxent();
125 
126 	/*
127 	 * Determine our login name before we reopen() stdout
128 	 * and before entering capability sandbox.
129 	 */
130 	myuid = getuid();
131 	if ((login = getlogin()) == NULL) {
132 		if ((pwd = getpwuid(myuid)))
133 			login = pwd->pw_name;
134 		else
135 			login = "???";
136 	}
137 
138 	if (caph_enter() < 0)
139 		err(1, "cap_enter");
140 
141 	while (getopt(argc, argv, "") != -1)
142 		usage();
143 	argc -= optind;
144 	argv += optind;
145 
146 	/* check that sender has write enabled */
147 	if (isatty(fileno(stdin)))
148 		myttyfd = fileno(stdin);
149 	else if (isatty(fileno(stdout)))
150 		myttyfd = fileno(stdout);
151 	else if (isatty(fileno(stderr)))
152 		myttyfd = fileno(stderr);
153 	else
154 		errx(1, "can't find your tty");
155 	if (!(mytty = ttyname(myttyfd)))
156 		errx(1, "can't find your tty's name");
157 	if (!strncmp(mytty, _PATH_DEV, strlen(_PATH_DEV)))
158 		mytty += strlen(_PATH_DEV);
159 	if (term_chk(devfd, mytty, &msgsok, &atime, 1))
160 		exit(1);
161 	if (!msgsok)
162 		errx(1, "you have write permission turned off");
163 
164 	/* check args */
165 	switch (argc) {
166 	case 1:
167 		search_utmp(devfd, argv[0], tty, mytty, myuid);
168 		do_write(devfd, tty, mytty, login);
169 		break;
170 	case 2:
171 		if (!strncmp(argv[1], _PATH_DEV, strlen(_PATH_DEV)))
172 			argv[1] += strlen(_PATH_DEV);
173 		if (utmp_chk(argv[0], argv[1]))
174 			errx(1, "%s is not logged in on %s", argv[0], argv[1]);
175 		if (term_chk(devfd, argv[1], &msgsok, &atime, 1))
176 			exit(1);
177 		if (myuid && !msgsok)
178 			errx(1, "%s has messages disabled on %s", argv[0], argv[1]);
179 		do_write(devfd, argv[1], mytty, login);
180 		break;
181 	default:
182 		usage();
183 	}
184 	done(0);
185 	return (0);
186 }
187 
188 static void
189 usage(void)
190 {
191 	(void)fprintf(stderr, "usage: write user [tty]\n");
192 	exit(1);
193 }
194 
195 /*
196  * utmp_chk - checks that the given user is actually logged in on
197  *     the given tty
198  */
199 int
200 utmp_chk(char *user, char *tty)
201 {
202 	struct utmpx lu, *u;
203 
204 	strncpy(lu.ut_line, tty, sizeof lu.ut_line);
205 	while ((u = getutxline(&lu)) != NULL)
206 		if (u->ut_type == USER_PROCESS &&
207 		    strcmp(user, u->ut_user) == 0) {
208 			endutxent();
209 			return(0);
210 		}
211 	endutxent();
212 	return(1);
213 }
214 
215 /*
216  * search_utmp - search utmp for the "best" terminal to write to
217  *
218  * Ignores terminals with messages disabled, and of the rest, returns
219  * the one with the most recent access time.  Returns as value the number
220  * of the user's terminals with messages enabled, or -1 if the user is
221  * not logged in at all.
222  *
223  * Special case for writing to yourself - ignore the terminal you're
224  * writing from, unless that's the only terminal with messages enabled.
225  */
226 void
227 search_utmp(int devfd, char *user, char *tty, char *mytty, uid_t myuid)
228 {
229 	struct utmpx *u;
230 	time_t bestatime, atime;
231 	int nloggedttys, nttys, msgsok, user_is_me;
232 
233 	nloggedttys = nttys = 0;
234 	bestatime = 0;
235 	user_is_me = 0;
236 
237 	while ((u = getutxent()) != NULL)
238 		if (u->ut_type == USER_PROCESS &&
239 		    strcmp(user, u->ut_user) == 0) {
240 			++nloggedttys;
241 			if (term_chk(devfd, u->ut_line, &msgsok, &atime, 0))
242 				continue;	/* bad term? skip */
243 			if (myuid && !msgsok)
244 				continue;	/* skip ttys with msgs off */
245 			if (strcmp(u->ut_line, mytty) == 0) {
246 				user_is_me = 1;
247 				continue;	/* don't write to yourself */
248 			}
249 			++nttys;
250 			if (atime > bestatime) {
251 				bestatime = atime;
252 				(void)strlcpy(tty, u->ut_line, MAXPATHLEN);
253 			}
254 		}
255 	endutxent();
256 
257 	if (nloggedttys == 0)
258 		errx(1, "%s is not logged in", user);
259 	if (nttys == 0) {
260 		if (user_is_me) {		/* ok, so write to yourself! */
261 			(void)strlcpy(tty, mytty, MAXPATHLEN);
262 			return;
263 		}
264 		errx(1, "%s has messages disabled", user);
265 	} else if (nttys > 1) {
266 		warnx("%s is logged in more than once; writing to %s", user, tty);
267 	}
268 }
269 
270 /*
271  * term_chk - check that a terminal exists, and get the message bit
272  *     and the access time
273  */
274 int
275 term_chk(int devfd, char *tty, int *msgsokP, time_t *atimeP, int showerror)
276 {
277 	struct stat s;
278 
279 	if (fstatat(devfd, tty, &s, 0) < 0) {
280 		if (showerror)
281 			warn("%s%s", _PATH_DEV, tty);
282 		return(1);
283 	}
284 	*msgsokP = (s.st_mode & (S_IWRITE >> 3)) != 0;	/* group write bit */
285 	*atimeP = s.st_atime;
286 	return(0);
287 }
288 
289 /*
290  * do_write - actually make the connection
291  */
292 void
293 do_write(int devfd, char *tty, char *mytty, const char *login)
294 {
295 	char *nows;
296 	time_t now;
297 	char host[MAXHOSTNAMELEN];
298 	wchar_t line[512];
299 	int fd;
300 
301 	fd = openat(devfd, tty, O_WRONLY);
302 	if (fd < 0)
303 		err(1, "openat(%s%s)", _PATH_DEV, tty);
304 	fclose(stdout);
305 	stdout = fdopen(fd, "w");
306 	if (stdout == NULL)
307 		err(1, "%s%s", _PATH_DEV, tty);
308 
309 	(void)signal(SIGINT, done);
310 	(void)signal(SIGHUP, done);
311 
312 	/* print greeting */
313 	if (gethostname(host, sizeof(host)) < 0)
314 		(void)strcpy(host, "???");
315 	now = time((time_t *)NULL);
316 	nows = ctime(&now);
317 	nows[16] = '\0';
318 	(void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
319 	    login, host, mytty, nows + 11);
320 
321 	while (fgetws(line, sizeof(line)/sizeof(wchar_t), stdin) != NULL)
322 		wr_fputs(line);
323 }
324 
325 /*
326  * done - cleanup and exit
327  */
328 void
329 done(int n __unused)
330 {
331 	(void)printf("EOF\r\n");
332 	exit(0);
333 }
334 
335 /*
336  * wr_fputs - like fputs(), but makes control characters visible and
337  *     turns \n into \r\n
338  */
339 void
340 wr_fputs(wchar_t *s)
341 {
342 
343 #define	PUTC(c)	if (putwchar(c) == WEOF) err(1, NULL);
344 
345 	for (; *s != L'\0'; ++s) {
346 		if (*s == L'\n') {
347 			PUTC(L'\r');
348 			PUTC(L'\n');
349 		} else if (iswprint(*s) || iswspace(*s)) {
350 			PUTC(*s);
351 		} else {
352 			wprintf(L"<0x%X>", *s);
353 		}
354 	}
355 	return;
356 #undef PUTC
357 }
358