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.100 2017/11/25 02:06:43 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, TERMTYPE2 *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(TERMTYPE2 *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 unsigned limit2 = sizeof(filename) - (2 + LEAF_LEN);
275 static int call_count;
276 static time_t start_time; /* time at start of writes */
278 #endif /* USE_HASHED_DB */
280 char name_list[MAX_TERMINFO_LENGTH];
281 char *first_name, *other_names;
283 char *term_names = tp->term_names;
284 size_t name_size = strlen(term_names);
286 if (name_size == 0) {
287 _nc_syserr_abort("no terminal name found.");
288 } else if (name_size >= sizeof(name_list) - 1) {
289 _nc_syserr_abort("terminal name too long: %s", term_names);
292 _nc_STRCPY(name_list, term_names, sizeof(name_list));
293 DEBUG(7, ("Name list = '%s'", name_list));
295 first_name = name_list;
297 ptr = &name_list[name_size - 1];
298 other_names = ptr + 1;
300 while (ptr > name_list && *ptr != '|')
303 if (ptr != name_list) {
306 for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
313 other_names = ptr + 1;
317 DEBUG(7, ("First name = '%s'", first_name));
318 DEBUG(7, ("Other names = '%s'", other_names));
320 _nc_set_type(first_name);
323 if (_nc_write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
324 DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
330 memset(&key, 0, sizeof(key));
331 key.data = term_names;
332 key.size = name_size;
334 memset(&data, 0, sizeof(data));
336 data.size = offset + 1;
338 _nc_db_put(capdb, &key, &data);
342 key.data = name_list;
343 key.size = strlen(name_list);
345 _nc_STRCPY(buffer + 1,
348 data.size = name_size + 1;
350 total_size += data.size;
352 _nc_db_put(capdb, &key, &data);
354 while (*other_names != '\0') {
356 assert(ptr < buffer + sizeof(buffer) - 1);
357 while (*other_names != '|' && *other_names != '\0')
360 if (*other_names != '\0')
361 *(other_names++) = '\0';
364 key.size = strlen(ptr);
366 total_size += data.size;
368 _nc_db_put(capdb, &key, &data);
372 #else /* !USE_HASHED_DB */
373 if (call_count++ == 0) {
377 if (strlen(first_name) >= sizeof(filename) - (2 + LEAF_LEN)) {
378 _nc_warning("terminal name too long.");
379 saved = first_name[limit2];
380 first_name[limit2] = '\0';
383 _nc_SPRINTF(filename, _nc_SLIMIT(sizeof(filename))
384 LEAF_FMT "/%s", first_name[0], first_name);
387 first_name[limit2] = saved;
390 * Has this primary name been written since the first call to
391 * write_entry()? If so, the newer write will step on the older,
394 if (start_time > 0 &&
395 stat(filename, &statbuf) >= 0
396 && statbuf.st_mtime >= start_time) {
397 #if HAVE_LINK && !USE_SYMLINKS
399 * If the file has more than one link, the reason for the previous
400 * write could be that the current primary name used to be an alias for
401 * the previous entry. In that case, unlink the file so that we will
402 * not modify the previous entry as we write this one.
404 if (statbuf.st_nlink > 1) {
405 _nc_warning("name redefined.");
408 _nc_warning("name multiply defined.");
411 _nc_warning("name multiply defined.");
415 check_writeable(first_name[0]);
416 write_file(filename, tp);
418 if (start_time == 0) {
419 if (stat(filename, &statbuf) < 0
420 || (start_time = statbuf.st_mtime) == 0) {
421 _nc_syserr_abort("error obtaining time from %s/%s",
422 _nc_tic_dir(0), filename);
425 while (*other_names != '\0') {
427 while (*other_names != '|' && *other_names != '\0')
430 if (*other_names != '\0')
431 *(other_names++) = '\0';
433 if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
434 _nc_warning("terminal alias %s too long.", ptr);
437 if (strchr(ptr, '/') != 0) {
438 _nc_warning("cannot link alias %s.", ptr);
442 check_writeable(ptr[0]);
443 _nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
444 LEAF_FMT "/%s", ptr[0], ptr);
446 if (strcmp(filename, linkname) == 0) {
447 _nc_warning("self-synonym ignored");
448 } else if (stat(linkname, &statbuf) >= 0 &&
449 statbuf.st_mtime < start_time) {
450 _nc_warning("alias %s multiply defined.", ptr);
451 } else if (_nc_access(linkname, W_OK) == 0)
456 #define MY_SIZE sizeof(symlinkname) - 1
457 if (first_name[0] == linkname[0]) {
458 _nc_STRNCPY(symlinkname, first_name, MY_SIZE);
460 _nc_STRCPY(symlinkname, "../", sizeof(symlinkname));
461 _nc_STRNCPY(symlinkname + 3, filename, MY_SIZE - 3);
463 symlinkname[MY_SIZE] = '\0';
464 #endif /* USE_SYMLINKS */
466 code = remove(linkname);
468 code = unlink(linkname);
470 if (code != 0 && errno == ENOENT)
473 if (symlink(symlinkname, linkname) < 0)
475 if (link(filename, linkname) < 0)
476 #endif /* USE_SYMLINKS */
479 * If there wasn't anything there, and we cannot
480 * link to the target because it is the same as the
481 * target, then the source must be on a filesystem
482 * that uses caseless filenames, such as Win32, etc.
484 if (code == 0 && errno == EEXIST)
485 _nc_warning("can't link %s to %s", filename, linkname);
486 else if (code == 0 && (errno == EPERM || errno == ENOENT))
487 write_file(linkname, tp);
489 #if MIXEDCASE_FILENAMES
490 _nc_syserr_abort("can't link %s to %s", filename, linkname);
492 _nc_warning("can't link %s to %s (errno=%d)", filename,
497 DEBUG(1, ("Linked %s", linkname));
500 #else /* just make copies */
501 write_file(linkname, tp);
502 #endif /* HAVE_LINK */
504 #endif /* USE_HASHED_DB */
508 fake_write(char *dst,
515 size_t have = (limit - *offset);
521 memcpy(dst + *offset, src, want);
522 *offset += (unsigned) want;
526 return (want / size);
529 #define Write(buf, size, count) fake_write(buffer, offset, (size_t) limit, (char *) buf, (size_t) count, (size_t) size)
531 #undef LITTLE_ENDIAN /* BSD/OS defines this as a feature macro */
532 #define HI(x) ((x) / 256)
533 #define LO(x) ((x) % 256)
534 #define LITTLE_ENDIAN(p, x) (p)[0] = (unsigned char)LO(x), \
535 (p)[1] = (unsigned char)HI(x)
537 #define WRITE_STRING(str) (Write(str, sizeof(char), strlen(str) + 1) == strlen(str) + 1)
540 compute_offsets(char **Strings, size_t strmax, short *offsets)
545 for (i = 0; i < strmax; i++) {
546 if (Strings[i] == ABSENT_STRING) {
548 } else if (Strings[i] == CANCELLED_STRING) {
551 offsets[i] = (short) nextfree;
552 nextfree += (int) strlen(Strings[i]) + 1;
553 TRACE_OUT(("put Strings[%d]=%s(%d)", (int) i,
554 _nc_visbuf(Strings[i]), (int) nextfree));
561 convert_shorts(unsigned char *buf, short *Numbers, size_t count)
564 for (i = 0; i < count; i++) {
565 if (Numbers[i] == ABSENT_NUMERIC) { /* HI/LO won't work */
566 buf[2 * i] = buf[2 * i + 1] = 0377;
567 } else if (Numbers[i] == CANCELLED_NUMERIC) { /* HI/LO won't work */
569 buf[2 * i + 1] = 0377;
571 LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
572 TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
577 #if NCURSES_EXT_NUMBERS
579 convert_numbers(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
582 for (i = 0; i < count; i++) {
583 if (Numbers[i] == ABSENT_NUMERIC) { /* HI/LO won't work */
584 buf[2 * i] = buf[2 * i + 1] = 0377;
585 } else if (Numbers[i] == CANCELLED_NUMERIC) { /* HI/LO won't work */
587 buf[2 * i + 1] = 0377;
589 LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
590 TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
596 #define convert_numbers(buf,vec,len) convert_shorts(buf,vec,len)
599 #define even_boundary(value) \
600 ((value) % 2 != 0 && Write(&zero, sizeof(char), 1) != 1)
604 extended_Booleans(TERMTYPE2 *tp)
609 for (i = 0; i < tp->ext_Booleans; ++i) {
610 if (tp->Booleans[BOOLCOUNT + i] == TRUE)
617 extended_Numbers(TERMTYPE2 *tp)
622 for (i = 0; i < tp->ext_Numbers; ++i) {
623 if (tp->Numbers[NUMCOUNT + i] != ABSENT_NUMERIC)
630 extended_Strings(TERMTYPE2 *tp)
632 unsigned short result = 0;
635 for (i = 0; i < tp->ext_Strings; ++i) {
636 if (tp->Strings[STRCOUNT + i] != ABSENT_STRING)
637 result = (unsigned short) (i + 1);
643 * _nc_align_termtype() will extend entries that are referenced in a use=
644 * clause - discard the unneeded data.
647 extended_object(TERMTYPE2 *tp)
651 if (_nc_user_definable) {
652 result = ((extended_Booleans(tp)
653 + extended_Numbers(tp)
654 + extended_Strings(tp)) != 0);
661 _nc_write_object(TERMTYPE2 *tp, char *buffer, unsigned *offset, unsigned limit)
664 size_t namelen, boolmax, nummax, strmax;
668 short offsets[MAX_ENTRY_SIZE / 2];
669 unsigned char buf[MAX_ENTRY_SIZE];
670 unsigned last_bool = BOOLWRITE;
671 unsigned last_num = NUMWRITE;
672 unsigned last_str = STRWRITE;
676 * Normally we limit the list of values to exclude the "obsolete"
677 * capabilities. However, if we are accepting extended names, add
678 * these as well, since they are used for supporting translation
681 if (_nc_user_definable) {
682 last_bool = BOOLCOUNT;
688 namelist = tp->term_names;
689 namelen = strlen(namelist) + 1;
692 for (i = 0; i < last_bool; i++) {
693 if (tp->Booleans[i] == TRUE)
698 for (i = 0; i < last_num; i++) {
699 if (tp->Numbers[i] != ABSENT_NUMERIC)
704 for (i = 0; i < last_str; i++) {
705 if (tp->Strings[i] != ABSENT_STRING)
709 nextfree = compute_offsets(tp->Strings, strmax, offsets);
711 /* fill in the header */
712 LITTLE_ENDIAN(buf, MAGIC);
713 LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
714 LITTLE_ENDIAN(buf + 4, boolmax);
715 LITTLE_ENDIAN(buf + 6, nummax);
716 LITTLE_ENDIAN(buf + 8, strmax);
717 LITTLE_ENDIAN(buf + 10, nextfree);
719 /* write out the header */
720 TRACE_OUT(("Header of %s @%d", namelist, *offset));
721 if (Write(buf, 12, 1) != 1
722 || Write(namelist, sizeof(char), namelen) != namelen)
725 for (i = 0; i < boolmax; i++)
726 if (tp->Booleans[i] == TRUE)
730 if (Write(buf, sizeof(char), boolmax) != boolmax)
733 if (even_boundary(namelen + boolmax))
736 TRACE_OUT(("Numerics begin at %04x", *offset));
739 convert_numbers(buf, tp->Numbers, nummax);
740 if (Write(buf, 2, nummax) != nummax)
743 TRACE_OUT(("String offsets begin at %04x", *offset));
745 /* the string offsets */
746 convert_shorts(buf, offsets, strmax);
747 if (Write(buf, 2, strmax) != strmax)
750 TRACE_OUT(("String table begins at %04x", *offset));
753 for (i = 0; i < strmax; i++)
754 if (VALID_STRING(tp->Strings[i]))
755 if (!WRITE_STRING(tp->Strings[i]))
759 if (extended_object(tp)) {
760 unsigned extcnt = (unsigned) NUM_EXT_NAMES(tp);
762 if (even_boundary(nextfree))
765 nextfree = compute_offsets(tp->Strings + STRCOUNT,
766 (size_t) tp->ext_Strings,
768 TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
770 if (tp->ext_Strings >= SIZEOF(offsets))
773 nextfree += compute_offsets(tp->ext_Names,
775 offsets + tp->ext_Strings);
776 TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
777 strmax = tp->ext_Strings + extcnt;
780 * Write the extended header
782 LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
783 LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
784 LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
785 LITTLE_ENDIAN(buf + 6, strmax);
786 LITTLE_ENDIAN(buf + 8, nextfree);
787 TRACE_OUT(("WRITE extended-header @%d", *offset));
788 if (Write(buf, 10, 1) != 1)
791 TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
793 && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
794 tp->ext_Booleans) != tp->ext_Booleans)
797 if (even_boundary(tp->ext_Booleans))
800 TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
801 if (tp->ext_Numbers) {
802 convert_numbers(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
803 if (Write(buf, 2, tp->ext_Numbers) != tp->ext_Numbers)
808 * Convert the offsets for the ext_Strings and ext_Names tables,
811 convert_shorts(buf, offsets, strmax);
812 TRACE_OUT(("WRITE offsets @%d", *offset));
813 if (Write(buf, 2, strmax) != strmax)
817 * Write the string table after the offset tables so we do not
818 * have to do anything about alignment.
820 for (i = 0; i < tp->ext_Strings; i++) {
821 if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
822 TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
823 _nc_visbuf(tp->Strings[i + STRCOUNT])));
824 if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
830 * Write the extended names
832 for (i = 0; i < extcnt; i++) {
833 TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
834 if (!WRITE_STRING(tp->ext_Names[i]))
839 #endif /* NCURSES_XNAMES */
843 total_size = total_size + (int) (*offset + 1);
848 * Returns the total number of entries written by this process
851 _nc_tic_written(void)
853 TR(TRACE_DATABASE, ("_nc_tic_written %d entries, %d parts, %d size",
854 total_written, total_parts, total_size));
855 return total_written;