]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/wall.c
293275cb3ef6aded91e9e2862529eb298109e3dc
[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 #include "strv.h"
82
83 #define TERM_WIDTH 79
84 #define WRITE_TIME_OUT 300 /* in seconds */
85
86 /* Function prototypes */
87 static char *makemsg(char *fname, char **mvec, int mvecsz,
88 size_t *mbufsize, int print_banner);
89
90 static void __attribute__((__noreturn__)) usage(void)
91 {
92 FILE *out = stdout;
93 fputs(USAGE_HEADER, out);
94 fprintf(out,
95 _(" %s [options] [<file> | <message>]\n"), program_invocation_short_name);
96
97 fputs(USAGE_SEPARATOR, out);
98 fputs(_("Write a message to all users.\n"), out);
99
100 fputs(USAGE_OPTIONS, out);
101 fputs(_(" -g, --group <group> only send message to group\n"), out);
102 fputs(_(" -n, --nobanner do not print banner, works only for root\n"), out);
103 fputs(_(" -t, --timeout <timeout> write timeout in seconds\n"), out);
104 fputs(USAGE_SEPARATOR, out);
105 fprintf(out, USAGE_HELP_OPTIONS(25));
106 fprintf(out, USAGE_MAN_TAIL("wall(1)"));
107
108 exit(EXIT_SUCCESS);
109 }
110
111 struct group_workspace {
112 gid_t requested_group;
113 int ngroups;
114
115 /* getgrouplist() on OSX takes int* not gid_t* */
116 #ifdef __APPLE__
117 int *groups;
118 #else
119 gid_t *groups;
120 #endif
121 };
122
123 static gid_t get_group_gid(const char *group)
124 {
125 struct group *gr;
126 gid_t gid;
127
128 if ((gr = getgrnam(group)))
129 return gr->gr_gid;
130
131 gid = strtou32_or_err(group, _("invalid group argument"));
132 if (!getgrgid(gid))
133 errx(EXIT_FAILURE, _("%s: unknown gid"), group);
134
135 return gid;
136 }
137
138 static struct group_workspace *init_group_workspace(const char *group)
139 {
140 struct group_workspace *buf;
141 long n;
142
143 n = sysconf(_SC_NGROUPS_MAX);
144 if (n < 0 || n > INT_MAX - 1)
145 return NULL;
146
147 buf = xmalloc(sizeof(struct group_workspace));
148 buf->ngroups = n + 1; /* room for the primary gid */
149
150 buf->requested_group = get_group_gid(group);
151 buf->groups = xcalloc(buf->ngroups, sizeof(*buf->groups));
152
153 return buf;
154 }
155
156 static void free_group_workspace(struct group_workspace *buf)
157 {
158 if (!buf)
159 return;
160
161 free(buf->groups);
162 free(buf);
163 }
164
165 static int is_gr_member(const char *login, const struct group_workspace *buf)
166 {
167 struct passwd *pw;
168 int ngroups = buf->ngroups;
169 int rc;
170
171 pw = getpwnam(login);
172 if (!pw)
173 return 0;
174
175 if (buf->requested_group == pw->pw_gid)
176 return 1;
177
178 rc = getgrouplist(login, pw->pw_gid, buf->groups, &ngroups);
179 if (rc < 0) {
180 /* buffer too small, not sure how this can happen, since
181 we used sysconf to get the size... */
182 errx(EXIT_FAILURE,
183 _("getgrouplist found more groups than sysconf allows"));
184 }
185
186 for (; ngroups >= 0; --ngroups) {
187 if (buf->requested_group == (gid_t) buf->groups[ngroups])
188 return 1;
189 }
190
191 return 0;
192 }
193
194 static int has_tty(char **ttys, char *name)
195 {
196 char **str;
197
198 UL_STRV_FOREACH(str, ttys) {
199 if (strcmp(*str, name) == 0)
200 return 1;
201 }
202
203 return 0;
204 }
205
206 int main(int argc, char **argv)
207 {
208 int ch;
209 struct iovec iov;
210 struct utmpx *utmpptr;
211 char line[sizeof(utmpptr->ut_line) + 1];
212 int print_banner = TRUE;
213 struct group_workspace *group_buf = NULL;
214 char *mbuf, *fname = NULL;
215 size_t mbufsize;
216 unsigned timeout = WRITE_TIME_OUT;
217 char **mvec = NULL, **ttys = NULL, **str;
218 int mvecsz = 0;
219
220 static const struct option longopts[] = {
221 { "nobanner", no_argument, NULL, 'n' },
222 { "timeout", required_argument, NULL, 't' },
223 { "group", required_argument, NULL, 'g' },
224 { "version", no_argument, NULL, 'V' },
225 { "help", no_argument, NULL, 'h' },
226 { NULL, 0, NULL, 0 }
227 };
228
229 setlocale(LC_ALL, "");
230 bindtextdomain(PACKAGE, LOCALEDIR);
231 textdomain(PACKAGE);
232 close_stdout_atexit();
233
234 while ((ch = getopt_long(argc, argv, "nt:g:Vh", longopts, NULL)) != -1) {
235 switch (ch) {
236 case 'n':
237 if (geteuid() == 0)
238 print_banner = FALSE;
239 else
240 warnx(_("--nobanner is available only for root"));
241 break;
242 case 't':
243 timeout = strtou32_or_err(optarg, _("invalid timeout argument"));
244 if (timeout < 1)
245 errx(EXIT_FAILURE, _("invalid timeout argument: %s"), optarg);
246 break;
247 case 'g':
248 group_buf = init_group_workspace(optarg);
249 break;
250
251 case 'V':
252 print_version(EXIT_SUCCESS);
253 case 'h':
254 usage();
255 default:
256 errtryhelp(EXIT_FAILURE);
257 }
258 }
259 argc -= optind;
260 argv += optind;
261
262 if (argc == 1 && access(argv[0], F_OK) == 0)
263 fname = argv[0];
264 else if (argc >= 1) {
265 mvec = argv;
266 mvecsz = argc;
267 }
268
269 mbuf = makemsg(fname, mvec, mvecsz, &mbufsize, print_banner);
270
271 iov.iov_base = mbuf;
272 iov.iov_len = mbufsize;
273
274 #if defined(USE_SYSTEMD) && HAVE_DECL_SD_SESSION_GET_USERNAME == 1
275 if (sd_booted() > 0) {
276 char **sessions_list;
277 int sessions;
278
279 sessions = sd_get_sessions(&sessions_list);
280 if (sessions < 0) {
281 warnx(_("error getting sessions: %s"), strerror(-sessions));
282 goto utmp;
283 }
284
285 for (int i = 0; i < sessions; i++) {
286 char *name, *tty;
287 int r;
288
289 if ((r = sd_session_get_username(sessions_list[i], &name)) < 0) {
290 warnx(_("get user name failed: %s"), strerror (-r));
291 goto utmp;
292 }
293 if (!(group_buf && !is_gr_member(name, group_buf))
294 && sd_session_get_tty(sessions_list[i], &tty) >= 0
295 && ul_strv_consume(&ttys, tty) < 0)
296 err(EXIT_FAILURE, _("failed to allocate lines list"));
297
298 free(name);
299 free(sessions_list[i]);
300 }
301 free(sessions_list);
302 }
303 utmp:
304 #endif
305 {
306 while ((utmpptr = getutxent())) {
307 if (!utmpptr->ut_user[0])
308 continue;
309 #ifdef USER_PROCESS
310 if (utmpptr->ut_type != USER_PROCESS)
311 continue;
312 #endif
313 /* Joey Hess reports that use-sessreg in /etc/X11/wdm/ produces
314 * ut_line entries like :0, and a write to /dev/:0 fails.
315 *
316 * It also seems that some login manager may produce empty ut_line.
317 */
318 if (!*utmpptr->ut_line || *utmpptr->ut_line == ':')
319 continue;
320
321 if (group_buf && !is_gr_member(utmpptr->ut_user, group_buf))
322 continue;
323
324 mem2strcpy(line, utmpptr->ut_line, sizeof(utmpptr->ut_line), sizeof(line));
325 if (has_tty(ttys, line))
326 continue;
327 if (ul_strv_extend(&ttys, line) < 0)
328 err(EXIT_FAILURE, _("failed to allocate lines list"));
329 }
330 endutxent();
331 }
332
333 UL_STRV_FOREACH(str, ttys) {
334 char *er = ttymsg(&iov, 1, *str, timeout);
335 if (er)
336 warnx("%s", er);
337 }
338
339 ul_strv_free(ttys);
340 free(mbuf);
341 free_group_workspace(group_buf);
342 exit(EXIT_SUCCESS);
343 }
344
345 static char *makemsg(char *fname, char **mvec, int mvecsz,
346 size_t *mbufsize, int print_banner)
347 {
348 char *lbuf, *retbuf;
349 FILE * fs = open_memstream(&retbuf, mbufsize);
350 size_t lbuflen = 512;
351 lbuf = xmalloc(lbuflen);
352
353 if (print_banner == TRUE) {
354 char *hostname = xgethostname();
355 char *whombuf, *whom, *where, date[CTIME_BUFSIZ];
356 time_t now;
357
358 whombuf = whom = xgetlogin();
359 if (!whom) {
360 whom = "<someone>";
361 warn(_("cannot get passwd uid"));
362 }
363 where = ttyname(STDOUT_FILENO);
364 if (!where) {
365 where = "somewhere";
366 } else if (strncmp(where, "/dev/", 5) == 0)
367 where += 5;
368
369 time(&now);
370 ctime_r(&now, date);
371 date[strlen(date) - 1] = '\0';
372
373 /*
374 * all this stuff is to blank out a square for the message;
375 * we wrap message lines at column 79, not 80, because some
376 * terminals wrap after 79, some do not, and we can't tell.
377 * Which means that we may leave a non-blank character
378 * in column 80, but that can't be helped.
379 */
380 /* snprintf is not always available, but the sprintf's here
381 will not overflow as long as %d takes at most 100 chars */
382 fprintf(fs, "\r%*s\r\n", TERM_WIDTH, " ");
383
384 snprintf(lbuf, lbuflen,
385 _("Broadcast message from %s@%s (%s) (%s):"),
386 whom, hostname, where, date);
387 fprintf(fs, "%-*.*s\007\007\r\n", TERM_WIDTH, TERM_WIDTH, lbuf);
388 free(hostname);
389 free(whombuf);
390 }
391 fprintf(fs, "%*s\r\n", TERM_WIDTH, " ");
392
393 if (mvec) {
394 /*
395 * Read message from argv[]
396 */
397 int i;
398
399 for (i = 0; i < mvecsz; i++) {
400 fputs_careful(mvec[i], fs, '^', true, TERM_WIDTH);
401 if (i < mvecsz - 1)
402 fputc(' ', fs);
403 }
404 fputs("\r\n", fs);
405 } else {
406 /*
407 * read message from <file>
408 */
409 if (fname) {
410 /*
411 * When we are not root, but suid or sgid, refuse to read files
412 * (e.g. device files) that the user may not have access to.
413 * After all, our invoker can easily do "wall < file"
414 * instead of "wall file".
415 */
416 if (getuid() && is_privileged_execution())
417 errx(EXIT_FAILURE, _("will not read %s - use stdin."),
418 fname);
419
420 if (!freopen(fname, "r", stdin))
421 err(EXIT_FAILURE, _("cannot open %s"), fname);
422
423 }
424
425 /*
426 * Read message from stdin.
427 */
428 while (getline(&lbuf, &lbuflen, stdin) >= 0)
429 fputs_careful(lbuf, fs, '^', true, TERM_WIDTH);
430 }
431 fprintf(fs, "%*s\r\n", TERM_WIDTH, " ");
432
433 free(lbuf);
434
435 fclose(fs);
436 return retbuf;
437 }