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