1 /****************************************************************************
2 * Copyright 2018-2024,2025 Thomas E. Dickey *
3 * Copyright 1998-2016,2017 Free Software Foundation, Inc. *
4 * *
5 * Permission is hereby granted, free of charge, to any person obtaining a *
6 * copy of this software and associated documentation files (the *
7 * "Software"), to deal in the Software without restriction, including *
8 * without limitation the rights to use, copy, modify, merge, publish, *
9 * distribute, distribute with modifications, sublicense, and/or sell *
10 * copies of the Software, and to permit persons to whom the Software is *
11 * furnished to do so, subject to the following conditions: *
12 * *
13 * The above copyright notice and this permission notice shall be included *
14 * in all copies or substantial portions of the Software. *
15 * *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
19 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
20 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
21 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
22 * THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
23 * *
24 * Except as contained in this notice, the name(s) of the above copyright *
25 * holders shall not be used in advertising or otherwise to promote the *
26 * sale, use or other dealings in this Software without prior written *
27 * authorization. *
28 ****************************************************************************/
29
30 /****************************************************************************
31 * Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
32 * and: Eric S. Raymond <esr@snark.thyrsus.com> *
33 * and: Thomas E. Dickey 1996-on *
34 ****************************************************************************/
35
36 /*
37 * tput.c -- shellscript access to terminal capabilities
38 *
39 * by Eric S. Raymond <esr@snark.thyrsus.com>, portions based on code from
40 * Ross Ridge's mytinfo package.
41 */
42
43 #include <tparm_type.h>
44 #include <clear_cmd.h>
45 #include <reset_cmd.h>
46
47 #include <transform.h>
48 #include <tty_settings.h>
49
50 MODULE_ID("$Id: tput.c,v 1.110 2025/01/12 00:36:15 tom Exp $")
51
52 #define PUTS(s) fputs(s, stdout)
53
54 const char *_nc_progname = "tput";
55
56 static bool opt_v = FALSE; /* quiet, do not show warnings */
57 static bool opt_x = FALSE; /* clear scrollback if possible */
58
59 static bool is_init = FALSE;
60 static bool is_reset = FALSE;
61 static bool is_clear = FALSE;
62
63 static GCC_NORETURN void
quit(int status,const char * fmt,...)64 quit(int status, const char *fmt, ...)
65 {
66 va_list argp;
67
68 va_start(argp, fmt);
69 fprintf(stderr, "%s: ", _nc_progname);
70 vfprintf(stderr, fmt, argp);
71 fprintf(stderr, "\n");
72 va_end(argp);
73 ExitProgram(status);
74 }
75
76 static GCC_NORETURN void
usage(const char * optstring)77 usage(const char *optstring)
78 {
79 #define KEEP(s) s "\n"
80 static const char msg[] =
81 {
82 KEEP("")
83 KEEP("Options:")
84 KEEP(" -S << read commands from standard input")
85 KEEP(" -T TERM use this instead of $TERM")
86 KEEP(" -V print curses-version")
87 KEEP(" -v verbose, show warnings")
88 KEEP(" -x do not try to clear scrollback")
89 KEEP("")
90 KEEP("Commands:")
91 KEEP(" clear clear the screen")
92 KEEP(" init initialize the terminal")
93 KEEP(" reset reinitialize the terminal")
94 KEEP(" capname unlike clear/init/reset, print value for capability \"capname\"")
95 };
96 #undef KEEP
97 (void) fprintf(stderr, "Usage: %s [options] [command]\n", _nc_progname);
98 if (optstring != NULL) {
99 const char *s = msg;
100 while (*s != '\0') {
101 fputc(UChar(*s), stderr);
102 if (!strncmp(s, " -", 3)) {
103 if (strchr(optstring, s[3]) == NULL)
104 s = strchr(s, '\n') + 1;
105 } else if (!strncmp(s, "\n\nC", 3))
106 break;
107 ++s;
108 }
109 } else {
110 fputs(msg, stderr);
111 }
112 ExitProgram(ErrUsage);
113 }
114
115 static char *
check_aliases(char * name,bool program)116 check_aliases(char *name, bool program)
117 {
118 static char my_init[] = "init";
119 static char my_reset[] = "reset";
120 static char my_clear[] = "clear";
121
122 char *result = name;
123 if ((is_init = same_program(name, program ? PROG_INIT : my_init)) == TRUE)
124 result = my_init;
125 if ((is_reset = same_program(name, program ? PROG_RESET : my_reset)) == TRUE)
126 result = my_reset;
127 if ((is_clear = same_program(name, program ? PROG_CLEAR : my_clear)) == TRUE)
128 result = my_clear;
129 return result;
130 }
131
132 static int
exit_code(int token,int value)133 exit_code(int token, int value)
134 {
135 int result = 99;
136
137 switch (token) {
138 case BOOLEAN:
139 result = !value; /* TRUE=0, FALSE=1 */
140 break;
141 case NUMBER:
142 result = 0; /* always zero */
143 break;
144 case STRING:
145 result = value; /* 0=normal, 1=missing */
146 break;
147 }
148 return result;
149 }
150
151 /*
152 * Returns nonzero on error.
153 */
154 static int
tput_cmd(int fd,TTY * settings,int argc,char ** argv,int * used)155 tput_cmd(int fd, TTY * settings, int argc, char **argv, int *used)
156 {
157 NCURSES_CONST char *name;
158 char *s;
159 int status;
160 #if !PURE_TERMINFO
161 bool termcap = FALSE;
162 #endif
163
164 name = check_aliases(argv[0], FALSE);
165 *used = 1;
166 if (is_reset || is_init) {
167 TTY oldmode = *settings;
168
169 int terasechar = -1; /* new erase character */
170 int intrchar = -1; /* new interrupt character */
171 int tkillchar = -1; /* new kill character */
172
173 if (is_reset) {
174 reset_start(stdout, TRUE, FALSE);
175 reset_tty_settings(fd, settings, FALSE);
176 } else {
177 reset_start(stdout, FALSE, TRUE);
178 }
179
180 #if HAVE_SIZECHANGE
181 {
182 NCURSES_INT2 my_rows = lines;
183 NCURSES_INT2 my_cols = columns;
184 set_window_size(fd, &my_rows, &my_cols);
185 lines = (short) my_rows;
186 columns = (short) my_cols;
187 }
188 #else
189 (void) fd;
190 #endif
191 set_control_chars(settings, terasechar, intrchar, tkillchar);
192 set_conversions(settings);
193
194 if (send_init_strings(fd, &oldmode)) {
195 reset_flush();
196 }
197
198 update_tty_settings(&oldmode, settings);
199 return 0;
200 }
201
202 if (strcmp(name, "longname") == 0) {
203 PUTS(longname());
204 return 0;
205 }
206 #if !PURE_TERMINFO
207 retry:
208 #endif
209 if (strcmp(name, "clear") == 0) {
210 return (clear_cmd(opt_x) == ERR) ? ErrUsage : 0;
211 } else if ((status = tigetflag(name)) != -1) {
212 return exit_code(BOOLEAN, status);
213 } else if ((status = tigetnum(name)) != CANCELLED_NUMERIC) {
214 (void) printf("%d\n", status);
215 return exit_code(NUMBER, 0);
216 } else if ((s = tigetstr(name)) == CANCELLED_STRING) {
217 #if !PURE_TERMINFO
218 if (!termcap) {
219 const struct name_table_entry *np;
220
221 termcap = TRUE;
222 if ((np = _nc_find_entry(name, _nc_get_hash_table(termcap))) != NULL) {
223 switch (np->nte_type) {
224 case BOOLEAN:
225 name = boolnames[np->nte_index];
226 break;
227
228 case NUMBER:
229 name = numnames[np->nte_index];
230 break;
231
232 case STRING:
233 name = strnames[np->nte_index];
234 break;
235 }
236 goto retry;
237 }
238 }
239 #endif
240 quit(ErrCapName, "unknown terminfo capability '%s'", name);
241 } else if (VALID_STRING(s)) {
242 TParams paramType;
243 long numbers[1 + NUM_PARM];
244 char *strings[1 + NUM_PARM];
245 char *p_is_s[NUM_PARM];
246 int k;
247 int narg;
248 int analyzed = 0;
249 int provided = 0;
250 int popcount = 0;
251
252 paramType = tparm_type(name);
253 #if NCURSES_XNAMES
254 /*
255 * If the capability is an extended one, analyze the string.
256 */
257 if (paramType == Numbers) {
258 struct name_table_entry const *entry_ptr;
259 entry_ptr = _nc_find_type_entry(name, STRING, FALSE);
260 if (entry_ptr == NULL) {
261 paramType = Other;
262 }
263 }
264 #endif
265 /* Nasty hack time. The tparm function needs to see numeric parameters
266 * as numbers, not as pointers to their string representations
267 */
268 for (k = 1; (k < argc) && (k <= NUM_PARM); k++) {
269 char *tmp = NULL;
270 strings[k] = argv[k];
271 numbers[k] = strtol(argv[k], &tmp, 0);
272 if (tmp == NULL || *tmp != 0)
273 numbers[k] = 0;
274 }
275 for (k = argc; k <= NUM_PARM; k++) {
276 numbers[k] = 0;
277 strings[k] = NULL;
278 }
279
280 switch (paramType) {
281 case Str:
282 analyzed = 1;
283 break;
284 case Str_Str:
285 analyzed = 2;
286 break;
287 case Num_Str:
288 analyzed = 2;
289 break;
290 case Num_Str_Str:
291 analyzed = 3;
292 break;
293 case Numbers:
294 case Other:
295 analyzed = _nc_tparm_analyze(NULL, s, p_is_s, &popcount);
296 break;
297 }
298 if (analyzed < popcount) {
299 analyzed = popcount;
300 }
301
302 if (argc > 1) {
303 _nc_reset_tparm(NULL);
304 /*
305 * Count the number of numeric parameters which are provided.
306 */
307 for (narg = 1; narg < argc; ++narg) {
308 char *ending = NULL;
309 long check = strtol(argv[narg], &ending, 0);
310 if (check < 0 || ending == argv[narg] || *ending != '\0')
311 break;
312 provided = narg;
313 }
314 switch (paramType) {
315 case Str:
316 s = TPARM_1(s, strings[1]);
317 if (provided == 0 && argc >= 1)
318 provided++;
319 break;
320 case Str_Str:
321 s = TPARM_2(s, strings[1], strings[2]);
322 if (provided == 0 && argc >= 1)
323 provided++;
324 if (provided == 1 && argc >= 2)
325 provided++;
326 break;
327 case Num_Str:
328 s = TPARM_2(s, numbers[1], strings[2]);
329 if (provided == 1 && argc >= 2)
330 provided++;
331 break;
332 case Num_Str_Str:
333 s = TPARM_3(s, numbers[1], strings[2], strings[3]);
334 if (provided == 1 && argc >= 2)
335 provided++;
336 if (provided == 2 && argc >= 3)
337 provided++;
338 break;
339 case Numbers:
340 #define myParam(n) numbers[n]
341 s = TIPARM_N(analyzed, s,
342 myParam(1),
343 myParam(2),
344 myParam(3),
345 myParam(4),
346 myParam(5),
347 myParam(6),
348 myParam(7),
349 myParam(8),
350 myParam(9));
351 #undef myParam
352 break;
353 case Other:
354 /* FALLTHRU */
355 default:
356 #define myParam(n) (p_is_s[n - 1] != NULL ? ((TPARM_ARG) strings[n]) : numbers[n])
357 s = TIPARM_N(analyzed, s,
358 myParam(1),
359 myParam(2),
360 myParam(3),
361 myParam(4),
362 myParam(5),
363 myParam(6),
364 myParam(7),
365 myParam(8),
366 myParam(9));
367 #undef myParam
368 break;
369 }
370 if (opt_v && (analyzed != provided)) {
371 fprintf(stderr, "%s: %s parameters for \"%s\"\n",
372 _nc_progname,
373 (analyzed < provided ? "extra" : "missing"),
374 argv[0]);
375 }
376 *used += provided;
377 } else {
378 if (opt_v) {
379 fprintf(stderr, "%s: missing parameters for \"%s\"\n",
380 _nc_progname,
381 argv[0]);
382 }
383 }
384
385 /* use putp() in order to perform padding */
386 putp(s);
387 return exit_code(STRING, 0);
388 }
389 return exit_code(STRING, 1);
390 }
391
392 int
main(int argc,char ** argv)393 main(int argc, char **argv)
394 {
395 char *term;
396 int errret;
397 bool cmdline = TRUE;
398 int c;
399 char buf[BUFSIZ];
400 int result = 0;
401 int fd;
402 int used;
403 TTY old_settings;
404 TTY tty_settings;
405 bool is_alias;
406 bool need_tty;
407
408 _nc_progname = check_aliases(_nc_rootname(argv[0]), TRUE);
409 is_alias = (is_clear || is_reset || is_init);
410
411 term = getenv("TERM");
412
413 while ((c = getopt(argc, argv, is_alias ? "T:Vvx" : "ST:Vvx")) != -1) {
414 switch (c) {
415 case 'S':
416 cmdline = FALSE;
417 break;
418 case 'T':
419 use_env(FALSE);
420 use_tioctl(TRUE);
421 term = optarg;
422 break;
423 case 'V':
424 puts(curses_version());
425 ExitProgram(EXIT_SUCCESS);
426 case 'v': /* verbose */
427 opt_v = TRUE;
428 break;
429 case 'x': /* do not try to clear scrollback */
430 opt_x = TRUE;
431 break;
432 default:
433 usage(is_alias ? "TVx" : NULL);
434 /* NOTREACHED */
435 }
436 }
437
438 need_tty = ((is_reset || is_init) ||
439 (optind < argc &&
440 (!strcmp(argv[optind], "reset") ||
441 !strcmp(argv[optind], "init"))));
442
443 /*
444 * Modify the argument list to omit the options we processed.
445 */
446 if (is_alias) {
447 if (optind-- < argc) {
448 argc -= optind;
449 argv += optind;
450 }
451 argv[0] = strdup(_nc_progname);
452 } else {
453 argc -= optind;
454 argv += optind;
455 }
456
457 if (term == NULL || *term == '\0')
458 quit(ErrUsage, "No value for $TERM and no -T specified");
459
460 fd = save_tty_settings(&tty_settings, need_tty);
461 old_settings = tty_settings;
462
463 if (setupterm(term, fd, &errret) != OK && errret <= 0)
464 quit(ErrTermType, "unknown terminal \"%s\"", term);
465
466 if (cmdline) {
467 int code = 0;
468 if ((argc <= 0) && !is_alias)
469 usage(NULL);
470 while (argc > 0) {
471 tty_settings = old_settings;
472 code = tput_cmd(fd, &tty_settings, argc, argv, &used);
473 if (code != 0)
474 break;
475 argc -= used;
476 argv += used;
477 }
478 ExitProgram(code);
479 }
480
481 while (fgets(buf, sizeof(buf), stdin) != NULL) {
482 size_t need = strlen(buf);
483 char **argvec = typeCalloc(char *, need + 1);
484 char **argnow;
485 int argnum = 0;
486 char *cp;
487
488 if (argvec == NULL) {
489 quit(ErrSystem(1), strerror(errno));
490 }
491
492 /* split the buffer into tokens */
493 for (cp = buf; *cp; cp++) {
494 if (isspace(UChar(*cp))) {
495 *cp = '\0';
496 } else if (cp == buf || cp[-1] == '\0') {
497 argvec[argnum++] = cp;
498 if (argnum >= (int) need)
499 break;
500 }
501 }
502
503 argnow = argvec;
504 while (argnum > 0) {
505 int code;
506 tty_settings = old_settings;
507 code = tput_cmd(fd, &tty_settings, argnum, argnow, &used);
508 if (code != 0) {
509 if (result == 0)
510 result = ErrSystem(0); /* will return value >4 */
511 ++result;
512 }
513 argnum -= used;
514 argnow += used;
515 }
516 free(argvec);
517 }
518
519 ExitProgram(result);
520 }
521