1 /****************************************************************************
2  * Copyright (c) 1998-2004,2005 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey 1996-2003                                      *
33  ****************************************************************************/
34 
35 /*
36  * Terminal setup routines common to termcap and terminfo:
37  *
38  *		use_env(bool)
39  *		setupterm(char *, int, int *)
40  */
41 
42 #include <curses.priv.h>
43 #include <tic.h>		/* for MAX_NAME_SIZE */
44 #include <term_entry.h>
45 
46 #if SVR4_TERMIO && !defined(_POSIX_SOURCE)
47 #define _POSIX_SOURCE
48 #endif
49 
50 #if HAVE_LOCALE_H
51 #include <locale.h>
52 #endif
53 
54 #include <term.h>		/* lines, columns, cur_term */
55 
56 MODULE_ID("$Id: lib_setup.c,v 1.88 2005/03/12 19:41:45 tom Exp $")
57 #ifdef __MirBSD__
58 __RCSID("$MirOS: src/lib/libncurses/src/ncurses/tinfo/lib_setup.c,v 1.6 2009/09/06 13:46:36 tg Exp $");
59 #endif
60 
61 /****************************************************************************
62  *
63  * Terminal size computation
64  *
65  ****************************************************************************/
66 
67 #if HAVE_SIZECHANGE
68 # if !defined(sun) || !TERMIOS
69 #  if HAVE_SYS_IOCTL_H
70 #   include <sys/ioctl.h>
71 #  endif
72 # endif
73 #endif
74 
75 #if NEED_PTEM_H
76  /* On SCO, they neglected to define struct winsize in termios.h -- it's only
77   * in termio.h and ptem.h (the former conflicts with other definitions).
78   */
79 # include <sys/stream.h>
80 # include <sys/ptem.h>
81 #endif
82 
83 #if HAVE_LANGINFO_CODESET
84 #include <langinfo.h>
85 #endif
86 
87 /*
88  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
89  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
90  */
91 #ifdef TIOCGSIZE
92 # define IOCTL_WINSIZE TIOCGSIZE
93 # define STRUCT_WINSIZE struct ttysize
94 # define WINSIZE_ROWS(n) (int)n.ts_lines
95 # define WINSIZE_COLS(n) (int)n.ts_cols
96 #else
97 # ifdef TIOCGWINSZ
98 #  define IOCTL_WINSIZE TIOCGWINSZ
99 #  define STRUCT_WINSIZE struct winsize
100 #  define WINSIZE_ROWS(n) (int)n.ws_row
101 #  define WINSIZE_COLS(n) (int)n.ws_col
102 # endif
103 #endif
104 
105 NCURSES_EXPORT_VAR(char) ttytype[NAMESIZE] = "";
106 NCURSES_EXPORT_VAR(int) LINES = 0;
107 NCURSES_EXPORT_VAR(int) COLS = 0;
108 NCURSES_EXPORT_VAR(int) TABSIZE = 0;
109 
110 static int _use_env = TRUE;
111 
112 NCURSES_EXPORT(void)
use_env(bool f)113 use_env(bool f)
114 {
115     T((T_CALLED("use_env()")));
116     _use_env = f;
117     returnVoid;
118 }
119 
120 static void
_nc_get_screensize(int * linep,int * colp)121 _nc_get_screensize(int *linep, int *colp)
122 /* Obtain lines/columns values from the environment and/or terminfo entry */
123 {
124     /* figure out the size of the screen */
125     T(("screen size: terminfo lines = %d columns = %d", lines, columns));
126 
127     if (!_use_env) {
128 	*linep = (int) lines;
129 	*colp = (int) columns;
130     } else {			/* usually want to query LINES and COLUMNS from environment */
131 	int value;
132 
133 	*linep = *colp = 0;
134 
135 	/* first, look for environment variables */
136 	if ((value = _nc_getenv_num("LINES")) > 0) {
137 	    *linep = value;
138 	}
139 	if ((value = _nc_getenv_num("COLUMNS")) > 0) {
140 	    *colp = value;
141 	}
142 	T(("screen size: environment LINES = %d COLUMNS = %d", *linep, *colp));
143 
144 #ifdef __EMX__
145 	if (*linep <= 0 || *colp <= 0) {
146 	    int screendata[2];
147 	    _scrsize(screendata);
148 	    *colp = screendata[0];
149 	    *linep = screendata[1];
150 	    T(("EMX screen size: environment LINES = %d COLUMNS = %d",
151 	       *linep, *colp));
152 	}
153 #endif
154 #if HAVE_SIZECHANGE
155 	/* if that didn't work, maybe we can try asking the OS */
156 	if (*linep <= 0 || *colp <= 0) {
157 	    if (isatty(cur_term->Filedes)) {
158 		STRUCT_WINSIZE size;
159 
160 		errno = 0;
161 		do {
162 		    if (ioctl(cur_term->Filedes, IOCTL_WINSIZE, &size) < 0
163 			&& errno != EINTR)
164 			goto failure;
165 		} while
166 		    (errno == EINTR);
167 
168 		/*
169 		 * Solaris lets users override either dimension with an
170 		 * environment variable.
171 		 */
172 		if (*linep <= 0)
173 		    *linep = WINSIZE_ROWS(size);
174 		if (*colp <= 0)
175 		    *colp = WINSIZE_COLS(size);
176 	    }
177 	    /* FALLTHRU */
178 	  failure:;
179 	}
180 #endif /* HAVE_SIZECHANGE */
181 
182 	/* if we can't get dynamic info about the size, use static */
183 	if (*linep <= 0) {
184 	    *linep = (int) lines;
185 	}
186 	if (*colp <= 0) {
187 	    *colp = (int) columns;
188 	}
189 
190 	/* the ultimate fallback, assume fixed 24x80 size */
191 	if (*linep <= 0) {
192 	    *linep = 24;
193 	}
194 	if (*colp <= 0) {
195 	    *colp = 80;
196 	}
197 
198 	/*
199 	 * Put the derived values back in the screen-size caps, so
200 	 * tigetnum() and tgetnum() will do the right thing.
201 	 */
202 	lines = (short) (*linep);
203 	columns = (short) (*colp);
204     }
205 
206     T(("screen size is %dx%d", *linep, *colp));
207 
208     if (VALID_NUMERIC(init_tabs))
209 	TABSIZE = (int) init_tabs;
210     else
211 	TABSIZE = 8;
212     T(("TABSIZE = %d", TABSIZE));
213 }
214 
215 #if USE_SIZECHANGE
216 NCURSES_EXPORT(void)
_nc_update_screensize(void)217 _nc_update_screensize(void)
218 {
219     int old_lines = lines;
220     int new_lines;
221     int old_cols = columns;
222     int new_cols;
223 
224     _nc_get_screensize(&new_lines, &new_cols);
225 
226     /*
227      * See is_term_resized() and resizeterm().
228      * We're doing it this way because those functions belong to the upper
229      * ncurses library, while this resides in the lower terminfo library.
230      */
231     if (SP != 0
232 	&& SP->_resize != 0) {
233 	if ((new_lines != old_lines) || (new_cols != old_cols))
234 	    SP->_resize(new_lines, new_cols);
235 	SP->_sig_winch = FALSE;
236     }
237 }
238 #endif
239 
240 /****************************************************************************
241  *
242  * Terminal setup
243  *
244  ****************************************************************************/
245 
246 #define ret_error(code, fmt, arg)	if (errret) {\
247 					    *errret = code;\
248 					    returnCode(ERR);\
249 					} else {\
250 					    fprintf(stderr, fmt, arg);\
251 					    exit(EXIT_FAILURE);\
252 					}
253 
254 #define ret_error0(code, msg)		if (errret) {\
255 					    *errret = code;\
256 					    returnCode(ERR);\
257 					} else {\
258 					    fprintf(stderr, msg);\
259 					    exit(EXIT_FAILURE);\
260 					}
261 
262 #if USE_DATABASE || USE_TERMCAP
263 static int
grab_entry(const char * const tn,TERMTYPE * const tp)264 grab_entry(const char *const tn, TERMTYPE *const tp)
265 /* return 1 if entry found, 0 if not found, -1 if database not accessible */
266 {
267 #if USE_DATABASE
268     char filename[PATH_MAX];
269 #endif
270     int status;
271 
272     /*
273      * $TERM shouldn't contain pathname delimiters.
274      */
275     if (strchr(tn, '/'))
276 	return 0;
277 
278 #if USE_DATABASE
279     if ((status = _nc_read_entry(tn, filename, tp)) != 1) {
280 
281 #if !PURE_TERMINFO
282 	/*
283 	 * Try falling back on the termcap file.
284 	 * Note:  allowing this call links the entire terminfo/termcap
285 	 * compiler into the startup code.  It's preferable to build a
286 	 * real terminfo database and use that.
287 	 */
288 	status = _nc_read_termcap_entry(tn, tp);
289 #endif /* PURE_TERMINFO */
290 
291     }
292 #else
293     status = _nc_read_termcap_entry(tn, tp);
294 #endif
295 
296     /*
297      * If we have an entry, force all of the cancelled strings to null
298      * pointers so we don't have to test them in the rest of the library.
299      * (The terminfo compiler bypasses this logic, since it must know if
300      * a string is cancelled, for merging entries).
301      */
302     if (status == 1) {
303 	unsigned n;
304 	for_each_boolean(n, tp) {
305 	    if (!VALID_BOOLEAN(tp->Booleans[n]))
306 		tp->Booleans[n] = FALSE;
307 	}
308 	for_each_string(n, tp) {
309 	    if (tp->Strings[n] == CANCELLED_STRING)
310 		tp->Strings[n] = ABSENT_STRING;
311 	}
312     }
313     return (status);
314 }
315 #endif
316 
317 /*
318 **	do_prototype()
319 **
320 **	Take the real command character out of the CC environment variable
321 **	and substitute it in for the prototype given in 'command_character'.
322 **
323 */
324 static void
do_prototype(void)325 do_prototype(void)
326 {
327     int i;
328     char CC;
329     char proto;
330     char *tmp;
331 
332     tmp = getenv("CC");
333     CC = *tmp;
334     proto = *command_character;
335 
336     for_each_string(i, &(cur_term->type)) {
337 	for (tmp = cur_term->type.Strings[i]; *tmp; tmp++) {
338 	    if (*tmp == proto)
339 		*tmp = CC;
340 	}
341     }
342 }
343 
344 /*
345  * Override the locale which is in effect.
346  */
347 static char *_nc_locale_string = NULL;
348 static int _nc_locale_isutf8;
349 
350 NCURSES_EXPORT(int)
_nc_overridden_locale(void)351 _nc_overridden_locale(void)
352 {
353 	return (_nc_locale_string == NULL ? 0 : 1);
354 }
355 
356 NCURSES_EXPORT(void)
_nc_set_locale(char * newlocale)357 _nc_set_locale(char *newlocale)
358 {
359 	if ((_nc_locale_string = newlocale) != NULL) {
360 		if (strstr(newlocale, "UTF-8") != NULL ||
361 		    strstr(newlocale, "utf-8") != NULL ||
362 		    strstr(newlocale, "UTF8") != NULL ||
363 		    strstr(newlocale, "utf8") != NULL)
364 			_nc_locale_isutf8 = 1;
365 		else
366 			_nc_locale_isutf8 = 0;
367 	}
368 }
369 
370 /*
371  * Find the locale which is in effect.
372  */
373 #ifdef __MirBSD__
374 static char _nc_get_locale_storage[16];
375 #endif
376 
377 NCURSES_EXPORT(char *)
_nc_get_locale(void)378 _nc_get_locale(void)
379 {
380     char *env;
381 
382     if (_nc_overridden_locale()) {
383 	env = _nc_locale_string;
384 	goto _nc_get_locale_out;
385     }
386 
387 #ifdef __MirBSD__
388     /* this result is constant in MirBSD */
389     memcpy(env = _nc_get_locale_storage, "en_US.UTF-8", 12);
390 #else
391 #if HAVE_LOCALE_H
392     /*
393      * This is preferable to using getenv() since it ensures that we are using
394      * the locale which was actually initialized by the application.
395      */
396     env = setlocale(LC_CTYPE, 0);
397 #else
398     if (((env = getenv("LC_ALL")) != 0 && *env != '\0')
399 	|| ((env = getenv("LC_CTYPE")) != 0 && *env != '\0')
400 	|| ((env = getenv("LANG")) != 0 && *env != '\0')) {
401 	;
402     }
403 #endif
404 #endif
405  _nc_get_locale_out:
406     T(("_nc_get_locale %s", _nc_visbuf(env)));
407     return env;
408 }
409 
410 /*
411  * Check if we are running in a UTF-8 locale.
412  */
413 NCURSES_EXPORT(int)
_nc_unicode_locale(void)414 _nc_unicode_locale(void)
415 {
416 #ifndef __MirBSD__
417     int result = 0;
418     char *env;
419 #endif
420 
421     if (_nc_overridden_locale())
422 	return (_nc_locale_isutf8);
423 
424 #ifdef __MirBSD__
425     return (1);
426 #else
427 #if HAVE_LANGINFO_CODESET
428     env = nl_langinfo(CODESET);
429     result = !strcmp(env, "UTF-8");
430     T(("_nc_unicode_locale(%s) ->%d", env, result));
431 #else
432     env = _nc_get_locale();
433     if (env != 0) {
434 	if (strstr(env, ".UTF-8") != 0) {
435 	    result = 1;
436 	    T(("_nc_unicode_locale(%s) ->%d", env, result));
437 	}
438     }
439 #endif
440     return result;
441 #endif
442 }
443 
444 #define CONTROL_N(s) ((s) != 0 && strstr(s, "\016") != 0)
445 #define CONTROL_O(s) ((s) != 0 && strstr(s, "\017") != 0)
446 
447 /*
448  * Check for known broken cases where a UTF-8 locale breaks the alternate
449  * character set.
450  */
451 NCURSES_EXPORT(int)
_nc_locale_breaks_acs(void)452 _nc_locale_breaks_acs(void)
453 {
454     char *env;
455 
456     if ((env = getenv("NCURSES_NO_UTF8_ACS")) != 0) {
457 	return atoi(env);
458     } else if ((env = getenv("TERM")) != 0) {
459 	if (strstr(env, "linux"))
460 	    return 1;		/* always broken */
461 	if (strstr(env, "screen") != 0
462 	    && ((env = getenv("TERMCAP")) != 0
463 		&& strstr(env, "screen") != 0)
464 	    && strstr(env, "hhII00") != 0) {
465 	    if (CONTROL_N(enter_alt_charset_mode) ||
466 		CONTROL_O(enter_alt_charset_mode) ||
467 		CONTROL_N(set_attributes) ||
468 		CONTROL_O(set_attributes))
469 		return 1;
470 	}
471     }
472     return 0;
473 }
474 
475 /*
476  * This entrypoint is called from tgetent() to allow special a case of reusing
477  * the same TERMINAL data (see comment).
478  */
479 NCURSES_EXPORT(int)
_nc_setupterm(NCURSES_CONST char * tname,int Filedes,int * errret,bool reuse)480 _nc_setupterm(NCURSES_CONST char *tname, int Filedes, int *errret, bool reuse)
481 {
482     int status;
483 
484     START_TRACE();
485     T((T_CALLED("setupterm(%s,%d,%p)"), _nc_visbuf(tname), Filedes, errret));
486 
487     if (tname == 0) {
488 	tname = getenv("TERM");
489 	if (tname == 0 || *tname == '\0') {
490 	    ret_error0(-1, "TERM environment variable not set.\n");
491 	}
492     }
493     if (strlen(tname) > MAX_NAME_SIZE) {
494 	ret_error(-1, "TERM environment must be <= %d characters.\n",
495 		  MAX_NAME_SIZE);
496     }
497 
498     T(("your terminal name is %s", tname));
499 
500     /*
501      * Allow output redirection.  This is what SVr3 does.  If stdout is
502      * directed to a file, screen updates go to standard error.
503      */
504     if (Filedes == STDOUT_FILENO && !isatty(Filedes))
505 	Filedes = STDERR_FILENO;
506 
507     /*
508      * Check if we have already initialized to use this terminal.  If so, we
509      * do not need to re-read the terminfo entry, or obtain TTY settings.
510      *
511      * This is an improvement on SVr4 curses.  If an application mixes curses
512      * and termcap calls, it may call both initscr and tgetent.  This is not
513      * really a good thing to do, but can happen if someone tries using ncurses
514      * with the readline library.  The problem we are fixing is that when
515      * tgetent calls setupterm, the resulting Ottyb struct in cur_term is
516      * zeroed.  A subsequent call to endwin uses the zeroed terminal settings
517      * rather than the ones saved in initscr.  So we check if cur_term appears
518      * to contain terminal settings for the same output file as our current
519      * call - and copy those terminal settings.  (SVr4 curses does not do this,
520      * however applications that are working around the problem will still work
521      * properly with this feature).
522      */
523     if (reuse
524 	&& cur_term != 0
525 	&& cur_term->Filedes == Filedes
526 	&& cur_term->_termname != 0
527 	&& !strcmp(cur_term->_termname, tname)
528 	&& _nc_name_match(cur_term->type.term_names, tname, "|")) {
529 	T(("reusing existing terminal information and mode-settings"));
530     } else {
531 	TERMINAL *term_ptr;
532 
533 	term_ptr = typeCalloc(TERMINAL, 1);
534 
535 	if (term_ptr == 0) {
536 	    ret_error0(-1,
537 		       "Not enough memory to create terminal structure.\n");
538 	}
539 #if USE_DATABASE || USE_TERMCAP
540 	status = grab_entry(tname, &term_ptr->type);
541 #else
542 	status = 0;
543 #endif
544 
545 	/* try fallback list if entry on disk */
546 	if (status != 1) {
547 	    const TERMTYPE *fallback = _nc_fallback(tname);
548 
549 	    if (fallback) {
550 		term_ptr->type = *fallback;
551 		status = 1;
552 	    }
553 	}
554 
555 	if (status <= 0) {
556 	    del_curterm(term_ptr);
557 	    if (status == -1) {
558 		ret_error0(-1, "terminals database is inaccessible\n");
559 	    } else if (status == 0) {
560 		ret_error(0, "'%s': unknown terminal type.\n", tname);
561 	    }
562 	}
563 
564 	set_curterm(term_ptr);
565 
566 	if (command_character && getenv("CC"))
567 	    do_prototype();
568 
569 	strncpy(ttytype, cur_term->type.term_names, NAMESIZE - 1);
570 	ttytype[NAMESIZE - 1] = '\0';
571 
572 	cur_term->Filedes = Filedes;
573 	cur_term->_termname = strdup(tname);
574 
575 	/*
576 	 * If an application calls setupterm() rather than initscr() or
577 	 * newterm(), we will not have the def_prog_mode() call in
578 	 * _nc_setupscreen().  Do it now anyway, so we can initialize the
579 	 * baudrate.
580 	 */
581 	if (isatty(Filedes)) {
582 	    def_prog_mode();
583 	    baudrate();
584 	}
585     }
586 
587     /*
588      * We should always check the screensize, just in case.
589      */
590     _nc_get_screensize(&LINES, &COLS);
591 
592     if (errret)
593 	*errret = 1;
594 
595     T((T_CREATE("screen %s %dx%d"), tname, LINES, COLS));
596 
597     if (generic_type) {
598 	ret_error(0, "'%s': I need something more specific.\n", tname);
599     }
600     if (hard_copy) {
601 	ret_error(1, "'%s': I can't handle hardcopy terminals.\n", tname);
602     }
603     returnCode(OK);
604 }
605 
606 /*
607  *	setupterm(termname, Filedes, errret)
608  *
609  *	Find and read the appropriate object file for the terminal
610  *	Make cur_term point to the structure.
611  *
612  */
613 
614 NCURSES_EXPORT(int)
setupterm(NCURSES_CONST char * tname,int Filedes,int * errret)615 setupterm(NCURSES_CONST char *tname, int Filedes, int *errret)
616 {
617     return _nc_setupterm(tname, Filedes, errret, FALSE);
618 }
619