]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/wall.c
wall: query logind for list of users with tty (#2088)
[thirdparty/util-linux.git] / term-utils / wall.c
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 * Modified Sun Mar 12 10:34:34 1995, faith@cs.unc.edu, for Linux
34 */
35
36 /*
37 * This program is not related to David Wall, whose Stanford Ph.D. thesis
38 * is entitled "Mechanisms for Broadcast and Selective Broadcast".
39 *
40 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
41 * - added Native Language Support
42 *
43 */
44
45 #include <sys/param.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/uio.h>
49
50 #include <errno.h>
51 #include <paths.h>
52 #include <ctype.h>
53 #include <pwd.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <time.h>
58 #include <unistd.h>
59 #include <utmpx.h>
60 #include <getopt.h>
61 #include <sys/types.h>
62 #include <grp.h>
63
64 #if defined(USE_SYSTEMD) && HAVE_DECL_SD_SESSION_GET_USERNAME == 1
65 # include <systemd/sd-login.h>
66 # include <systemd/sd-daemon.h>
67 #endif
68
69 #include "nls.h"
70 #include "xalloc.h"
71 #include "strutils.h"
72 #include "ttymsg.h"
73 #include "pathnames.h"
74 #include "carefulputc.h"
75 #include "c.h"
76 #include "cctype.h"
77 #include "fileutils.h"
78 #include "closestream.h"
79 #include "timeutils.h"
80 #include "pwdutils.h"
81
82 #define TERM_WIDTH 79
83 #define WRITE_TIME_OUT 300 /* in seconds */
84
85 /* Function prototypes */
86 static char *makemsg(char *fname, char **mvec, int mvecsz,
87 size_t *mbufsize, int print_banner);
88
89 static void __attribute__((__noreturn__)) usage(void)
90 {
91 FILE *out = stdout;
92 fputs(USAGE_HEADER, out);
93 fprintf(out,
94 _(" %s [options] [<file> | <message>]\n"), program_invocation_short_name);
95
96 fputs(USAGE_SEPARATOR, out);
97 fputs(_("Write a message to all users.\n"), out);
98
99 fputs(USAGE_OPTIONS, out);
100 fputs(_(" -g, --group <group> only send message to group\n"), out);
101 fputs(_(" -n, --nobanner do not print banner, works only for root\n"), out);
102 fputs(_(" -t, --timeout <timeout> write timeout in seconds\n"), out);
103 fputs(USAGE_SEPARATOR, out);
104 printf(USAGE_HELP_OPTIONS(25));
105 printf(USAGE_MAN_TAIL("wall(1)"));
106
107 exit(EXIT_SUCCESS);
108 }
109
110 struct group_workspace {
111 gid_t requested_group;
112 int ngroups;
113
114 /* getgrouplist() on OSX takes int* not gid_t* */
115 #ifdef __APPLE__
116 int *groups;
117 #else
118 gid_t *groups;
119 #endif
120 };
121
122 static gid_t get_group_gid(const char *group)
123 {
124 struct group *gr;
125 gid_t gid;
126
127 if ((gr = getgrnam(group)))
128 return gr->gr_gid;
129
130 gid = strtou32_or_err(group, _("invalid group argument"));
131 if (!getgrgid(gid))
132 errx(EXIT_FAILURE, _("%s: unknown gid"), group);
133
134 return gid;
135 }
136
137 static struct group_workspace *init_group_workspace(const char *group)
138 {
139 struct group_workspace *buf = xmalloc(sizeof(struct group_workspace));
140
141 buf->requested_group = get_group_gid(group);
142 buf->ngroups = sysconf(_SC_NGROUPS_MAX) + 1; /* room for the primary gid */
143 buf->groups = xcalloc(sizeof(*buf->groups), buf->ngroups);
144
145 return buf;
146 }
147
148 static void free_group_workspace(struct group_workspace *buf)
149 {
150 if (!buf)
151 return;
152
153 free(buf->groups);
154 free(buf);
155 }
156
157 static int is_gr_member(const char *login, const struct group_workspace *buf)
158 {
159 struct passwd *pw;
160 int ngroups = buf->ngroups;
161 int rc;
162
163 pw = getpwnam(login);
164 if (!pw)
165 return 0;
166
167 if (buf->requested_group == pw->pw_gid)
168 return 1;
169
170 rc = getgrouplist(login, pw->pw_gid, buf->groups, &ngroups);
171 if (rc < 0) {
172 /* buffer too small, not sure how this can happen, since
173 we used sysconf to get the size... */
174 errx(EXIT_FAILURE,
175 _("getgrouplist found more groups than sysconf allows"));
176 }
177
178 for (; ngroups >= 0; --ngroups) {
179 if (buf->requested_group == (gid_t) buf->groups[ngroups])
180 return 1;
181 }
182
183 return 0;
184 }
185
186 int main(int argc, char **argv)
187 {
188 int ch;
189 struct iovec iov;
190 struct utmpx *utmpptr;
191 char *p;
192 char line[sizeof(utmpptr->ut_line) + 1];
193 int print_banner = TRUE;
194 struct group_workspace *group_buf = NULL;
195 char *mbuf, *fname = NULL;
196 size_t mbufsize;
197 unsigned timeout = WRITE_TIME_OUT;
198 char **mvec = NULL;
199 int mvecsz = 0;
200
201 static const struct option longopts[] = {
202 { "nobanner", no_argument, NULL, 'n' },
203 { "timeout", required_argument, NULL, 't' },
204 { "group", required_argument, NULL, 'g' },
205 { "version", no_argument, NULL, 'V' },
206 { "help", no_argument, NULL, 'h' },
207 { NULL, 0, NULL, 0 }
208 };
209
210 setlocale(LC_ALL, "");
211 bindtextdomain(PACKAGE, LOCALEDIR);
212 textdomain(PACKAGE);
213 close_stdout_atexit();
214
215 while ((ch = getopt_long(argc, argv, "nt:g:Vh", longopts, NULL)) != -1) {
216 switch (ch) {
217 case 'n':
218 if (geteuid() == 0)
219 print_banner = FALSE;
220 else
221 warnx(_("--nobanner is available only for root"));
222 break;
223 case 't':
224 timeout = strtou32_or_err(optarg, _("invalid timeout argument"));
225 if (timeout < 1)
226 errx(EXIT_FAILURE, _("invalid timeout argument: %s"), optarg);
227 break;
228 case 'g':
229 group_buf = init_group_workspace(optarg);
230 break;
231
232 case 'V':
233 print_version(EXIT_SUCCESS);
234 case 'h':
235 usage();
236 default:
237 errtryhelp(EXIT_FAILURE);
238 }
239 }
240 argc -= optind;
241 argv += optind;
242
243 if (argc == 1 && access(argv[0], F_OK) == 0)
244 fname = argv[0];
245 else if (argc >= 1) {
246 mvec = argv;
247 mvecsz = argc;
248 }
249
250 mbuf = makemsg(fname, mvec, mvecsz, &mbufsize, print_banner);
251
252 iov.iov_base = mbuf;
253 iov.iov_len = mbufsize;
254 #if defined(USE_SYSTEMD) && HAVE_DECL_SD_SESSION_GET_USERNAME == 1
255 if (sd_booted() > 0) {
256 char **sessions_list;
257 int sessions;
258
259 sessions = sd_get_sessions(&sessions_list);
260 if (sessions < 0)
261 errx(EXIT_FAILURE, _("error getting sessions: %s"),
262 strerror(-sessions));
263
264 for (int i = 0; i < sessions; i++) {
265 char *name, *tty;
266 int r;
267
268 if ((r = sd_session_get_username(sessions_list[i], &name)) < 0)
269 errx(EXIT_FAILURE, _("get user name failed: %s"), strerror (-r));
270
271 if (!(group_buf && !is_gr_member(name, group_buf))) {
272 if (sd_session_get_tty(sessions_list[i], &tty) >= 0) {
273 if ((p = ttymsg(&iov, 1, tty, timeout)) != NULL)
274 warnx("%s", p);
275
276 free(tty);
277 }
278 }
279 free(name);
280 free(sessions_list[i]);
281 }
282 free(sessions_list);
283 } else {
284 #endif
285 while((utmpptr = getutxent())) {
286 if (!utmpptr->ut_user[0])
287 continue;
288 #ifdef USER_PROCESS
289 if (utmpptr->ut_type != USER_PROCESS)
290 continue;
291 #endif
292 /* Joey Hess reports that use-sessreg in /etc/X11/wdm/ produces
293 * ut_line entries like :0, and a write to /dev/:0 fails.
294 *
295 * It also seems that some login manager may produce empty ut_line.
296 */
297 if (!*utmpptr->ut_line || *utmpptr->ut_line == ':')
298 continue;
299
300 if (group_buf && !is_gr_member(utmpptr->ut_user, group_buf))
301 continue;
302
303 mem2strcpy(line, utmpptr->ut_line, sizeof(utmpptr->ut_line), sizeof(line));
304 if ((p = ttymsg(&iov, 1, line, timeout)) != NULL)
305 warnx("%s", p);
306 }
307 endutxent();
308 #if defined(USE_SYSTEMD) && HAVE_DECL_SD_SESSION_GET_USERNAME == 1
309 }
310 #endif
311 free(mbuf);
312 free_group_workspace(group_buf);
313 exit(EXIT_SUCCESS);
314 }
315
316 struct buffer {
317 size_t sz;
318 size_t used;
319 char *data;
320 };
321
322 static void buf_enlarge(struct buffer *bs, size_t len)
323 {
324 if (bs->sz == 0 || len > bs->sz - bs->used) {
325 bs->sz += len < 128 ? 128 : len;
326 bs->data = xrealloc(bs->data, bs->sz);
327 }
328 }
329
330 static void buf_puts(struct buffer *bs, const char *s)
331 {
332 size_t len = strlen(s);
333
334 buf_enlarge(bs, len + 1);
335 memcpy(bs->data + bs->used, s, len + 1);
336 bs->used += len;
337 }
338
339 static void __attribute__((__format__ (__printf__, 2, 3)))
340 buf_printf(struct buffer *bs, const char *fmt, ...)
341 {
342 int rc;
343 va_list ap;
344 size_t limit;
345
346 buf_enlarge(bs, 0); /* default size */
347 limit = bs->sz - bs->used;
348
349 va_start(ap, fmt);
350 rc = vsnprintf(bs->data + bs->used, limit, fmt, ap);
351 va_end(ap);
352
353 if (rc >= 0 && (size_t) rc >= limit) { /* not enough, enlarge */
354 buf_enlarge(bs, (size_t)rc + 1);
355 limit = bs->sz - bs->used;
356 va_start(ap, fmt);
357 rc = vsnprintf(bs->data + bs->used, limit, fmt, ap);
358 va_end(ap);
359 }
360
361 if (rc > 0)
362 bs->used += rc;
363 }
364
365 static void buf_putc_careful(struct buffer *bs, int c)
366 {
367 if (isprint(c) || c == '\a' || c == '\t' || c == '\r' || c == '\n') {
368 buf_enlarge(bs, 1);
369 bs->data[bs->used++] = c;
370 } else if (!c_isascii(c))
371 buf_printf(bs, "\\%3o", (unsigned char)c);
372 else {
373 char tmp[] = { '^', c ^ 0x40, '\0' };
374 buf_puts(bs, tmp);
375 }
376 }
377
378 static char *makemsg(char *fname, char **mvec, int mvecsz,
379 size_t *mbufsize, int print_banner)
380 {
381 struct buffer _bs = {.used = 0}, *bs = &_bs;
382 register int ch, cnt;
383 char *p, *lbuf;
384 long line_max;
385
386 line_max = sysconf(_SC_LINE_MAX);
387 if (line_max <= 0)
388 line_max = 512;
389
390 lbuf = xmalloc(line_max);
391
392 if (print_banner == TRUE) {
393 char *hostname = xgethostname();
394 char *whom, *where, date[CTIME_BUFSIZ];
395 time_t now;
396
397 whom = xgetlogin();
398 if (!whom) {
399 whom = "<someone>";
400 warn(_("cannot get passwd uid"));
401 }
402 where = ttyname(STDOUT_FILENO);
403 if (!where) {
404 where = "somewhere";
405 } else if (strncmp(where, "/dev/", 5) == 0)
406 where += 5;
407
408 time(&now);
409 ctime_r(&now, date);
410 date[strlen(date) - 1] = '\0';
411
412 /*
413 * all this stuff is to blank out a square for the message;
414 * we wrap message lines at column 79, not 80, because some
415 * terminals wrap after 79, some do not, and we can't tell.
416 * Which means that we may leave a non-blank character
417 * in column 80, but that can't be helped.
418 */
419 /* snprintf is not always available, but the sprintf's here
420 will not overflow as long as %d takes at most 100 chars */
421 buf_printf(bs, "\r%*s\r\n", TERM_WIDTH, " ");
422
423 snprintf(lbuf, line_max,
424 _("Broadcast message from %s@%s (%s) (%s):"),
425 whom, hostname, where, date);
426 buf_printf(bs, "%-*.*s\007\007\r\n", TERM_WIDTH, TERM_WIDTH, lbuf);
427 free(hostname);
428 }
429 buf_printf(bs, "%*s\r\n", TERM_WIDTH, " ");
430
431 if (mvec) {
432 /*
433 * Read message from argv[]
434 */
435 int i;
436
437 for (i = 0; i < mvecsz; i++) {
438 buf_puts(bs, mvec[i]);
439 if (i < mvecsz - 1)
440 buf_puts(bs, " ");
441 }
442 buf_puts(bs, "\r\n");
443 } else {
444 /*
445 * read message from <file>
446 */
447 if (fname) {
448 /*
449 * When we are not root, but suid or sgid, refuse to read files
450 * (e.g. device files) that the user may not have access to.
451 * After all, our invoker can easily do "wall < file"
452 * instead of "wall file".
453 */
454 uid_t uid = getuid();
455 if (uid && (uid != geteuid() || getgid() != getegid()))
456 errx(EXIT_FAILURE, _("will not read %s - use stdin."),
457 fname);
458
459 if (!freopen(fname, "r", stdin))
460 err(EXIT_FAILURE, _("cannot open %s"), fname);
461
462 }
463
464 /*
465 * Read message from stdin.
466 */
467 while (fgets(lbuf, line_max, stdin)) {
468 for (cnt = 0, p = lbuf; (ch = *p) != '\0'; ++p, ++cnt) {
469 if (cnt == TERM_WIDTH || ch == '\n') {
470 for (; cnt < TERM_WIDTH; ++cnt)
471 buf_puts(bs, " ");
472 buf_puts(bs, "\r\n");
473 cnt = 0;
474 }
475 if (ch == '\t')
476 cnt += (7 - (cnt % 8));
477 if (ch != '\n')
478 buf_putc_careful(bs, ch);
479 }
480 }
481 }
482 buf_printf(bs, "%*s\r\n", TERM_WIDTH, " ");
483
484 free(lbuf);
485
486 bs->data[bs->used] = '\0'; /* be paranoid */
487 *mbufsize = bs->used;
488 return bs->data;
489 }