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-on                 *
33  ****************************************************************************/
34 
35 /*
36  *	parse_entry.c -- compile one terminfo or termcap entry
37  *
38  *	Get an exact in-core representation of an entry.  Don't
39  *	try to resolve use or tc capabilities, that is someone
40  *	else's job.  Depends on the lexical analyzer to get tokens
41  *	from the input stream.
42  */
43 
44 #define __INTERNAL_CAPS_VISIBLE
45 #include <curses.priv.h>
46 
47 #include <ctype.h>
48 #include <tic.h>
49 #include <term_entry.h>
50 
51 MODULE_ID("$Id: parse_entry.c,v 1.62 2005/06/02 22:04:32 tom Exp $")
52 
53 #ifdef LINT
54 static short const parametrized[] =
55 {0};
56 #else
57 #include <parametrized.h>
58 #endif
59 
60 static void postprocess_termcap(TERMTYPE *, bool);
61 static void postprocess_terminfo(TERMTYPE *);
62 static struct name_table_entry const *lookup_fullname(const char *name);
63 
64 #if NCURSES_XNAMES
65 
66 static struct name_table_entry const *
_nc_extend_names(ENTRY * entryp,char * name,int token_type)67 _nc_extend_names(ENTRY * entryp, char *name, int token_type)
68 {
69     static struct name_table_entry temp;
70     TERMTYPE *tp = &(entryp->tterm);
71     unsigned offset = 0;
72     unsigned actual;
73     unsigned tindex;
74     unsigned first, last, n;
75     bool found;
76 
77     switch (token_type) {
78     case BOOLEAN:
79 	first = 0;
80 	last = tp->ext_Booleans;
81 	offset = tp->ext_Booleans;
82 	tindex = tp->num_Booleans;
83 	break;
84     case NUMBER:
85 	first = tp->ext_Booleans;
86 	last = tp->ext_Numbers + first;
87 	offset = tp->ext_Booleans + tp->ext_Numbers;
88 	tindex = tp->num_Numbers;
89 	break;
90     case STRING:
91 	first = tp->ext_Booleans + tp->ext_Numbers;
92 	last = tp->ext_Strings + first;
93 	offset = tp->ext_Booleans + tp->ext_Numbers + tp->ext_Strings;
94 	tindex = tp->num_Strings;
95 	break;
96     case CANCEL:
97 	actual = NUM_EXT_NAMES(tp);
98 	for (n = 0; n < actual; n++) {
99 	    if (!strcmp(name, tp->ext_Names[n])) {
100 		if (n > (unsigned) (tp->ext_Booleans + tp->ext_Numbers)) {
101 		    token_type = STRING;
102 		} else if (n > tp->ext_Booleans) {
103 		    token_type = NUMBER;
104 		} else {
105 		    token_type = BOOLEAN;
106 		}
107 		return _nc_extend_names(entryp, name, token_type);
108 	    }
109 	}
110 	/* Well, we are given a cancel for a name that we don't recognize */
111 	return _nc_extend_names(entryp, name, STRING);
112     default:
113 	return 0;
114     }
115 
116     /* Adjust the 'offset' (insertion-point) to keep the lists of extended
117      * names sorted.
118      */
119     for (n = first, found = FALSE; n < last; n++) {
120 	int cmp = strcmp(tp->ext_Names[n], name);
121 	if (cmp == 0)
122 	    found = TRUE;
123 	if (cmp >= 0) {
124 	    offset = n;
125 	    tindex = n - first;
126 	    switch (token_type) {
127 	    case BOOLEAN:
128 		tindex += BOOLCOUNT;
129 		break;
130 	    case NUMBER:
131 		tindex += NUMCOUNT;
132 		break;
133 	    case STRING:
134 		tindex += STRCOUNT;
135 		break;
136 	    }
137 	    break;
138 	}
139     }
140     if (!found) {
141 	switch (token_type) {
142 	case BOOLEAN:
143 	    tp->ext_Booleans += 1;
144 	    tp->num_Booleans += 1;
145 	    tp->Booleans = typeRealloc(char, tp->num_Booleans, tp->Booleans);
146 	    for (last = tp->num_Booleans - 1; last > tindex; last--)
147 		tp->Booleans[last] = tp->Booleans[last - 1];
148 	    break;
149 	case NUMBER:
150 	    tp->ext_Numbers += 1;
151 	    tp->num_Numbers += 1;
152 	    tp->Numbers = typeRealloc(short, tp->num_Numbers, tp->Numbers);
153 	    for (last = tp->num_Numbers - 1; last > tindex; last--)
154 		tp->Numbers[last] = tp->Numbers[last - 1];
155 	    break;
156 	case STRING:
157 	    tp->ext_Strings += 1;
158 	    tp->num_Strings += 1;
159 	    tp->Strings = typeRealloc(char *, tp->num_Strings, tp->Strings);
160 	    for (last = tp->num_Strings - 1; last > tindex; last--)
161 		tp->Strings[last] = tp->Strings[last - 1];
162 	    break;
163 	}
164 	actual = NUM_EXT_NAMES(tp);
165 	tp->ext_Names = typeRealloc(char *, actual, tp->ext_Names);
166 	while (--actual > offset)
167 	    tp->ext_Names[actual] = tp->ext_Names[actual - 1];
168 	tp->ext_Names[offset] = _nc_save_str(name);
169     }
170 
171     temp.nte_name = tp->ext_Names[offset];
172     temp.nte_type = token_type;
173     temp.nte_index = tindex;
174     temp.nte_link = -1;
175 
176     return &temp;
177 }
178 #endif /* NCURSES_XNAMES */
179 
180 /*
181  *	int
182  *	_nc_parse_entry(entry, literal, silent)
183  *
184  *	Compile one entry.  Doesn't try to resolve use or tc capabilities.
185  *
186  *	found-forward-use = FALSE
187  *	re-initialise internal arrays
188  *	get_token();
189  *	if the token was not a name in column 1, complain and die
190  *	save names in entry's string table
191  *	while (get_token() is not EOF and not NAMES)
192  *	        check for existence and type-correctness
193  *	        enter cap into structure
194  *	        if STRING
195  *	            save string in entry's string table
196  *	push back token
197  */
198 
199 #define BAD_TC_USAGE if (!bad_tc_usage) \
200  	{ bad_tc_usage = TRUE; \
201 	 _nc_warning("Legacy termcap allows only a trailing tc= clause"); }
202 
203 NCURSES_EXPORT(int)
_nc_parse_entry(struct entry * entryp,int literal,bool silent)204 _nc_parse_entry(struct entry *entryp, int literal, bool silent)
205 {
206     int token_type;
207     struct name_table_entry const *entry_ptr;
208     char *ptr, *base;
209     bool bad_tc_usage = FALSE;
210 
211     token_type = _nc_get_token(silent);
212 
213     if (token_type == EOF)
214 	return (EOF);
215     if (token_type != NAMES)
216 	_nc_err_abort("Entry does not start with terminal names in column one");
217 
218     _nc_init_entry(&entryp->tterm);
219 
220     entryp->cstart = _nc_comment_start;
221     entryp->cend = _nc_comment_end;
222     entryp->startline = _nc_start_line;
223     DEBUG(2, ("Comment range is %ld to %ld", entryp->cstart, entryp->cend));
224 
225     /*
226      * Strip off the 2-character termcap name, if present.  Originally termcap
227      * used that as an indexing aid.  We can retain 2-character terminfo names,
228      * but note that they would be lost if we translate to/from termcap.  This
229      * feature is supposedly obsolete since "newer" BSD implementations do not
230      * use it; however our reference for this feature is SunOS 4.x, which
231      * implemented it.  Note that the resulting terminal type was never the
232      * 2-character name, but was instead the first alias after that.
233      */
234     ptr = _nc_curr_token.tk_name;
235     if (_nc_syntax == SYN_TERMCAP
236 #if NCURSES_XNAMES
237 	&& !_nc_user_definable
238 #endif
239 	) {
240 	if (ptr[2] == '|') {
241 	    ptr += 3;
242 	    _nc_curr_token.tk_name[2] = '\0';
243 	}
244     }
245 
246     entryp->tterm.str_table = entryp->tterm.term_names = _nc_save_str(ptr);
247 
248     DEBUG(1, ("Starting '%s'", ptr));
249 
250     /*
251      * We do this because the one-token lookahead in the parse loop
252      * results in the terminal type getting prematurely set to correspond
253      * to that of the next entry.
254      */
255     _nc_set_type(_nc_first_name(entryp->tterm.term_names));
256 
257     /* check for overly-long names and aliases */
258     for (base = entryp->tterm.term_names; (ptr = strchr(base, '|')) != 0;
259 	 base = ptr + 1) {
260 	if (ptr - base > MAX_ALIAS) {
261 	    _nc_warning("%s `%.*s' may be too long",
262 			(base == entryp->tterm.term_names)
263 			? "primary name"
264 			: "alias",
265 			(int) (ptr - base), base);
266 	}
267     }
268 
269     entryp->nuses = 0;
270 
271     for (token_type = _nc_get_token(silent);
272 	 token_type != EOF && token_type != NAMES;
273 	 token_type = _nc_get_token(silent)) {
274 	bool is_use = (strcmp(_nc_curr_token.tk_name, "use") == 0);
275 	bool is_tc = !is_use && (strcmp(_nc_curr_token.tk_name, "tc") == 0);
276 	if (is_use || is_tc) {
277 	    entryp->uses[entryp->nuses].name = _nc_save_str(_nc_curr_token.tk_valstring);
278 	    entryp->uses[entryp->nuses].line = _nc_curr_line;
279 	    entryp->nuses++;
280 	    if (entryp->nuses > 1 && is_tc) {
281 		BAD_TC_USAGE
282 	    }
283 	} else {
284 	    /* normal token lookup */
285 	    entry_ptr = _nc_find_entry(_nc_curr_token.tk_name,
286 				       _nc_syntax ? _nc_cap_hash_table : _nc_info_hash_table);
287 
288 	    /*
289 	     * Our kluge to handle aliasing.  The reason it's done
290 	     * this ugly way, with a linear search, is so the hashing
291 	     * machinery doesn't have to be made really complicated
292 	     * (also we get better warnings this way).  No point in
293 	     * making this case fast, aliased caps aren't common now
294 	     * and will get rarer.
295 	     */
296 	    if (entry_ptr == NOTFOUND) {
297 		const struct alias *ap;
298 
299 		if (_nc_syntax == SYN_TERMCAP) {
300 		    if (entryp->nuses != 0) {
301 			BAD_TC_USAGE
302 		    }
303 		    for (ap = _nc_capalias_table; ap->from; ap++)
304 			if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
305 			    if (ap->to == (char *) 0) {
306 				_nc_warning("%s (%s termcap extension) ignored",
307 					    ap->from, ap->source);
308 				goto nexttok;
309 			    }
310 
311 			    entry_ptr = _nc_find_entry(ap->to, _nc_cap_hash_table);
312 			    if (entry_ptr && !silent)
313 				_nc_warning("%s (%s termcap extension) aliased to %s",
314 					    ap->from, ap->source, ap->to);
315 			    break;
316 			}
317 		} else {	/* if (_nc_syntax == SYN_TERMINFO) */
318 		    for (ap = _nc_infoalias_table; ap->from; ap++)
319 			if (strcmp(ap->from, _nc_curr_token.tk_name) == 0) {
320 			    if (ap->to == (char *) 0) {
321 				_nc_warning("%s (%s terminfo extension) ignored",
322 					    ap->from, ap->source);
323 				goto nexttok;
324 			    }
325 
326 			    entry_ptr = _nc_find_entry(ap->to, _nc_info_hash_table);
327 			    if (entry_ptr && !silent)
328 				_nc_warning("%s (%s terminfo extension) aliased to %s",
329 					    ap->from, ap->source, ap->to);
330 			    break;
331 			}
332 
333 		    if (entry_ptr == NOTFOUND) {
334 			entry_ptr = lookup_fullname(_nc_curr_token.tk_name);
335 		    }
336 		}
337 	    }
338 #if NCURSES_XNAMES
339 	    /*
340 	     * If we have extended-names active, we will automatically
341 	     * define a name based on its context.
342 	     */
343 	    if (entry_ptr == NOTFOUND
344 		&& _nc_user_definable
345 		&& (entry_ptr = _nc_extend_names(entryp,
346 						 _nc_curr_token.tk_name,
347 						 token_type)) != 0) {
348 		if (_nc_tracing >= DEBUG_LEVEL(1))
349 		    _nc_warning("extended capability '%s'", _nc_curr_token.tk_name);
350 	    }
351 #endif /* NCURSES_XNAMES */
352 
353 	    /* can't find this cap name, not even as an alias */
354 	    if (entry_ptr == NOTFOUND) {
355 		if (!silent)
356 		    _nc_warning("unknown capability '%s'",
357 				_nc_curr_token.tk_name);
358 		continue;
359 	    }
360 
361 	    /* deal with bad type/value combinations. */
362 	    if (token_type != CANCEL && entry_ptr->nte_type != token_type) {
363 		/*
364 		 * Nasty special cases here handle situations in which type
365 		 * information can resolve name clashes.  Normal lookup
366 		 * finds the last instance in the capability table of a
367 		 * given name, regardless of type.  find_type_entry looks
368 		 * for a first matching instance with given type.  So as
369 		 * long as all ambiguous names occur in pairs of distinct
370 		 * type, this will do the job.
371 		 */
372 
373 		/* tell max_attributes from arrow_key_map */
374 		if (token_type == NUMBER
375 		    && !strcmp("ma", _nc_curr_token.tk_name)) {
376 		    entry_ptr = _nc_find_type_entry("ma", NUMBER,
377 						    _nc_get_table(_nc_syntax
378 								  != 0));
379 
380 		    /* map terminfo's string MT to MT */
381 		} else if (token_type == STRING
382 			   && !strcmp("MT", _nc_curr_token.tk_name)) {
383 		    entry_ptr = _nc_find_type_entry("MT", STRING,
384 						    _nc_get_table(_nc_syntax
385 								  != 0));
386 
387 		    /* treat strings without following "=" as empty strings */
388 		} else if (token_type == BOOLEAN
389 			   && entry_ptr->nte_type == STRING) {
390 		    token_type = STRING;
391 		    /* we couldn't recover; skip this token */
392 		} else {
393 		    if (!silent) {
394 			const char *type_name;
395 			switch (entry_ptr->nte_type) {
396 			case BOOLEAN:
397 			    type_name = "boolean";
398 			    break;
399 			case STRING:
400 			    type_name = "string";
401 			    break;
402 			case NUMBER:
403 			    type_name = "numeric";
404 			    break;
405 			default:
406 			    type_name = "unknown";
407 			    break;
408 			}
409 			_nc_warning("wrong type used for %s capability '%s'",
410 				    type_name, _nc_curr_token.tk_name);
411 		    }
412 		    continue;
413 		}
414 	    }
415 
416 	    /* now we know that the type/value combination is OK */
417 	    switch (token_type) {
418 	    case CANCEL:
419 		switch (entry_ptr->nte_type) {
420 		case BOOLEAN:
421 		    entryp->tterm.Booleans[entry_ptr->nte_index] = CANCELLED_BOOLEAN;
422 		    break;
423 
424 		case NUMBER:
425 		    entryp->tterm.Numbers[entry_ptr->nte_index] = CANCELLED_NUMERIC;
426 		    break;
427 
428 		case STRING:
429 		    entryp->tterm.Strings[entry_ptr->nte_index] = CANCELLED_STRING;
430 		    break;
431 		}
432 		break;
433 
434 	    case BOOLEAN:
435 		entryp->tterm.Booleans[entry_ptr->nte_index] = TRUE;
436 		break;
437 
438 	    case NUMBER:
439 		entryp->tterm.Numbers[entry_ptr->nte_index] =
440 		    _nc_curr_token.tk_valnumber;
441 		break;
442 
443 	    case STRING:
444 		ptr = _nc_curr_token.tk_valstring;
445 		if (_nc_syntax == SYN_TERMCAP)
446 		    ptr = _nc_captoinfo(_nc_curr_token.tk_name,
447 					ptr,
448 					parametrized[entry_ptr->nte_index]);
449 		entryp->tterm.Strings[entry_ptr->nte_index] = _nc_save_str(ptr);
450 		break;
451 
452 	    default:
453 		if (!silent)
454 		    _nc_warning("unknown token type");
455 		_nc_panic_mode((_nc_syntax == SYN_TERMCAP) ? ':' : ',');
456 		continue;
457 	    }
458 	}			/* end else cur_token.name != "use" */
459       nexttok:
460 	continue;		/* cannot have a label w/o statement */
461     }				/* endwhile (not EOF and not NAMES) */
462 
463     _nc_push_token(token_type);
464     _nc_set_type(_nc_first_name(entryp->tterm.term_names));
465 
466     /*
467      * Try to deduce as much as possible from extension capabilities
468      * (this includes obsolete BSD capabilities).  Sigh...it would be more
469      * space-efficient to call this after use resolution, but it has
470      * to be done before entry allocation is wrapped up.
471      */
472     if (!literal) {
473 	if (_nc_syntax == SYN_TERMCAP) {
474 	    bool has_base_entry = FALSE;
475 	    int i;
476 
477 	    /*
478 	     * Don't insert defaults if this is a `+' entry meant only
479 	     * for inclusion in other entries (not sure termcap ever
480 	     * had these, actually).
481 	     */
482 	    if (strchr(entryp->tterm.term_names, '+'))
483 		has_base_entry = TRUE;
484 	    else
485 		/*
486 		 * Otherwise, look for a base entry that will already
487 		 * have picked up defaults via translation.
488 		 */
489 		for (i = 0; i < entryp->nuses; i++)
490 		    if (!strchr((char *) entryp->uses[i].name, '+'))
491 			has_base_entry = TRUE;
492 
493 	    postprocess_termcap(&entryp->tterm, has_base_entry);
494 	} else
495 	    postprocess_terminfo(&entryp->tterm);
496     }
497     _nc_wrap_entry(entryp, FALSE);
498 
499     return (OK);
500 }
501 
502 NCURSES_EXPORT(int)
_nc_capcmp(const char * s,const char * t)503 _nc_capcmp(const char *s, const char *t)
504 /* compare two string capabilities, stripping out padding */
505 {
506     if (!s && !t)
507 	return (0);
508     else if (!s || !t)
509 	return (1);
510 
511     for (;;) {
512 	if (s[0] == '$' && s[1] == '<') {
513 	    for (s += 2;; s++)
514 		if (!(isdigit(UChar(*s))
515 		      || *s == '.'
516 		      || *s == '*'
517 		      || *s == '/'
518 		      || *s == '>'))
519 		    break;
520 	}
521 
522 	if (t[0] == '$' && t[1] == '<') {
523 	    for (t += 2;; t++)
524 		if (!(isdigit(UChar(*t))
525 		      || *t == '.'
526 		      || *t == '*'
527 		      || *t == '/'
528 		      || *t == '>'))
529 		    break;
530 	}
531 
532 	/* we've now pushed s and t past any padding they were pointing at */
533 
534 	if (*s == '\0' && *t == '\0')
535 	    return (0);
536 
537 	if (*s != *t)
538 	    return (*t - *s);
539 
540 	/* else *s == *t but one is not NUL, so continue */
541 	s++, t++;
542     }
543 }
544 
545 static void
append_acs0(string_desc * dst,int code,int src)546 append_acs0(string_desc * dst, int code, int src)
547 {
548     if (src != 0) {
549 	char temp[3];
550 	temp[0] = code;
551 	temp[1] = src;
552 	temp[2] = 0;
553 	_nc_safe_strcat(dst, temp);
554     }
555 }
556 
557 static void
append_acs(string_desc * dst,int code,char * src)558 append_acs(string_desc * dst, int code, char *src)
559 {
560     if (src != 0 && strlen(src) == 1) {
561 	append_acs0(dst, code, *src);
562     }
563 }
564 
565 /*
566  * The ko capability, if present, consists of a comma-separated capability
567  * list.  For each capability, we may assume there is a keycap that sends the
568  * string which is the value of that capability.
569  */
570 typedef struct {
571     const char *from;
572     const char *to;
573 } assoc;
574 static assoc const ko_xlate[] =
575 {
576     {"al", "kil1"},		/* insert line key  -> KEY_IL    */
577     {"bt", "kcbt"},		/* back tab         -> KEY_BTAB  */
578     {"cd", "ked"},		/* clear-to-eos key -> KEY_EOL   */
579     {"ce", "kel"},		/* clear-to-eol key -> KEY_EOS   */
580     {"cl", "kclr"},		/* clear key        -> KEY_CLEAR */
581     {"ct", "tbc"},		/* clear all tabs   -> KEY_CATAB */
582     {"dc", "kdch1"},		/* delete char      -> KEY_DC    */
583     {"dl", "kdl1"},		/* delete line      -> KEY_DL    */
584     {"do", "kcud1"},		/* down key         -> KEY_DOWN  */
585     {"ei", "krmir"},		/* exit insert key  -> KEY_EIC   */
586     {"ho", "khome"},		/* home key         -> KEY_HOME  */
587     {"ic", "kich1"},		/* insert char key  -> KEY_IC    */
588     {"im", "kIC"},		/* insert-mode key  -> KEY_SIC   */
589     {"le", "kcub1"},		/* le key           -> KEY_LEFT  */
590     {"nd", "kcuf1"},		/* nd key           -> KEY_RIGHT */
591     {"nl", "kent"},		/* new line key     -> KEY_ENTER */
592     {"st", "khts"},		/* set-tab key      -> KEY_STAB  */
593     {"ta", CANCELLED_STRING},
594     {"up", "kcuu1"},		/* up-arrow key     -> KEY_UP    */
595     {(char *) 0, (char *) 0},
596 };
597 
598 /*
599  * This routine fills in string caps that either had defaults under
600  * termcap or can be manufactured from obsolete termcap capabilities.
601  * It was lifted from Ross Ridge's mytinfo package.
602  */
603 
604 static const char C_CR[] = "\r";
605 static const char C_LF[] = "\n";
606 static const char C_BS[] = "\b";
607 static const char C_HT[] = "\t";
608 
609 /*
610  * Note that WANTED and PRESENT are not simple inverses!  If a capability
611  * has been explicitly cancelled, it's not considered WANTED.
612  */
613 #define WANTED(s)	((s) == ABSENT_STRING)
614 #define PRESENT(s)	(((s) != ABSENT_STRING) && ((s) != CANCELLED_STRING))
615 
616 /*
617  * This bit of legerdemain turns all the terminfo variable names into
618  * references to locations in the arrays Booleans, Numbers, and Strings ---
619  * precisely what's needed.
620  */
621 
622 #undef CUR
623 #define CUR tp->
624 
625 static void
postprocess_termcap(TERMTYPE * tp,bool has_base)626 postprocess_termcap(TERMTYPE *tp, bool has_base)
627 {
628     char buf[MAX_LINE * 2 + 2];
629     string_desc result;
630 
631     /*
632      * TERMCAP DEFAULTS AND OBSOLETE-CAPABILITY TRANSLATIONS
633      *
634      * This first part of the code is the functional inverse of the
635      * fragment in capdefaults.c.
636      * ----------------------------------------------------------------------
637      */
638 
639     /* if there was a tc entry, assume we picked up defaults via that */
640     if (!has_base) {
641 	if (WANTED(init_3string) && termcap_init2)
642 	    init_3string = _nc_save_str(termcap_init2);
643 
644 	if (WANTED(reset_2string) && termcap_reset)
645 	    reset_2string = _nc_save_str(termcap_reset);
646 
647 	if (WANTED(carriage_return)) {
648 	    if (carriage_return_delay > 0) {
649 		sprintf(buf, "%s$<%d>", C_CR, carriage_return_delay);
650 		carriage_return = _nc_save_str(buf);
651 	    } else
652 		carriage_return = _nc_save_str(C_CR);
653 	}
654 	if (WANTED(cursor_left)) {
655 	    if (backspace_delay > 0) {
656 		sprintf(buf, "%s$<%d>", C_BS, backspace_delay);
657 		cursor_left = _nc_save_str(buf);
658 	    } else if (backspaces_with_bs == 1)
659 		cursor_left = _nc_save_str(C_BS);
660 	    else if (PRESENT(backspace_if_not_bs))
661 		cursor_left = backspace_if_not_bs;
662 	}
663 	/* vi doesn't use "do", but it does seems to use nl (or '\n') instead */
664 	if (WANTED(cursor_down)) {
665 	    if (PRESENT(linefeed_if_not_lf))
666 		cursor_down = linefeed_if_not_lf;
667 	    else if (linefeed_is_newline != 1) {
668 		if (new_line_delay > 0) {
669 		    sprintf(buf, "%s$<%d>", C_LF, new_line_delay);
670 		    cursor_down = _nc_save_str(buf);
671 		} else
672 		    cursor_down = _nc_save_str(C_LF);
673 	    }
674 	}
675 	if (WANTED(scroll_forward) && crt_no_scrolling != 1) {
676 	    if (PRESENT(linefeed_if_not_lf))
677 		cursor_down = linefeed_if_not_lf;
678 	    else if (linefeed_is_newline != 1) {
679 		if (new_line_delay > 0) {
680 		    sprintf(buf, "%s$<%d>", C_LF, new_line_delay);
681 		    scroll_forward = _nc_save_str(buf);
682 		} else
683 		    scroll_forward = _nc_save_str(C_LF);
684 	    }
685 	}
686 	if (WANTED(newline)) {
687 	    if (linefeed_is_newline == 1) {
688 		if (new_line_delay > 0) {
689 		    sprintf(buf, "%s$<%d>", C_LF, new_line_delay);
690 		    newline = _nc_save_str(buf);
691 		} else
692 		    newline = _nc_save_str(C_LF);
693 	    } else if (PRESENT(carriage_return) && PRESENT(scroll_forward)) {
694 		_nc_str_init(&result, buf, sizeof(buf));
695 		if (_nc_safe_strcat(&result, carriage_return)
696 		    && _nc_safe_strcat(&result, scroll_forward))
697 		    newline = _nc_save_str(buf);
698 	    } else if (PRESENT(carriage_return) && PRESENT(cursor_down)) {
699 		_nc_str_init(&result, buf, sizeof(buf));
700 		if (_nc_safe_strcat(&result, carriage_return)
701 		    && _nc_safe_strcat(&result, cursor_down))
702 		    newline = _nc_save_str(buf);
703 	    }
704 	}
705     }
706 
707     /*
708      * Inverse of capdefaults.c code ends here.
709      * ----------------------------------------------------------------------
710      *
711      * TERMCAP-TO TERMINFO MAPPINGS FOR SOURCE TRANSLATION
712      *
713      * These translations will *not* be inverted by tgetent().
714      */
715 
716     if (!has_base) {
717 	/*
718 	 * We wait until now to decide if we've got a working cr because even
719 	 * one that doesn't work can be used for newline. Unfortunately the
720 	 * space allocated for it is wasted.
721 	 */
722 	if (return_does_clr_eol == 1 || no_correctly_working_cr == 1)
723 	    carriage_return = ABSENT_STRING;
724 
725 	/*
726 	 * Supposedly most termcap entries have ta now and '\t' is no longer a
727 	 * default, but it doesn't seem to be true...
728 	 */
729 	if (WANTED(tab)) {
730 	    if (horizontal_tab_delay > 0) {
731 		sprintf(buf, "%s$<%d>", C_HT, horizontal_tab_delay);
732 		tab = _nc_save_str(buf);
733 	    } else
734 		tab = _nc_save_str(C_HT);
735 	}
736 	if (init_tabs == ABSENT_NUMERIC && has_hardware_tabs == TRUE)
737 	    init_tabs = 8;
738 
739 	/*
740 	 * Assume we can beep with ^G unless we're given bl@.
741 	 */
742 	if (WANTED(bell))
743 	    bell = _nc_save_str("\007");
744     }
745 
746     /*
747      * Translate the old termcap :pt: capability to it#8 + ht=\t
748      */
749     if (has_hardware_tabs == TRUE) {
750 	if (init_tabs != 8 && init_tabs != ABSENT_NUMERIC)
751 	    _nc_warning("hardware tabs with a width other than 8: %d", init_tabs);
752 	else {
753 	    if (tab && _nc_capcmp(tab, C_HT))
754 		_nc_warning("hardware tabs with a non-^I tab string %s",
755 			    _nc_visbuf(tab));
756 	    else {
757 		if (WANTED(tab))
758 		    tab = _nc_save_str(C_HT);
759 		init_tabs = 8;
760 	    }
761 	}
762     }
763     /*
764      * Now translate the ko capability, if there is one.  This
765      * isn't from mytinfo...
766      */
767     if (PRESENT(other_non_function_keys)) {
768 	char *base = other_non_function_keys;
769 	char *bp, *cp, *dp;
770 	struct name_table_entry const *from_ptr;
771 	struct name_table_entry const *to_ptr;
772 	assoc const *ap;
773 	char buf2[MAX_TERMINFO_LENGTH];
774 	bool foundim;
775 
776 	/* we're going to use this for a special case later */
777 	dp = strchr(other_non_function_keys, 'i');
778 	foundim = (dp != 0) && (dp[1] == 'm');
779 
780 	/* look at each comma-separated capability in the ko string... */
781 	for (base = other_non_function_keys;
782 	     (cp = strchr(base, ',')) != 0;
783 	     base = cp + 1) {
784 	    size_t len = cp - base;
785 
786 	    for (ap = ko_xlate; ap->from; ap++)
787 		if (len == strlen(ap->from)
788 		    && strncmp(ap->from, base, len) == 0)
789 		    break;
790 	    if (!ap->to) {
791 		_nc_warning("unknown capability `%.*s' in ko string",
792 			    (int) len, base);
793 		continue;
794 	    } else if (ap->to == CANCELLED_STRING)	/* ignore it */
795 		continue;
796 
797 	    /* now we know we found a match in ko_table, so... */
798 
799 	    from_ptr = _nc_find_entry(ap->from, _nc_cap_hash_table);
800 	    to_ptr = _nc_find_entry(ap->to, _nc_info_hash_table);
801 
802 	    if (!from_ptr || !to_ptr)	/* should never happen! */
803 		_nc_err_abort("ko translation table is invalid, I give up");
804 
805 	    if (WANTED(tp->Strings[from_ptr->nte_index])) {
806 		_nc_warning("no value for ko capability %s", ap->from);
807 		continue;
808 	    }
809 
810 	    if (tp->Strings[to_ptr->nte_index]) {
811 		/* There's no point in warning about it if it's the same
812 		 * string; that's just an inefficiency.
813 		 */
814 		if (strcmp(
815 			      tp->Strings[from_ptr->nte_index],
816 			      tp->Strings[to_ptr->nte_index]) != 0)
817 		    _nc_warning("%s (%s) already has an explicit value %s, ignoring ko",
818 				ap->to, ap->from,
819 				_nc_visbuf(tp->Strings[to_ptr->nte_index]));
820 		continue;
821 	    }
822 
823 	    /*
824 	     * The magic moment -- copy the mapped key string over,
825 	     * stripping out padding.
826 	     */
827 	    for (dp = buf2, bp = tp->Strings[from_ptr->nte_index]; *bp; bp++) {
828 		if (bp[0] == '$' && bp[1] == '<') {
829 		    while (*bp && *bp != '>') {
830 			++bp;
831 		    }
832 		} else
833 		    *dp++ = *bp;
834 	    }
835 	    *dp++ = '\0';
836 
837 	    tp->Strings[to_ptr->nte_index] = _nc_save_str(buf2);
838 	}
839 
840 	/*
841 	 * Note: ko=im and ko=ic both want to grab the `Insert'
842 	 * keycap.  There's a kich1 but no ksmir, so the ic capability
843 	 * got mapped to kich1 and im to kIC to avoid a collision.
844 	 * If the description has im but not ic, hack kIC back to kich1.
845 	 */
846 	if (foundim && WANTED(key_ic) && key_sic) {
847 	    key_ic = key_sic;
848 	    key_sic = ABSENT_STRING;
849 	}
850     }
851 
852     if (!has_base) {
853 	if (!hard_copy) {
854 	    if (WANTED(key_backspace))
855 		key_backspace = _nc_save_str(C_BS);
856 	    if (WANTED(key_left))
857 		key_left = _nc_save_str(C_BS);
858 	    if (WANTED(key_down))
859 		key_down = _nc_save_str(C_LF);
860 	}
861     }
862 
863     /*
864      * Translate XENIX forms characters.
865      */
866     if (PRESENT(acs_ulcorner) ||
867 	PRESENT(acs_llcorner) ||
868 	PRESENT(acs_urcorner) ||
869 	PRESENT(acs_lrcorner) ||
870 	PRESENT(acs_ltee) ||
871 	PRESENT(acs_rtee) ||
872 	PRESENT(acs_btee) ||
873 	PRESENT(acs_ttee) ||
874 	PRESENT(acs_hline) ||
875 	PRESENT(acs_vline) ||
876 	PRESENT(acs_plus)) {
877 	char buf2[MAX_TERMCAP_LENGTH];
878 
879 	_nc_str_init(&result, buf2, sizeof(buf2));
880 	_nc_safe_strcat(&result, acs_chars);
881 
882 	append_acs(&result, 'j', acs_lrcorner);
883 	append_acs(&result, 'k', acs_urcorner);
884 	append_acs(&result, 'l', acs_ulcorner);
885 	append_acs(&result, 'm', acs_llcorner);
886 	append_acs(&result, 'n', acs_plus);
887 	append_acs(&result, 'q', acs_hline);
888 	append_acs(&result, 't', acs_ltee);
889 	append_acs(&result, 'u', acs_rtee);
890 	append_acs(&result, 'v', acs_btee);
891 	append_acs(&result, 'w', acs_ttee);
892 	append_acs(&result, 'x', acs_vline);
893 
894 	if (buf2[0]) {
895 	    acs_chars = _nc_save_str(buf2);
896 	    _nc_warning("acsc string synthesized from XENIX capabilities");
897 	}
898     } else if (acs_chars == 0
899 	       && enter_alt_charset_mode != 0
900 	       && exit_alt_charset_mode != 0) {
901 	acs_chars = _nc_save_str(VT_ACSC);
902     }
903 }
904 
905 static void
postprocess_terminfo(TERMTYPE * tp)906 postprocess_terminfo(TERMTYPE *tp)
907 {
908     /*
909      * TERMINFO-TO-TERMINFO MAPPINGS FOR SOURCE TRANSLATION
910      * ----------------------------------------------------------------------
911      */
912 
913     /*
914      * Translate AIX forms characters.
915      */
916     if (PRESENT(box_chars_1)) {
917 	char buf2[MAX_TERMCAP_LENGTH];
918 	string_desc result;
919 
920 	_nc_str_init(&result, buf2, sizeof(buf2));
921 	_nc_safe_strcat(&result, acs_chars);
922 
923 	append_acs0(&result, 'l', box_chars_1[0]);	/* ACS_ULCORNER */
924 	append_acs0(&result, 'q', box_chars_1[1]);	/* ACS_HLINE */
925 	append_acs0(&result, 'k', box_chars_1[2]);	/* ACS_URCORNER */
926 	append_acs0(&result, 'x', box_chars_1[3]);	/* ACS_VLINE */
927 	append_acs0(&result, 'j', box_chars_1[4]);	/* ACS_LRCORNER */
928 	append_acs0(&result, 'm', box_chars_1[5]);	/* ACS_LLCORNER */
929 	append_acs0(&result, 'w', box_chars_1[6]);	/* ACS_TTEE */
930 	append_acs0(&result, 'u', box_chars_1[7]);	/* ACS_RTEE */
931 	append_acs0(&result, 'v', box_chars_1[8]);	/* ACS_BTEE */
932 	append_acs0(&result, 't', box_chars_1[9]);	/* ACS_LTEE */
933 	append_acs0(&result, 'n', box_chars_1[10]);	/* ACS_PLUS */
934 
935 	if (buf2[0]) {
936 	    acs_chars = _nc_save_str(buf2);
937 	    _nc_warning("acsc string synthesized from AIX capabilities");
938 	    box_chars_1 = ABSENT_STRING;
939 	}
940     }
941     /*
942      * ----------------------------------------------------------------------
943      */
944 }
945 
946 /*
947  * Do a linear search through the terminfo tables to find a given full-name.
948  * We don't expect to do this often, so there's no hashing function.
949  *
950  * In effect, this scans through the 3 lists of full-names, and looks them
951  * up in _nc_info_table, which is organized so that the nte_index fields are
952  * sorted, but the nte_type fields are not necessarily grouped together.
953  */
954 static struct name_table_entry const *
lookup_fullname(const char * find)955 lookup_fullname(const char *find)
956 {
957     int state = -1;
958 
959     for (;;) {
960 	int count = 0;
961 	NCURSES_CONST char *const *names;
962 
963 	switch (++state) {
964 	case BOOLEAN:
965 	    names = boolfnames;
966 	    break;
967 	case STRING:
968 	    names = strfnames;
969 	    break;
970 	case NUMBER:
971 	    names = numfnames;
972 	    break;
973 	default:
974 	    return NOTFOUND;
975 	}
976 
977 	for (count = 0; names[count] != 0; count++) {
978 	    if (!strcmp(names[count], find)) {
979 		struct name_table_entry const *entry_ptr = _nc_get_table(FALSE);
980 		while (entry_ptr->nte_type != state
981 		       || entry_ptr->nte_index != count)
982 		    entry_ptr++;
983 		return entry_ptr;
984 	    }
985 	}
986     }
987 }
988 
989 /* parse_entry.c ends here */
990