Back to index

tetex-bin  3.0
write_entry.c
Go to the documentation of this file.
00001 /****************************************************************************
00002  * Copyright (c) 1998-2000,2002 Free Software Foundation, Inc.              *
00003  *                                                                          *
00004  * Permission is hereby granted, free of charge, to any person obtaining a  *
00005  * copy of this software and associated documentation files (the            *
00006  * "Software"), to deal in the Software without restriction, including      *
00007  * without limitation the rights to use, copy, modify, merge, publish,      *
00008  * distribute, distribute with modifications, sublicense, and/or sell       *
00009  * copies of the Software, and to permit persons to whom the Software is    *
00010  * furnished to do so, subject to the following conditions:                 *
00011  *                                                                          *
00012  * The above copyright notice and this permission notice shall be included  *
00013  * in all copies or substantial portions of the Software.                   *
00014  *                                                                          *
00015  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
00016  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
00017  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
00018  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
00019  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
00020  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
00021  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
00022  *                                                                          *
00023  * Except as contained in this notice, the name(s) of the above copyright   *
00024  * holders shall not be used in advertising or otherwise to promote the     *
00025  * sale, use or other dealings in this Software without prior written       *
00026  * authorization.                                                           *
00027  ****************************************************************************/
00028 
00029 /****************************************************************************
00030  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
00031  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
00032  ****************************************************************************/
00033 
00034 /*
00035  *     write_entry.c -- write a terminfo structure onto the file system
00036  */
00037 
00038 #include <curses.priv.h>
00039 
00040 #include <sys/stat.h>
00041 
00042 #include <tic.h>
00043 #include <term_entry.h>
00044 
00045 #ifndef S_ISDIR
00046 #define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
00047 #endif
00048 
00049 #if 0
00050 #define TRACE_OUT(p) DEBUG(2, p)
00051 #else
00052 #define TRACE_OUT(p)        /*nothing */
00053 #endif
00054 
00055 MODULE_ID("$Id: write_entry.c,v 1.58 2002/04/21 20:35:08 tom Exp $")
00056 
00057 static int total_written;
00058 
00059 static int write_object(FILE *, TERMTYPE *);
00060 
00061 static void
00062 write_file(char *filename, TERMTYPE * tp)
00063 {
00064     FILE *fp = (_nc_access(filename, W_OK) == 0) ? fopen(filename, "wb") : 0;
00065     if (fp == 0) {
00066        perror(filename);
00067        _nc_syserr_abort("can't open %s/%s", _nc_tic_dir(0), filename);
00068     }
00069     DEBUG(1, ("Created %s", filename));
00070 
00071     if (write_object(fp, tp) == ERR) {
00072        _nc_syserr_abort("error writing %s/%s", _nc_tic_dir(0), filename);
00073     }
00074     fclose(fp);
00075 }
00076 
00077 /*
00078  *     make_directory(char *path)
00079  *
00080  *     Make a directory if it doesn't exist.
00081  */
00082 static int
00083 make_directory(const char *path)
00084 {
00085     int rc;
00086     struct stat statbuf;
00087     char fullpath[PATH_MAX];
00088     const char *destination = _nc_tic_dir(0);
00089 
00090     if (path == destination || *path == '/') {
00091        if (strlen(path) + 1 > sizeof(fullpath))
00092            return (-1);
00093        (void) strcpy(fullpath, path);
00094     } else {
00095        if (strlen(destination) + strlen(path) + 2 > sizeof(fullpath))
00096            return (-1);
00097        (void) sprintf(fullpath, "%s/%s", destination, path);
00098     }
00099 
00100     if ((rc = stat(path, &statbuf)) < 0) {
00101        rc = mkdir(path, 0777);
00102     } else {
00103        if (_nc_access(path, R_OK | W_OK | X_OK) < 0) {
00104            rc = -1;         /* permission denied */
00105        } else if (!(S_ISDIR(statbuf.st_mode))) {
00106            rc = -1;         /* not a directory */
00107        }
00108     }
00109     return rc;
00110 }
00111 
00112 NCURSES_EXPORT(void)
00113 _nc_set_writedir(char *dir)
00114 /* set the write directory for compiled entries */
00115 {
00116     const char *destination;
00117     char actual[PATH_MAX];
00118 
00119     if (dir == 0
00120        && use_terminfo_vars())
00121        dir = getenv("TERMINFO");
00122 
00123     if (dir != 0)
00124        (void) _nc_tic_dir(dir);
00125 
00126     destination = _nc_tic_dir(0);
00127     if (make_directory(destination) < 0) {
00128        char *home = _nc_home_terminfo();
00129 
00130        if (home != 0) {
00131            destination = home;
00132            if (make_directory(destination) < 0)
00133               _nc_err_abort("%s: permission denied (errno %d)",
00134                            destination, errno);
00135        }
00136     }
00137 
00138     /*
00139      * Note: because of this code, this logic should be exercised
00140      * *once only* per run.
00141      */
00142     if (chdir(_nc_tic_dir(destination)) < 0
00143        || getcwd(actual, sizeof(actual)) == 0)
00144        _nc_err_abort("%s: not a directory", destination);
00145     _nc_keep_tic_dir(strdup(actual));
00146 }
00147 
00148 /*
00149  *     check_writeable(char code)
00150  *
00151  *     Miscellaneous initialisations
00152  *
00153  *     Check for access rights to destination directories
00154  *     Create any directories which don't exist.
00155  *     Note: there's no reason to return the result of make_directory(), since
00156  *     this function is called only in instances where that has to succeed.
00157  *
00158  */
00159 
00160 static void
00161 check_writeable(int code)
00162 {
00163     static const char dirnames[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
00164     static bool verified[sizeof(dirnames)];
00165 
00166     char dir[2];
00167     char *s = 0;
00168 
00169     if (code == 0 || (s = strchr(dirnames, code)) == 0)
00170        _nc_err_abort("Illegal terminfo subdirectory \"%c\"", code);
00171 
00172     if (verified[s - dirnames])
00173        return;
00174 
00175     dir[0] = code;
00176     dir[1] = '\0';
00177     if (make_directory(dir) < 0) {
00178        _nc_err_abort("%s/%s: permission denied", _nc_tic_dir(0), dir);
00179     }
00180 
00181     verified[s - dirnames] = TRUE;
00182 }
00183 
00184 /*
00185  *     _nc_write_entry()
00186  *
00187  *     Save the compiled version of a description in the filesystem.
00188  *
00189  *     make a copy of the name-list
00190  *     break it up into first-name and all-but-last-name
00191  *     creat(first-name)
00192  *     write object information to first-name
00193  *     close(first-name)
00194  *      for each name in all-but-last-name
00195  *         link to first-name
00196  *
00197  *     Using 'time()' to obtain a reference for file timestamps is unreliable,
00198  *     e.g., with NFS, because the filesystem may have a different time
00199  *     reference.  We check for pre-existence of links by latching the first
00200  *     timestamp from a file that we create.
00201  *
00202  *     The _nc_warning() calls will report a correct line number only if
00203  *     _nc_curr_line is properly set before the write_entry() call.
00204  */
00205 
00206 void
00207 _nc_write_entry(TERMTYPE * const tp)
00208 {
00209     struct stat statbuf;
00210     char name_list[MAX_TERMINFO_LENGTH];
00211     char *first_name, *other_names;
00212     char *ptr;
00213     char filename[PATH_MAX];
00214     char linkname[PATH_MAX];
00215 #if USE_SYMLINKS
00216     char symlinkname[PATH_MAX];
00217 #if !HAVE_LINK
00218 #undef HAVE_LINK
00219 #define HAVE_LINK 1
00220 #endif
00221 #endif /* USE_SYMLINKS */
00222     static int call_count;
00223     static time_t start_time;      /* time at start of writes */
00224 
00225     if (call_count++ == 0) {
00226        start_time = 0;
00227     }
00228 
00229     (void) strcpy(name_list, tp->term_names);
00230     DEBUG(7, ("Name list = '%s'", name_list));
00231 
00232     first_name = name_list;
00233 
00234     ptr = &name_list[strlen(name_list) - 1];
00235     other_names = ptr + 1;
00236 
00237     while (ptr > name_list && *ptr != '|')
00238        ptr--;
00239 
00240     if (ptr != name_list) {
00241        *ptr = '\0';
00242 
00243        for (ptr = name_list; *ptr != '\0' && *ptr != '|'; ptr++)
00244            continue;
00245 
00246        if (*ptr == '\0')
00247            other_names = ptr;
00248        else {
00249            *ptr = '\0';
00250            other_names = ptr + 1;
00251        }
00252     }
00253 
00254     DEBUG(7, ("First name = '%s'", first_name));
00255     DEBUG(7, ("Other names = '%s'", other_names));
00256 
00257     _nc_set_type(first_name);
00258 
00259     if (strlen(first_name) > sizeof(filename) - 3)
00260        _nc_warning("terminal name too long.");
00261 
00262     sprintf(filename, "%c/%s", first_name[0], first_name);
00263 
00264     /*
00265      * Has this primary name been written since the first call to
00266      * write_entry()?  If so, the newer write will step on the older,
00267      * so warn the user.
00268      */
00269     if (start_time > 0 &&
00270        stat(filename, &statbuf) >= 0
00271        && statbuf.st_mtime >= start_time) {
00272        _nc_warning("name multiply defined.");
00273     }
00274 
00275     check_writeable(first_name[0]);
00276     write_file(filename, tp);
00277 
00278     if (start_time == 0) {
00279        if (stat(filename, &statbuf) < 0
00280            || (start_time = statbuf.st_mtime) == 0) {
00281            _nc_syserr_abort("error obtaining time from %s/%s",
00282                           _nc_tic_dir(0), filename);
00283        }
00284     }
00285     while (*other_names != '\0') {
00286        ptr = other_names++;
00287        while (*other_names != '|' && *other_names != '\0')
00288            other_names++;
00289 
00290        if (*other_names != '\0')
00291            *(other_names++) = '\0';
00292 
00293        if (strlen(ptr) > sizeof(linkname) - 3) {
00294            _nc_warning("terminal alias %s too long.", ptr);
00295            continue;
00296        }
00297        if (strchr(ptr, '/') != 0) {
00298            _nc_warning("cannot link alias %s.", ptr);
00299            continue;
00300        }
00301 
00302        check_writeable(ptr[0]);
00303        sprintf(linkname, "%c/%s", ptr[0], ptr);
00304 
00305        if (strcmp(filename, linkname) == 0) {
00306            _nc_warning("self-synonym ignored");
00307        } else if (stat(linkname, &statbuf) >= 0 &&
00308                  statbuf.st_mtime < start_time) {
00309            _nc_warning("alias %s multiply defined.", ptr);
00310        } else if (_nc_access(linkname, W_OK) == 0)
00311 #if HAVE_LINK
00312        {
00313            int code;
00314 #if USE_SYMLINKS
00315            strcpy(symlinkname, "../");
00316            strncat(symlinkname, filename, sizeof(symlinkname) - 4);
00317            symlinkname[sizeof(symlinkname) - 1] = '\0';
00318 #endif /* USE_SYMLINKS */
00319 #if HAVE_REMOVE
00320            code = remove(linkname);
00321 #else
00322            code = unlink(linkname);
00323 #endif
00324            if (code != 0 && errno == ENOENT)
00325               code = 0;
00326 #if USE_SYMLINKS
00327            if (symlink(symlinkname, linkname) < 0)
00328 #else
00329            if (link(filename, linkname) < 0)
00330 #endif /* USE_SYMLINKS */
00331            {
00332               /*
00333                * If there wasn't anything there, and we cannot
00334                * link to the target because it is the same as the
00335                * target, then the source must be on a filesystem
00336                * that uses caseless filenames, such as Win32, etc.
00337                */
00338               if (code == 0 && errno == EEXIST)
00339                   _nc_warning("can't link %s to %s", filename, linkname);
00340               else if (code == 0 && (errno == EPERM || errno == ENOENT))
00341                   write_file(linkname, tp);
00342               else {
00343 #if MIXEDCASE_FILENAMES
00344                   _nc_syserr_abort("can't link %s to %s", filename, linkname);
00345 #else
00346                   _nc_warning("can't link %s to %s (errno=%d)", filename,
00347                             linkname, errno);
00348 #endif
00349               }
00350            } else {
00351               DEBUG(1, ("Linked %s", linkname));
00352            }
00353        }
00354 #else /* just make copies */
00355            write_file(linkname, tp);
00356 #endif /* HAVE_LINK */
00357     }
00358 }
00359 
00360 #undef LITTLE_ENDIAN        /* BSD/OS defines this as a feature macro */
00361 #define HI(x)               ((x) / 256)
00362 #define LO(x)               ((x) % 256)
00363 #define LITTLE_ENDIAN(p, x) (p)[0] = LO(x), (p)[1] = HI(x)
00364 
00365 #define WRITE_STRING(str) (fwrite(str, sizeof(char), strlen(str) + 1, fp) == strlen(str) + 1)
00366 
00367 static int
00368 compute_offsets(char **Strings, unsigned strmax, short *offsets)
00369 {
00370     size_t nextfree = 0;
00371     unsigned i;
00372 
00373     for (i = 0; i < strmax; i++) {
00374        if (Strings[i] == ABSENT_STRING) {
00375            offsets[i] = -1;
00376        } else if (Strings[i] == CANCELLED_STRING) {
00377            offsets[i] = -2;
00378        } else {
00379            offsets[i] = nextfree;
00380            nextfree += strlen(Strings[i]) + 1;
00381            TRACE_OUT(("put Strings[%d]=%s(%d)", i, _nc_visbuf(Strings[i]), nextfree));
00382        }
00383     }
00384     return nextfree;
00385 }
00386 
00387 static void
00388 convert_shorts(unsigned char *buf, short *Numbers, unsigned count)
00389 {
00390     unsigned i;
00391     for (i = 0; i < count; i++) {
00392        if (Numbers[i] == ABSENT_NUMERIC) {       /* HI/LO won't work */
00393            buf[2 * i] = buf[2 * i + 1] = 0377;
00394        } else if (Numbers[i] == CANCELLED_NUMERIC) {    /* HI/LO won't work */
00395            buf[2 * i] = 0376;
00396            buf[2 * i + 1] = 0377;
00397        } else {
00398            LITTLE_ENDIAN(buf + 2 * i, Numbers[i]);
00399            TRACE_OUT(("put Numbers[%d]=%d", i, Numbers[i]));
00400        }
00401     }
00402 }
00403 
00404 #define even_boundary(value) \
00405            ((value) % 2 != 0 && fwrite(&zero, sizeof(char), 1, fp) != 1)
00406 
00407 static int
00408 write_object(FILE * fp, TERMTYPE * tp)
00409 {
00410     char *namelist;
00411     size_t namelen, boolmax, nummax, strmax;
00412     char zero = '\0';
00413     size_t i;
00414     short nextfree;
00415     short offsets[MAX_ENTRY_SIZE / 2];
00416     unsigned char buf[MAX_ENTRY_SIZE];
00417     unsigned last_bool = BOOLWRITE;
00418     unsigned last_num = NUMWRITE;
00419     unsigned last_str = STRWRITE;
00420 
00421 #if NCURSES_XNAMES
00422     /*
00423      * Normally we limit the list of values to exclude the "obsolete"
00424      * capabilities.  However, if we are accepting extended names, add
00425      * these as well, since they are used for supporting translation
00426      * to/from termcap.
00427      */
00428     if (_nc_user_definable) {
00429        last_bool = BOOLCOUNT;
00430        last_num = NUMCOUNT;
00431        last_str = STRCOUNT;
00432     }
00433 #endif
00434 
00435     namelist = tp->term_names;
00436     namelen = strlen(namelist) + 1;
00437 
00438     boolmax = 0;
00439     for (i = 0; i < last_bool; i++) {
00440        if (tp->Booleans[i] == TRUE)
00441            boolmax = i + 1;
00442     }
00443 
00444     nummax = 0;
00445     for (i = 0; i < last_num; i++) {
00446        if (tp->Numbers[i] != ABSENT_NUMERIC)
00447            nummax = i + 1;
00448     }
00449 
00450     strmax = 0;
00451     for (i = 0; i < last_str; i++) {
00452        if (tp->Strings[i] != ABSENT_STRING)
00453            strmax = i + 1;
00454     }
00455 
00456     nextfree = compute_offsets(tp->Strings, strmax, offsets);
00457 
00458     /* fill in the header */
00459     LITTLE_ENDIAN(buf, MAGIC);
00460     LITTLE_ENDIAN(buf + 2, min(namelen, MAX_NAME_SIZE + 1));
00461     LITTLE_ENDIAN(buf + 4, boolmax);
00462     LITTLE_ENDIAN(buf + 6, nummax);
00463     LITTLE_ENDIAN(buf + 8, strmax);
00464     LITTLE_ENDIAN(buf + 10, nextfree);
00465 
00466     /* write out the header */
00467     TRACE_OUT(("Header of %s @%ld", namelist, ftell(fp)));
00468     if (fwrite(buf, 12, 1, fp) != 1
00469        || fwrite(namelist, sizeof(char), namelen, fp) != namelen)
00470          return (ERR);
00471 
00472     for (i = 0; i < boolmax; i++)
00473        if (tp->Booleans[i] == TRUE)
00474            buf[i] = TRUE;
00475        else
00476            buf[i] = FALSE;
00477     if (fwrite(buf, sizeof(char), boolmax, fp) != boolmax)
00478          return (ERR);
00479 
00480     if (even_boundary(namelen + boolmax))
00481        return (ERR);
00482 
00483     TRACE_OUT(("Numerics begin at %04lx", ftell(fp)));
00484 
00485     /* the numerics */
00486     convert_shorts(buf, tp->Numbers, nummax);
00487     if (fwrite(buf, 2, nummax, fp) != nummax)
00488        return (ERR);
00489 
00490     TRACE_OUT(("String offsets begin at %04lx", ftell(fp)));
00491 
00492     /* the string offsets */
00493     convert_shorts(buf, offsets, strmax);
00494     if (fwrite(buf, 2, strmax, fp) != strmax)
00495        return (ERR);
00496 
00497     TRACE_OUT(("String table begins at %04lx", ftell(fp)));
00498 
00499     /* the strings */
00500     for (i = 0; i < strmax; i++)
00501        if (VALID_STRING(tp->Strings[i]))
00502            if (!WRITE_STRING(tp->Strings[i]))
00503               return (ERR);
00504 
00505 #if NCURSES_XNAMES
00506     if (NUM_EXT_NAMES(tp)) {
00507        unsigned extcnt = NUM_EXT_NAMES(tp);
00508 
00509        if (even_boundary(nextfree))
00510            return (ERR);
00511 
00512        nextfree = compute_offsets(tp->Strings + STRCOUNT, tp->ext_Strings, offsets);
00513        TRACE_OUT(("after extended string capabilities, nextfree=%d", nextfree));
00514        nextfree += compute_offsets(tp->ext_Names, extcnt, offsets + tp->ext_Strings);
00515        TRACE_OUT(("after extended capnames, nextfree=%d", nextfree));
00516        strmax = tp->ext_Strings + extcnt;
00517 
00518        /*
00519         * Write the extended header
00520         */
00521        LITTLE_ENDIAN(buf + 0, tp->ext_Booleans);
00522        LITTLE_ENDIAN(buf + 2, tp->ext_Numbers);
00523        LITTLE_ENDIAN(buf + 4, tp->ext_Strings);
00524        LITTLE_ENDIAN(buf + 6, strmax);
00525        LITTLE_ENDIAN(buf + 8, nextfree);
00526        TRACE_OUT(("WRITE extended-header @%ld", ftell(fp)));
00527        if (fwrite(buf, 10, 1, fp) != 1)
00528            return (ERR);
00529 
00530        TRACE_OUT(("WRITE %d booleans @%ld", tp->ext_Booleans, ftell(fp)));
00531        if (tp->ext_Booleans
00532            && fwrite(tp->Booleans + BOOLCOUNT, sizeof(char),
00533                     tp->ext_Booleans, fp) != tp->ext_Booleans)
00534              return (ERR);
00535 
00536        if (even_boundary(tp->ext_Booleans))
00537            return (ERR);
00538 
00539        TRACE_OUT(("WRITE %d numbers @%ld", tp->ext_Numbers, ftell(fp)));
00540        if (tp->ext_Numbers) {
00541            convert_shorts(buf, tp->Numbers + NUMCOUNT, tp->ext_Numbers);
00542            if (fwrite(buf, 2, tp->ext_Numbers, fp) != tp->ext_Numbers)
00543               return (ERR);
00544        }
00545 
00546        /*
00547         * Convert the offsets for the ext_Strings and ext_Names tables,
00548         * in that order.
00549         */
00550        convert_shorts(buf, offsets, strmax);
00551        TRACE_OUT(("WRITE offsets @%ld", ftell(fp)));
00552        if (fwrite(buf, 2, strmax, fp) != strmax)
00553            return (ERR);
00554 
00555        /*
00556         * Write the string table after the offset tables so we do not
00557         * have to do anything about alignment.
00558         */
00559        for (i = 0; i < tp->ext_Strings; i++) {
00560            if (VALID_STRING(tp->Strings[i + STRCOUNT])) {
00561               TRACE_OUT(("WRITE ext_Strings[%d]=%s", i,
00562                         _nc_visbuf(tp->Strings[i + STRCOUNT])));
00563               if (!WRITE_STRING(tp->Strings[i + STRCOUNT]))
00564                   return (ERR);
00565            }
00566        }
00567 
00568        /*
00569         * Write the extended names
00570         */
00571        for (i = 0; i < extcnt; i++) {
00572            TRACE_OUT(("WRITE ext_Names[%d]=%s", i, tp->ext_Names[i]));
00573            if (!WRITE_STRING(tp->ext_Names[i]))
00574               return (ERR);
00575        }
00576 
00577     }
00578 #endif /* NCURSES_XNAMES */
00579 
00580     total_written++;
00581     return (OK);
00582 }
00583 
00584 /*
00585  * Returns the total number of entries written by this process
00586  */
00587 NCURSES_EXPORT(int)
00588 _nc_tic_written(void)
00589 {
00590     return total_written;
00591 }