xref: /dragonfly/usr.bin/write/write.c (revision cecb9aae)
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  * @(#) Copyright (c) 1989, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)write.c	8.1 (Berkeley) 6/6/93
38  * $FreeBSD: src/usr.bin/write/write.c,v 1.12 1999/08/28 01:07:48 peter Exp $
39  * $DragonFly: src/usr.bin/write/write.c,v 1.7 2005/08/30 22:02:36 liamfoy Exp $
40  */
41 
42 #include <sys/param.h>
43 #include <sys/stat.h>
44 #include <sys/file.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <locale.h>
49 #include <paths.h>
50 #include <pwd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <signal.h>
55 #include <time.h>
56 #include <unistd.h>
57 #include "utmpentry.h"
58 
59 static void	done(int);
60 static void	do_write(const char *, const char *, uid_t, int *);
61 static void	usage(void);
62 static int	term_chk(const char *, int *, time_t *, int);
63 static void	wr_fputs(unsigned char *s);
64 static void	search_utmp(const char *, char *, size_t, const char *, uid_t);
65 static int	utmp_chk(const char *, const char *);
66 
67 int
68 main(int argc, char **argv)
69 {
70 	time_t atime;
71 	uid_t myuid;
72 	int msgsok, mymsgok, myttyfd;
73 	char tty[MAXPATHLEN], *mytty;
74 
75 	setlocale(LC_CTYPE, "");
76 
77 	/* check that sender has write enabled */
78 	if (isatty(fileno(stdin)))
79 		myttyfd = fileno(stdin);
80 	else if (isatty(fileno(stdout)))
81 		myttyfd = fileno(stdout);
82 	else if (isatty(fileno(stderr)))
83 		myttyfd = fileno(stderr);
84 	else
85 		errx(1, "can't find your tty");
86 	if (!(mytty = ttyname(myttyfd)))
87 		errx(1, "can't find your tty's name");
88 	if (!strncmp(mytty, _PATH_DEV, strlen(_PATH_DEV)))
89 		mytty += strlen(_PATH_DEV);
90 	if (term_chk(mytty, &mymsgok, &atime, 1))
91 		exit(1);
92 	if (!mymsgok)
93 		warnx("you have write permission turned off (man mesg)");
94 
95 	myuid = getuid();
96 
97 	/* check args */
98 	switch (argc) {
99 	case 2:
100 		search_utmp(argv[1], tty, sizeof tty, mytty, myuid);
101 		do_write(tty, mytty, myuid, &mymsgok);
102 		break;
103 	case 3:
104 		if (!strncmp(argv[2], _PATH_DEV, strlen(_PATH_DEV)))
105 			argv[2] += strlen(_PATH_DEV);
106 		if (utmp_chk(argv[1], argv[2]))
107 			errx(1, "%s is not logged in on %s", argv[1], argv[2]);
108 		if (term_chk(argv[2], &msgsok, &atime, 1))
109 			exit(1);
110 		if (myuid && !msgsok)
111 			errx(1, "%s has messages disabled on %s", argv[1], argv[2]);
112 		do_write(argv[2], mytty, myuid, &mymsgok);
113 		break;
114 	default:
115 		usage();
116 	}
117 	done(0);
118 	return (0);
119 }
120 
121 static void
122 usage(void)
123 {
124 	fprintf(stderr, "usage: write user [tty]\n");
125 	exit(1);
126 }
127 
128 /*
129  * utmp_chk - checks that the given user is actually logged in on
130  *     the given tty
131  */
132 static int
133 utmp_chk(const char *user, const char *tty)
134 {
135 	struct utmpentry *ep;
136 
137 	getutentries(NULL, &ep);
138 
139 	for (; ep; ep = ep->next) {
140 		if (strcmp(user, ep->name) == 0 &&
141 		    strcmp(tty, ep->line) == 0) {
142 			return(0);
143 		}
144 	}
145 
146 	return(1);
147 }
148 
149 /*
150  * search_utmp - search utmp for the "best" terminal to write to
151  *
152  * Ignores terminals with messages disabled, and of the rest, returns
153  * the one with the most recent access time.  Returns as value the number
154  * of the user's terminals with messages enabled, or -1 if the user is
155  * not logged in at all.
156  *
157  * Special case for writing to yourself - ignore the terminal you're
158  * writing from, unless that's the only terminal with messages enabled.
159  */
160 static void
161 search_utmp(const char *user, char *tty, size_t ttyl, const char *mytty, uid_t myuid)
162 {
163 	struct utmpentry *ep;
164 	time_t bestatime, atime;
165 	int nloggedttys, nttys, msgsok, user_is_me;
166 
167 	getutentries(NULL, &ep);
168 
169 	nloggedttys = nttys = 0;
170 	bestatime = 0;
171 	user_is_me = 0;
172 	for (; ep; ep = ep->next)
173 		if (strcmp(user, ep->name) == 0) {
174 			++nloggedttys;
175 			if (term_chk(ep->line, &msgsok, &atime, 0))
176 				continue;	/* bad term? skip */
177 			if (myuid && !msgsok)
178 				continue;	/* skip ttys with msgs off */
179 			if (strcmp(ep->line, mytty) == 0) {
180 				user_is_me = 1;
181 				continue;	/* don't write to yourself */
182 			}
183 			++nttys;
184 			if (atime > bestatime) {
185 				bestatime = atime;
186 				strlcpy(tty, ep->line, ttyl);
187 			}
188 		}
189 
190 	if (nloggedttys == 0)
191 		errx(1, "%s is not logged in", user);
192 	if (nttys == 0) {
193 		if (user_is_me) {		/* ok, so write to yourself! */
194 			strlcpy(tty, mytty, ttyl);
195 			return;
196 		}
197 		errx(1, "%s has messages disabled", user);
198 	} else if (nttys > 1) {
199 		warnx("%s is logged in more than once; writing to %s", user, tty);
200 	}
201 }
202 
203 /*
204  * term_chk - check that a terminal exists, and get the message bit
205  *     and the access time
206  */
207 static int
208 term_chk(const char *tty, int *msgsokP, time_t *atimeP, int showerror)
209 {
210 	struct stat s;
211 	char path[MAXPATHLEN];
212 
213 	snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
214 	if (stat(path, &s) < 0) {
215 		if (showerror)
216 			warn("%s", path);
217 		return(1);
218 	}
219 	*msgsokP = (s.st_mode & S_IWGRP) != 0;	/* group write bit */
220 	*atimeP = s.st_atime;
221 	return(0);
222 }
223 
224 /*
225  * do_write - actually make the connection
226  */
227 static void
228 do_write(const char *tty, const char *mytty, uid_t myuid, int *mymsgok)
229 {
230 	const char *login;
231 	char *nows;
232 	struct passwd *pwd;
233 	time_t now;
234 	char path[MAXPATHLEN], host[MAXHOSTNAMELEN], line[512];
235 
236 	/* Determine our login name before we reopen() stdout */
237 	if ((login = getlogin()) == NULL) {
238 		if ((pwd = getpwuid(myuid)))
239 			login = pwd->pw_name;
240 		else
241 			login = "???";
242 	}
243 
244 	snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
245 	if ((freopen(path, "w", stdout)) == NULL)
246 		err(1, "%s", path);
247 
248 	signal(SIGINT, done);
249 	signal(SIGHUP, done);
250 
251 	/* print greeting */
252 	if (gethostname(host, sizeof(host)) < 0)
253 		strlcpy(host, "???", sizeof host);
254 	now = time(NULL);
255 	nows = ctime(&now);
256 	nows[16] = '\0';
257 	printf("\r\n\007\007\007Message from %s@%s on %s at %s (%s %s replies)...\r\n",
258 	    login, host, mytty, nows + 11, login, *mymsgok == 0 ? "does not accept" : "accepts");
259 
260 	while (fgets(line, sizeof(line), stdin) != NULL)
261 		wr_fputs(line);
262 }
263 
264 /*
265  * done - cleanup and exit
266  */
267 static void
268 done(__unused int n)
269 {
270 	printf("EOF\r\n");
271 	exit(0);
272 }
273 
274 /*
275  * wr_fputs - like fputs(), but makes control characters visible and
276  *     turns \n into \r\n
277  */
278 static void
279 wr_fputs(unsigned char *s)
280 {
281 
282 #define	PUTC(c)	if (putchar(c) == EOF) err(1, NULL);
283 
284 	for (; *s != '\0'; ++s) {
285 		if (*s == '\n') {
286 			PUTC('\r');
287 		} else if (((*s & 0x80) && *s < 0xA0) ||
288 			   /* disable upper controls */
289 			   (!isprint(*s) && !isspace(*s) &&
290 			    *s != '\a' && *s != '\b')
291 			  ) {
292 			if (*s & 0x80) {
293 				*s &= ~0x80;
294 				PUTC('M');
295 				PUTC('-');
296 			}
297 			if (iscntrl(*s)) {
298 				*s ^= 0x40;
299 				PUTC('^');
300 			}
301 		}
302 		PUTC(*s);
303 	}
304 	return;
305 #undef PUTC
306 }
307