]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/write_entry.c
ncurses 4.2
[ncurses.git] / ncurses / write_entry.c
1 /****************************************************************************
2  * Copyright (c) 1998 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
36 /*
37  *      write_entry.c -- write a terminfo structure onto the file system
38  */
39
40 #include <curses.priv.h>
41
42 #include <sys/stat.h>
43
44 #include <tic.h>
45 #include <term.h>
46 #include <term_entry.h>
47
48 #ifndef S_ISDIR
49 #define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
50 #endif
51
52 MODULE_ID("$Id: write_entry.c,v 1.22 1998/02/11 12:13:59 tom Exp $")
53
54 static int total_written;
55
56 static int write_object(FILE *, TERMTYPE *);
57
58 static void write_file(char *filename, TERMTYPE *tp)
59 {
60         FILE *fp = fopen(filename, "wb");
61         if (fp == 0) {
62                 perror(filename);
63                 _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
64         }
65         DEBUG(1, ("Created %s", filename));
66
67         if (write_object(fp, tp) == ERR) {
68                 _nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
69         }
70         fclose(fp);
71 }
72
73 /*
74  *      make_directory(char *path)
75  *
76  *      Make a directory if it doesn't exist.
77  */
78 static int make_directory(const char *path)
79 {
80 int     rc;
81 struct  stat    statbuf;
82 char    fullpath[PATH_MAX];
83 const char *destination = _nc_tic_dir(0);
84
85         if (path == destination || *path == '/')
86                 (void)strcpy(fullpath, path);
87         else
88                 (void)sprintf(fullpath, "%s/%s", destination, path);
89
90         if ((rc = stat(path, &statbuf)) < 0) {
91                 rc = mkdir(path, 0777);
92         } else {
93                 if (access(path, R_OK|W_OK|X_OK) < 0) {
94                         rc = -1;        /* permission denied */
95                 } else if (!(S_ISDIR(statbuf.st_mode))) {
96                         rc = -1;        /* not a directory */
97                 }
98         }
99         return rc;
100 }
101
102 void  _nc_set_writedir(char *dir)
103 /* set the write directory for compiled entries */
104 {
105     const char *destination;
106
107     if (dir != 0)
108         (void) _nc_tic_dir(dir);
109     else if (getenv("TERMINFO") != NULL)
110         (void) _nc_tic_dir(getenv("TERMINFO"));
111
112     destination = _nc_tic_dir(0);
113     if (make_directory(destination) < 0)
114     {
115         char    *home;
116
117         /* ncurses extension...fall back on user's private directory */
118         if ((home = getenv("HOME")) != (char *)NULL)
119         {
120             char *temp = malloc(sizeof(PRIVATE_INFO) + strlen(home));
121             (void) sprintf(temp, PRIVATE_INFO, home);
122             destination = temp;
123
124             if (make_directory(destination) < 0)
125                 _nc_err_abort("%s: permission denied (errno %d)",
126                         destination, errno);
127         }
128     }
129
130     /*
131      * Note: because of this code, this logic should be exercised
132      * *once only* per run.
133      */
134     if (chdir(_nc_tic_dir(destination)) < 0)
135         _nc_err_abort("%s: not a directory", destination);
136 }
137
138 /*
139  *      check_writeable(char code)
140  *
141  *      Miscellaneous initialisations
142  *
143  *      Check for access rights to destination directories
144  *      Create any directories which don't exist.
145  *      Note: there's no reason to return the result of make_directory(), since
146  *      this function is called only in instances where that has to succeed.
147  *
148  */
149
150 static void check_writeable(int code)
151 {
152 static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
153 static bool verified[sizeof(dirnames)];
154
155 char            dir[2];
156 char            *s;
157
158         if (code == 0 || (s = strchr(dirnames, code)) == 0)
159             _nc_err_abort("Illegal terminfo subdirectory \"%c\"", code);
160
161         if (verified[s-dirnames])
162             return;
163
164         dir[0] = code;
165         dir[1] = '\0';
166         if (make_directory(dir) < 0) {
167                 _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
168         }
169
170         verified[s-dirnames] = TRUE;
171 }
172
173 /*
174  *      _nc_write_entry()
175  *
176  *      Save the compiled version of a description in the filesystem.
177  *
178  *      make a copy of the name-list
179  *      break it up into first-name and all-but-last-name
180  *      creat(first-name)
181  *      write object information to first-name
182  *      close(first-name)
183  *      for each name in all-but-last-name
184  *          link to first-name
185  *
186  *      Using 'time()' to obtain a reference for file timestamps is unreliable,
187  *      e.g., with NFS, because the filesystem may have a different time
188  *      reference.  We check for pre-existence of links by latching the first
189  *      timestamp from a file that we create.
190  *
191  *      The _nc_warning() calls will report a correct line number only if
192  *      _nc_curr_line is properly set before the write_entry() call.
193  */
194
195 void _nc_write_entry(TERMTYPE *const tp)
196 {
197 struct stat     statbuf;
198 char            name_list[MAX_TERMINFO_LENGTH];
199 char            *first_name, *other_names;
200 char            *ptr;
201 char            filename[PATH_MAX];
202 char            linkname[PATH_MAX];
203 #if USE_SYMLINKS
204 char            symlinkname[PATH_MAX];
205 #endif /* USE_SYMLINKS */
206 static int      call_count;
207 static time_t   start_time;             /* time at start of writes */
208
209         if (call_count++ == 0) {
210                 start_time = 0;
211         }
212
213         (void) strcpy(name_list, tp->term_names);
214         DEBUG(7, ("Name list = '%s'", name_list));
215
216         first_name = name_list;
217
218         ptr = &name_list[strlen(name_list) - 1];
219         other_names = ptr + 1;
220
221         while (ptr > name_list  &&  *ptr != '|')
222                 ptr--;
223
224         if (ptr != name_list) {
225                 *ptr = '\0';
226
227                 for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
228                         continue;
229
230                 if (*ptr == '\0')
231                         other_names = ptr;
232                 else {
233                         *ptr = '\0';
234                         other_names = ptr + 1;
235                 }
236         }
237
238         DEBUG(7, ("First name = '%s'", first_name));
239         DEBUG(7, ("Other names = '%s'", other_names));
240
241         _nc_set_type(first_name);
242
243         if (strlen(first_name) > sizeof(filename)-3)
244                 _nc_warning("terminal name too long.");
245
246         sprintf(filename, "%c/%s", first_name[0], first_name);
247
248         /*
249          * Has this primary name been written since the first call to
250          * write_entry()?  If so, the newer write will step on the older,
251          * so warn the user.
252          */
253         if (start_time > 0 &&
254             stat(filename, &statbuf) >= 0
255             && statbuf.st_mtime >= start_time)
256         {
257                 _nc_warning("name multiply defined.");
258         }
259
260         check_writeable(first_name[0]);
261         write_file(filename, tp);
262
263         if (start_time == 0) {
264                 if (stat(filename, &statbuf) < 0
265                  || (start_time = statbuf.st_mtime) == 0) {
266                         _nc_syserr_abort("error obtaining time from %s/%s",
267                                 _nc_tic_dir(0), filename);
268                 }
269         }
270         while (*other_names != '\0') {
271                 ptr = other_names++;
272                 while (*other_names != '|'  &&  *other_names != '\0')
273                         other_names++;
274
275                 if (*other_names != '\0')
276                         *(other_names++) = '\0';
277
278                 if (strlen(ptr) > sizeof(linkname)-3) {
279                         _nc_warning("terminal alias %s too long.", ptr);
280                         continue;
281                 }
282
283                 check_writeable(ptr[0]);
284                 sprintf(linkname, "%c/%s", ptr[0], ptr);
285
286                 if (strcmp(filename, linkname) == 0) {
287                         _nc_warning("self-synonym ignored");
288                 }
289                 else if (stat(linkname, &statbuf) >= 0  &&
290                                                 statbuf.st_mtime < start_time)
291                 {
292                         _nc_warning("alias %s multiply defined.", ptr);
293                 }
294                 else
295 #if HAVE_LINK
296                 {
297 #if USE_SYMLINKS
298                         strcpy(symlinkname, "../");
299                         strcat(symlinkname, filename);
300 #endif /* USE_SYMLINKS */
301 #if HAVE_REMOVE
302                         remove(linkname);
303 #else
304                         unlink(linkname);
305 #endif
306 #if USE_SYMLINKS
307                         if (symlink(symlinkname, linkname) < 0)
308 #else
309                         if (link(filename, linkname) < 0)
310 #endif /* USE_SYMLINKS */
311                             _nc_syserr_abort("can't link %s to %s", filename, linkname);
312                         DEBUG(1, ("Linked %s", linkname));
313                 }
314 #else /* just make copies */
315                 write_file(linkname, tp);
316 #endif /* HAVE_LINK */
317         }
318 }
319
320 #undef LITTLE_ENDIAN    /* BSD/OS defines this as a feature macro */
321 #define HI(x)                   ((x) / 256)
322 #define LO(x)                   ((x) % 256)
323 #define LITTLE_ENDIAN(p, x)     (p)[0] = LO(x), (p)[1] = HI(x)
324
325 static int write_object(FILE *fp, TERMTYPE *tp)
326 {
327 char            *namelist;
328 size_t          namelen, boolmax, nummax, strmax;
329 char            zero = '\0';
330 size_t          i;
331 short           nextfree;
332 short           offsets[STRCOUNT];
333 unsigned char   buf[MAX_ENTRY_SIZE];
334
335         namelist = tp->term_names;
336         namelen = strlen(namelist) + 1;
337
338         boolmax = 0;
339         for (i = 0; i < BOOLWRITE; i++)
340                 if (tp->Booleans[i])
341                         boolmax = i+1;
342
343         nummax = 0;
344         for (i = 0; i < NUMWRITE; i++)
345                 if (tp->Numbers[i] != ABSENT_NUMERIC)
346                         nummax = i+1;
347
348         strmax = 0;
349         for (i = 0; i < STRWRITE; i++)
350                 if (tp->Strings[i] != ABSENT_STRING)
351                         strmax = i+1;
352
353         nextfree = 0;
354         for (i = 0; i < strmax; i++)
355             if (tp->Strings[i] == ABSENT_STRING)
356                 offsets[i] = -1;
357             else if (tp->Strings[i] == CANCELLED_STRING)
358                 offsets[i] = -2;
359             else
360             {
361                 offsets[i] = nextfree;
362                 nextfree += strlen(tp->Strings[i]) + 1;
363             }
364
365         /* fill in the header */
366         LITTLE_ENDIAN(buf,    MAGIC);
367         LITTLE_ENDIAN(buf+2,  min(namelen, MAX_NAME_SIZE + 1));
368         LITTLE_ENDIAN(buf+4,  boolmax);
369         LITTLE_ENDIAN(buf+6,  nummax);
370         LITTLE_ENDIAN(buf+8,  strmax);
371         LITTLE_ENDIAN(buf+10, nextfree);
372
373         /* write out the header */
374         if (fwrite(buf, 12, 1, fp) != 1
375                 ||  fwrite(namelist, sizeof(char), (size_t)namelen, fp) != namelen
376                 ||  fwrite(tp->Booleans, sizeof(char), (size_t)boolmax, fp) != boolmax)
377                 return(ERR);
378
379         /* the even-boundary padding byte */
380         if ((namelen+boolmax) % 2 != 0 &&  fwrite(&zero, sizeof(char), 1, fp) != 1)
381                 return(ERR);
382
383 #ifdef SHOWOFFSET
384         (void) fprintf(stderr, "Numerics begin at %04lx\n", ftell(fp));
385 #endif /* SHOWOFFSET */
386
387         /* the numerics */
388         for (i = 0; i < nummax; i++)
389         {
390                 if (tp->Numbers[i] == -1)       /* HI/LO won't work */
391                         buf[2*i] = buf[2*i + 1] = 0377;
392                 else
393                         LITTLE_ENDIAN(buf + 2*i, tp->Numbers[i]);
394         }
395         if (fwrite(buf, 2, (size_t)nummax, fp) != nummax)
396                 return(ERR);
397
398 #ifdef SHOWOFFSET
399         (void) fprintf(stderr, "String offets begin at %04lx\n", ftell(fp));
400 #endif /* SHOWOFFSET */
401
402         /* the string offsets */
403         for (i = 0; i < strmax; i++)
404                 if (offsets[i] == -1)   /* HI/LO won't work */
405                         buf[2*i] = buf[2*i + 1] = 0377;
406                 else if (offsets[i] == -2)      /* HI/LO won't work */
407                 {
408                         buf[2*i] = 0376;
409                         buf[2*i + 1] = 0377;
410                 }
411                 else
412                         LITTLE_ENDIAN(buf + 2*i, offsets[i]);
413         if (fwrite(buf, 2, (size_t)strmax, fp) != strmax)
414                 return(ERR);
415
416 #ifdef SHOWOFFSET
417         (void) fprintf(stderr, "String table begins at %04lx\n", ftell(fp));
418 #endif /* SHOWOFFSET */
419
420         /* the strings */
421         for (i = 0; i < strmax; i++)
422             if (tp->Strings[i] != ABSENT_STRING && tp->Strings[i] != CANCELLED_STRING)
423                 if (fwrite(tp->Strings[i], sizeof(char), strlen(tp->Strings[i]) + 1, fp) != strlen(tp->Strings[i]) + 1)
424                     return(ERR);
425
426         total_written++;
427         return(OK);
428 }
429
430 /*
431  * Returns the total number of entries written by this process
432  */
433 int _nc_tic_written(void)
434 {
435         return total_written;
436 }