]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tinfo/write_entry.c
12aedd6e565ca942087e9512300270516ec66899
[ncurses.git] / ncurses / tinfo / write_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998,1999,2000 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  ****************************************************************************/
33
34 /*
35  *      write_entry.c -- write a terminfo structure onto the file system
36  */
37
38 #include <curses.priv.h>
39
40 #include <sys/stat.h>
41
42 #include <tic.h>
43 #include <term_entry.h>
44
45 #ifndef S_ISDIR
46 #define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
47 #endif
48
49 #if 0
50 #define TRACE_OUT(p) DEBUG(2, p)
51 #else
52 #define TRACE_OUT(p)            /*nothing */
53 #endif
54
55 MODULE_ID("$Id: write_entry.c,v 1.52 2000/03/11 12:23:42 tom Exp $")
56
57 static int total_written;
58
59 static int write_object(FILE *, TERMTYPE *);
60
61 static void
62 write_file(char *filename, TERMTYPE * tp)
63 {
64     FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
65     if (fp == 0) {
66         perror(filename);
67         _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
68     }
69     DEBUG(1, ("Created %s", filename));
70
71     if (write_object(fp, tp) == ERR) {
72         _nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
73     }
74     fclose(fp);
75 }
76
77 /*
78  *      make_directory(char *path)
79  *
80  *      Make a directory if it doesn't exist.
81  */
82 static int
83 make_directory(const char *path)
84 {
85     int rc;
86     struct stat statbuf;
87     char fullpath[PATH_MAX];
88     const char *destination = _nc_tic_dir(0);
89
90     if (path == destination || *path == '/') {
91         if (strlen(path) + 1 > sizeof(fullpath))
92             return (-1);
93         (void) strcpy(fullpath, path);
94     } else {
95         if (strlen(destination) + strlen(path) + 2 > sizeof(fullpath))
96             return (-1);
97         (void) sprintf(fullpath, "%s/%s", destination, path);
98     }
99
100     if ((rc = stat(path, &statbuf)) < 0) {
101         rc = mkdir(path, 0777);
102     } else {
103         if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
104             rc = -1;            /* permission denied */
105         } else if (!(S_ISDIR(statbuf.st_mode))) {
106             rc = -1;            /* not a directory */
107         }
108     }
109     return rc;
110 }
111
112 void
113 _nc_set_writedir(char *dir)
114 /* set the write directory for compiled entries */
115 {
116     const char *destination;
117     char actual[PATH_MAX];
118
119     if (dir != 0)
120         (void) _nc_tic_dir(dir);
121     else if (getenv("TERMINFO") != NULL)
122         (void) _nc_tic_dir(getenv("TERMINFO"));
123
124     destination = _nc_tic_dir(0);
125     if (make_directory(destination) < 0) {
126         char *home = _nc_home_terminfo();
127
128         if (home != 0) {
129             destination = home;
130             if (make_directory(destination) < 0)
131                 _nc_err_abort("%s: permission denied (errno %d)",
132                     destination, errno);
133         }
134     }
135
136     /*
137      * Note: because of this code, this logic should be exercised
138      * *once only* per run.
139      */
140     if (chdir(_nc_tic_dir(destination)) < 0
141         || getcwd(actual, sizeof(actual)) == 0)
142         _nc_err_abort("%s: not a directory", destination);
143     _nc_keep_tic_dir(strdup(actual));
144 }
145
146 /*
147  *      check_writeable(char code)
148  *
149  *      Miscellaneous initialisations
150  *
151  *      Check for access rights to destination directories
152  *      Create any directories which don't exist.
153  *      Note: there's no reason to return the result of make_directory(), since
154  *      this function is called only in instances where that has to succeed.
155  *
156  */
157
158 static void
159 check_writeable(int code)
160 {
161     static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
162     static bool verified[sizeof(dirnames)];
163
164     char dir[2];
165     char *s;
166
167     if (code == 0 || (s = strchr(dirnames, code)) == 0)
168         _nc_err_abort("Illegal terminfo subdirectory \"%c\"", code);
169
170     if (verified[s - dirnames])
171         return;
172
173     dir[0] = code;
174     dir[1] = '\0';
175     if (make_directory(dir) < 0) {
176         _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
177     }
178
179     verified[s - dirnames] = TRUE;
180 }
181
182 /*
183  *      _nc_write_entry()
184  *
185  *      Save the compiled version of a description in the filesystem.
186  *
187  *      make a copy of the name-list
188  *      break it up into first-name and all-but-last-name
189  *      creat(first-name)
190  *      write object information to first-name
191  *      close(first-name)
192  *      for each name in all-but-last-name
193  *          link to first-name
194  *
195  *      Using 'time()' to obtain a reference for file timestamps is unreliable,
196  *      e.g., with NFS, because the filesystem may have a different time
197  *      reference.  We check for pre-existence of links by latching the first
198  *      timestamp from a file that we create.
199  *
200  *      The _nc_warning() calls will report a correct line number only if
201  *      _nc_curr_line is properly set before the write_entry() call.
202  */
203
204 void
205 _nc_write_entry(TERMTYPE * const tp)
206 {
207     struct stat statbuf;
208     char name_list[MAX_TERMINFO_LENGTH];
209     char *first_name, *other_names;
210     char *ptr;
211     char filename[PATH_MAX];
212     char linkname[PATH_MAX];
213 #if USE_SYMLINKS
214     char symlinkname[PATH_MAX];
215 #endif /* USE_SYMLINKS */
216     static int call_count;
217     static time_t start_time;   /* time at start of writes */
218
219     if (call_count++ == 0) {
220         start_time = 0;
221     }
222
223     (void) strcpy(name_list, tp->term_names);
224     DEBUG(7, ("Name list = '%s'", name_list));
225
226     first_name = name_list;
227
228     ptr = &name_list[strlen(name_list) - 1];
229     other_names = ptr + 1;
230
231     while (ptr > name_list && *ptr != '|')
232         ptr--;
233
234     if (ptr != name_list) {
235         *ptr = '\0';
236
237         for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
238             continue;
239
240         if (*ptr == '\0')
241             other_names = ptr;
242         else {
243             *ptr = '\0';
244             other_names = ptr + 1;
245         }
246     }
247
248     DEBUG(7, ("First name = '%s'", first_name));
249     DEBUG(7, ("Other names = '%s'", other_names));
250
251     _nc_set_type(first_name);
252
253     if (strlen(first_name) > sizeof(filename) - 3)
254         _nc_warning("terminal name too long.");
255
256     sprintf(filename, "%c/%s", first_name[0], first_name);
257
258     /*
259      * Has this primary name been written since the first call to
260      * write_entry()?  If so, the newer write will step on the older,
261      * so warn the user.
262      */
263     if (start_time > 0 &&
264         stat(filename, &statbuf) >= 0
265         && statbuf.st_mtime >= start_time) {
266         _nc_warning("name multiply defined.");
267     }
268
269     check_writeable(first_name[0]);
270     write_file(filename, tp);
271
272     if (start_time == 0) {
273         if (stat(filename, &statbuf) < 0
274             || (start_time = statbuf.st_mtime) == 0) {
275             _nc_syserr_abort("error obtaining time from %s/%s",
276                 _nc_tic_dir(0), filename);
277         }
278     }
279     while (*other_names != '\0') {
280         ptr = other_names++;
281         while (*other_names != '|' && *other_names != '\0')
282             other_names++;
283
284         if (*other_names != '\0')
285             *(other_names++) = '\0';
286
287         if (strlen(ptr) > sizeof(linkname) - 3) {
288             _nc_warning("terminal alias %s too long.", ptr);
289             continue;
290         }
291         if (strchr(ptr, '/') != 0) {
292             _nc_warning("cannot link alias %s.", ptr);
293             continue;
294         }
295
296         check_writeable(ptr[0]);
297         sprintf(linkname, "%c/%s", ptr[0], ptr);
298
299         if (strcmp(filename, linkname) == 0) {
300             _nc_warning("self-synonym ignored");
301         } else if (stat(linkname, &statbuf) >= 0 &&
302             statbuf.st_mtime < start_time) {
303             _nc_warning("alias %s multiply defined.", ptr);
304         } else if (_nc_access(linkname, W_OK) == 0)
305 #if HAVE_LINK
306         {
307             int code;
308 #if USE_SYMLINKS
309             strcpy(symlinkname, "../");
310             strncat(symlinkname, filename, sizeof(symlinkname) - 4);
311             symlinkname[sizeof(symlinkname) - 1] = '\0';
312 #endif /* USE_SYMLINKS */
313 #if HAVE_REMOVE
314             code = remove(linkname);
315 #else
316             code = unlink(linkname);
317 #endif
318             if (code != 0 && errno == ENOENT)
319                 code = 0;
320 #if USE_SYMLINKS
321             if (symlink(symlinkname, linkname) < 0)
322 #else
323             if (link(filename, linkname) < 0)
324 #endif /* USE_SYMLINKS */
325             {
326                 /*
327                  * If there wasn't anything there, and we cannot
328                  * link to the target because it is the same as the
329                  * target, then the source must be on a filesystem
330                  * that uses caseless filenames, such as Win32, etc.
331                  */
332                 if (code == 0 && errno == EEXIST)
333                     _nc_warning("can't link %s to %s", filename, linkname);
334                 else if (code == 0 && errno == EPERM)
335                     write_file(linkname, tp);
336                 else
337                     _nc_syserr_abort("can't link %s to %s", filename, linkname);
338             } else {
339                 DEBUG(1, ("Linked %s", linkname));
340             }
341         }
342 #else /* just make copies */
343             write_file(linkname, tp);
344 #endif /* HAVE_LINK */
345     }
346 }
347
348 #undef LITTLE_ENDIAN            /* BSD/OS defines this as a feature macro */
349 #define HI(x)                   ((x) / 256)
350 #define LO(x)                   ((x) % 256)
351 #define LITTLE_ENDIAN(p, x)     (p)[0] = LO(x), (p)[1] = HI(x)
352
353 #define WRITE_STRING(str) (fwrite(str, sizeof(char), strlen(str) + 1, fp) == strlen(str) + 1)
354
355 static int
356 compute_offsets(char **Strings, int strmax, short *offsets)
357 {
358     size_t nextfree = 0;
359     int i;
360
361     for (i = 0; i < strmax; i++) {
362         if (Strings[i] == ABSENT_STRING) {
363             offsets[i] = -1;
364         } else if (Strings[i] == CANCELLED_STRING) {
365             offsets[i] = -2;
366         } else {
367             offsets[i] = nextfree;
368             nextfree += strlen(Strings[i]) + 1;
369             TRACE_OUT(("put Strings[%d]=%s(%d)", i, _nc_visbuf(Strings[i]), nextfree));
370         }
371     }
372     return nextfree;
373 }
374
375 static void
376 convert_shorts(unsigned char *buf, short *Numbers, int count)
377 {
378     int i;
379     for (i = 0; i < count; i++) {
380         if (Numbers[i] == ABSENT_NUMERIC) {     /* HI/LO won't work */
381             buf[2 * i] = buf[2 * i + 1] = 0377;
382         } else if (Numbers[i] == CANCELLED_NUMERIC) {   /* HI/LO won't work */
383             buf[2 * i] = 0376;
384             buf[2 * i + 1] = 0377;
385         } else {
386             LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
387             TRACE_OUT(("put Numbers[%d]=%d", i, Numbers[i]));
388         }
389     }
390 }
391
392 #define even_boundary(value) \
393             ((value) % 2 != 0 && fwrite(&zero, sizeof(char), 1, fp) != 1)
394
395 static int
396 write_object(FILE * fp, TERMTYPE * tp)
397 {
398     char *namelist;
399     size_t namelen, boolmax, nummax, strmax;
400     char zero = '\0';
401     size_t i;
402     short nextfree;
403     short offsets[MAX_ENTRY_SIZE / 2];
404     unsigned char buf[MAX_ENTRY_SIZE];
405     unsigned last_bool = BOOLWRITE;
406     unsigned last_num = NUMWRITE;
407     unsigned last_str = STRWRITE;
408
409 #if NCURSES_XNAMES
410     /*
411      * Normally we limit the list of values to exclude the "obsolete"
412      * capabilities.  However, if we are accepting extended names, add
413      * these as well, since they are used for supporting translation
414      * to/from termcap.
415      */
416     if (_nc_user_definable) {
417         last_bool = BOOLCOUNT;
418         last_num = NUMCOUNT;
419         last_str = STRCOUNT;
420     }
421 #endif
422
423     namelist = tp->term_names;
424     namelen = strlen(namelist) + 1;
425
426     boolmax = 0;
427     for (i = 0; i < last_bool; i++) {
428         if (tp->Booleans[i] == TRUE)
429             boolmax = i + 1;
430     }
431
432     nummax = 0;
433     for (i = 0; i < last_num; i++) {
434         if (tp->Numbers[i] != ABSENT_NUMERIC)
435             nummax = i + 1;
436     }
437
438     strmax = 0;
439     for (i = 0; i < last_str; i++) {
440         if (tp->Strings[i] != ABSENT_STRING)
441             strmax = i + 1;
442     }
443
444     nextfree = compute_offsets(tp->Strings, strmax, offsets);
445
446     /* fill in the header */
447     LITTLE_ENDIAN(buf, MAGIC);
448     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
449     LITTLE_ENDIAN(buf + 4, boolmax);
450     LITTLE_ENDIAN(buf + 6, nummax);
451     LITTLE_ENDIAN(buf + 8, strmax);
452     LITTLE_ENDIAN(buf + 10, nextfree);
453
454     /* write out the header */
455     TRACE_OUT(("Header of %s @%ld", namelist, ftell(fp)));
456     if (fwrite(buf, 12, 1, fp) != 1
457         || fwrite(namelist, sizeof(char), namelen, fp) != namelen)
458           return (ERR);
459
460     for (i = 0; i < boolmax; i++)
461         if (tp->Booleans[i] == TRUE)
462             buf[i] = TRUE;
463         else
464             buf[i] = FALSE;
465     if (fwrite(buf, sizeof(char), boolmax, fp) != boolmax)
466           return (ERR);
467
468     if (even_boundary(namelen + boolmax))
469         return (ERR);
470
471     TRACE_OUT(("Numerics begin at %04lx", ftell(fp)));
472
473     /* the numerics */
474     convert_shorts(buf, tp->Numbers, nummax);
475     if (fwrite(buf, 2, nummax, fp) != nummax)
476         return (ERR);
477
478     TRACE_OUT(("String offsets begin at %04lx", ftell(fp)));
479
480     /* the string offsets */
481     convert_shorts(buf, offsets, strmax);
482     if (fwrite(buf, 2, strmax, fp) != strmax)
483         return (ERR);
484
485     TRACE_OUT(("String table begins at %04lx", ftell(fp)));
486
487     /* the strings */
488     for (i = 0; i < strmax; i++)
489         if (VALID_STRING(tp->Strings[i]))
490             if (!WRITE_STRING(tp->Strings[i]))
491                 return (ERR);
492
493 #if NCURSES_XNAMES
494     if (NUM_EXT_NAMES(tp)) {
495         unsigned extcnt = NUM_EXT_NAMES(tp);
496
497         if (even_boundary(nextfree))
498             return (ERR);
499
500         nextfree = compute_offsets(tp->Strings + STRCOUNT, tp->ext_Strings, offsets);
501         TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
502         nextfree += compute_offsets(tp->ext_Names, extcnt, offsets + tp->ext_Strings);
503         TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
504         strmax = tp->ext_Strings + extcnt;
505
506         /*
507          * Write the extended header
508          */
509         LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
510         LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
511         LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
512         LITTLE_ENDIAN(buf + 6, strmax);
513         LITTLE_ENDIAN(buf + 8, nextfree);
514         TRACE_OUT(("WRITE extended-header @%ld", ftell(fp)));
515         if (fwrite(buf, 10, 1, fp) != 1)
516             return (ERR);
517
518         TRACE_OUT(("WRITE %d booleans @%ld", tp->ext_Booleans, ftell(fp)));
519         if (tp->ext_Booleans
520             && fwrite(tp->Booleans + BOOLCOUNT, sizeof(char),
521                 tp->ext_Booleans, fp) != tp->ext_Booleans)
522               return (ERR);
523
524         if (even_boundary(tp->ext_Booleans))
525             return (ERR);
526
527         TRACE_OUT(("WRITE %d numbers @%ld", tp->ext_Numbers, ftell(fp)));
528         if (tp->ext_Numbers) {
529             convert_shorts(buf, tp->Numbers + NUMCOUNT, tp->ext_Numbers);
530             if (fwrite(buf, 2, tp->ext_Numbers, fp) != tp->ext_Numbers)
531                 return (ERR);
532         }
533
534         /*
535          * Convert the offsets for the ext_Strings and ext_Names tables,
536          * in that order.
537          */
538         convert_shorts(buf, offsets, strmax);
539         TRACE_OUT(("WRITE offsets @%ld", ftell(fp)));
540         if (fwrite(buf, 2, strmax, fp) != strmax)
541             return (ERR);
542
543         /*
544          * Write the string table after the offset tables so we do not
545          * have to do anything about alignment.
546          */
547         for (i = 0; i < tp->ext_Strings; i++) {
548             if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
549                 TRACE_OUT(("WRITE ext_Strings[%d]=%s", i,
550                         _nc_visbuf(tp->Strings[i + STRCOUNT])));
551                 if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
552                     return (ERR);
553             }
554         }
555
556         /*
557          * Write the extended names
558          */
559         for (i = 0; i < extcnt; i++) {
560             TRACE_OUT(("WRITE ext_Names[%d]=%s", i, tp->ext_Names[i]));
561             if (!WRITE_STRING(tp->ext_Names[i]))
562                 return (ERR);
563         }
564
565     }
566 #endif /* NCURSES_XNAMES */
567
568     total_written++;
569     return (OK);
570 }
571
572 /*
573  * Returns the total number of entries written by this process
574  */
575 int
576 _nc_tic_written(void)
577 {
578     return total_written;
579 }