xref: /openbsd-src/lib/libcurses/tinfo/write_entry.c (revision 84af20cee44481ef9eb2070c76702603863c1a4c)
1 /*	$OpenBSD: write_entry.c,v 1.10 2001/01/22 18:01:57 millert Exp $	*/
2 
3 /****************************************************************************
4  * Copyright (c) 1998,1999,2000 Free Software Foundation, Inc.              *
5  *                                                                          *
6  * Permission is hereby granted, free of charge, to any person obtaining a  *
7  * copy of this software and associated documentation files (the            *
8  * "Software"), to deal in the Software without restriction, including      *
9  * without limitation the rights to use, copy, modify, merge, publish,      *
10  * distribute, distribute with modifications, sublicense, and/or sell       *
11  * copies of the Software, and to permit persons to whom the Software is    *
12  * furnished to do so, subject to the following conditions:                 *
13  *                                                                          *
14  * The above copyright notice and this permission notice shall be included  *
15  * in all copies or substantial portions of the Software.                   *
16  *                                                                          *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
20  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
21  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
22  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
23  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
24  *                                                                          *
25  * Except as contained in this notice, the name(s) of the above copyright   *
26  * holders shall not be used in advertising or otherwise to promote the     *
27  * sale, use or other dealings in this Software without prior written       *
28  * authorization.                                                           *
29  ****************************************************************************/
30 
31 /****************************************************************************
32  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
33  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
34  ****************************************************************************/
35 
36 /*
37  *	write_entry.c -- write a terminfo structure onto the file system
38  */
39 
40 #include <curses.priv.h>
41 
42 #include <sys/stat.h>
43 
44 #include <tic.h>
45 #include <term_entry.h>
46 
47 #ifndef S_ISDIR
48 #define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
49 #endif
50 
51 #if 0
52 #define TRACE_OUT(p) DEBUG(2, p)
53 #else
54 #define TRACE_OUT(p)		/*nothing */
55 #endif
56 
57 MODULE_ID("$From: write_entry.c,v 1.56 2000/12/10 02:55:08 tom Exp $")
58 
59 static int total_written;
60 
61 static int write_object(FILE *, TERMTYPE *);
62 
63 static void
64 write_file(char *filename, TERMTYPE * tp)
65 {
66     FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
67     if (fp == 0) {
68 	perror(filename);
69 	_nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
70     }
71     DEBUG(1, ("Created %s", filename));
72 
73     if (write_object(fp, tp) == ERR) {
74 	_nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
75     }
76     fclose(fp);
77 }
78 
79 /*
80  *	make_directory(char *path)
81  *
82  *	Make a directory if it doesn't exist.
83  */
84 static int
85 make_directory(const char *path)
86 {
87     int rc;
88     struct stat statbuf;
89     char fullpath[PATH_MAX];
90     const char *destination = _nc_tic_dir(0);
91 
92     if (path == destination || *path == '/') {
93 	if (strlen(path) + 1 > sizeof(fullpath))
94 	    return (-1);
95 	(void) strcpy(fullpath, path);
96     } else {
97 	if (strlen(destination) + strlen(path) + 2 > sizeof(fullpath))
98 	    return (-1);
99 	(void) sprintf(fullpath, "%s/%s", destination, path);
100     }
101 
102     if ((rc = stat(path, &statbuf)) < 0) {
103 	rc = mkdir(path, 0777);
104     } else {
105 	if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
106 	    rc = -1;		/* permission denied */
107 	} else if (!(S_ISDIR(statbuf.st_mode))) {
108 	    rc = -1;		/* not a directory */
109 	}
110     }
111     return rc;
112 }
113 
114 NCURSES_EXPORT(void)
115 _nc_set_writedir(char *dir)
116 /* set the write directory for compiled entries */
117 {
118     const char *destination;
119     char actual[PATH_MAX];
120 
121     if (dir == 0
122 	&& use_terminfo_vars())
123 	dir = getenv("TERMINFO");
124 
125     if (dir != 0)
126 	(void) _nc_tic_dir(dir);
127 
128     destination = _nc_tic_dir(0);
129     if (make_directory(destination) < 0) {
130 	char *home = _nc_home_terminfo();
131 
132 	if (home != 0) {
133 	    destination = home;
134 	    if (make_directory(destination) < 0)
135 		_nc_err_abort("%s: permission denied (errno %d)",
136 			      destination, errno);
137 	}
138     }
139 
140     /*
141      * Note: because of this code, this logic should be exercised
142      * *once only* per run.
143      */
144     if (chdir(_nc_tic_dir(destination)) < 0
145 	|| getcwd(actual, sizeof(actual)) == 0)
146 	_nc_err_abort("%s: not a directory", destination);
147     _nc_keep_tic_dir(strdup(actual));
148 }
149 
150 /*
151  *	check_writeable(char code)
152  *
153  *	Miscellaneous initialisations
154  *
155  *	Check for access rights to destination directories
156  *	Create any directories which don't exist.
157  *	Note: there's no reason to return the result of make_directory(), since
158  *	this function is called only in instances where that has to succeed.
159  *
160  */
161 
162 static void
163 check_writeable(int code)
164 {
165     static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
166     static bool verified[sizeof(dirnames)];
167 
168     char dir[2];
169     char *s = 0;
170 
171     if (code == 0 || (s = strchr(dirnames, code)) == 0)
172 	_nc_err_abort("Illegal terminfo subdirectory \"%c\"", code);
173 
174     if (verified[s - dirnames])
175 	return;
176 
177     dir[0] = code;
178     dir[1] = '\0';
179     if (make_directory(dir) < 0) {
180 	_nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
181     }
182 
183     verified[s - dirnames] = TRUE;
184 }
185 
186 /*
187  *	_nc_write_entry()
188  *
189  *	Save the compiled version of a description in the filesystem.
190  *
191  *	make a copy of the name-list
192  *	break it up into first-name and all-but-last-name
193  *	creat(first-name)
194  *	write object information to first-name
195  *	close(first-name)
196  *      for each name in all-but-last-name
197  *	    link to first-name
198  *
199  *	Using 'time()' to obtain a reference for file timestamps is unreliable,
200  *	e.g., with NFS, because the filesystem may have a different time
201  *	reference.  We check for pre-existence of links by latching the first
202  *	timestamp from a file that we create.
203  *
204  *	The _nc_warning() calls will report a correct line number only if
205  *	_nc_curr_line is properly set before the write_entry() call.
206  */
207 
208 void
209 _nc_write_entry(TERMTYPE * const tp)
210 {
211     struct stat statbuf;
212     char name_list[MAX_TERMINFO_LENGTH];
213     char *first_name, *other_names;
214     char *ptr;
215     char filename[PATH_MAX];
216     char linkname[PATH_MAX];
217 #if USE_SYMLINKS
218     char symlinkname[PATH_MAX];
219 #endif /* USE_SYMLINKS */
220     static int call_count;
221     static time_t start_time;	/* time at start of writes */
222 
223     if (call_count++ == 0) {
224 	start_time = 0;
225     }
226 
227     (void) strcpy(name_list, tp->term_names);
228     DEBUG(7, ("Name list = '%s'", name_list));
229 
230     first_name = name_list;
231 
232     ptr = &name_list[strlen(name_list) - 1];
233     other_names = ptr + 1;
234 
235     while (ptr > name_list && *ptr != '|')
236 	ptr--;
237 
238     if (ptr != name_list) {
239 	*ptr = '\0';
240 
241 	for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
242 	    continue;
243 
244 	if (*ptr == '\0')
245 	    other_names = ptr;
246 	else {
247 	    *ptr = '\0';
248 	    other_names = ptr + 1;
249 	}
250     }
251 
252     DEBUG(7, ("First name = '%s'", first_name));
253     DEBUG(7, ("Other names = '%s'", other_names));
254 
255     _nc_set_type(first_name);
256 
257     if (strlen(first_name) > sizeof(filename) - 3)
258 	_nc_warning("terminal name too long.");
259 
260     sprintf(filename, "%c/%s", first_name[0], first_name);
261 
262     /*
263      * Has this primary name been written since the first call to
264      * write_entry()?  If so, the newer write will step on the older,
265      * so warn the user.
266      */
267     if (start_time > 0 &&
268 	stat(filename, &statbuf) >= 0
269 	&& statbuf.st_mtime >= start_time) {
270 	_nc_warning("name multiply defined.");
271     }
272 
273     check_writeable(first_name[0]);
274     write_file(filename, tp);
275 
276     if (start_time == 0) {
277 	if (stat(filename, &statbuf) < 0
278 	    || (start_time = statbuf.st_mtime) == 0) {
279 	    _nc_syserr_abort("error obtaining time from %s/%s",
280 			     _nc_tic_dir(0), filename);
281 	}
282     }
283     while (*other_names != '\0') {
284 	ptr = other_names++;
285 	while (*other_names != '|' && *other_names != '\0')
286 	    other_names++;
287 
288 	if (*other_names != '\0')
289 	    *(other_names++) = '\0';
290 
291 	if (strlen(ptr) > sizeof(linkname) - 3) {
292 	    _nc_warning("terminal alias %s too long.", ptr);
293 	    continue;
294 	}
295 	if (strchr(ptr, '/') != 0) {
296 	    _nc_warning("cannot link alias %s.", ptr);
297 	    continue;
298 	}
299 
300 	check_writeable(ptr[0]);
301 	sprintf(linkname, "%c/%s", ptr[0], ptr);
302 
303 	if (strcmp(filename, linkname) == 0) {
304 	    _nc_warning("self-synonym ignored");
305 	} else if (stat(linkname, &statbuf) >= 0 &&
306 		   statbuf.st_mtime < start_time) {
307 	    _nc_warning("alias %s multiply defined.", ptr);
308 	} else if (_nc_access(linkname, W_OK) == 0)
309 #if HAVE_LINK
310 	{
311 	    int code;
312 #if USE_SYMLINKS
313 	    strcpy(symlinkname, "../");
314 	    strncat(symlinkname, filename, sizeof(symlinkname) - 4);
315 	    symlinkname[sizeof(symlinkname) - 1] = '\0';
316 #endif /* USE_SYMLINKS */
317 #if HAVE_REMOVE
318 	    code = remove(linkname);
319 #else
320 	    code = unlink(linkname);
321 #endif
322 	    if (code != 0 && errno == ENOENT)
323 		code = 0;
324 #if USE_SYMLINKS
325 	    if (symlink(symlinkname, linkname) < 0)
326 #else
327 	    if (link(filename, linkname) < 0)
328 #endif /* USE_SYMLINKS */
329 	    {
330 		/*
331 		 * If there wasn't anything there, and we cannot
332 		 * link to the target because it is the same as the
333 		 * target, then the source must be on a filesystem
334 		 * that uses caseless filenames, such as Win32, etc.
335 		 */
336 		if (code == 0 && errno == EEXIST)
337 		    _nc_warning("can't link %s to %s", filename, linkname);
338 		else if (code == 0 && (errno == EPERM || errno == ENOENT))
339 		    write_file(linkname, tp);
340 		else {
341 #if MIXEDCASE_FILENAMES
342 		    _nc_syserr_abort("can't link %s to %s", filename, linkname);
343 #else
344 		    _nc_warning("can't link %s to %s (errno=%d)", filename,
345 				linkname, errno);
346 #endif
347 		}
348 	    } else {
349 		DEBUG(1, ("Linked %s", linkname));
350 	    }
351 	}
352 #else /* just make copies */
353 	    write_file(linkname, tp);
354 #endif /* HAVE_LINK */
355     }
356 }
357 
358 #undef LITTLE_ENDIAN		/* BSD/OS defines this as a feature macro */
359 #define HI(x)			((x) / 256)
360 #define LO(x)			((x) % 256)
361 #define LITTLE_ENDIAN(p, x)	(p)[0] = LO(x), (p)[1] = HI(x)
362 
363 #define WRITE_STRING(str) (fwrite(str, sizeof(char), strlen(str) + 1, fp) == strlen(str) + 1)
364 
365 static int
366 compute_offsets(char **Strings, int strmax, short *offsets)
367 {
368     size_t nextfree = 0;
369     int i;
370 
371     for (i = 0; i < strmax; i++) {
372 	if (Strings[i] == ABSENT_STRING) {
373 	    offsets[i] = -1;
374 	} else if (Strings[i] == CANCELLED_STRING) {
375 	    offsets[i] = -2;
376 	} else {
377 	    offsets[i] = nextfree;
378 	    nextfree += strlen(Strings[i]) + 1;
379 	    TRACE_OUT(("put Strings[%d]=%s(%d)", i, _nc_visbuf(Strings[i]), nextfree));
380 	}
381     }
382     return nextfree;
383 }
384 
385 static void
386 convert_shorts(unsigned char *buf, short *Numbers, int count)
387 {
388     int i;
389     for (i = 0; i < count; i++) {
390 	if (Numbers[i] == ABSENT_NUMERIC) {	/* HI/LO won't work */
391 	    buf[2 * i] = buf[2 * i + 1] = 0377;
392 	} else if (Numbers[i] == CANCELLED_NUMERIC) {	/* HI/LO won't work */
393 	    buf[2 * i] = 0376;
394 	    buf[2 * i + 1] = 0377;
395 	} else {
396 	    LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
397 	    TRACE_OUT(("put Numbers[%d]=%d", i, Numbers[i]));
398 	}
399     }
400 }
401 
402 #define even_boundary(value) \
403 	    ((value) % 2 != 0 && fwrite(&zero, sizeof(char), 1, fp) != 1)
404 
405 static int
406 write_object(FILE * fp, TERMTYPE * tp)
407 {
408     char *namelist;
409     size_t namelen, boolmax, nummax, strmax;
410     char zero = '\0';
411     size_t i;
412     short nextfree;
413     short offsets[MAX_ENTRY_SIZE / 2];
414     unsigned char buf[MAX_ENTRY_SIZE];
415     unsigned last_bool = BOOLWRITE;
416     unsigned last_num = NUMWRITE;
417     unsigned last_str = STRWRITE;
418 
419 #if NCURSES_XNAMES
420     /*
421      * Normally we limit the list of values to exclude the "obsolete"
422      * capabilities.  However, if we are accepting extended names, add
423      * these as well, since they are used for supporting translation
424      * to/from termcap.
425      */
426     if (_nc_user_definable) {
427 	last_bool = BOOLCOUNT;
428 	last_num = NUMCOUNT;
429 	last_str = STRCOUNT;
430     }
431 #endif
432 
433     namelist = tp->term_names;
434     namelen = strlen(namelist) + 1;
435 
436     boolmax = 0;
437     for (i = 0; i < last_bool; i++) {
438 	if (tp->Booleans[i] == TRUE)
439 	    boolmax = i + 1;
440     }
441 
442     nummax = 0;
443     for (i = 0; i < last_num; i++) {
444 	if (tp->Numbers[i] != ABSENT_NUMERIC)
445 	    nummax = i + 1;
446     }
447 
448     strmax = 0;
449     for (i = 0; i < last_str; i++) {
450 	if (tp->Strings[i] != ABSENT_STRING)
451 	    strmax = i + 1;
452     }
453 
454     nextfree = compute_offsets(tp->Strings, strmax, offsets);
455 
456     /* fill in the header */
457     LITTLE_ENDIAN(buf, MAGIC);
458     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
459     LITTLE_ENDIAN(buf + 4, boolmax);
460     LITTLE_ENDIAN(buf + 6, nummax);
461     LITTLE_ENDIAN(buf + 8, strmax);
462     LITTLE_ENDIAN(buf + 10, nextfree);
463 
464     /* write out the header */
465     TRACE_OUT(("Header of %s @%ld", namelist, ftell(fp)));
466     if (fwrite(buf, 12, 1, fp) != 1
467 	|| fwrite(namelist, sizeof(char), namelen, fp) != namelen)
468 	  return (ERR);
469 
470     for (i = 0; i < boolmax; i++)
471 	if (tp->Booleans[i] == TRUE)
472 	    buf[i] = TRUE;
473 	else
474 	    buf[i] = FALSE;
475     if (fwrite(buf, sizeof(char), boolmax, fp) != boolmax)
476 	  return (ERR);
477 
478     if (even_boundary(namelen + boolmax))
479 	return (ERR);
480 
481     TRACE_OUT(("Numerics begin at %04lx", ftell(fp)));
482 
483     /* the numerics */
484     convert_shorts(buf, tp->Numbers, nummax);
485     if (fwrite(buf, 2, nummax, fp) != nummax)
486 	return (ERR);
487 
488     TRACE_OUT(("String offsets begin at %04lx", ftell(fp)));
489 
490     /* the string offsets */
491     convert_shorts(buf, offsets, strmax);
492     if (fwrite(buf, 2, strmax, fp) != strmax)
493 	return (ERR);
494 
495     TRACE_OUT(("String table begins at %04lx", ftell(fp)));
496 
497     /* the strings */
498     for (i = 0; i < strmax; i++)
499 	if (VALID_STRING(tp->Strings[i]))
500 	    if (!WRITE_STRING(tp->Strings[i]))
501 		return (ERR);
502 
503 #if NCURSES_XNAMES
504     if (NUM_EXT_NAMES(tp)) {
505 	unsigned extcnt = NUM_EXT_NAMES(tp);
506 
507 	if (even_boundary(nextfree))
508 	    return (ERR);
509 
510 	nextfree = compute_offsets(tp->Strings + STRCOUNT, tp->ext_Strings, offsets);
511 	TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
512 	nextfree += compute_offsets(tp->ext_Names, extcnt, offsets + tp->ext_Strings);
513 	TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
514 	strmax = tp->ext_Strings + extcnt;
515 
516 	/*
517 	 * Write the extended header
518 	 */
519 	LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
520 	LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
521 	LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
522 	LITTLE_ENDIAN(buf + 6, strmax);
523 	LITTLE_ENDIAN(buf + 8, nextfree);
524 	TRACE_OUT(("WRITE extended-header @%ld", ftell(fp)));
525 	if (fwrite(buf, 10, 1, fp) != 1)
526 	    return (ERR);
527 
528 	TRACE_OUT(("WRITE %d booleans @%ld", tp->ext_Booleans, ftell(fp)));
529 	if (tp->ext_Booleans
530 	    && fwrite(tp->Booleans + BOOLCOUNT, sizeof(char),
531 		      tp->ext_Booleans, fp) != tp->ext_Booleans)
532 	      return (ERR);
533 
534 	if (even_boundary(tp->ext_Booleans))
535 	    return (ERR);
536 
537 	TRACE_OUT(("WRITE %d numbers @%ld", tp->ext_Numbers, ftell(fp)));
538 	if (tp->ext_Numbers) {
539 	    convert_shorts(buf, tp->Numbers + NUMCOUNT, tp->ext_Numbers);
540 	    if (fwrite(buf, 2, tp->ext_Numbers, fp) != tp->ext_Numbers)
541 		return (ERR);
542 	}
543 
544 	/*
545 	 * Convert the offsets for the ext_Strings and ext_Names tables,
546 	 * in that order.
547 	 */
548 	convert_shorts(buf, offsets, strmax);
549 	TRACE_OUT(("WRITE offsets @%ld", ftell(fp)));
550 	if (fwrite(buf, 2, strmax, fp) != strmax)
551 	    return (ERR);
552 
553 	/*
554 	 * Write the string table after the offset tables so we do not
555 	 * have to do anything about alignment.
556 	 */
557 	for (i = 0; i < tp->ext_Strings; i++) {
558 	    if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
559 		TRACE_OUT(("WRITE ext_Strings[%d]=%s", i,
560 			   _nc_visbuf(tp->Strings[i + STRCOUNT])));
561 		if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
562 		    return (ERR);
563 	    }
564 	}
565 
566 	/*
567 	 * Write the extended names
568 	 */
569 	for (i = 0; i < extcnt; i++) {
570 	    TRACE_OUT(("WRITE ext_Names[%d]=%s", i, tp->ext_Names[i]));
571 	    if (!WRITE_STRING(tp->ext_Names[i]))
572 		return (ERR);
573 	}
574 
575     }
576 #endif /* NCURSES_XNAMES */
577 
578     total_written++;
579     return (OK);
580 }
581 
582 /*
583  * Returns the total number of entries written by this process
584  */
585 NCURSES_EXPORT(int)
586 _nc_tic_written(void)
587 {
588     return total_written;
589 }
590