1 /****************************************************************************
2  * Copyright 2018-2019,2020 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  *     and: Juergen Pfeifer                         2009                    *
35  ****************************************************************************/
36 
37 /*
38  * Terminal setup routines common to termcap and terminfo:
39  *
40  *		use_env(bool)
41  *		use_tioctl(bool)
42  *		setupterm(char *, int, int *)
43  */
44 
45 #include <curses.priv.h>
46 #include <tic.h>		/* for MAX_NAME_SIZE */
47 
48 #if HAVE_LOCALE_H
49 #include <locale.h>
50 #endif
51 
52 MODULE_ID("$Id: lib_setup.c,v 1.207 2020/02/02 23:34:34 tom Exp $")
53 
54 /****************************************************************************
55  *
56  * Terminal size computation
57  *
58  ****************************************************************************/
59 
60 #if HAVE_SIZECHANGE
61 # if !defined(sun) || !TERMIOS
62 #  if HAVE_SYS_IOCTL_H
63 #   include <sys/ioctl.h>
64 #  endif
65 # endif
66 #endif
67 
68 #if NEED_PTEM_H
69  /* On SCO, they neglected to define struct winsize in termios.h -- it's only
70   * in termio.h and ptem.h (the former conflicts with other definitions).
71   */
72 # include <sys/stream.h>
73 # include <sys/ptem.h>
74 #endif
75 
76 #if HAVE_LANGINFO_CODESET
77 #include <langinfo.h>
78 #endif
79 
80 /*
81  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
82  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
83  */
84 #ifdef TIOCGSIZE
85 # define IOCTL_WINSIZE TIOCGSIZE
86 # define STRUCT_WINSIZE struct ttysize
87 # define WINSIZE_ROWS(n) (int)n.ts_lines
88 # define WINSIZE_COLS(n) (int)n.ts_cols
89 #else
90 # ifdef TIOCGWINSZ
91 #  define IOCTL_WINSIZE TIOCGWINSZ
92 #  define STRUCT_WINSIZE struct winsize
93 #  define WINSIZE_ROWS(n) (int)n.ws_row
94 #  define WINSIZE_COLS(n) (int)n.ws_col
95 # endif
96 #endif
97 
98 /*
99  * Reduce explicit use of "cur_term" global variable.
100  */
101 #undef CUR
102 #define CUR TerminalType(termp).
103 
104 /*
105  * Wrap global variables in this module.
106  */
107 #if USE_REENTRANT
108 
109 NCURSES_EXPORT(char *)
110 NCURSES_PUBLIC_VAR(ttytype) (void)
111 {
112     static char empty[] = "";
113     char *result = empty;
114 
115 #if NCURSES_SP_FUNCS
116     if (CURRENT_SCREEN) {
117 	TERMINAL *termp = TerminalOf(CURRENT_SCREEN);
118 	if (termp != 0) {
119 	    result = TerminalType(termp).term_names;
120 	}
121     }
122 #else
123     if (cur_term != 0) {
124 	result = TerminalType(cur_term).term_names;
125     }
126 #endif
127     return result;
128 }
129 
130 NCURSES_EXPORT(int *)
131 _nc_ptr_Lines(SCREEN *sp)
132 {
133     return ptrLines(sp);
134 }
135 
136 NCURSES_EXPORT(int)
137 NCURSES_PUBLIC_VAR(LINES) (void)
138 {
139     return *_nc_ptr_Lines(CURRENT_SCREEN);
140 }
141 
142 NCURSES_EXPORT(int *)
143 _nc_ptr_Cols(SCREEN *sp)
144 {
145     return ptrCols(sp);
146 }
147 
148 NCURSES_EXPORT(int)
149 NCURSES_PUBLIC_VAR(COLS) (void)
150 {
151     return *_nc_ptr_Cols(CURRENT_SCREEN);
152 }
153 
154 NCURSES_EXPORT(int *)
155 _nc_ptr_Tabsize(SCREEN *sp)
156 {
157     return ptrTabsize(sp);
158 }
159 
160 NCURSES_EXPORT(int)
161 NCURSES_PUBLIC_VAR(TABSIZE) (void)
162 {
163     return *_nc_ptr_Tabsize(CURRENT_SCREEN);
164 }
165 #else
166 NCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
167 NCURSES_EXPORT_VAR(int) LINES = 0;
168 NCURSES_EXPORT_VAR(int) COLS = 0;
169 NCURSES_EXPORT_VAR(int) TABSIZE = 8;
170 #endif
171 
172 #if NCURSES_EXT_FUNCS
173 NCURSES_EXPORT(int)
174 NCURSES_SP_NAME(set_tabsize) (NCURSES_SP_DCLx int value)
175 {
176     int code = OK;
177     if (value <= 0) {
178 	code = ERR;
179     } else {
180 #if USE_REENTRANT
181 	if (SP_PARM) {
182 	    SP_PARM->_TABSIZE = value;
183 	} else {
184 	    code = ERR;
185 	}
186 #else
187 	(void) SP_PARM;
188 	TABSIZE = value;
189 #endif
190     }
191     return code;
192 }
193 
194 #if NCURSES_SP_FUNCS
195 NCURSES_EXPORT(int)
196 set_tabsize(int value)
197 {
198     return NCURSES_SP_NAME(set_tabsize) (CURRENT_SCREEN, value);
199 }
200 #endif
201 #endif /* NCURSES_EXT_FUNCS */
202 
203 #if USE_SIGWINCH
204 /*
205  * If we have a pending SIGWINCH, set the flag in each screen.
206  */
207 NCURSES_EXPORT(int)
208 _nc_handle_sigwinch(SCREEN *sp)
209 {
210     SCREEN *scan;
211 
212     if (_nc_globals.have_sigwinch) {
213 	_nc_globals.have_sigwinch = 0;
214 
215 	for (each_screen(scan)) {
216 	    scan->_sig_winch = TRUE;
217 	}
218     }
219 
220     return (sp ? sp->_sig_winch : 0);
221 }
222 
223 #endif
224 
225 NCURSES_EXPORT(void)
226 NCURSES_SP_NAME(use_env) (NCURSES_SP_DCLx bool f)
227 {
228     START_TRACE();
229     T((T_CALLED("use_env(%p,%d)"), (void *) SP_PARM, (int) f));
230 #if NCURSES_SP_FUNCS
231     if (IsPreScreen(SP_PARM)) {
232 	SP_PARM->_use_env = f;
233     }
234 #else
235     _nc_prescreen.use_env = f;
236 #endif
237     returnVoid;
238 }
239 
240 NCURSES_EXPORT(void)
241 NCURSES_SP_NAME(use_tioctl) (NCURSES_SP_DCLx bool f)
242 {
243     START_TRACE();
244     T((T_CALLED("use_tioctl(%p,%d)"), (void *) SP_PARM, (int) f));
245 #if NCURSES_SP_FUNCS
246     if (IsPreScreen(SP_PARM)) {
247 	SP_PARM->use_tioctl = f;
248     }
249 #else
250     _nc_prescreen.use_tioctl = f;
251 #endif
252     returnVoid;
253 }
254 
255 #if NCURSES_SP_FUNCS
256 NCURSES_EXPORT(void)
257 use_env(bool f)
258 {
259     START_TRACE();
260     T((T_CALLED("use_env(%d)"), (int) f));
261     _nc_prescreen.use_env = f;
262     returnVoid;
263 }
264 
265 NCURSES_EXPORT(void)
266 use_tioctl(bool f)
267 {
268     START_TRACE();
269     T((T_CALLED("use_tioctl(%d)"), (int) f));
270     _nc_prescreen.use_tioctl = f;
271     returnVoid;
272 }
273 #endif
274 
275 NCURSES_EXPORT(void)
276 _nc_get_screensize(SCREEN *sp,
277 #ifdef USE_TERM_DRIVER
278 		   TERMINAL *termp,
279 #endif
280 		   int *linep, int *colp)
281 /* Obtain lines/columns values from the environment and/or terminfo entry */
282 {
283 #ifdef USE_TERM_DRIVER
284     TERMINAL_CONTROL_BLOCK *TCB;
285     int my_tabsize;
286 
287     assert(termp != 0 && linep != 0 && colp != 0);
288     TCB = (TERMINAL_CONTROL_BLOCK *) termp;
289 
290     my_tabsize = TCB->info.tabsize;
291     TCB->drv->td_size(TCB, linep, colp);
292 
293 #if USE_REENTRANT
294     if (sp != 0) {
295 	sp->_TABSIZE = my_tabsize;
296     }
297 #else
298     (void) sp;
299     TABSIZE = my_tabsize;
300 #endif
301     T(("TABSIZE = %d", my_tabsize));
302 #else /* !USE_TERM_DRIVER */
303     TERMINAL *termp = cur_term;
304     int my_tabsize;
305     bool useEnv = _nc_prescreen.use_env;
306     bool useTioctl = _nc_prescreen.use_tioctl;
307 
308     /* figure out the size of the screen */
309     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
310 
311     *linep = (int) lines;
312     *colp = (int) columns;
313 
314 #if NCURSES_SP_FUNCS
315     if (sp) {
316 	useEnv = sp->_use_env;
317 	useTioctl = sp->use_tioctl;
318     }
319 #endif
320 
321     if (useEnv || useTioctl) {
322 #ifdef __EMX__
323 	{
324 	    int screendata[2];
325 	    _scrsize(screendata);
326 	    *colp = screendata[0];
327 	    *linep = ((sp != 0 && sp->_filtered)
328 		      ? 1
329 		      : screendata[1]);
330 	    T(("EMX screen size: environment LINES = %d COLUMNS = %d",
331 	       *linep, *colp));
332 	}
333 #endif
334 #if HAVE_SIZECHANGE
335 	/* try asking the OS */
336 	if (NC_ISATTY(cur_term->Filedes)) {
337 	    STRUCT_WINSIZE size;
338 
339 	    errno = 0;
340 	    do {
341 		if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) >= 0) {
342 		    *linep = ((sp != 0 && sp->_filtered)
343 			      ? 1
344 			      : WINSIZE_ROWS(size));
345 		    *colp = WINSIZE_COLS(size);
346 		    T(("SYS screen size: environment LINES = %d COLUMNS = %d",
347 		       *linep, *colp));
348 		    break;
349 		}
350 	    } while
351 		(errno == EINTR);
352 	}
353 #endif /* HAVE_SIZECHANGE */
354 
355 	if (useEnv) {
356 	    int value;
357 
358 	    if (useTioctl) {
359 		/*
360 		 * If environment variables are used, update them.
361 		 */
362 		if ((sp == 0 || !sp->_filtered) && _nc_getenv_num("LINES") > 0) {
363 		    _nc_setenv_num("LINES", *linep);
364 		}
365 		if (_nc_getenv_num("COLUMNS") > 0) {
366 		    _nc_setenv_num("COLUMNS", *colp);
367 		}
368 	    }
369 
370 	    /*
371 	     * Finally, look for environment variables.
372 	     *
373 	     * Solaris lets users override either dimension with an environment
374 	     * variable.
375 	     */
376 	    if ((value = _nc_getenv_num("LINES")) > 0) {
377 		*linep = value;
378 		T(("screen size: environment LINES = %d", *linep));
379 	    }
380 	    if ((value = _nc_getenv_num("COLUMNS")) > 0) {
381 		*colp = value;
382 		T(("screen size: environment COLUMNS = %d", *colp));
383 	    }
384 	}
385 
386 	/* if we can't get dynamic info about the size, use static */
387 	if (*linep <= 0) {
388 	    *linep = (int) lines;
389 	}
390 	if (*colp <= 0) {
391 	    *colp = (int) columns;
392 	}
393 
394 	/* the ultimate fallback, assume fixed 24x80 size */
395 	if (*linep <= 0) {
396 	    *linep = 24;
397 	}
398 	if (*colp <= 0) {
399 	    *colp = 80;
400 	}
401 
402 	/*
403 	 * Put the derived values back in the screen-size caps, so
404 	 * tigetnum() and tgetnum() will do the right thing.
405 	 */
406 	lines = (NCURSES_INT2) (*linep);
407 	columns = (NCURSES_INT2) (*colp);
408 #if NCURSES_EXT_NUMBERS
409 #define OldNumber(termp,name) \
410 	(termp)->type.Numbers[(&name - (termp)->type2.Numbers)]
411 	OldNumber(termp, lines) = (short) (*linep);
412 	OldNumber(termp, columns) = (short) (*colp);
413 #endif
414     }
415 
416     T(("screen size is %dx%d", *linep, *colp));
417 
418     if (VALID_NUMERIC(init_tabs))
419 	my_tabsize = (int) init_tabs;
420     else
421 	my_tabsize = 8;
422 
423 #if USE_REENTRANT
424     if (sp != 0)
425 	sp->_TABSIZE = my_tabsize;
426 #else
427     TABSIZE = my_tabsize;
428 #endif
429     T(("TABSIZE = %d", TABSIZE));
430 #endif /* USE_TERM_DRIVER */
431 }
432 
433 #if USE_SIZECHANGE
434 NCURSES_EXPORT(void)
435 _nc_update_screensize(SCREEN *sp)
436 {
437     int new_lines;
438     int new_cols;
439 
440 #ifdef USE_TERM_DRIVER
441     int old_lines;
442     int old_cols;
443 
444     assert(sp != 0);
445 
446     CallDriver_2(sp, td_getsize, &old_lines, &old_cols);
447 
448 #else
449     TERMINAL *termp = cur_term;
450     int old_lines = lines;
451     int old_cols = columns;
452 #endif
453 
454     if (sp != 0) {
455 	TINFO_GET_SIZE(sp, sp->_term, &new_lines, &new_cols);
456 	/*
457 	 * See is_term_resized() and resizeterm().
458 	 * We're doing it this way because those functions belong to the upper
459 	 * ncurses library, while this resides in the lower terminfo library.
460 	 */
461 	if (sp->_resize != 0) {
462 	    if ((new_lines != old_lines) || (new_cols != old_cols)) {
463 		sp->_resize(NCURSES_SP_ARGx new_lines, new_cols);
464 	    } else if (sp->_sig_winch && (sp->_ungetch != 0)) {
465 		sp->_ungetch(SP_PARM, KEY_RESIZE);	/* so application can know this */
466 	    }
467 	    sp->_sig_winch = FALSE;
468 	}
469     }
470 }
471 #endif /* USE_SIZECHANGE */
472 
473 /****************************************************************************
474  *
475  * Terminal setup
476  *
477  ****************************************************************************/
478 
479 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
480 /*
481  * Return 1 if entry found, 0 if not found, -1 if database not accessible,
482  * just like tgetent().
483  */
484 int
485 _nc_setup_tinfo(const char *const tn, TERMTYPE2 *const tp)
486 {
487     char filename[PATH_MAX];
488     int status = _nc_read_entry2(tn, filename, tp);
489 
490     /*
491      * If we have an entry, force all of the cancelled strings to null
492      * pointers so we don't have to test them in the rest of the library.
493      * (The terminfo compiler bypasses this logic, since it must know if
494      * a string is cancelled, for merging entries).
495      */
496     if (status == TGETENT_YES) {
497 	unsigned n;
498 	for_each_boolean(n, tp) {
499 	    if (!VALID_BOOLEAN(tp->Booleans[n]))
500 		tp->Booleans[n] = FALSE;
501 	}
502 	for_each_string(n, tp) {
503 	    if (tp->Strings[n] == CANCELLED_STRING)
504 		tp->Strings[n] = ABSENT_STRING;
505 	}
506     }
507     return (status);
508 }
509 #endif
510 
511 /*
512 **	Take the real command character out of the CC environment variable
513 **	and substitute it in for the prototype given in 'command_character'.
514 */
515 void
516 _nc_tinfo_cmdch(TERMINAL *termp, int proto)
517 {
518     char *tmp;
519 
520     /*
521      * Only use the character if the string is a single character,
522      * since it is fairly common for developers to set the C compiler
523      * name as an environment variable - using the same symbol.
524      */
525     if ((tmp = getenv("CC")) != 0 && strlen(tmp) == 1) {
526 	unsigned i;
527 	char CC = *tmp;
528 
529 	for_each_string(i, &(termp->type)) {
530 	    for (tmp = termp->type.Strings[i]; tmp && *tmp; tmp++) {
531 		if (UChar(*tmp) == proto)
532 		    *tmp = CC;
533 	    }
534 	}
535     }
536 }
537 
538 /*
539  * Find the locale which is in effect.
540  */
541 NCURSES_EXPORT(char *)
542 _nc_get_locale(void)
543 {
544     char *env;
545 #if HAVE_LOCALE_H
546     /*
547      * This is preferable to using getenv() since it ensures that we are using
548      * the locale which was actually initialized by the application.
549      */
550     env = setlocale(LC_CTYPE, 0);
551 #else
552     if (((env = getenv("LANG")) != 0 && *env != '\0')
553 	|| ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
554 	|| ((env = getenv("LC_ALL")) != 0 && *env != '\0')) {
555 	;
556     }
557 #endif
558     T(("_nc_get_locale %s", _nc_visbuf(env)));
559     return env;
560 }
561 
562 /*
563  * Check if we are running in a UTF-8 locale.
564  */
565 NCURSES_EXPORT(int)
566 _nc_unicode_locale(void)
567 {
568     int result = 0;
569 #if defined(_WIN32) && USE_WIDEC_SUPPORT
570     result = 1;
571 #elif HAVE_LANGINFO_CODESET
572     char *env = nl_langinfo(CODESET);
573     result = !strcmp(env, "UTF-8");
574     T(("_nc_unicode_locale(%s) ->%d", env, result));
575 #else
576     char *env = _nc_get_locale();
577     if (env != 0) {
578 	if (strstr(env, ".UTF-8") != 0) {
579 	    result = 1;
580 	    T(("_nc_unicode_locale(%s) ->%d", env, result));
581 	}
582     }
583 #endif
584     return result;
585 }
586 
587 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
588 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
589 
590 /*
591  * Check for known broken cases where a UTF-8 locale breaks the alternate
592  * character set.
593  */
594 NCURSES_EXPORT(int)
595 _nc_locale_breaks_acs(TERMINAL *termp)
596 {
597     const char *env_name = "NCURSES_NO_UTF8_ACS";
598     const char *env;
599     int value;
600     int result = 0;
601 
602     T((T_CALLED("_nc_locale_breaks_acs:%d"), result));
603     if (getenv(env_name) != 0) {
604 	result = _nc_getenv_num(env_name);
605     } else if ((value = tigetnum("U8")) >= 0) {
606 	result = value;		/* use extension feature */
607     } else if ((env = getenv("TERM")) != 0) {
608 	if (strstr(env, "linux")) {
609 	    result = 1;		/* always broken */
610 	} else if (strstr(env, "screen") != 0
611 		   && ((env = getenv("TERMCAP")) != 0
612 		       && strstr(env, "screen") != 0)
613 		   && strstr(env, "hhII00") != 0) {
614 	    if (CONTROL_N(enter_alt_charset_mode) ||
615 		CONTROL_O(enter_alt_charset_mode) ||
616 		CONTROL_N(set_attributes) ||
617 		CONTROL_O(set_attributes)) {
618 		result = 1;
619 	    }
620 	}
621     }
622     returnCode(result);
623 }
624 
625 NCURSES_EXPORT(int)
626 TINFO_SETUP_TERM(TERMINAL **tp,
627 		 const char *tname,
628 		 int Filedes,
629 		 int *errret,
630 		 int reuse)
631 {
632 #ifdef USE_TERM_DRIVER
633     TERMINAL_CONTROL_BLOCK *TCB = 0;
634 #endif
635     TERMINAL *termp;
636     SCREEN *sp = 0;
637     char *myname;
638     int code = ERR;
639 
640     START_TRACE();
641 
642 #ifdef USE_TERM_DRIVER
643     T((T_CALLED("_nc_setupterm_ex(%p,%s,%d,%p)"),
644        (void *) tp, _nc_visbuf(tname), Filedes, (void *) errret));
645 
646     if (tp == 0) {
647 	ret_error0(TGETENT_ERR,
648 		   "Invalid parameter, internal error.\n");
649     } else
650 	termp = *tp;
651 #else
652     termp = cur_term;
653     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, (void *) errret));
654 #endif
655 
656     if (tname == 0) {
657 	tname = getenv("TERM");
658 	if (tname == 0 || *tname == '\0') {
659 #ifdef USE_TERM_DRIVER
660 	    tname = "unknown";
661 #else
662 	    ret_error0(TGETENT_ERR, "TERM environment variable not set.\n");
663 #endif
664 	}
665     }
666     myname = strdup(tname);
667 
668     if (strlen(myname) > MAX_NAME_SIZE) {
669 	ret_error(TGETENT_ERR,
670 		  "TERM environment must be <= %d characters.\n",
671 		  MAX_NAME_SIZE,
672 		  free(myname));
673     }
674 
675     T(("your terminal name is %s", myname));
676 
677     /*
678      * Allow output redirection.  This is what SVr3 does.  If stdout is
679      * directed to a file, screen updates go to standard error.
680      */
681     if (Filedes == STDOUT_FILENO && !NC_ISATTY(Filedes))
682 	Filedes = STDERR_FILENO;
683 
684     /*
685      * Check if we have already initialized to use this terminal.  If so, we
686      * do not need to re-read the terminfo entry, or obtain TTY settings.
687      *
688      * This is an improvement on SVr4 curses.  If an application mixes curses
689      * and termcap calls, it may call both initscr and tgetent.  This is not
690      * really a good thing to do, but can happen if someone tries using ncurses
691      * with the readline library.  The problem we are fixing is that when
692      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
693      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
694      * rather than the ones saved in initscr.  So we check if cur_term appears
695      * to contain terminal settings for the same output file as our current
696      * call - and copy those terminal settings.  (SVr4 curses does not do this,
697      * however applications that are working around the problem will still work
698      * properly with this feature).
699      */
700     if (reuse
701 	&& (termp != 0)
702 	&& termp->Filedes == Filedes
703 	&& termp->_termname != 0
704 	&& !strcmp(termp->_termname, myname)
705 	&& _nc_name_match(TerminalType(termp).term_names, myname, "|")) {
706 	T(("reusing existing terminal information and mode-settings"));
707 	code = OK;
708 #ifdef USE_TERM_DRIVER
709 	TCB = (TERMINAL_CONTROL_BLOCK *) termp;
710 #endif
711     } else {
712 #ifdef USE_TERM_DRIVER
713 	TERMINAL_CONTROL_BLOCK *my_tcb;
714 	termp = 0;
715 	if ((my_tcb = typeCalloc(TERMINAL_CONTROL_BLOCK, 1)) != 0)
716 	    termp = &(my_tcb->term);
717 #else
718 	int status;
719 
720 	termp = typeCalloc(TERMINAL, 1);
721 #endif
722 	if (termp == 0) {
723 	    ret_error1(TGETENT_ERR,
724 		       "Not enough memory to create terminal structure.\n",
725 		       myname, free(myname));
726 	}
727 #if HAVE_SYSCONF
728 	{
729 	    long limit;
730 #ifdef LINE_MAX
731 	    limit = LINE_MAX;
732 #else
733 	    limit = _nc_globals.getstr_limit;
734 #endif
735 #ifdef _SC_LINE_MAX
736 	    if (limit < sysconf(_SC_LINE_MAX))
737 		limit = sysconf(_SC_LINE_MAX);
738 #endif
739 	    if (_nc_globals.getstr_limit < (int) limit)
740 		_nc_globals.getstr_limit = (int) limit;
741 	}
742 #endif /* HAVE_SYSCONF */
743 	T(("using %d for getstr limit", _nc_globals.getstr_limit));
744 
745 #ifdef USE_TERM_DRIVER
746 	INIT_TERM_DRIVER();
747 	TCB = (TERMINAL_CONTROL_BLOCK *) termp;
748 	code = _nc_globals.term_driver(TCB, myname, errret);
749 	if (code == OK) {
750 	    termp->Filedes = (short) Filedes;
751 	    termp->_termname = strdup(myname);
752 	} else {
753 	    ret_error1(errret ? *errret : TGETENT_ERR,
754 		       "Could not find any driver to handle terminal.\n",
755 		       myname, free(myname));
756 	}
757 #else
758 #if NCURSES_USE_DATABASE || NCURSES_USE_TERMCAP
759 	status = _nc_setup_tinfo(myname, &TerminalType(termp));
760 	T(("_nc_setup_tinfo returns %d", status));
761 #else
762 	T(("no database available"));
763 	status = TGETENT_NO;
764 #endif
765 
766 	/* try fallback list if entry on disk */
767 	if (status != TGETENT_YES) {
768 	    const TERMTYPE2 *fallback = _nc_fallback2(myname);
769 
770 	    if (fallback) {
771 		T(("found fallback entry"));
772 		_nc_copy_termtype2(&(TerminalType(termp)), fallback);
773 		status = TGETENT_YES;
774 	    }
775 	}
776 
777 	if (status != TGETENT_YES) {
778 	    del_curterm(termp);
779 	    if (status == TGETENT_ERR) {
780 		free(myname);
781 		ret_error0(status, "terminals database is inaccessible\n");
782 	    } else if (status == TGETENT_NO) {
783 		ret_error1(status, "unknown terminal type.\n",
784 			   myname, free(myname));
785 	    } else {
786 		ret_error0(status, "unexpected return-code\n");
787 	    }
788 	}
789 #if NCURSES_EXT_NUMBERS
790 	_nc_export_termtype2(&termp->type, &TerminalType(termp));
791 #endif
792 #if !USE_REENTRANT
793 	save_ttytype(termp);
794 #endif
795 
796 	termp->Filedes = (short) Filedes;
797 	termp->_termname = strdup(myname);
798 
799 	set_curterm(termp);
800 
801 	if (command_character)
802 	    _nc_tinfo_cmdch(termp, UChar(*command_character));
803 
804 	/*
805 	 * If an application calls setupterm() rather than initscr() or
806 	 * newterm(), we will not have the def_prog_mode() call in
807 	 * _nc_setupscreen().  Do it now anyway, so we can initialize the
808 	 * baudrate.  Also get the shell-mode so that erasechar() works.
809 	 */
810 	if (NC_ISATTY(Filedes)) {
811 	    NCURSES_SP_NAME(def_shell_mode) (NCURSES_SP_ARG);
812 	    NCURSES_SP_NAME(def_prog_mode) (NCURSES_SP_ARG);
813 	    baudrate();
814 	}
815 	code = OK;
816 #endif
817     }
818 
819 #ifdef USE_TERM_DRIVER
820     *tp = termp;
821     NCURSES_SP_NAME(set_curterm) (sp, termp);
822     TCB->drv->td_init(TCB);
823 #else
824     sp = SP;
825 #endif
826 
827     /*
828      * We should always check the screensize, just in case.
829      */
830     TINFO_GET_SIZE(sp, termp, ptrLines(sp), ptrCols(sp));
831 
832     if (errret)
833 	*errret = TGETENT_YES;
834 
835 #ifndef USE_TERM_DRIVER
836     if (generic_type) {
837 	/*
838 	 * BSD 4.3's termcap contains mis-typed "gn" for wy99.  Do a sanity
839 	 * check before giving up.
840 	 */
841 	if ((VALID_STRING(cursor_address)
842 	     || (VALID_STRING(cursor_down) && VALID_STRING(cursor_home)))
843 	    && VALID_STRING(clear_screen)) {
844 	    ret_error1(TGETENT_YES, "terminal is not really generic.\n",
845 		       myname, free(myname));
846 	} else {
847 	    del_curterm(termp);
848 	    ret_error1(TGETENT_NO, "I need something more specific.\n",
849 		       myname, free(myname));
850 	}
851     } else if (hard_copy) {
852 	ret_error1(TGETENT_YES, "I can't handle hardcopy terminals.\n",
853 		   myname, free(myname));
854     }
855 #endif
856     free(myname);
857     returnCode(code);
858 }
859 
860 #ifdef USE_PTHREADS
861 /*
862  * Returns a non-null pointer unless a new screen should be allocated because
863  * no match was found in the pre-screen cache.
864  */
865 NCURSES_EXPORT(SCREEN *)
866 _nc_find_prescr(void)
867 {
868     SCREEN *result = 0;
869     PRESCREEN_LIST *p;
870     pthread_t id = GetThreadID();
871     for (p = _nc_prescreen.allocated; p != 0; p = p->next) {
872 	if (p->id == id) {
873 	    result = p->sp;
874 	    break;
875 	}
876     }
877     return result;
878 }
879 
880 /*
881  * Tells ncurses to forget that this thread was associated with the pre-screen
882  * cache.  It does not modify the pre-screen cache itself, since that is used
883  * for creating new screens.
884  */
885 NCURSES_EXPORT(void)
886 _nc_forget_prescr(void)
887 {
888     PRESCREEN_LIST *p, *q;
889     pthread_t id = GetThreadID();
890     for (p = _nc_prescreen.allocated, q = 0; p != 0; q = p, p = p->next) {
891 	if (p->id == id) {
892 	    if (q) {
893 		q->next = p->next;
894 	    } else {
895 		_nc_prescreen.allocated = p->next;
896 	    }
897 	    free(p);
898 	    break;
899 	}
900     }
901 }
902 #endif /* USE_PTHREADS */
903 
904 #if NCURSES_SP_FUNCS
905 /*
906  * In case of handling multiple screens, we need to have a screen before
907  * initialization in _nc_setupscreen takes place.  This is to extend the
908  * substitute for some of the stuff in _nc_prescreen, especially for slk and
909  * ripoff handling which should be done per screen.
910  */
911 NCURSES_EXPORT(SCREEN *)
912 new_prescr(void)
913 {
914     SCREEN *sp;
915 
916     START_TRACE();
917     T((T_CALLED("new_prescr()")));
918 
919     _nc_lock_global(screen);
920     if ((sp = _nc_find_prescr()) == 0) {
921 	sp = _nc_alloc_screen_sp();
922 	T(("_nc_alloc_screen_sp %p", (void *) sp));
923 	if (sp != 0) {
924 #ifdef USE_PTHREADS
925 	    PRESCREEN_LIST *p = typeCalloc(PRESCREEN_LIST, 1);
926 	    if (p != 0) {
927 		p->id = GetThreadID();
928 		p->sp = sp;
929 		p->next = _nc_prescreen.allocated;
930 		_nc_prescreen.allocated = p;
931 	    }
932 #else
933 	    _nc_prescreen.allocated = sp;
934 #endif
935 	    sp->rsp = sp->rippedoff;
936 	    sp->_filtered = _nc_prescreen.filter_mode;
937 	    sp->_use_env = _nc_prescreen.use_env;
938 #if NCURSES_NO_PADDING
939 	    sp->_no_padding = _nc_prescreen._no_padding;
940 #endif
941 	    sp->slk_format = 0;
942 	    sp->_slk = 0;
943 	    sp->_prescreen = TRUE;
944 	    SP_PRE_INIT(sp);
945 #if USE_REENTRANT
946 	    sp->_TABSIZE = _nc_prescreen._TABSIZE;
947 	    sp->_ESCDELAY = _nc_prescreen._ESCDELAY;
948 #endif
949 	}
950     } else {
951 	T(("_nc_alloc_screen_sp %p (reuse)", (void *) sp));
952     }
953     _nc_unlock_global(screen);
954     returnSP(sp);
955 }
956 #endif
957 
958 #ifdef USE_TERM_DRIVER
959 /*
960  * This entrypoint is called from tgetent() to allow a special case of reusing
961  * the same TERMINAL data (see comment).
962  */
963 NCURSES_EXPORT(int)
964 _nc_setupterm(const char *tname,
965 	      int Filedes,
966 	      int *errret,
967 	      int reuse)
968 {
969     int rc = ERR;
970     TERMINAL *termp = 0;
971 
972     _nc_lock_global(prescreen);
973     START_TRACE();
974     if (TINFO_SETUP_TERM(&termp, tname, Filedes, errret, reuse) == OK) {
975 	_nc_forget_prescr();
976 	if (NCURSES_SP_NAME(set_curterm) (CURRENT_SCREEN_PRE, termp) != 0) {
977 	    rc = OK;
978 	}
979     }
980     _nc_unlock_global(prescreen);
981     return rc;
982 }
983 #endif
984 
985 /*
986  *	setupterm(termname, Filedes, errret)
987  *
988  *	Find and read the appropriate object file for the terminal
989  *	Make cur_term point to the structure.
990  */
991 NCURSES_EXPORT(int)
992 setupterm(const char *tname, int Filedes, int *errret)
993 {
994     START_TRACE();
995     return _nc_setupterm(tname, Filedes, errret, FALSE);
996 }
997