1 /****************************************************************************
2 * Copyright (c) 1998-2015,2017 Free Software Foundation, Inc. *
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: *
12 * The above copyright notice and this permission notice shall be included *
13 * in all copies or substantial portions of the Software. *
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. *
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 *
27 ****************************************************************************/
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 ****************************************************************************/
36 * write_entry.c -- write a terminfo structure onto the file system
39 #include <curses.priv.h>
40 #include <hashed_db.h>
45 #define TRACE_OUT(p) DEBUG(2, p)
47 #define TRACE_OUT(p) /*nothing */
50 MODULE_ID("$Id: write_entry.c,v 1.98 2017/02/05 01:47:34 tom Exp $")
52 static int total_written;
53 static int total_parts;
54 static int total_size;
56 static int make_db_root(const char *);
60 write_file(char *filename, TERMTYPE *tp)
62 char buffer[MAX_ENTRY_SIZE];
63 unsigned limit = sizeof(buffer);
66 FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
69 _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
71 DEBUG(1, ("Created %s", filename));
73 if (_nc_write_object(tp, buffer, &offset, limit) == ERR
74 || fwrite(buffer, sizeof(char), (size_t) offset, fp) != offset) {
75 _nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
82 * Check for access rights to destination directories
83 * Create any directories which don't exist.
85 * Note: there's no reason to return the result of make_db_root(), since
86 * this function is called only in instances where that has to succeed.
89 check_writeable(int code)
91 static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
92 static bool verified[sizeof(dirnames)];
94 char dir[sizeof(LEAF_FMT)];
97 if (code == 0 || (s = (strchr) (dirnames, code)) == 0)
98 _nc_err_abort("Illegal terminfo subdirectory \"" LEAF_FMT "\"", code);
100 if (verified[s - dirnames])
103 _nc_SPRINTF(dir, _nc_SLIMIT(sizeof(dir)) LEAF_FMT, code);
104 if (make_db_root(dir) < 0) {
105 _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
108 verified[s - dirnames] = TRUE;
110 #endif /* !USE_HASHED_DB */
113 make_db_path(char *dst, const char *src, size_t limit)
116 const char *top = _nc_tic_dir(0);
118 if (src == top || _nc_is_abs_path(src)) {
119 if (strlen(src) + 1 <= limit) {
120 _nc_STRCPY(dst, src, limit);
124 if (strlen(top) + strlen(src) + 2 <= limit) {
125 _nc_SPRINTF(dst, _nc_SLIMIT(limit) "%s/%s", top, src);
131 static const char suffix[] = DBM_SUFFIX;
132 size_t have = strlen(dst);
133 size_t need = strlen(suffix);
134 if (have > need && strcmp(dst + (int) (have - need), suffix)) {
135 if (have + need <= limit) {
136 _nc_STRCAT(dst, suffix, limit);
140 } else if (_nc_is_dir_path(dst)) {
149 * Make a database-root if it doesn't exist.
152 make_db_root(const char *path)
155 char fullpath[PATH_MAX];
157 if ((rc = make_db_path(fullpath, path, sizeof(fullpath))) == 0) {
161 if ((capdbp = _nc_db_open(fullpath, TRUE)) == NULL) {
163 } else if (_nc_db_close(capdbp) < 0) {
169 if ((rc = stat(path, &statbuf)) < 0) {
171 #if !defined(__MINGW32__)
175 } else if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
176 rc = -1; /* permission denied */
177 } else if (!(S_ISDIR(statbuf.st_mode))) {
178 rc = -1; /* not a directory */
186 * Set the write directory for compiled entries.
189 _nc_set_writedir(const char *dir)
191 const char *destination;
192 char actual[PATH_MAX];
195 #ifndef USE_ROOT_ENVIRON
196 && use_terminfo_vars()
199 dir = getenv("TERMINFO");
202 (void) _nc_tic_dir(dir);
204 destination = _nc_tic_dir(0);
205 if (make_db_root(destination) < 0) {
206 char *home = _nc_home_terminfo();
210 if (make_db_root(destination) < 0)
211 _nc_err_abort("%s: permission denied (errno %d)",
217 * Note: because of this code, this logic should be exercised
218 * *once only* per run.
221 make_db_path(actual, destination, sizeof(actual));
223 if (chdir(_nc_tic_dir(destination)) < 0
224 || getcwd(actual, sizeof(actual)) == 0)
225 _nc_err_abort("%s: not a directory", destination);
227 _nc_keep_tic_dir(strdup(actual));
231 * Save the compiled version of a description in the filesystem.
233 * make a copy of the name-list
234 * break it up into first-name and all-but-last-name
236 * write object information to first-name
238 * for each name in all-but-last-name
241 * Using 'time()' to obtain a reference for file timestamps is unreliable,
242 * e.g., with NFS, because the filesystem may have a different time
243 * reference. We check for pre-existence of links by latching the first
244 * timestamp from a file that we create.
246 * The _nc_warning() calls will report a correct line number only if
247 * _nc_curr_line is properly set before the write_entry() call.
251 _nc_write_entry(TERMTYPE *const tp)
255 char buffer[MAX_ENTRY_SIZE + 1];
256 unsigned limit = sizeof(buffer);
259 #else /* !USE_HASHED_DB */
262 char filename[PATH_MAX];
263 char linkname[PATH_MAX];
265 char symlinkname[PATH_MAX];
270 #endif /* USE_SYMLINKS */
272 static int call_count;
273 static time_t start_time; /* time at start of writes */
275 #endif /* USE_HASHED_DB */
277 char name_list[MAX_TERMINFO_LENGTH];
278 char *first_name, *other_names;
280 char *term_names = tp->term_names;
281 size_t name_size = strlen(term_names);
283 if (name_size == 0) {
284 _nc_syserr_abort("no terminal name found.");
285 } else if (name_size >= sizeof(name_list) - 1) {
286 _nc_syserr_abort("terminal name too long: %s", term_names);
289 _nc_STRCPY(name_list, term_names, sizeof(name_list));
290 DEBUG(7, ("Name list = '%s'", name_list));
292 first_name = name_list;
294 ptr = &name_list[name_size - 1];
295 other_names = ptr + 1;
297 while (ptr > name_list && *ptr != '|')
300 if (ptr != name_list) {
303 for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
310 other_names = ptr + 1;
314 DEBUG(7, ("First name = '%s'", first_name));
315 DEBUG(7, ("Other names = '%s'", other_names));
317 _nc_set_type(first_name);
320 if (_nc_write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
321 DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
327 memset(&key, 0, sizeof(key));
328 key.data = term_names;
329 key.size = name_size;
331 memset(&data, 0, sizeof(data));
333 data.size = offset + 1;
335 _nc_db_put(capdb, &key, &data);
339 key.data = name_list;
340 key.size = strlen(name_list);
342 _nc_STRCPY(buffer + 1,
345 data.size = name_size + 1;
347 total_size += data.size;
349 _nc_db_put(capdb, &key, &data);
351 while (*other_names != '\0') {
353 assert(ptr < buffer + sizeof(buffer) - 1);
354 while (*other_names != '|' && *other_names != '\0')
357 if (*other_names != '\0')
358 *(other_names++) = '\0';
361 key.size = strlen(ptr);
363 total_size += data.size;
365 _nc_db_put(capdb, &key, &data);
369 #else /* !USE_HASHED_DB */
370 if (call_count++ == 0) {
374 if (strlen(first_name) >= sizeof(filename) - (2 + LEAF_LEN))
375 _nc_warning("terminal name too long.");
377 _nc_SPRINTF(filename, _nc_SLIMIT(sizeof(filename))
378 LEAF_FMT "/%s", first_name[0], first_name);
381 * Has this primary name been written since the first call to
382 * write_entry()? If so, the newer write will step on the older,
385 if (start_time > 0 &&
386 stat(filename, &statbuf) >= 0
387 && statbuf.st_mtime >= start_time) {
388 #if HAVE_LINK && !USE_SYMLINKS
390 * If the file has more than one link, the reason for the previous
391 * write could be that the current primary name used to be an alias for
392 * the previous entry. In that case, unlink the file so that we will
393 * not modify the previous entry as we write this one.
395 if (statbuf.st_nlink > 1) {
396 _nc_warning("name redefined.");
399 _nc_warning("name multiply defined.");
402 _nc_warning("name multiply defined.");
406 check_writeable(first_name[0]);
407 write_file(filename, tp);
409 if (start_time == 0) {
410 if (stat(filename, &statbuf) < 0
411 || (start_time = statbuf.st_mtime) == 0) {
412 _nc_syserr_abort("error obtaining time from %s/%s",
413 _nc_tic_dir(0), filename);
416 while (*other_names != '\0') {
418 while (*other_names != '|' && *other_names != '\0')
421 if (*other_names != '\0')
422 *(other_names++) = '\0';
424 if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
425 _nc_warning("terminal alias %s too long.", ptr);
428 if (strchr(ptr, '/') != 0) {
429 _nc_warning("cannot link alias %s.", ptr);
433 check_writeable(ptr[0]);
434 _nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
435 LEAF_FMT "/%s", ptr[0], ptr);
437 if (strcmp(filename, linkname) == 0) {
438 _nc_warning("self-synonym ignored");
439 } else if (stat(linkname, &statbuf) >= 0 &&
440 statbuf.st_mtime < start_time) {
441 _nc_warning("alias %s multiply defined.", ptr);
442 } else if (_nc_access(linkname, W_OK) == 0)
447 #define MY_SIZE sizeof(symlinkname) - 1
448 if (first_name[0] == linkname[0]) {
449 _nc_STRNCPY(symlinkname, first_name, MY_SIZE);
451 _nc_STRCPY(symlinkname, "../", sizeof(symlinkname));
452 _nc_STRNCPY(symlinkname + 3, filename, MY_SIZE - 3);
454 symlinkname[MY_SIZE] = '\0';
455 #endif /* USE_SYMLINKS */
457 code = remove(linkname);
459 code = unlink(linkname);
461 if (code != 0 && errno == ENOENT)
464 if (symlink(symlinkname, linkname) < 0)
466 if (link(filename, linkname) < 0)
467 #endif /* USE_SYMLINKS */
470 * If there wasn't anything there, and we cannot
471 * link to the target because it is the same as the
472 * target, then the source must be on a filesystem
473 * that uses caseless filenames, such as Win32, etc.
475 if (code == 0 && errno == EEXIST)
476 _nc_warning("can't link %s to %s", filename, linkname);
477 else if (code == 0 && (errno == EPERM || errno == ENOENT))
478 write_file(linkname, tp);
480 #if MIXEDCASE_FILENAMES
481 _nc_syserr_abort("can't link %s to %s", filename, linkname);
483 _nc_warning("can't link %s to %s (errno=%d)", filename,
488 DEBUG(1, ("Linked %s", linkname));
491 #else /* just make copies */
492 write_file(linkname, tp);
493 #endif /* HAVE_LINK */
495 #endif /* USE_HASHED_DB */
499 fake_write(char *dst,
506 size_t have = (limit - *offset);
512 memcpy(dst + *offset, src, want);
513 *offset += (unsigned) want;
517 return (want / size);
520 #define Write(buf, size, count) fake_write(buffer, offset, (size_t) limit, (char *) buf, (size_t) count, (size_t) size)
522 #undef LITTLE_ENDIAN /* BSD/OS defines this as a feature macro */
523 #define HI(x) ((x) / 256)
524 #define LO(x) ((x) % 256)
525 #define LITTLE_ENDIAN(p, x) (p)[0] = (unsigned char)LO(x), \
526 (p)[1] = (unsigned char)HI(x)
528 #define WRITE_STRING(str) (Write(str, sizeof(char), strlen(str) + 1) == strlen(str) + 1)
531 compute_offsets(char **Strings, size_t strmax, short *offsets)
536 for (i = 0; i < strmax; i++) {
537 if (Strings[i] == ABSENT_STRING) {
539 } else if (Strings[i] == CANCELLED_STRING) {
542 offsets[i] = (short) nextfree;
543 nextfree += (int) strlen(Strings[i]) + 1;
544 TRACE_OUT(("put Strings[%d]=%s(%d)", (int) i,
545 _nc_visbuf(Strings[i]), (int) nextfree));
552 convert_shorts(unsigned char *buf, short *Numbers, size_t count)
555 for (i = 0; i < count; i++) {
556 if (Numbers[i] == ABSENT_NUMERIC) { /* HI/LO won't work */
557 buf[2 * i] = buf[2 * i + 1] = 0377;
558 } else if (Numbers[i] == CANCELLED_NUMERIC) { /* HI/LO won't work */
560 buf[2 * i + 1] = 0377;
562 LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
563 TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
568 #define even_boundary(value) \
569 ((value) % 2 != 0 && Write(&zero, sizeof(char), 1) != 1)
573 extended_Booleans(TERMTYPE *tp)
578 for (i = 0; i < tp->ext_Booleans; ++i) {
579 if (tp->Booleans[BOOLCOUNT + i] == TRUE)
586 extended_Numbers(TERMTYPE *tp)
591 for (i = 0; i < tp->ext_Numbers; ++i) {
592 if (tp->Numbers[NUMCOUNT + i] != ABSENT_NUMERIC)
599 extended_Strings(TERMTYPE *tp)
601 unsigned short result = 0;
604 for (i = 0; i < tp->ext_Strings; ++i) {
605 if (tp->Strings[STRCOUNT + i] != ABSENT_STRING)
606 result = (unsigned short) (i + 1);
612 * _nc_align_termtype() will extend entries that are referenced in a use=
613 * clause - discard the unneeded data.
616 extended_object(TERMTYPE *tp)
620 if (_nc_user_definable) {
621 result = ((extended_Booleans(tp)
622 + extended_Numbers(tp)
623 + extended_Strings(tp)) != 0);
630 _nc_write_object(TERMTYPE *tp, char *buffer, unsigned *offset, unsigned limit)
633 size_t namelen, boolmax, nummax, strmax;
637 short offsets[MAX_ENTRY_SIZE / 2];
638 unsigned char buf[MAX_ENTRY_SIZE];
639 unsigned last_bool = BOOLWRITE;
640 unsigned last_num = NUMWRITE;
641 unsigned last_str = STRWRITE;
645 * Normally we limit the list of values to exclude the "obsolete"
646 * capabilities. However, if we are accepting extended names, add
647 * these as well, since they are used for supporting translation
650 if (_nc_user_definable) {
651 last_bool = BOOLCOUNT;
657 namelist = tp->term_names;
658 namelen = strlen(namelist) + 1;
661 for (i = 0; i < last_bool; i++) {
662 if (tp->Booleans[i] == TRUE)
667 for (i = 0; i < last_num; i++) {
668 if (tp->Numbers[i] != ABSENT_NUMERIC)
673 for (i = 0; i < last_str; i++) {
674 if (tp->Strings[i] != ABSENT_STRING)
678 nextfree = compute_offsets(tp->Strings, strmax, offsets);
680 /* fill in the header */
681 LITTLE_ENDIAN(buf, MAGIC);
682 LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
683 LITTLE_ENDIAN(buf + 4, boolmax);
684 LITTLE_ENDIAN(buf + 6, nummax);
685 LITTLE_ENDIAN(buf + 8, strmax);
686 LITTLE_ENDIAN(buf + 10, nextfree);
688 /* write out the header */
689 TRACE_OUT(("Header of %s @%d", namelist, *offset));
690 if (Write(buf, 12, 1) != 1
691 || Write(namelist, sizeof(char), namelen) != namelen)
694 for (i = 0; i < boolmax; i++)
695 if (tp->Booleans[i] == TRUE)
699 if (Write(buf, sizeof(char), boolmax) != boolmax)
702 if (even_boundary(namelen + boolmax))
705 TRACE_OUT(("Numerics begin at %04x", *offset));
708 convert_shorts(buf, tp->Numbers, nummax);
709 if (Write(buf, 2, nummax) != nummax)
712 TRACE_OUT(("String offsets begin at %04x", *offset));
714 /* the string offsets */
715 convert_shorts(buf, offsets, strmax);
716 if (Write(buf, 2, strmax) != strmax)
719 TRACE_OUT(("String table begins at %04x", *offset));
722 for (i = 0; i < strmax; i++)
723 if (VALID_STRING(tp->Strings[i]))
724 if (!WRITE_STRING(tp->Strings[i]))
728 if (extended_object(tp)) {
729 unsigned extcnt = (unsigned) NUM_EXT_NAMES(tp);
731 if (even_boundary(nextfree))
734 nextfree = compute_offsets(tp->Strings + STRCOUNT,
735 (size_t) tp->ext_Strings,
737 TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
739 if (tp->ext_Strings >= SIZEOF(offsets))
742 nextfree += compute_offsets(tp->ext_Names,
744 offsets + tp->ext_Strings);
745 TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
746 strmax = tp->ext_Strings + extcnt;
749 * Write the extended header
751 LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
752 LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
753 LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
754 LITTLE_ENDIAN(buf + 6, strmax);
755 LITTLE_ENDIAN(buf + 8, nextfree);
756 TRACE_OUT(("WRITE extended-header @%d", *offset));
757 if (Write(buf, 10, 1) != 1)
760 TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
762 && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
763 tp->ext_Booleans) != tp->ext_Booleans)
766 if (even_boundary(tp->ext_Booleans))
769 TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
770 if (tp->ext_Numbers) {
771 convert_shorts(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
772 if (Write(buf, 2, tp->ext_Numbers) != tp->ext_Numbers)
777 * Convert the offsets for the ext_Strings and ext_Names tables,
780 convert_shorts(buf, offsets, strmax);
781 TRACE_OUT(("WRITE offsets @%d", *offset));
782 if (Write(buf, 2, strmax) != strmax)
786 * Write the string table after the offset tables so we do not
787 * have to do anything about alignment.
789 for (i = 0; i < tp->ext_Strings; i++) {
790 if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
791 TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
792 _nc_visbuf(tp->Strings[i + STRCOUNT])));
793 if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
799 * Write the extended names
801 for (i = 0; i < extcnt; i++) {
802 TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
803 if (!WRITE_STRING(tp->ext_Names[i]))
808 #endif /* NCURSES_XNAMES */
812 total_size = total_size + (int) (*offset + 1);
817 * Returns the total number of entries written by this process
820 _nc_tic_written(void)
822 TR(TRACE_DATABASE, ("_nc_tic_written %d entries, %d parts, %d size",
823 total_written, total_parts, total_size));
824 return total_written;