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