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