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