1/*
2 * Copyright (c) 1988, 1990, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35
36__FBSDID("$FreeBSD: src/usr.bin/wall/wall.c,v 1.25 2008/01/15 07:40:30 das Exp $");
37
38#ifndef lint
39static const char copyright[] =
40"@(#) Copyright (c) 1988, 1990, 1993\n\
41	The Regents of the University of California.  All rights reserved.\n";
42#endif
43
44#ifndef lint
45static const char sccsid[] = "@(#)wall.c	8.2 (Berkeley) 11/16/93";
46#endif
47
48/*
49 * This program is not related to David Wall, whose Stanford Ph.D. thesis
50 * is entitled "Mechanisms for Broadcast and Selective Broadcast".
51 */
52
53#include <sys/param.h>
54#include <sys/stat.h>
55#include <sys/uio.h>
56
57#include <ctype.h>
58#include <err.h>
59#include <grp.h>
60#include <locale.h>
61#include <paths.h>
62#include <pwd.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <time.h>
67#include <unistd.h>
68#ifdef __APPLE__
69#include <utmpx.h>
70#else
71#include <utmp.h>
72#endif
73
74#include "ttymsg.h"
75
76static void makemsg(char *);
77static void usage(void);
78
79struct wallgroup {
80	struct wallgroup *next;
81	char		*name;
82	gid_t		gid;
83} *grouplist;
84int nobanner;
85int mbufsize;
86char *mbuf;
87
88#ifndef __APPLE__
89static int
90ttystat(char *line, int sz)
91{
92	struct stat sb;
93	char ttybuf[MAXPATHLEN];
94
95	(void)snprintf(ttybuf, sizeof(ttybuf), "%s%.*s", _PATH_DEV, sz, line);
96	if (stat(ttybuf, &sb) == 0) {
97		return (0);
98	} else
99		return (-1);
100}
101#endif
102
103int
104main(int argc, char *argv[])
105{
106	struct iovec iov;
107#ifdef __APPLE__
108	// rdar://problem/4433603
109	struct utmpx *u;
110#else
111	struct utmp utmp;
112#endif
113	int ch;
114	int ingroup;
115#ifndef __APPLE__
116	FILE *fp;
117#endif
118	struct wallgroup *g;
119	struct group *grp;
120	char **np;
121	const char *p;
122	struct passwd *pw;
123#ifdef __APPLE__
124	char line[sizeof(u->ut_line) + 1];
125	char username[sizeof(u->ut_user) + 1];
126#else
127	char line[sizeof(utmp.ut_line) + 1];
128	char username[sizeof(utmp.ut_name) + 1];
129#endif
130
131	(void)setlocale(LC_CTYPE, "");
132
133	while ((ch = getopt(argc, argv, "g:n")) != -1)
134		switch (ch) {
135		case 'n':
136			/* undoc option for shutdown: suppress banner */
137			if (geteuid() == 0)
138				nobanner = 1;
139			break;
140		case 'g':
141			g = (struct wallgroup *)malloc(sizeof *g);
142			g->next = grouplist;
143			g->name = optarg;
144			g->gid = -1;
145			grouplist = g;
146			break;
147		case '?':
148		default:
149			usage();
150		}
151	argc -= optind;
152	argv += optind;
153	if (argc > 1)
154		usage();
155
156	for (g = grouplist; g; g = g->next) {
157		grp = getgrnam(g->name);
158		if (grp != NULL)
159			g->gid = grp->gr_gid;
160		else
161			warnx("%s: no such group", g->name);
162	}
163
164	makemsg(*argv);
165
166#ifdef __APPLE__
167	setutxent();
168#else
169	if (!(fp = fopen(_PATH_UTMP, "r")))
170		err(1, "cannot read %s", _PATH_UTMP);
171#endif
172	iov.iov_base = mbuf;
173	iov.iov_len = mbufsize;
174	/* NOSTRICT */
175#ifdef __APPLE__
176	while ((u = getutxent()) != NULL) {
177		if (!u->ut_user[0] || u->ut_type != USER_PROCESS)
178			continue;
179#else
180	while (fread((char *)&utmp, sizeof(utmp), 1, fp) == 1) {
181		if (!utmp.ut_name[0])
182			continue;
183		if (ttystat(utmp.ut_line, UT_LINESIZE) != 0)
184			continue;
185#endif
186		if (grouplist) {
187			ingroup = 0;
188#ifdef __APPLE__
189			strlcpy(username, u->ut_user, sizeof(username));
190#else
191			strlcpy(username, utmp.ut_name, sizeof(utmp.ut_name));
192#endif
193			pw = getpwnam(username);
194			if (!pw)
195				continue;
196			for (g = grouplist; g && ingroup == 0; g = g->next) {
197				if (g->gid == (gid_t)-1)
198					continue;
199				if (g->gid == pw->pw_gid)
200					ingroup = 1;
201				else if ((grp = getgrgid(g->gid)) != NULL) {
202					for (np = grp->gr_mem; *np; np++) {
203						if (strcmp(*np, username) == 0) {
204							ingroup = 1;
205							break;
206						}
207					}
208				}
209			}
210			if (ingroup == 0)
211				continue;
212		}
213#ifdef __APPLE__
214		strlcpy(line, u->ut_line, sizeof(line));
215#else
216		strncpy(line, utmp.ut_line, sizeof(utmp.ut_line));
217		line[sizeof(utmp.ut_line)] = '\0';
218#endif
219		if ((p = ttymsg(&iov, 1, line, 60*5)) != NULL)
220			warnx("%s", p);
221	}
222	exit(0);
223}
224
225static void
226usage()
227{
228	(void)fprintf(stderr, "usage: wall [-g group] [file]\n");
229	exit(1);
230}
231
232void
233makemsg(char *fname)
234{
235	int cnt;
236	unsigned char ch;
237	struct tm *lt;
238	struct passwd *pw;
239	struct stat sbuf;
240	time_t now;
241	FILE *fp;
242	int fd;
243	char *p, hostname[MAXHOSTNAMELEN], lbuf[256], tmpname[64];
244	const char *tty;
245	const char *whom;
246	gid_t egid;
247
248	(void)snprintf(tmpname, sizeof(tmpname), "%s/wall.XXXXXX", _PATH_TMP);
249	if ((fd = mkstemp(tmpname)) == -1 || !(fp = fdopen(fd, "r+")))
250		err(1, "can't open temporary file");
251	(void)unlink(tmpname);
252
253	if (!nobanner) {
254		tty = ttyname(STDERR_FILENO);
255		if (tty == NULL)
256			tty = "no tty";
257
258		if (!(whom = getlogin()))
259			whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";
260		(void)gethostname(hostname, sizeof(hostname));
261		(void)time(&now);
262		lt = localtime(&now);
263
264		/*
265		 * all this stuff is to blank out a square for the message;
266		 * we wrap message lines at column 79, not 80, because some
267		 * terminals wrap after 79, some do not, and we can't tell.
268		 * Which means that we may leave a non-blank character
269		 * in column 80, but that can't be helped.
270		 */
271		(void)fprintf(fp, "\r%79s\r\n", " ");
272		(void)snprintf(lbuf, sizeof(lbuf),
273		    "Broadcast Message from %s@%s",
274		    whom, hostname);
275		(void)fprintf(fp, "%-79.79s\007\007\r\n", lbuf);
276		(void)snprintf(lbuf, sizeof(lbuf),
277		    "        (%s) at %d:%02d %s...", tty,
278		    lt->tm_hour, lt->tm_min, lt->tm_zone);
279		(void)fprintf(fp, "%-79.79s\r\n", lbuf);
280	}
281	(void)fprintf(fp, "%79s\r\n", " ");
282
283	if (fname) {
284		egid = getegid();
285		setegid(getgid());
286	       	if (freopen(fname, "r", stdin) == NULL)
287			err(1, "can't read %s", fname);
288		setegid(egid);
289	}
290	while (fgets(lbuf, sizeof(lbuf), stdin)) {
291		for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
292			if (ch == '\r') {
293				putc('\r', fp);
294				cnt = 0;
295				continue;
296			} else if (ch == '\n') {
297				for (; cnt < 79; ++cnt)
298					putc(' ', fp);
299				putc('\r', fp);
300				putc('\n', fp);
301				break;
302			}
303			if (cnt == 79) {
304				putc('\r', fp);
305				putc('\n', fp);
306				cnt = 0;
307			}
308#ifdef __APPLE__
309			else // rdar://problem/3066405
310#endif
311			if (((ch & 0x80) && ch < 0xA0) ||
312				   /* disable upper controls */
313				   (!isprint(ch) && !isspace(ch) &&
314				    ch != '\a' && ch != '\b')
315				  ) {
316				if (ch & 0x80) {
317					ch &= 0x7F;
318					putc('M', fp);
319					if (++cnt == 79) {
320						putc('\r', fp);
321						putc('\n', fp);
322						cnt = 0;
323					}
324					putc('-', fp);
325					if (++cnt == 79) {
326						putc('\r', fp);
327						putc('\n', fp);
328						cnt = 0;
329					}
330				}
331				if (iscntrl(ch)) {
332					ch ^= 040;
333					putc('^', fp);
334					if (++cnt == 79) {
335						putc('\r', fp);
336						putc('\n', fp);
337						cnt = 0;
338					}
339				}
340			}
341#ifdef __APPLE__
342			// rdar://problem/4557295
343			if (ch != '\n')
344#endif
345			putc(ch, fp);
346		}
347	}
348	(void)fprintf(fp, "%79s\r\n", " ");
349	rewind(fp);
350
351	if (fstat(fd, &sbuf))
352		err(1, "can't stat temporary file");
353	mbufsize = sbuf.st_size;
354	if (!(mbuf = malloc((u_int)mbufsize)))
355		err(1, "out of memory");
356	if ((int)fread(mbuf, sizeof(*mbuf), mbufsize, fp) != mbufsize)
357		err(1, "can't read temporary file");
358	(void)close(fd);
359}
360