]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/setterm.c
agetty: make output more robust
[thirdparty/util-linux.git] / term-utils / setterm.c
1 /* setterm.c, set terminal attributes.
2 *
3 * Copyright (C) 1990 Gordon Irlam (gordoni@cs.ua.oz.au). Conditions of use,
4 * modification, and redistribution are contained in the file COPYRIGHT that
5 * forms part of this distribution.
6 *
7 * Adaption to Linux by Peter MacDonald.
8 *
9 * Enhancements by Mika Liljeberg (liljeber@cs.Helsinki.FI)
10 *
11 * Beep modifications by Christophe Jolif (cjolif@storm.gatelink.fr.net)
12 *
13 * Sanity increases by Cafeine Addict [sic].
14 *
15 * Powersave features by todd j. derr <tjd@wordsmith.org>
16 *
17 * Converted to terminfo by Kars de Jong (jongk@cs.utwente.nl)
18 *
19 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
20 * - added Native Language Support
21 *
22 * Semantics:
23 *
24 * Setterm writes to standard output a character string that will
25 * invoke the specified terminal capabilities. Where possible
26 * terminfo is consulted to find the string to use. Some options
27 * however do not correspond to a terminfo capability. In this case if
28 * the terminal type is "con*", or "linux*" the string that invokes
29 * the specified capabilities on the PC Linux virtual console driver
30 * is output. Options that are not implemented by the terminal are
31 * ignored.
32 *
33 * The following options are non-obvious.
34 *
35 * -term can be used to override the TERM environment variable.
36 *
37 * -reset displays the terminal reset string, which typically resets the
38 * terminal to its power on state.
39 *
40 * -initialize displays the terminal initialization string, which typically
41 * sets the terminal's rendering options, and other attributes to the
42 * default values.
43 *
44 * -default sets the terminal's rendering options to the default values.
45 *
46 * -store stores the terminal's current rendering options as the default
47 * values. */
48
49 #include <ctype.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <getopt.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <sys/ioctl.h>
57 #include <sys/klog.h>
58 #include <sys/param.h> /* for MAXPATHLEN */
59 #include <sys/time.h>
60 #include <termios.h>
61 #include <unistd.h>
62
63 #if defined(HAVE_NCURSESW_TERM_H)
64 # include <ncursesw/term.h>
65 #elif defined(HAVE_NCURSES_TERM_H)
66 # include <ncurses/term.h>
67 #elif defined(HAVE_TERM_H)
68 # include <term.h>
69 #endif
70
71 #ifdef HAVE_LINUX_TIOCL_H
72 # include <linux/tiocl.h>
73 #endif
74
75 #include "all-io.h"
76 #include "c.h"
77 #include "closestream.h"
78 #include "nls.h"
79 #include "optutils.h"
80 #include "strutils.h"
81 #include "xalloc.h"
82
83 /* Constants. */
84
85 /* Non-standard return values. */
86 #define EXIT_DUMPFILE -1
87
88 /* Colors. */
89 enum {
90 BLACK = 0,
91 RED,
92 GREEN,
93 YELLOW,
94 BLUE,
95 MAGENTA,
96 CYAN,
97 WHITE,
98 GREY,
99 DEFAULT
100 };
101
102 static const char *colornames[] = {
103 [BLACK] = "black",
104 [RED] = "red",
105 [GREEN] = "green",
106 [YELLOW]= "yellow",
107 [BLUE] = "blue",
108 [MAGENTA]="magenta",
109 [CYAN] = "cyan",
110 [WHITE] = "white",
111 [GREY] = "grey",
112 [DEFAULT] = "default"
113 };
114
115 #define is_valid_color(x) (x >= 0 && (size_t) x < ARRAY_SIZE(colornames))
116
117 /* Blank commands */
118 enum {
119 BLANKSCREEN = -1,
120 UNBLANKSCREEN = -2,
121 BLANKEDSCREEN = -3
122 };
123
124 /* <linux/tiocl.h> fallback */
125 #ifndef TIOCL_BLANKSCREEN
126 enum {
127 TIOCL_UNBLANKSCREEN = 4, /* unblank screen */
128 TIOCL_SETVESABLANK = 10, /* set vesa blanking mode */
129 TIOCL_BLANKSCREEN = 14, /* keep screen blank even if a key is pressed */
130 TIOCL_BLANKEDSCREEN = 15 /* return which vt was blanked */
131 };
132 #endif
133
134 /* Powersave modes */
135 enum {
136 VESA_BLANK_MODE_OFF = 0,
137 VESA_BLANK_MODE_SUSPENDV,
138 VESA_BLANK_MODE_SUSPENDH,
139 VESA_BLANK_MODE_POWERDOWN
140 };
141
142 /* klogctl() actions */
143 enum {
144 SYSLOG_ACTION_CONSOLE_OFF = 6,
145 SYSLOG_ACTION_CONSOLE_ON = 7,
146 SYSLOG_ACTION_CONSOLE_LEVEL = 8
147 };
148
149 /* Console log levels */
150 enum {
151 CONSOLE_LEVEL_MIN = 0,
152 CONSOLE_LEVEL_MAX = 8
153 };
154
155 /* Various numbers */
156 #define DEFAULT_TAB_LEN 8
157 #define BLANK_MAX 60
158 #define TABS_MAX 160
159 #define BLENGTH_MAX 2000
160
161 /* Command controls. */
162 struct setterm_control {
163 char *opt_te_terminal_name; /* terminal name */
164 int opt_bl_min; /* blank screen */
165 int opt_blength_l; /* bell duration in milliseconds */
166 int opt_bfreq_f; /* bell frequency in Hz */
167 int opt_sn_num; /* console number to be snapshot */
168 char *opt_sn_name; /* path to write snap */
169 char *in_device; /* device to snapshot */
170 int opt_msglevel_num; /* printk() logging level */
171 int opt_ps_mode; /* powersave mode */
172 int opt_pd_min; /* powerdown time */
173 int opt_rt_len; /* regular tab length */
174 int opt_tb_array[TABS_MAX + 1]; /* array for tab list */
175 /* colors */
176 unsigned int opt_fo_color:4, opt_ba_color:4, opt_ul_color:4, opt_hb_color:4;
177 /* boolean options */
178 unsigned int opt_cu_on:1, opt_li_on:1, opt_bo_on:1, opt_hb_on:1,
179 opt_bl_on:1, opt_re_on:1, opt_un_on:1, opt_rep_on:1,
180 opt_appck_on:1, opt_invsc_on:1, opt_msg_on:1, opt_cl_all:1,
181 vcterm:1;
182 /* Option flags. Set when an option is invoked. */
183 uint64_t opt_term:1, opt_reset:1, opt_resize:1, opt_initialize:1, opt_cursor:1,
184 opt_linewrap:1, opt_default:1, opt_foreground:1,
185 opt_background:1, opt_bold:1, opt_blink:1, opt_reverse:1,
186 opt_underline:1, opt_store:1, opt_clear:1, opt_blank:1,
187 opt_snap:1, opt_snapfile:1, opt_append:1, opt_ulcolor:1,
188 opt_hbcolor:1, opt_halfbright:1, opt_repeat:1, opt_tabs:1,
189 opt_clrtabs:1, opt_regtabs:1, opt_appcursorkeys:1,
190 opt_inversescreen:1, opt_msg:1, opt_msglevel:1, opt_powersave:1,
191 opt_powerdown:1, opt_blength:1, opt_bfreq:1;
192 };
193
194 static int parse_color(const char *arg)
195 {
196 size_t i;
197
198 for (i = 0; i < ARRAY_SIZE(colornames); i++) {
199 if (strcmp(colornames[i], arg) == 0)
200 return i;
201 }
202
203 return -EINVAL;
204 }
205
206 static int parse_febg_color(const char *arg)
207 {
208 int color = parse_color(arg);
209
210 if (color < 0)
211 color = strtos32_or_err(arg, _("argument error"));
212
213 if (!is_valid_color(color) || color == GREY)
214 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
215 return color;
216 }
217
218 static int parse_ulhb_color(char **av, int *oi)
219 {
220 char *color_name;
221 int bright = 0;
222 int color = -1;
223
224 if (av[*oi] && strcmp(av[*oi - 1], "bright") == 0) {
225 bright = 1;
226 color_name = av[*oi];
227 (*oi)++;
228 } else
229 color_name = av[*oi - 1];
230
231 color = parse_color(color_name);
232 if (color < 0)
233 color = strtos32_or_err(color_name, _("argument error"));
234 if (!is_valid_color(color))
235 errx(EXIT_FAILURE, "%s: %s", _("argument error"), color_name);
236 if (bright && (color == BLACK || color == GREY))
237 errx(EXIT_FAILURE, _("argument error: bright %s is not supported"), color_name);
238
239 return color;
240 }
241
242 static char *find_optional_arg(char **av, char *oa, int *oi)
243 {
244 char *arg;
245 if (oa)
246 return oa;
247 else {
248 arg = av[*oi];
249 if (!arg || arg[0] == '-')
250 return NULL;
251 }
252 (*oi)++;
253 return arg;
254 }
255
256 static int parse_blank(char **av, char *oa, int *oi)
257 {
258 char *arg;
259
260 arg = find_optional_arg(av, oa, oi);
261 if (!arg)
262 return BLANKEDSCREEN;
263 if (!strcmp(arg, "force"))
264 return BLANKSCREEN;
265 else if (!strcmp(arg, "poke"))
266 return UNBLANKSCREEN;
267 else {
268 int ret;
269
270 ret = strtos32_or_err(arg, _("argument error"));
271 if (ret < 0 || BLANK_MAX < ret)
272 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
273 return ret;
274 }
275 }
276
277 static int parse_powersave(const char *arg)
278 {
279 if (strcmp(arg, "on") == 0)
280 return VESA_BLANK_MODE_SUSPENDV;
281 else if (strcmp(arg, "vsync") == 0)
282 return VESA_BLANK_MODE_SUSPENDV;
283 else if (strcmp(arg, "hsync") == 0)
284 return VESA_BLANK_MODE_SUSPENDH;
285 else if (strcmp(arg, "powerdown") == 0)
286 return VESA_BLANK_MODE_POWERDOWN;
287 else if (strcmp(arg, "off") == 0)
288 return VESA_BLANK_MODE_OFF;
289 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
290 }
291
292 static int parse_msglevel(const char *arg)
293 {
294 int ret;
295
296 ret = strtos32_or_err(arg, _("argument error"));
297 if (ret < CONSOLE_LEVEL_MIN || CONSOLE_LEVEL_MAX < ret)
298 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
299 return ret;
300 }
301
302 static int parse_snap(char **av, char *oa, int *oi)
303 {
304 int ret;
305 char *arg;
306
307 arg = find_optional_arg(av, oa, oi);
308 if (!arg)
309 return 0;
310 ret = strtos32_or_err(arg, _("argument error"));
311 if (ret < 1)
312 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
313 return ret;
314 }
315
316 static void parse_tabs(char **av, char *oa, int *oi, int *tab_array)
317 {
318 int i = 0;
319
320 if (oa) {
321 tab_array[i] = strtos32_or_err(oa, _("argument error"));
322 i++;
323 }
324 while (av[*oi]) {
325 if (TABS_MAX < i)
326 errx(EXIT_FAILURE, _("too many tabs"));
327 if (av[*oi][0] == '-')
328 break;
329 tab_array[i] = strtos32_or_err(av[*oi], _("argument error"));
330 (*oi)++;
331 i++;
332 }
333 tab_array[i] = -1;
334 }
335
336 static int parse_regtabs(char **av, char *oa, int *oi)
337 {
338 int ret;
339 char *arg;
340
341 arg = find_optional_arg(av, oa, oi);
342 if (!arg)
343 return DEFAULT_TAB_LEN;
344 ret = strtos32_or_err(arg, _("argument error"));
345 if (ret < 1 || TABS_MAX < ret)
346 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
347 return ret;
348 }
349
350 static int parse_blength(char **av, char *oa, int *oi)
351 {
352 int ret = -1;
353 char *arg;
354
355 arg = find_optional_arg(av, oa, oi);
356 if (!arg)
357 return 0;
358 ret = strtos32_or_err(arg, _("argument error"));
359 if (ret < 0 || BLENGTH_MAX < ret)
360 errx(EXIT_FAILURE, "%s: %s", _("argument error"), arg);
361 return ret;
362 }
363
364 static int parse_bfreq(char **av, char *oa, int *oi)
365 {
366 char *arg;
367
368 arg = find_optional_arg(av, oa, oi);
369 if (!arg)
370 return 0;
371 return strtos32_or_err(arg, _("argument error"));
372 }
373
374 static void __attribute__((__noreturn__)) usage(void)
375 {
376 FILE *out = stdout;
377 fputs(USAGE_HEADER, out);
378 fprintf(out,
379 _(" %s [options]\n"), program_invocation_short_name);
380
381 fputs(USAGE_SEPARATOR, out);
382 fputs(_("Set the attributes of a terminal.\n"), out);
383
384 fputs(USAGE_OPTIONS, out);
385 fputs(_(" --term <terminal_name> override TERM environment variable\n"), out);
386 fputs(_(" --reset reset terminal to power-on state\n"), out);
387 fputs(_(" --resize reset terminal rows and columns\n"), out);
388 fputs(_(" --initialize display init string, and use default settings\n"), out);
389 fputs(_(" --default use default terminal settings\n"), out);
390 fputs(_(" --store save current terminal settings as default\n"), out);
391 fputs(_(" --cursor [on|off] display cursor\n"), out);
392 fputs(_(" --repeat [on|off] keyboard repeat\n"), out);
393 fputs(_(" --appcursorkeys [on|off] cursor key application mode\n"), out);
394 fputs(_(" --linewrap [on|off] continue on a new line when a line is full\n"), out);
395 fputs(_(" --inversescreen [on|off] swap colors for the whole screen\n"), out);
396 fputs(_(" --foreground default|<color> set foreground color\n"), out);
397 fputs(_(" --background default|<color> set background color\n"), out);
398 fputs(_(" --ulcolor [bright] <color> set underlined text color\n"), out);
399 fputs(_(" --hbcolor [bright] <color> set bold text color\n"), out);
400 fputs(_(" <color>: black blue cyan green grey magenta red white yellow\n"), out);
401 fputs(_(" --bold [on|off] bold\n"), out);
402 fputs(_(" --half-bright [on|off] dim\n"), out);
403 fputs(_(" --blink [on|off] blink\n"), out);
404 fputs(_(" --underline [on|off] underline\n"), out);
405 fputs(_(" --reverse [on|off] swap foreground and background colors\n"), out);
406 fputs(_(" --clear [all|rest] clear screen and set cursor position\n"), out);
407 fputs(_(" --tabs [<number>...] set these tab stop positions, or show them\n"), out);
408 fputs(_(" --clrtabs [<number>...] clear these tab stop positions, or all\n"), out);
409 fputs(_(" --regtabs [1-160] set a regular tab stop interval\n"), out);
410 fputs(_(" --blank [0-60|force|poke] set time of inactivity before screen blanks\n"), out);
411 fputs(_(" --dump [<number>] write vcsa<number> console dump to file\n"), out);
412 fputs(_(" --append [<number>] append vcsa<number> console dump to file\n"), out);
413 fputs(_(" --file <filename> name of the dump file\n"), out);
414 fputs(_(" --msg [on|off] send kernel messages to console\n"), out);
415 fputs(_(" --msglevel 0-8 kernel console log level\n"), out);
416 fputs(_(" --powersave [on|vsync|hsync|powerdown|off]\n"), out);
417 fputs(_(" set vesa powersaving features\n"), out);
418 fputs(_(" --powerdown [0-60] set vesa powerdown interval in minutes\n"), out);
419 fputs(_(" --blength [0-2000] duration of the bell in milliseconds\n"), out);
420 fputs(_(" --bfreq <number> bell frequency in Hertz\n"), out);
421 printf( " --help %s\n", USAGE_OPTSTR_HELP);
422 printf( " --version %s\n", USAGE_OPTSTR_VERSION);
423
424 printf(USAGE_MAN_TAIL("setterm(1)"));
425 exit(EXIT_SUCCESS);
426 }
427
428 static int __attribute__((__pure__)) set_opt_flag(int opt)
429 {
430 if (opt)
431 errx(EXIT_FAILURE, _("duplicate use of an option"));
432 return 1;
433 }
434
435 static void parse_option(struct setterm_control *ctl, int ac, char **av)
436 {
437 int c;
438 enum {
439 OPT_TERM = CHAR_MAX + 1,
440 OPT_RESET,
441 OPT_RESIZE,
442 OPT_INITIALIZE,
443 OPT_CURSOR,
444 OPT_REPEAT,
445 OPT_APPCURSORKEYS,
446 OPT_LINEWRAP,
447 OPT_DEFAULT,
448 OPT_FOREGROUND,
449 OPT_BACKGROUND,
450 OPT_ULCOLOR,
451 OPT_HBCOLOR,
452 OPT_INVERSESCREEN,
453 OPT_BOLD,
454 OPT_HALF_BRIGHT,
455 OPT_BLINK,
456 OPT_REVERSE,
457 OPT_UNDERLINE,
458 OPT_STORE,
459 OPT_CLEAR,
460 OPT_TABS,
461 OPT_CLRTABS,
462 OPT_REGTABS,
463 OPT_BLANK,
464 OPT_DUMP,
465 OPT_APPEND,
466 OPT_FILE,
467 OPT_MSG,
468 OPT_MSGLEVEL,
469 OPT_POWERSAVE,
470 OPT_POWERDOWN,
471 OPT_BLENGTH,
472 OPT_BFREQ,
473 OPT_VERSION,
474 OPT_HELP
475 };
476 static const struct option longopts[] = {
477 {"term", required_argument, NULL, OPT_TERM},
478 {"reset", no_argument, NULL, OPT_RESET},
479 {"resize", no_argument, NULL, OPT_RESIZE},
480 {"initialize", no_argument, NULL, OPT_INITIALIZE},
481 {"cursor", required_argument, NULL, OPT_CURSOR},
482 {"repeat", required_argument, NULL, OPT_REPEAT},
483 {"appcursorkeys", required_argument, NULL, OPT_APPCURSORKEYS},
484 {"linewrap", required_argument, NULL, OPT_LINEWRAP},
485 {"default", no_argument, NULL, OPT_DEFAULT},
486 {"foreground", required_argument, NULL, OPT_FOREGROUND},
487 {"background", required_argument, NULL, OPT_BACKGROUND},
488 {"ulcolor", required_argument, NULL, OPT_ULCOLOR},
489 {"hbcolor", required_argument, NULL, OPT_HBCOLOR},
490 {"inversescreen", required_argument, NULL, OPT_INVERSESCREEN},
491 {"bold", required_argument, NULL, OPT_BOLD},
492 {"half-bright", required_argument, NULL, OPT_HALF_BRIGHT},
493 {"blink", required_argument, NULL, OPT_BLINK},
494 {"reverse", required_argument, NULL, OPT_REVERSE},
495 {"underline", required_argument, NULL, OPT_UNDERLINE},
496 {"store", no_argument, NULL, OPT_STORE},
497 {"clear", required_argument, NULL, OPT_CLEAR},
498 {"tabs", optional_argument, NULL, OPT_TABS},
499 {"clrtabs", optional_argument, NULL, OPT_CLRTABS},
500 {"regtabs", optional_argument, NULL, OPT_REGTABS},
501 {"blank", optional_argument, NULL, OPT_BLANK},
502 {"dump", optional_argument, NULL, OPT_DUMP},
503 {"append", required_argument, NULL, OPT_APPEND},
504 {"file", required_argument, NULL, OPT_FILE},
505 {"msg", required_argument, NULL, OPT_MSG},
506 {"msglevel", required_argument, NULL, OPT_MSGLEVEL},
507 {"powersave", required_argument, NULL, OPT_POWERSAVE},
508 {"powerdown", optional_argument, NULL, OPT_POWERDOWN},
509 {"blength", optional_argument, NULL, OPT_BLENGTH},
510 {"bfreq", optional_argument, NULL, OPT_BFREQ},
511 {"version", no_argument, NULL, OPT_VERSION},
512 {"help", no_argument, NULL, OPT_HELP},
513 {NULL, 0, NULL, 0}
514 };
515 static const ul_excl_t excl[] = {
516 { OPT_DEFAULT, OPT_STORE },
517 { OPT_TABS, OPT_CLRTABS, OPT_REGTABS },
518 { OPT_MSG, OPT_MSGLEVEL },
519 { 0 }
520 };
521 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
522
523 while ((c = getopt_long_only(ac, av, "", longopts, NULL)) != -1) {
524 err_exclusive_options(c, longopts, excl, excl_st);
525 switch (c) {
526 case OPT_TERM:
527 ctl->opt_term = set_opt_flag(ctl->opt_term);
528 ctl->opt_te_terminal_name = optarg;
529 break;
530 case OPT_RESET:
531 ctl->opt_reset = set_opt_flag(ctl->opt_reset);
532 break;
533 case OPT_RESIZE:
534 ctl->opt_resize = set_opt_flag(ctl->opt_resize);
535 break;
536 case OPT_INITIALIZE:
537 ctl->opt_initialize = set_opt_flag(ctl->opt_initialize);
538 break;
539 case OPT_CURSOR:
540 ctl->opt_cursor = set_opt_flag(ctl->opt_cursor);
541 ctl->opt_cu_on = parse_switch(optarg, _("argument error"),
542 "on", "off", NULL);
543 break;
544 case OPT_REPEAT:
545 ctl->opt_repeat = set_opt_flag(ctl->opt_repeat);
546 ctl->opt_rep_on = parse_switch(optarg, _("argument error"),
547 "on", "off", NULL);
548 break;
549 case OPT_APPCURSORKEYS:
550 ctl->opt_appcursorkeys = set_opt_flag(ctl->opt_appcursorkeys);
551 ctl->opt_appck_on = parse_switch(optarg, _("argument error"),
552 "on", "off", NULL);
553 break;
554 case OPT_LINEWRAP:
555 ctl->opt_linewrap = set_opt_flag(ctl->opt_linewrap);
556 ctl->opt_li_on = parse_switch(optarg, _("argument error"),
557 "on", "off", NULL);
558 break;
559 case OPT_DEFAULT:
560 ctl->opt_default = set_opt_flag(ctl->opt_default);
561 break;
562 case OPT_FOREGROUND:
563 ctl->opt_foreground = set_opt_flag(ctl->opt_foreground);
564 ctl->opt_fo_color = parse_febg_color(optarg);
565 break;
566 case OPT_BACKGROUND:
567 ctl->opt_background = set_opt_flag(ctl->opt_background);
568 ctl->opt_ba_color = parse_febg_color(optarg);
569 break;
570 case OPT_ULCOLOR:
571 ctl->opt_ulcolor = set_opt_flag(ctl->opt_ulcolor);
572 ctl->opt_ul_color = parse_ulhb_color(av, &optind);
573 break;
574 case OPT_HBCOLOR:
575 ctl->opt_hbcolor = set_opt_flag(ctl->opt_hbcolor);
576 ctl->opt_hb_color = parse_ulhb_color(av, &optind);
577 break;
578 case OPT_INVERSESCREEN:
579 ctl->opt_inversescreen = set_opt_flag(ctl->opt_inversescreen);
580 ctl->opt_invsc_on = parse_switch(optarg, _("argument error"),
581 "on", "off", NULL);
582 break;
583 case OPT_BOLD:
584 ctl->opt_bold = set_opt_flag(ctl->opt_bold);
585 ctl->opt_bo_on = parse_switch(optarg, _("argument error"),
586 "on", "off", NULL);
587 break;
588 case OPT_HALF_BRIGHT:
589 ctl->opt_halfbright = set_opt_flag(ctl->opt_halfbright);
590 ctl->opt_hb_on = parse_switch(optarg, _("argument error"),
591 "on", "off", NULL);
592 break;
593 case OPT_BLINK:
594 ctl->opt_blink = set_opt_flag(ctl->opt_blink);
595 ctl->opt_bl_on = parse_switch(optarg, _("argument error"),
596 "on", "off", NULL);
597 break;
598 case OPT_REVERSE:
599 ctl->opt_reverse = set_opt_flag(ctl->opt_reverse);
600 ctl->opt_re_on = parse_switch(optarg, _("argument error"),
601 "on", "off", NULL);
602 break;
603 case OPT_UNDERLINE:
604 ctl->opt_underline = set_opt_flag(ctl->opt_underline);
605 ctl->opt_un_on = parse_switch(optarg, _("argument error"),
606 "on", "off", NULL);
607 break;
608 case OPT_STORE:
609 ctl->opt_store = set_opt_flag(ctl->opt_store);
610 break;
611 case OPT_CLEAR:
612 ctl->opt_clear = set_opt_flag(ctl->opt_clear);
613 ctl->opt_cl_all = parse_switch(optarg, _("argument error"),
614 "all", "reset", NULL);
615 break;
616 case OPT_TABS:
617 ctl->opt_tabs = set_opt_flag(ctl->opt_tabs);
618 parse_tabs(av, optarg, &optind, ctl->opt_tb_array);
619 break;
620 case OPT_CLRTABS:
621 ctl->opt_clrtabs = set_opt_flag(ctl->opt_clrtabs);
622 parse_tabs(av, optarg, &optind, ctl->opt_tb_array);
623 break;
624 case OPT_REGTABS:
625 ctl->opt_regtabs = set_opt_flag(ctl->opt_regtabs);
626 ctl->opt_rt_len = parse_regtabs(av, optarg, &optind);
627 break;
628 case OPT_BLANK:
629 ctl->opt_blank = set_opt_flag(ctl->opt_blank);
630 ctl->opt_bl_min = parse_blank(av, optarg, &optind);
631 break;
632 case OPT_DUMP:
633 ctl->opt_snap = set_opt_flag(ctl->opt_snap);
634 ctl->opt_sn_num = parse_snap(av, optarg, &optind);
635 break;
636 case OPT_APPEND:
637 ctl->opt_append = set_opt_flag(ctl->opt_append);
638 ctl->opt_sn_num = parse_snap(av, optarg, &optind);
639 break;
640 case OPT_FILE:
641 ctl->opt_snapfile = set_opt_flag(ctl->opt_snapfile);
642 ctl->opt_sn_name = optarg;
643 break;
644 case OPT_MSG:
645 ctl->opt_msg = set_opt_flag(ctl->opt_msg);
646 ctl->opt_msg_on = parse_switch(optarg, _("argument error"),
647 "on", "off", NULL);
648 break;
649 case OPT_MSGLEVEL:
650 ctl->opt_msglevel = set_opt_flag(ctl->opt_msglevel);
651 ctl->opt_msglevel_num = parse_msglevel(optarg);
652 if (ctl->opt_msglevel_num == 0) {
653 ctl->opt_msg = set_opt_flag(ctl->opt_msg);
654 ctl->opt_msg_on |= 1;
655 }
656 break;
657 case OPT_POWERSAVE:
658 ctl->opt_powersave = set_opt_flag(ctl->opt_powersave);
659 ctl->opt_ps_mode = parse_powersave(optarg);
660 break;
661 case OPT_POWERDOWN:
662 ctl->opt_powerdown = set_opt_flag(ctl->opt_powerdown);
663 ctl->opt_pd_min = parse_blank(av, optarg, &optind);
664 break;
665 case OPT_BLENGTH:
666 ctl->opt_blength = set_opt_flag(ctl->opt_blength);
667 ctl->opt_blength_l = parse_blength(av, optarg, &optind);
668 break;
669 case OPT_BFREQ:
670 ctl->opt_bfreq = set_opt_flag(ctl->opt_bfreq);
671 ctl->opt_bfreq_f = parse_bfreq(av, optarg, &optind);
672 break;
673 case OPT_VERSION:
674 printf(UTIL_LINUX_VERSION);
675 exit(EXIT_SUCCESS);
676 case OPT_HELP:
677 usage();
678 default:
679 errtryhelp(EXIT_FAILURE);
680 }
681 }
682 }
683
684 /* Return the specified terminfo string, or an empty string if no such
685 * terminfo capability exists. */
686 static char *ti_entry(const char *name)
687 {
688 char *buf_ptr;
689
690 if ((buf_ptr = tigetstr(name)) == (char *)-1)
691 buf_ptr = NULL;
692 return buf_ptr;
693 }
694
695 static void show_tabs(void)
696 {
697 int i, co = tigetnum("cols");
698
699 if (co > 0) {
700 printf("\r ");
701 for (i = 10; i < co - 2; i += 10)
702 printf("%-10d", i);
703 putchar('\n');
704 for (i = 1; i <= co; i++)
705 putchar(i % 10 + '0');
706 putchar('\n');
707 for (i = 1; i < co; i++)
708 printf("\tT\b");
709 putchar('\n');
710 }
711 }
712
713 static int open_snapshot_device(struct setterm_control *ctl)
714 {
715 int fd;
716
717 if (ctl->opt_sn_num)
718 xasprintf(&ctl->in_device, "/dev/vcsa%d", ctl->opt_sn_num);
719 else
720 xasprintf(&ctl->in_device, "/dev/vcsa");
721 fd = open(ctl->in_device, O_RDONLY);
722 if (fd < 0)
723 err(EXIT_DUMPFILE, _("cannot read %s"), ctl->in_device);
724 return fd;
725 }
726
727 static void set_blanking(struct setterm_control *ctl)
728 {
729 char ioctlarg;
730 int ret;
731
732 if (0 <= ctl->opt_bl_min) {
733 printf("\033[9;%d]", ctl->opt_bl_min);
734 return;
735 }
736 switch (ctl->opt_bl_min) {
737 case BLANKSCREEN:
738 ioctlarg = TIOCL_BLANKSCREEN;
739 if (ioctl(STDIN_FILENO, TIOCLINUX, &ioctlarg))
740 warn(_("cannot force blank"));
741 break;
742 case UNBLANKSCREEN:
743 ioctlarg = TIOCL_UNBLANKSCREEN;
744 if (ioctl(STDIN_FILENO, TIOCLINUX, &ioctlarg))
745 warn(_("cannot force unblank"));
746 break;
747 case BLANKEDSCREEN:
748 ioctlarg = TIOCL_BLANKEDSCREEN;
749 ret = ioctl(STDIN_FILENO, TIOCLINUX, &ioctlarg);
750 if (ret < 0)
751 warn(_("cannot get blank status"));
752 else
753 printf("%d\n", ret);
754 break;
755 default: /* should be impossible to reach */
756 abort();
757 }
758 return;
759 }
760
761 static void screendump(struct setterm_control *ctl)
762 {
763 unsigned char header[4];
764 unsigned int rows, cols;
765 int fd;
766 FILE *out;
767 size_t i, j;
768 ssize_t rc;
769 char *inbuf, *outbuf, *p, *q;
770
771 /* open source and destination files */
772 fd = open_snapshot_device(ctl);
773 if (!ctl->opt_sn_name)
774 ctl->opt_sn_name = "screen.dump";
775 out = fopen(ctl->opt_sn_name, ctl->opt_snap ? "w" : "a");
776 if (!out)
777 err(EXIT_DUMPFILE, _("cannot open dump file %s for output"), ctl->opt_sn_name);
778 /* determine snapshot size */
779 if (read(fd, header, 4) != 4)
780 err(EXIT_DUMPFILE, _("cannot read %s"), ctl->in_device);
781 rows = header[0];
782 cols = header[1];
783 if (rows * cols == 0)
784 err(EXIT_DUMPFILE, _("cannot read %s"), ctl->in_device);
785 /* allocate buffers */
786 inbuf = xmalloc(rows * cols * 2);
787 outbuf = xmalloc(rows * (cols + 1));
788 /* read input */
789 rc = read(fd, inbuf, rows * cols * 2);
790 if (rc < 0 || (size_t)rc != rows * cols * 2)
791 err(EXIT_DUMPFILE, _("cannot read %s"), ctl->in_device);
792 p = inbuf;
793 q = outbuf;
794 /* copy inbuf to outbuf */
795 for (i = 0; i < rows; i++) {
796 for (j = 0; j < cols; j++) {
797 *q++ = *p;
798 p += 2;
799 }
800 while (j-- > 0 && q[-1] == ' ')
801 q--;
802 *q++ = '\n';
803 }
804 fwrite(outbuf, 1, q - outbuf, out);
805 /* clean up allocations */
806 close(fd);
807 free(inbuf);
808 free(outbuf);
809 free(ctl->in_device);
810 if (close_stream(out) != 0)
811 errx(EXIT_FAILURE, _("write error"));
812 return;
813 }
814
815 /* Some options are applicable when terminal is virtual console. */
816 static int vc_only(struct setterm_control *ctl, const char *err)
817 {
818 if (!ctl->vcterm && err)
819 warnx(_("terminal %s does not support %s"),
820 ctl->opt_te_terminal_name, err);
821 return ctl->vcterm;
822 }
823
824 static void tty_raw(struct termios *saved_attributes, int *saved_fl)
825 {
826 struct termios tattr;
827
828 fcntl(STDIN_FILENO, F_GETFL, saved_fl);
829 tcgetattr(STDIN_FILENO, saved_attributes);
830 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
831 memcpy(&tattr, saved_attributes, sizeof(struct termios));
832 tattr.c_lflag &= ~(ICANON | ECHO);
833 tattr.c_cc[VMIN] = 1;
834 tattr.c_cc[VTIME] = 0;
835 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tattr);
836 }
837
838 static void tty_restore(struct termios *saved_attributes, int *saved_fl)
839 {
840 fcntl(STDIN_FILENO, F_SETFL, *saved_fl);
841 tcsetattr(STDIN_FILENO, TCSANOW, saved_attributes);
842 }
843
844 static int select_wait(void)
845 {
846 struct timeval tv;
847 fd_set set;
848 int ret;
849
850 FD_ZERO(&set);
851 FD_SET(STDIN_FILENO, &set);
852 tv.tv_sec = 10;
853 tv.tv_usec = 0;
854 while ((ret = select(1, &set, NULL, NULL, &tv)) < 0) {
855 if (errno == EINTR)
856 continue;
857 err(EXIT_FAILURE, _("select failed"));
858 }
859 return ret;
860 }
861
862 static int resizetty(void)
863 {
864 /*
865 * \e7 Save current state (cursor coordinates, attributes,
866 * character sets pointed at by G0, G1).
867 * \e[r Set scrolling region; parameters are top and bottom row.
868 * \e[32766E Move cursor down 32766 (INT16_MAX - 1) rows.
869 * \e[32766C Move cursor right 32766 columns.
870 * \e[6n Report cursor position.
871 * \e8 Restore state most recently saved by \e7.
872 */
873 static const char *getpos = "\e7\e[r\e[32766E\e[32766C\e[6n\e8";
874 char retstr[32];
875 int row, col;
876 size_t pos;
877 ssize_t rc;
878 struct winsize ws;
879 struct termios saved_attributes;
880 int saved_fl;
881
882 if (!isatty(STDIN_FILENO))
883 errx(EXIT_FAILURE, _("stdin does not refer to a terminal"));
884
885 tty_raw(&saved_attributes, &saved_fl);
886 if (write_all(STDIN_FILENO, getpos, strlen(getpos)) < 0) {
887 warn(_("write failed"));
888 tty_restore(&saved_attributes, &saved_fl);
889 return 1;
890 }
891 for (pos = 0; pos < sizeof(retstr) - 1;) {
892 if (0 == select_wait())
893 break;
894 if ((rc =
895 read(STDIN_FILENO, retstr + pos,
896 sizeof(retstr) - 1 - pos)) < 0) {
897 if (errno == EINTR)
898 continue;
899 warn(_("read failed"));
900 tty_restore(&saved_attributes, &saved_fl);
901 return 1;
902 }
903 pos += rc;
904 if (retstr[pos - 1] == 'R')
905 break;
906 }
907 retstr[pos] = 0;
908 tty_restore(&saved_attributes, &saved_fl);
909 rc = sscanf(retstr, "\033[%d;%dR", &row, &col);
910 if (rc != 2) {
911 warnx(_("invalid cursor position: %s"), retstr);
912 return 1;
913 }
914 memset(&ws, 0, sizeof(struct winsize));
915 ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
916 ws.ws_row = row;
917 ws.ws_col = col;
918 ioctl(STDIN_FILENO, TIOCSWINSZ, &ws);
919 return 0;
920 }
921
922 static void perform_sequence(struct setterm_control *ctl)
923 {
924 int result;
925
926 /* -reset. */
927 if (ctl->opt_reset)
928 putp(ti_entry("rs1"));
929
930 /* -resize. */
931 if (ctl->opt_resize)
932 if (resizetty())
933 warnx(_("reset failed"));
934
935 /* -initialize. */
936 if (ctl->opt_initialize)
937 putp(ti_entry("is2"));
938
939 /* -cursor [on|off]. */
940 if (ctl->opt_cursor) {
941 if (ctl->opt_cu_on)
942 putp(ti_entry("cnorm"));
943 else
944 putp(ti_entry("civis"));
945 }
946
947 /* -linewrap [on|off]. */
948 if (ctl->opt_linewrap)
949 fputs(ctl->opt_li_on ? "\033[?7h" : "\033[?7l", stdout);
950
951 /* -repeat [on|off]. */
952 if (ctl->opt_repeat && vc_only(ctl, "--repeat"))
953 fputs(ctl->opt_rep_on ? "\033[?8h" : "\033[?8l", stdout);
954
955 /* -appcursorkeys [on|off]. */
956 if (ctl->opt_appcursorkeys && vc_only(ctl, "--appcursorkeys"))
957 fputs(ctl->opt_appck_on ? "\033[?1h" : "\033[?1l", stdout);
958
959 /* -default. Vc sets default rendition, otherwise clears all
960 * attributes. */
961 if (ctl->opt_default) {
962 if (vc_only(ctl, NULL))
963 printf("\033[0m");
964 else
965 putp(ti_entry("sgr0"));
966 }
967
968 /* -foreground black|red|green|yellow|blue|magenta|cyan|white|default. */
969 if (ctl->opt_foreground)
970 printf("\033[3%c%s", '0' + ctl->opt_fo_color, "m");
971
972 /* -background black|red|green|yellow|blue|magenta|cyan|white|default. */
973 if (ctl->opt_background)
974 printf("\033[4%c%s", '0' + ctl->opt_ba_color, "m");
975
976 /* -ulcolor black|red|green|yellow|blue|magenta|cyan|white|default. */
977 if (ctl->opt_ulcolor && vc_only(ctl, "--ulcolor"))
978 printf("\033[1;%d]", ctl->opt_ul_color);
979
980 /* -hbcolor black|red|green|yellow|blue|magenta|cyan|white|default. */
981 if (ctl->opt_hbcolor)
982 printf("\033[2;%d]", ctl->opt_hb_color);
983
984 /* -inversescreen [on|off]. */
985 if (ctl->opt_inversescreen)
986 fputs(ctl->opt_invsc_on ? "\033[?5h" : "\033[?5l", stdout);
987
988 /* -bold [on|off]. Vc behaves as expected, otherwise off turns off
989 * all attributes. */
990 if (ctl->opt_bold) {
991 if (ctl->opt_bo_on)
992 putp(ti_entry("bold"));
993 else {
994 if (vc_only(ctl, NULL))
995 fputs("\033[22m", stdout);
996 else
997 putp(ti_entry("sgr0"));
998 }
999 }
1000
1001 /* -half-bright [on|off]. Vc behaves as expected, otherwise off
1002 * turns off all attributes. */
1003 if (ctl->opt_halfbright) {
1004 if (ctl->opt_hb_on)
1005 putp(ti_entry("dim"));
1006 else {
1007 if (vc_only(ctl, NULL))
1008 fputs("\033[22m", stdout);
1009 else
1010 putp(ti_entry("sgr0"));
1011 }
1012 }
1013
1014 /* -blink [on|off]. Vc behaves as expected, otherwise off turns off
1015 * all attributes. */
1016 if (ctl->opt_blink) {
1017 if (ctl->opt_bl_on)
1018 putp(ti_entry("blink"));
1019 else {
1020 if (vc_only(ctl, NULL))
1021 fputs("\033[25m", stdout);
1022 else
1023 putp(ti_entry("sgr0"));
1024 }
1025 }
1026
1027 /* -reverse [on|off]. Vc behaves as expected, otherwise off turns
1028 * off all attributes. */
1029 if (ctl->opt_reverse) {
1030 if (ctl->opt_re_on)
1031 putp(ti_entry("rev"));
1032 else {
1033 if (vc_only(ctl, NULL))
1034 fputs("\033[27m", stdout);
1035 else
1036 putp(ti_entry("sgr0"));
1037 }
1038 }
1039
1040 /* -underline [on|off]. */
1041 if (ctl->opt_underline)
1042 putp(ti_entry(ctl->opt_un_on ? "smul" : "rmul"));
1043
1044 /* -store. */
1045 if (ctl->opt_store && vc_only(ctl, "--store"))
1046 fputs("\033[8]", stdout);
1047
1048 /* -clear [all|rest]. */
1049 if (ctl->opt_clear)
1050 putp(ti_entry(ctl->opt_cl_all ? "clear" : "ed"));
1051
1052 /* -tabs. */
1053 if (ctl->opt_tabs) {
1054 if (ctl->opt_tb_array[0] == -1)
1055 show_tabs();
1056 else {
1057 int i;
1058
1059 for (i = 0; ctl->opt_tb_array[i] > 0; i++)
1060 printf("\033[%dG\033H", ctl->opt_tb_array[i]);
1061 putchar('\r');
1062 }
1063 }
1064
1065 /* -clrtabs. */
1066 if (ctl->opt_clrtabs && vc_only(ctl, "--clrtabs")) {
1067 int i;
1068
1069 if (ctl->opt_tb_array[0] == -1)
1070 fputs("\033[3g", stdout);
1071 else
1072 for (i = 0; ctl->opt_tb_array[i] > 0; i++)
1073 printf("\033[%dG\033[g", ctl->opt_tb_array[i]);
1074 putchar('\r');
1075 }
1076
1077 /* -regtabs. */
1078 if (ctl->opt_regtabs && vc_only(ctl, "--regtabs")) {
1079 int i;
1080
1081 fputs("\033[3g\r", stdout);
1082 for (i = ctl->opt_rt_len + 1; i <= TABS_MAX; i += ctl->opt_rt_len)
1083 printf("\033[%dC\033H", ctl->opt_rt_len);
1084 putchar('\r');
1085 }
1086
1087 /* -blank [0-60]. */
1088 if (ctl->opt_blank && vc_only(ctl, "--blank"))
1089 set_blanking(ctl);
1090
1091 /* -powersave [on|vsync|hsync|powerdown|off] (console) */
1092 if (ctl->opt_powersave) {
1093 char ioctlarg[2];
1094 ioctlarg[0] = TIOCL_SETVESABLANK;
1095 ioctlarg[1] = ctl->opt_ps_mode;
1096 if (ioctl(STDIN_FILENO, TIOCLINUX, ioctlarg))
1097 warn(_("cannot (un)set powersave mode"));
1098 }
1099
1100 /* -powerdown [0-60]. */
1101 if (ctl->opt_powerdown)
1102 printf("\033[14;%d]", ctl->opt_pd_min);
1103
1104 /* -snap [1-NR_CONS]. */
1105 if (ctl->opt_snap || ctl->opt_append)
1106 screendump(ctl);
1107
1108 /* -msg [on|off]. Controls printk's to console. */
1109 if (ctl->opt_msg && vc_only(ctl, "--msg")) {
1110 if (ctl->opt_msg_on)
1111 result = klogctl(SYSLOG_ACTION_CONSOLE_ON, NULL, 0);
1112 else
1113 result = klogctl(SYSLOG_ACTION_CONSOLE_OFF, NULL, 0);
1114
1115 if (result != 0)
1116 warn(_("klogctl error"));
1117 }
1118
1119 /* -msglevel [0-8]. Console printk message level. */
1120 if (ctl->opt_msglevel_num && vc_only(ctl, "--msglevel")) {
1121 result =
1122 klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL,
1123 ctl->opt_msglevel_num);
1124 if (result != 0)
1125 warn(_("klogctl error"));
1126 }
1127
1128 /* -blength [0-2000] */
1129 if (ctl->opt_blength && vc_only(ctl, "--blength")) {
1130 printf("\033[11;%d]", ctl->opt_blength_l);
1131 }
1132
1133 /* -bfreq freqnumber */
1134 if (ctl->opt_bfreq && vc_only(ctl, "--bfreq")) {
1135 printf("\033[10;%d]", ctl->opt_bfreq_f);
1136 }
1137 }
1138
1139 static void init_terminal(struct setterm_control *ctl)
1140 {
1141 int term_errno;
1142
1143 if (!ctl->opt_te_terminal_name) {
1144 ctl->opt_te_terminal_name = getenv("TERM");
1145 if (ctl->opt_te_terminal_name == NULL)
1146 errx(EXIT_FAILURE, _("$TERM is not defined."));
1147 }
1148
1149 /* Find terminfo entry. */
1150 if (setupterm(ctl->opt_te_terminal_name, STDOUT_FILENO, &term_errno))
1151 switch (term_errno) {
1152 case -1:
1153 errx(EXIT_FAILURE, _("terminfo database cannot be found"));
1154 case 0:
1155 errx(EXIT_FAILURE, _("%s: unknown terminal type"), ctl->opt_te_terminal_name);
1156 case 1:
1157 errx(EXIT_FAILURE, _("terminal is hardcopy"));
1158 }
1159
1160 /* See if the terminal is a virtual console terminal. */
1161 ctl->vcterm = (!strncmp(ctl->opt_te_terminal_name, "con", 3) ||
1162 !strncmp(ctl->opt_te_terminal_name, "linux", 5));
1163 }
1164
1165
1166 int main(int argc, char **argv)
1167 {
1168 struct setterm_control ctl = { NULL };
1169
1170 setlocale(LC_ALL, "");
1171 bindtextdomain(PACKAGE, LOCALEDIR);
1172 textdomain(PACKAGE);
1173 atexit(close_stdout);
1174
1175 if (argc < 2) {
1176 warnx(_("bad usage"));
1177 errtryhelp(EXIT_FAILURE);
1178 }
1179 parse_option(&ctl, argc, argv);
1180 init_terminal(&ctl);
1181 perform_sequence(&ctl);
1182
1183 return EXIT_SUCCESS;
1184 }