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