]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/write_entry.c
15a0d8152525088b3ef03e16b6f1ff1d0690a8f1
[ncurses.git] / ncurses / tinfo / write_entry.c
1 /****************************************************************************
2  * Copyright 2018-2022,2023 Thomas E. Dickey                                *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29
30 /****************************************************************************
31  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
32  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
33  *     and: Thomas E. Dickey                        1996-on                 *
34  ****************************************************************************/
35
36 /*
37  *      write_entry.c -- write a terminfo structure onto the file system
38  */
39
40 #include <curses.priv.h>
41 #include <hashed_db.h>
42
43 #include <tic.h>
44
45 #if 1
46 #define TRACE_OUT(p) DEBUG(2, p)
47 #define TRACE_NUM(n) if (VALID_NUMERIC(Numbers[n])) { \
48         TRACE_OUT(("put Numbers[%u]=%d", (unsigned) (n), Numbers[n])); }
49 #else
50 #define TRACE_OUT(p)            /*nothing */
51 #define TRACE_NUM(n)            /* nothing */
52 #endif
53
54 MODULE_ID("$Id: write_entry.c,v 1.122 2023/04/17 08:08:08 tom Exp $")
55
56 static int total_written;
57 static int total_parts;
58 static int total_size;
59
60 static int make_db_root(const char *);
61
62 #if !USE_HASHED_DB
63 static void
64 write_file(char *filename, TERMTYPE2 *tp)
65 {
66     char buffer[MAX_ENTRY_SIZE];
67     unsigned limit = sizeof(buffer);
68     unsigned offset = 0;
69
70     if (_nc_write_object(tp, buffer, &offset, limit) == ERR) {
71         _nc_warning("entry is larger than %u bytes", limit);
72     } else {
73         FILE *fp = ((_nc_access(filename, W_OK) == 0)
74                     ? safe_fopen(filename, BIN_W)
75                     : 0);
76         size_t actual;
77
78         if (fp == 0) {
79             perror(filename);
80             _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
81         }
82
83         actual = fwrite(buffer, sizeof(char), (size_t) offset, fp);
84         if (actual != offset) {
85             int myerr = ferror(fp) ? errno : 0;
86             if (myerr) {
87                 _nc_syserr_abort("error writing %s/%s: %s",
88                                  _nc_tic_dir(0),
89                                  filename,
90                                  strerror(myerr));
91             } else {
92                 _nc_syserr_abort("error writing %s/%s: %u bytes vs actual %lu",
93                                  _nc_tic_dir(0),
94                                  filename,
95                                  offset,
96                                  (unsigned long) actual);
97             }
98         } else {
99             fclose(fp);
100             DEBUG(1, ("Created %s", filename));
101         }
102     }
103 }
104
105 /*
106  * Check for access rights to destination directories
107  * Create any directories which don't exist.
108  *
109  * Note:  there's no reason to return the result of make_db_root(), since
110  * this function is called only in instances where that has to succeed.
111  */
112 static void
113 check_writeable(int code)
114 {
115     static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
116     static bool verified[sizeof(dirnames)];
117
118     char dir[sizeof(LEAF_FMT)];
119     char *s = 0;
120
121     if (code == 0 || (s = (strchr) (dirnames, code)) == 0)
122         _nc_err_abort("Illegal terminfo subdirectory \"" LEAF_FMT "\"", code);
123
124     if (verified[s - dirnames])
125         return;
126
127     _nc_SPRINTF(dir, _nc_SLIMIT(sizeof(dir)) LEAF_FMT, code);
128     if (make_db_root(dir) < 0) {
129         _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
130     }
131
132     verified[s - dirnames] = TRUE;
133 }
134 #endif /* !USE_HASHED_DB */
135
136 static int
137 make_db_path(char *dst, const char *src, size_t limit)
138 {
139     int rc = -1;
140     const char *top = _nc_tic_dir(0);
141
142     if (src == top || _nc_is_abs_path(src)) {
143         if (strlen(src) + 1 <= limit) {
144             _nc_STRCPY(dst, src, limit);
145             rc = 0;
146         }
147     } else {
148         if ((strlen(top) + strlen(src) + 6) <= limit) {
149             _nc_SPRINTF(dst, _nc_SLIMIT(limit) "%s/%s", top, src);
150             rc = 0;
151         }
152     }
153 #if USE_HASHED_DB
154     if (rc == 0) {
155         static const char suffix[] = DBM_SUFFIX;
156         size_t have = strlen(dst);
157         size_t need = strlen(suffix);
158         if (have > need && strcmp(dst + (int) (have - need), suffix)) {
159             if (have + need <= limit) {
160                 _nc_STRCAT(dst, suffix, limit);
161             } else {
162                 rc = -1;
163             }
164         } else if (_nc_is_dir_path(dst)) {
165             rc = -1;
166         }
167     }
168 #endif
169     return rc;
170 }
171
172 /*
173  * Make a database-root if it doesn't exist.
174  */
175 static int
176 make_db_root(const char *path)
177 {
178     int rc;
179     char fullpath[PATH_MAX];
180
181     if ((rc = make_db_path(fullpath, path, sizeof(fullpath))) == 0) {
182 #if USE_HASHED_DB
183         DB *capdbp;
184
185         if ((capdbp = _nc_db_open(fullpath, TRUE)) == NULL) {
186             rc = -1;
187         } else if (_nc_db_close(capdbp) < 0) {
188             rc = -1;
189         }
190 #else
191         struct stat statbuf;
192
193         if ((rc = stat(path, &statbuf)) == -1) {
194             rc = mkdir(path
195 #ifndef _NC_WINDOWS
196                        ,0777
197 #endif
198                 );
199         } else if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
200             rc = -1;            /* permission denied */
201         } else if (!(S_ISDIR(statbuf.st_mode))) {
202             rc = -1;            /* not a directory */
203         }
204 #endif
205     }
206     return rc;
207 }
208
209 /*
210  * Set the write directory for compiled entries.
211  */
212 NCURSES_EXPORT(void)
213 _nc_set_writedir(const char *dir)
214 {
215     const char *destination;
216     char actual[PATH_MAX];
217
218     if (dir == 0 && use_terminfo_vars())
219         dir = getenv("TERMINFO");
220
221     if (dir != 0)
222         (void) _nc_tic_dir(dir);
223
224     destination = _nc_tic_dir(0);
225     if (make_db_root(destination) < 0) {
226         char *home = _nc_home_terminfo();
227
228         if (home != 0) {
229             destination = home;
230             if (make_db_root(destination) < 0)
231                 _nc_err_abort("%s: permission denied (errno %d)",
232                               destination, errno);
233         }
234     }
235
236     /*
237      * Note: because of this code, this logic should be exercised
238      * *once only* per run.
239      */
240 #if USE_HASHED_DB
241     make_db_path(actual, destination, sizeof(actual));
242 #else
243     if (chdir(_nc_tic_dir(destination)) < 0
244         || getcwd(actual, sizeof(actual)) == 0)
245         _nc_err_abort("%s: not a directory", destination);
246 #endif
247     _nc_keep_tic_dir(actual);
248 }
249
250 /*
251  *      Save the compiled version of a description in the filesystem.
252  *
253  *      make a copy of the name-list
254  *      break it up into first-name and all-but-last-name
255  *      creat(first-name)
256  *      write object information to first-name
257  *      close(first-name)
258  *      for each name in all-but-last-name
259  *          link to first-name
260  *
261  *      Using 'time()' to obtain a reference for file timestamps is unreliable,
262  *      e.g., with NFS, because the filesystem may have a different time
263  *      reference.  We check for pre-existence of links by latching the first
264  *      timestamp from a file that we create.
265  *
266  *      The _nc_warning() calls will report a correct line number only if
267  *      _nc_curr_line is properly set before the write_entry() call.
268  */
269
270 NCURSES_EXPORT(void)
271 _nc_write_entry(TERMTYPE2 *const tp)
272 {
273 #if USE_HASHED_DB
274
275     char buffer[MAX_ENTRY_SIZE + 1];
276     unsigned limit = sizeof(buffer);
277     unsigned offset = 0;
278
279 #else /* !USE_HASHED_DB */
280
281     struct stat statbuf;
282     char filename[PATH_MAX];
283     char linkname[PATH_MAX];
284 #if USE_SYMLINKS
285     char symlinkname[PATH_MAX];
286 #if !HAVE_LINK
287 #undef HAVE_LINK
288 #define HAVE_LINK 1
289 #endif
290 #endif /* USE_SYMLINKS */
291
292     unsigned limit2 = sizeof(filename) - (2 + LEAF_LEN);
293     char saved = '\0';
294
295     static int call_count;
296     static time_t start_time;   /* time at start of writes */
297
298 #endif /* USE_HASHED_DB */
299
300     char name_list[MAX_TERMINFO_LENGTH];
301     char *first_name, *other_names;
302     char *ptr;
303     char *term_names = tp->term_names;
304     size_t name_size = strlen(term_names);
305
306     if (name_size == 0) {
307         _nc_syserr_abort("no terminal name found.");
308     } else if (name_size >= sizeof(name_list) - 1) {
309         _nc_syserr_abort("terminal name too long: %s", term_names);
310     }
311
312     _nc_STRCPY(name_list, term_names, sizeof(name_list));
313     DEBUG(7, ("Name list = '%s'", name_list));
314
315     first_name = name_list;
316
317     ptr = &name_list[name_size - 1];
318     other_names = ptr + 1;
319
320     while (ptr > name_list && *ptr != '|')
321         ptr--;
322
323     if (ptr != name_list) {
324         *ptr = '\0';
325
326         for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
327             continue;
328
329         if (*ptr == '\0')
330             other_names = ptr;
331         else {
332             *ptr = '\0';
333             other_names = ptr + 1;
334         }
335     }
336
337     DEBUG(7, ("First name = '%s'", first_name));
338     DEBUG(7, ("Other names = '%s'", other_names));
339
340     _nc_set_type(first_name);
341
342 #if USE_HASHED_DB
343     if (_nc_write_object(tp, buffer + 1, &offset, limit - 1) != ERR) {
344         DB *capdb = _nc_db_open(_nc_tic_dir(0), TRUE);
345         DBT key, data;
346
347         if (capdb != 0) {
348             buffer[0] = 0;
349
350             memset(&key, 0, sizeof(key));
351             key.data = term_names;
352             key.size = name_size;
353
354             memset(&data, 0, sizeof(data));
355             data.data = buffer;
356             data.size = offset + 1;
357
358             _nc_db_put(capdb, &key, &data);
359
360             buffer[0] = 2;
361
362             key.data = name_list;
363             key.size = strlen(name_list);
364
365             _nc_STRCPY(buffer + 1,
366                        term_names,
367                        sizeof(buffer) - 1);
368             data.size = name_size + 1;
369
370             total_size += data.size;
371             total_parts++;
372             _nc_db_put(capdb, &key, &data);
373
374             while (*other_names != '\0') {
375                 ptr = other_names++;
376                 assert(ptr < buffer + sizeof(buffer) - 1);
377                 while (*other_names != '|' && *other_names != '\0')
378                     other_names++;
379
380                 if (*other_names != '\0')
381                     *(other_names++) = '\0';
382
383                 key.data = ptr;
384                 key.size = strlen(ptr);
385
386                 total_size += data.size;
387                 total_parts++;
388                 _nc_db_put(capdb, &key, &data);
389             }
390         }
391     }
392 #else /* !USE_HASHED_DB */
393     if (call_count++ == 0) {
394         start_time = 0;
395     }
396
397     if (strlen(first_name) >= limit2) {
398         _nc_warning("terminal name too long.");
399         saved = first_name[limit2];
400         first_name[limit2] = '\0';
401     }
402
403     _nc_SPRINTF(filename, _nc_SLIMIT(sizeof(filename))
404                 LEAF_FMT "/%.*s", UChar(first_name[0]),
405                 (int) (sizeof(filename) - (LEAF_LEN + 2)),
406                 first_name);
407
408     if (saved)
409         first_name[limit2] = saved;
410
411     /*
412      * Has this primary name been written since the first call to
413      * write_entry()?  If so, the newer write will step on the older,
414      * so warn the user.
415      */
416     if (start_time > 0 &&
417         stat(filename, &statbuf) >= 0
418         && statbuf.st_mtime >= start_time) {
419 #if HAVE_LINK && !USE_SYMLINKS
420         /*
421          * If the file has more than one link, the reason for the previous
422          * write could be that the current primary name used to be an alias for
423          * the previous entry.  In that case, unlink the file so that we will
424          * not modify the previous entry as we write this one.
425          */
426         if (statbuf.st_nlink > 1) {
427             _nc_warning("name redefined.");
428             unlink(filename);
429         } else {
430             _nc_warning("name multiply defined.");
431         }
432 #else
433         _nc_warning("name multiply defined.");
434 #endif
435     }
436
437     check_writeable(first_name[0]);
438     write_file(filename, tp);
439
440     if (start_time == 0) {
441         if (stat(filename, &statbuf) == -1
442             || (start_time = statbuf.st_mtime) == 0) {
443             _nc_syserr_abort("error obtaining time from %s/%s",
444                              _nc_tic_dir(0), filename);
445         }
446     }
447     while (*other_names != '\0') {
448         ptr = other_names++;
449         while (*other_names != '|' && *other_names != '\0')
450             other_names++;
451
452         if (*other_names != '\0')
453             *(other_names++) = '\0';
454
455         if (strlen(ptr) > sizeof(linkname) - (2 + LEAF_LEN)) {
456             _nc_warning("terminal alias %s too long.", ptr);
457             continue;
458         }
459         if (strchr(ptr, '/') != 0) {
460             _nc_warning("cannot link alias %s.", ptr);
461             continue;
462         }
463
464         check_writeable(ptr[0]);
465         _nc_SPRINTF(linkname, _nc_SLIMIT(sizeof(linkname))
466                     LEAF_FMT "/%.*s", ptr[0],
467                     (int) sizeof(linkname) - (2 + LEAF_LEN), ptr);
468
469         if (strcmp(filename, linkname) == 0) {
470             _nc_warning("self-synonym ignored");
471         } else if (stat(linkname, &statbuf) >= 0 &&
472                    statbuf.st_mtime > start_time) {
473             _nc_warning("alias %s multiply defined.", ptr);
474         } else if (_nc_access(linkname, W_OK) == 0)
475 #if HAVE_LINK
476         {
477             int code;
478 #if USE_SYMLINKS
479 #define MY_SIZE sizeof(symlinkname) - 1
480             if (first_name[0] == linkname[0]) {
481                 _nc_STRNCPY(symlinkname, first_name, MY_SIZE);
482             } else {
483                 _nc_STRCPY(symlinkname, "../", sizeof(symlinkname));
484                 _nc_STRNCPY(symlinkname + 3, filename, MY_SIZE - 3);
485             }
486             symlinkname[MY_SIZE] = '\0';
487 #endif /* USE_SYMLINKS */
488 #if HAVE_REMOVE
489             code = remove(linkname);
490 #else
491             code = unlink(linkname);
492 #endif
493             if (code != 0 && errno == ENOENT)
494                 code = 0;
495 #if USE_SYMLINKS
496             if (symlink(symlinkname, linkname) < 0)
497 #else
498             if (link(filename, linkname) < 0)
499 #endif /* USE_SYMLINKS */
500             {
501                 /*
502                  * If there wasn't anything there, and we cannot
503                  * link to the target because it is the same as the
504                  * target, then the source must be on a filesystem
505                  * that uses caseless filenames, such as Win32, etc.
506                  */
507                 if (code == 0 && errno == EEXIST)
508                     _nc_warning("can't link %s to %s", filename, linkname);
509                 else if (code == 0 && (errno == EPERM || errno == ENOENT))
510                     write_file(linkname, tp);
511                 else {
512 #if MIXEDCASE_FILENAMES
513                     _nc_syserr_abort("can't link %s to %s", filename, linkname);
514 #else
515                     _nc_warning("can't link %s to %s (errno=%d)", filename,
516                                 linkname, errno);
517 #endif
518                 }
519             } else {
520                 DEBUG(1, ("Linked %s", linkname));
521             }
522         }
523 #else /* just make copies */
524             write_file(linkname, tp);
525 #endif /* HAVE_LINK */
526     }
527 #endif /* USE_HASHED_DB */
528 }
529
530 static size_t
531 fake_write(char *dst,
532            unsigned *offset,
533            size_t limit,
534            char *src,
535            size_t want,
536            size_t size)
537 {
538     size_t have = (limit - *offset);
539
540     want *= size;
541     if (have > 0) {
542         if (want > have)
543             want = have;
544         memcpy(dst + *offset, src, want);
545         *offset += (unsigned) want;
546     } else {
547         want = 0;
548     }
549     return (want / size);
550 }
551
552 #define Write(buf, size, count) fake_write(buffer, offset, (size_t) limit, (char *) buf, (size_t) count, (size_t) size)
553
554 #undef LITTLE_ENDIAN            /* BSD/OS defines this as a feature macro */
555 #define HI(x)                   ((x) / 256)
556 #define LO(x)                   ((x) % 256)
557 #define LITTLE_ENDIAN(p, x)     (p)[0] = (unsigned char)LO(x),  \
558                                 (p)[1] = (unsigned char)HI(x)
559
560 #define WRITE_STRING(str) (Write(str, sizeof(char), strlen(str) + 1) == strlen(str) + 1)
561
562 static int
563 compute_offsets(char **Strings, size_t strmax, short *offsets)
564 {
565     int nextfree = 0;
566     size_t i;
567
568     for (i = 0; i < strmax; i++) {
569         if (Strings[i] == ABSENT_STRING) {
570             offsets[i] = -1;
571         } else if (Strings[i] == CANCELLED_STRING) {
572             offsets[i] = -2;
573         } else {
574             offsets[i] = (short) nextfree;
575             nextfree += (int) strlen(Strings[i]) + 1;
576             TRACE_OUT(("put Strings[%d]=%s(%d)", (int) i,
577                        _nc_visbuf(Strings[i]), (int) nextfree));
578         }
579     }
580     return nextfree;
581 }
582
583 static size_t
584 convert_shorts(unsigned char *buf, short *Numbers, size_t count)
585 {
586     size_t i;
587     for (i = 0; i < count; i++) {
588         if (Numbers[i] == ABSENT_NUMERIC) {     /* HI/LO won't work */
589             buf[2 * i] = buf[2 * i + 1] = 0377;
590         } else if (Numbers[i] == CANCELLED_NUMERIC) {   /* HI/LO won't work */
591             buf[2 * i] = 0376;
592             buf[2 * i + 1] = 0377;
593         } else {
594             LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
595             TRACE_OUT(("put Numbers[%u]=%d", (unsigned) i, Numbers[i]));
596         }
597     }
598     return SIZEOF_SHORT;
599 }
600
601 #if NCURSES_EXT_NUMBERS
602 static size_t
603 convert_16bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
604 {
605     size_t i, j;
606     size_t size = SIZEOF_SHORT;
607     for (i = 0; i < count; i++) {
608         unsigned value = (unsigned) Numbers[i];
609         TRACE_NUM(i);
610         for (j = 0; j < size; ++j) {
611             *buf++ = value & 0xff;
612             value >>= 8;
613         }
614     }
615     return size;
616 }
617
618 static size_t
619 convert_32bit(unsigned char *buf, NCURSES_INT2 *Numbers, size_t count)
620 {
621     size_t i, j;
622     size_t size = SIZEOF_INT2;
623     for (i = 0; i < count; i++) {
624         unsigned value = (unsigned) Numbers[i];
625         TRACE_NUM(i);
626         for (j = 0; j < size; ++j) {
627             *buf++ = value & 0xff;
628             value >>= 8;
629         }
630     }
631     return size;
632 }
633 #endif
634
635 #define even_boundary(value) \
636             ((value) % 2 != 0 && Write(&zero, sizeof(char), 1) != 1)
637
638 #if NCURSES_XNAMES
639 static unsigned
640 extended_Booleans(TERMTYPE2 *tp)
641 {
642     unsigned result = 0;
643     unsigned i;
644
645     for (i = 0; i < tp->ext_Booleans; ++i) {
646         if (tp->Booleans[BOOLCOUNT + i] == TRUE)
647             result = (i + 1);
648     }
649     return result;
650 }
651
652 static unsigned
653 extended_Numbers(TERMTYPE2 *tp)
654 {
655     unsigned result = 0;
656     unsigned i;
657
658     for (i = 0; i < tp->ext_Numbers; ++i) {
659         if (tp->Numbers[NUMCOUNT + i] != ABSENT_NUMERIC)
660             result = (i + 1);
661     }
662     return result;
663 }
664
665 static unsigned
666 extended_Strings(TERMTYPE2 *tp)
667 {
668     unsigned short result = 0;
669     unsigned short i;
670
671     for (i = 0; i < tp->ext_Strings; ++i) {
672         if (tp->Strings[STRCOUNT + i] != ABSENT_STRING)
673             result = (unsigned short) (i + 1);
674     }
675     return result;
676 }
677
678 /*
679  * _nc_align_termtype() will extend entries that are referenced in a use=
680  * clause - discard the unneeded data.
681  */
682 static bool
683 extended_object(TERMTYPE2 *tp)
684 {
685     bool result = FALSE;
686
687     if (_nc_user_definable) {
688         result = ((extended_Booleans(tp)
689                    + extended_Numbers(tp)
690                    + extended_Strings(tp)) != 0);
691     }
692     return result;
693 }
694 #endif
695
696 NCURSES_EXPORT(int)
697 _nc_write_object(TERMTYPE2 *tp, char *buffer, unsigned *offset, unsigned limit)
698 {
699     char *namelist;
700     size_t namelen, boolmax, nummax, strmax, numlen;
701     char zero = '\0';
702     size_t i;
703     int nextfree;
704     short offsets[MAX_ENTRY_SIZE / 2];
705     unsigned char buf[MAX_ENTRY_SIZE];
706     unsigned last_bool = BOOLWRITE;
707     unsigned last_num = NUMWRITE;
708     unsigned last_str = STRWRITE;
709 #if NCURSES_EXT_NUMBERS
710     bool need_ints = FALSE;
711     size_t (*convert_numbers) (unsigned char *, NCURSES_INT2 *, size_t) = convert_32bit;
712 #else
713 #define convert_numbers convert_shorts
714 #endif
715
716 #if NCURSES_XNAMES
717     /*
718      * Normally we limit the list of values to exclude the "obsolete"
719      * capabilities.  However, if we are accepting extended names, add
720      * these as well, since they are used for supporting translation
721      * to/from termcap.
722      */
723     if (_nc_user_definable) {
724         last_bool = BOOLCOUNT;
725         last_num = NUMCOUNT;
726         last_str = STRCOUNT;
727     }
728 #endif
729
730     namelist = tp->term_names;
731     namelen = strlen(namelist) + 1;
732
733     boolmax = 0;
734     for (i = 0; i < last_bool; i++) {
735         if (tp->Booleans[i] == TRUE) {
736             boolmax = i + 1;
737         }
738     }
739
740     nummax = 0;
741     for (i = 0; i < last_num; i++) {
742         if (tp->Numbers[i] != ABSENT_NUMERIC) {
743             nummax = i + 1;
744 #if NCURSES_EXT_NUMBERS
745             if (tp->Numbers[i] > MAX_OF_TYPE(NCURSES_COLOR_T)) {
746                 need_ints = TRUE;
747             }
748 #endif
749         }
750     }
751
752     strmax = 0;
753     for (i = 0; i < last_str; i++) {
754         if (tp->Strings[i] != ABSENT_STRING)
755             strmax = i + 1;
756     }
757
758     nextfree = compute_offsets(tp->Strings, strmax, offsets);
759
760     /* fill in the header */
761 #if NCURSES_EXT_NUMBERS
762     if (need_ints) {
763         convert_numbers = convert_32bit;
764         LITTLE_ENDIAN(buf, MAGIC2);
765     } else {
766         convert_numbers = convert_16bit;
767         LITTLE_ENDIAN(buf, MAGIC);
768     }
769 #else
770     LITTLE_ENDIAN(buf, MAGIC);
771 #endif
772     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
773     LITTLE_ENDIAN(buf + 4, boolmax);
774     LITTLE_ENDIAN(buf + 6, nummax);
775     LITTLE_ENDIAN(buf + 8, strmax);
776     LITTLE_ENDIAN(buf + 10, nextfree);
777
778     /* write out the header */
779     TRACE_OUT(("Header of %s @%d", namelist, *offset));
780     if (Write(buf, 12, 1) != 1
781         || Write(namelist, sizeof(char), namelen) != namelen) {
782         return (ERR);
783     }
784
785     for (i = 0; i < boolmax; i++) {
786         if (tp->Booleans[i] == TRUE) {
787             buf[i] = TRUE;
788         } else {
789             buf[i] = FALSE;
790         }
791     }
792     if (Write(buf, sizeof(char), boolmax) != boolmax) {
793         return (ERR);
794     }
795
796     if (even_boundary(namelen + boolmax)) {
797         return (ERR);
798     }
799
800     TRACE_OUT(("Numerics begin at %04x", *offset));
801
802     /* the numerics */
803     numlen = convert_numbers(buf, tp->Numbers, nummax);
804     if (Write(buf, numlen, nummax) != nummax) {
805         return (ERR);
806     }
807
808     TRACE_OUT(("String offsets begin at %04x", *offset));
809
810     /* the string offsets */
811     convert_shorts(buf, offsets, strmax);
812     if (Write(buf, SIZEOF_SHORT, strmax) != strmax) {
813         return (ERR);
814     }
815
816     TRACE_OUT(("String table begins at %04x", *offset));
817
818     /* the strings */
819     for (i = 0; i < strmax; i++) {
820         if (VALID_STRING(tp->Strings[i])) {
821             if (!WRITE_STRING(tp->Strings[i])) {
822                 return (ERR);
823             }
824         }
825     }
826
827 #if NCURSES_XNAMES
828     if (extended_object(tp)) {
829         unsigned ext_total = (unsigned) NUM_EXT_NAMES(tp);
830         unsigned ext_usage = ext_total;
831
832         if (even_boundary(nextfree)) {
833             return (ERR);
834         }
835
836         nextfree = compute_offsets(tp->Strings + STRCOUNT,
837                                    (size_t) tp->ext_Strings,
838                                    offsets);
839         TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
840
841         if (tp->ext_Strings >= SIZEOF(offsets)) {
842             return (ERR);
843         }
844
845         nextfree += compute_offsets(tp->ext_Names,
846                                     (size_t) ext_total,
847                                     offsets + tp->ext_Strings);
848         TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
849         strmax = tp->ext_Strings + ext_total;
850         for (i = 0; i < tp->ext_Strings; ++i) {
851             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
852                 ext_usage++;
853             }
854         }
855         TRACE_OUT(("will write %u/%lu strings", ext_usage, (unsigned long) strmax));
856
857         /*
858          * Write the extended header
859          */
860         LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
861         LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
862         LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
863         LITTLE_ENDIAN(buf + 6, ext_usage);
864         LITTLE_ENDIAN(buf + 8, nextfree);
865         TRACE_OUT(("WRITE extended-header @%d", *offset));
866         if (Write(buf, 10, 1) != 1) {
867             return (ERR);
868         }
869
870         TRACE_OUT(("WRITE %d booleans @%d", tp->ext_Booleans, *offset));
871         if (tp->ext_Booleans
872             && Write(tp->Booleans + BOOLCOUNT, sizeof(char),
873                      tp->ext_Booleans) != tp->ext_Booleans) {
874             return (ERR);
875         }
876
877         if (even_boundary(tp->ext_Booleans)) {
878             return (ERR);
879         }
880
881         TRACE_OUT(("WRITE %d numbers @%d", tp->ext_Numbers, *offset));
882         if (tp->ext_Numbers) {
883             numlen = convert_numbers(buf, tp->Numbers + NUMCOUNT, (size_t) tp->ext_Numbers);
884             if (Write(buf, numlen, tp->ext_Numbers) != tp->ext_Numbers) {
885                 return (ERR);
886             }
887         }
888
889         /*
890          * Convert the offsets for the ext_Strings and ext_Names tables,
891          * in that order.
892          */
893         convert_shorts(buf, offsets, strmax);
894         TRACE_OUT(("WRITE offsets @%d", *offset));
895         if (Write(buf, SIZEOF_SHORT, strmax) != strmax) {
896             return (ERR);
897         }
898
899         /*
900          * Write the string table after the offset tables so we do not
901          * have to do anything about alignment.
902          */
903         for (i = 0; i < tp->ext_Strings; i++) {
904             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
905                 TRACE_OUT(("WRITE ext_Strings[%d]=%s", (int) i,
906                            _nc_visbuf(tp->Strings[i + STRCOUNT])));
907                 if (!WRITE_STRING(tp->Strings[i + STRCOUNT])) {
908                     return (ERR);
909                 }
910             }
911         }
912
913         /*
914          * Write the extended names
915          */
916         for (i = 0; i < ext_total; i++) {
917             TRACE_OUT(("WRITE ext_Names[%d]=%s", (int) i, tp->ext_Names[i]));
918             if (!WRITE_STRING(tp->ext_Names[i])) {
919                 return (ERR);
920             }
921         }
922
923     }
924 #endif /* NCURSES_XNAMES */
925
926     total_written++;
927     total_parts++;
928     total_size = total_size + (int) (*offset + 1);
929     return (OK);
930 }
931
932 /*
933  * Returns the total number of entries written by this process
934  */
935 NCURSES_EXPORT(int)
936 _nc_tic_written(void)
937 {
938     TR(TRACE_DATABASE, ("_nc_tic_written %d entries, %d parts, %d size",
939                         total_written, total_parts, total_size));
940     return total_written;
941 }