home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / rcs / sources / rcsfnms.c < prev    next >
C/C++ Source or Header  |  1992-02-17  |  29KB  |  1,099 lines

  1. /*
  2.  *                     RCS file name handling
  3.  */
  4. /****************************************************************************
  5.  *                     creation and deletion of /tmp temporaries
  6.  *                     pairing of RCS file names and working file names.
  7.  *                     Testprogram: define PAIRTEST
  8.  ****************************************************************************
  9.  */
  10.  
  11. /* Copyright (C) 1982, 1988, 1989 Walter Tichy
  12.    Copyright 1990, 1991, 1992 by Paul Eggert
  13.    Distributed under license by the Free Software Foundation, Inc.
  14.  
  15. This file is part of RCS.
  16.  
  17. RCS is free software; you can redistribute it and/or modify
  18. it under the terms of the GNU General Public License as published by
  19. the Free Software Foundation; either version 2, or (at your option)
  20. any later version.
  21.  
  22. RCS is distributed in the hope that it will be useful,
  23. but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  25. GNU General Public License for more details.
  26.  
  27. You should have received a copy of the GNU General Public License
  28. along with RCS; see the file COPYING.  If not, write to
  29. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  30.  
  31. Report problems and direct all questions to:
  32.  
  33.     rcs-bugs@cs.purdue.edu
  34.  
  35. */
  36.  
  37.  
  38.  
  39.  
  40. /* $Log: rcsfnms.c,v $
  41.  * Revision 5.11  1992/02/17  23:02:25  eggert
  42.  * `a/RCS/b/c' is now an RCS file with an empty extension, not just `a/b/RCS/c'.
  43.  *
  44.  * Revision 5.10  1992/01/24  18:44:19  eggert
  45.  * Fix bug: Expand and Ignored weren't reinitialized.
  46.  * Avoid `char const c=ch;' compiler bug.
  47.  * Add support for bad_creat0.
  48.  *
  49.  * Revision 5.9  1992/01/06  02:42:34  eggert
  50.  * Shorten long (>31 chars) name.
  51.  * while (E) ; -> while (E) continue;
  52.  *
  53.  * Revision 5.8  1991/09/24  00:28:40  eggert
  54.  * Don't export bindex().
  55.  *
  56.  * Revision 5.7  1991/08/19  03:13:55  eggert
  57.  * Fix messages when rcswriteopen fails.
  58.  * Look in $TMP and $TEMP if $TMPDIR isn't set.  Tune.
  59.  *
  60.  * Revision 5.6  1991/04/21  11:58:23  eggert
  61.  * Fix errno bugs.  Add -x, RCSINIT, MS-DOS support.
  62.  *
  63.  * Revision 5.5  1991/02/26  17:48:38  eggert
  64.  * Fix setuid bug.  Support new link behavior.
  65.  * Define more portable getcwd().
  66.  *
  67.  * Revision 5.4  1990/11/01  05:03:43  eggert
  68.  * Permit arbitrary data in comment leaders.
  69.  *
  70.  * Revision 5.3  1990/09/14  22:56:16  hammer
  71.  * added more filename extensions and their comment leaders
  72.  *
  73.  * Revision 5.2  1990/09/04  08:02:23  eggert
  74.  * Fix typo when !RCSSEP.
  75.  *
  76.  * Revision 5.1  1990/08/29  07:13:59  eggert
  77.  * Work around buggy compilers with defective argument promotion.
  78.  *
  79.  * Revision 5.0  1990/08/22  08:12:50  eggert
  80.  * Ignore signals when manipulating the semaphore file.
  81.  * Modernize list of file name extensions.
  82.  * Permit paths of arbitrary length.  Beware file names beginning with "-".
  83.  * Remove compile-time limits; use malloc instead.
  84.  * Permit dates past 1999/12/31.  Make lock and temp files faster and safer.
  85.  * Ansify and Posixate.
  86.  * Don't use access().  Fix test for non-regular files.  Tune.
  87.  *
  88.  * Revision 4.8  89/05/01  15:09:41  narten
  89.  * changed getwd to not stat empty directories.
  90.  *
  91.  * Revision 4.7  88/08/09  19:12:53  eggert
  92.  * Fix troff macro comment leader bug; add Prolog; allow cc -R; remove lint.
  93.  *
  94.  * Revision 4.6  87/12/18  11:40:23  narten
  95.  * additional file types added from 4.3 BSD version, and SPARC assembler
  96.  * comment character added. Also, more lint cleanups. (Guy Harris)
  97.  *
  98.  * Revision 4.5  87/10/18  10:34:16  narten
  99.  * Updating version numbers. Changes relative to 1.1 actually relative
  100.  * to verion 4.3
  101.  *
  102.  * Revision 1.3  87/03/27  14:22:21  jenkins
  103.  * Port to suns
  104.  *
  105.  * Revision 1.2  85/06/26  07:34:28  svb
  106.  * Comment leader '% ' for '*.tex' files added.
  107.  *
  108.  * Revision 4.3  83/12/15  12:26:48  wft
  109.  * Added check for KDELIM in file names to pairfilenames().
  110.  *
  111.  * Revision 4.2  83/12/02  22:47:45  wft
  112.  * Added csh, red, and sl file name suffixes.
  113.  *
  114.  * Revision 4.1  83/05/11  16:23:39  wft
  115.  * Added initialization of Dbranch to InitAdmin(). Canged pairfilenames():
  116.  * 1. added copying of path from workfile to RCS file, if RCS file is omitted;
  117.  * 2. added getting the file status of RCS and working files;
  118.  * 3. added ignoring of directories.
  119.  *
  120.  * Revision 3.7  83/05/11  15:01:58  wft
  121.  * Added comtable[] which pairs file name suffixes with comment leaders;
  122.  * updated InitAdmin() accordingly.
  123.  *
  124.  * Revision 3.6  83/04/05  14:47:36  wft
  125.  * fixed Suffix in InitAdmin().
  126.  *
  127.  * Revision 3.5  83/01/17  18:01:04  wft
  128.  * Added getwd() and rename(); these can be removed by defining
  129.  * V4_2BSD, since they are not needed in 4.2 bsd.
  130.  * Changed sys/param.h to sys/types.h.
  131.  *
  132.  * Revision 3.4  82/12/08  21:55:20  wft
  133.  * removed unused variable.
  134.  *
  135.  * Revision 3.3  82/11/28  20:31:37  wft
  136.  * Changed mktempfile() to store the generated file names.
  137.  * Changed getfullRCSname() to store the file and pathname, and to
  138.  * delete leading "../" and "./".
  139.  *
  140.  * Revision 3.2  82/11/12  14:29:40  wft
  141.  * changed pairfilenames() to handle file.sfx,v; also deleted checkpathnosfx(),
  142.  * checksuffix(), checkfullpath(). Semaphore name generation updated.
  143.  * mktempfile() now checks for nil path; freefilename initialized properly.
  144.  * Added Suffix .h to InitAdmin. Added testprogram PAIRTEST.
  145.  * Moved rmsema, trysema, trydiraccess, getfullRCSname from rcsutil.c to here.
  146.  *
  147.  * Revision 3.1  82/10/18  14:51:28  wft
  148.  * InitAdmin() now initializes StrictLocks=STRICT_LOCKING (def. in rcsbase.h).
  149.  * renamed checkpath() to checkfullpath().
  150.  */
  151.  
  152.  
  153. #include "rcsbase.h"
  154.  
  155. libId(fnmsId, "$Id: rcsfnms.c,v 5.11 1992/02/17 23:02:25 eggert Exp $")
  156.  
  157. char const *RCSfilename;
  158. char *workfilename;
  159. int fdlock;
  160. FILE *workstdout;
  161. struct stat RCSstat;
  162. char const *suffixes;
  163.  
  164. static char const rcsdir[] = "RCS";
  165. #define rcslen (sizeof(rcsdir)-1)
  166.  
  167. static struct buf RCSbuf, RCSb;
  168. static int RCSerrno;
  169.  
  170.  
  171. /* Temp file names to be unlinked when done, if they are not nil.  */
  172. #define TEMPNAMES 5 /* must be at least DIRTEMPNAMES (see rcsedit.c) */
  173. static char *volatile tfnames[TEMPNAMES];
  174.  
  175.  
  176. struct compair {
  177.     char const *suffix, *comlead;
  178. };
  179.  
  180. static struct compair const comtable[] = {
  181. /* comtable pairs each filename suffix with a comment leader. The comment   */
  182. /* leader is placed before each line generated by the $Log keyword. This    */
  183. /* table is used to guess the proper comment leader from the working file's */
  184. /* suffix during initial ci (see InitAdmin()). Comment leaders are needed   */
  185. /* for languages without multiline comments; for others they are optional.  */
  186.     "a",   "-- ",   /* Ada         */
  187.     "ada", "-- ",
  188.     "asm", ";; ",    /* assembler (MS-DOS) */
  189.     "bat", ":: ",    /* batch (MS-DOS) */
  190.         "c",   " * ",   /* C           */
  191.     "c++", "// ",    /* C++ in all its infinite guises */
  192.     "cc",  "// ",
  193.     "cpp", "// ",
  194.     "cxx", "// ",
  195.     "cl",  ";;; ",  /* Common Lisp */
  196.     "cmd", ":: ",    /* command (OS/2) */
  197.     "cmf", "c ",    /* CM Fortran  */
  198.     "cs",  " * ",    /* C*          */
  199.     "el",  "; ",    /* Emacs Lisp  */
  200.     "f",   "c ",    /* Fortran     */
  201.     "for", "c ",
  202.         "h",   " * ",   /* C-header    */
  203.     "hpp", "// ",    /* C++ header  */
  204.     "hxx", "// ",
  205.         "l",   " * ",   /* lex      NOTE: conflict between lex and franzlisp */
  206.     "lisp",";;; ",    /* Lucid Lisp  */
  207.     "lsp", ";; ",    /* Microsoft Lisp */
  208.     "mac", ";; ",    /* macro (DEC-10, MS-DOS, PDP-11, VMS, etc) */
  209.     "me",  ".\\\" ",/* me-macros   t/nroff*/
  210.     "ml",  "; ",    /* mocklisp    */
  211.     "mm",  ".\\\" ",/* mm-macros   t/nroff*/
  212.     "ms",  ".\\\" ",/* ms-macros   t/nroff*/
  213.     "p",   " * ",   /* Pascal      */
  214.     "pas", " * ",
  215.     "pl",  "% ",    /* Prolog      */
  216.     "tex", "% ",    /* TeX           */
  217.         "y",   " * ",   /* yacc        */
  218.     nil,   "# "     /* default for unknown suffix; must always be last */
  219. };
  220.  
  221. #if has_mktemp
  222.     static char const *
  223. tmp()
  224. /* Yield the name of the tmp directory.  */
  225. {
  226.     static char const *s;
  227.     if (!s
  228.         &&  !(s = cgetenv("TMPDIR"))    /* Unix tradition */
  229.         &&  !(s = cgetenv("TMP"))    /* DOS tradition */
  230.         &&  !(s = cgetenv("TEMP"))    /* another DOS tradition */
  231.     )
  232.         s = TMPDIR;
  233.     return s;
  234. }
  235. #endif
  236.  
  237.     char const *
  238. maketemp(n)
  239.     int n;
  240. /* Create a unique filename using n and the process id and store it
  241.  * into the nth slot in tfnames.
  242.  * Because of storage in tfnames, tempunlink() can unlink the file later.
  243.  * Returns a pointer to the filename created.
  244.  */
  245. {
  246.     char *p;
  247.     char const *t = tfnames[n];
  248.  
  249.     if (t)
  250.         return t;
  251.  
  252.     catchints();
  253.     {
  254. #    if has_mktemp
  255.         char const *tp = tmp();
  256.         p = testalloc(strlen(tp) + 10);
  257.         VOID sprintf(p, "%s%cT%cXXXXXX", tp, SLASH, '0'+n);
  258.         if (!mktemp(p) || !*p)
  259.         faterror("can't make temporary file name `%s%cT%cXXXXXX'",
  260.             tp, SLASH, '0'+n
  261.         );
  262. #    else
  263.         static char tfnamebuf[TEMPNAMES][L_tmpnam];
  264.         p = tfnamebuf[n];
  265.         if (!tmpnam(p) || !*p)
  266. #        ifdef P_tmpdir
  267.             faterror("can't make temporary file name `%s...'",P_tmpdir);
  268. #        else
  269.             faterror("can't make temporary file name");
  270. #        endif
  271. #    endif
  272.     }
  273.  
  274.     tfnames[n] = p;
  275.     return p;
  276. }
  277.  
  278.     void
  279. tempunlink()
  280. /* Clean up maketemp() files.  May be invoked by signal handler.
  281.  */
  282. {
  283.     register int i;
  284.     register char *p;
  285.  
  286.     for (i = TEMPNAMES;  0 <= --i;  )
  287.         if ((p = tfnames[i])) {
  288.         VOID unlink(p);
  289.         /*
  290.          * We would tfree(p) here,
  291.          * but this might dump core if we're handing a signal.
  292.          * We're about to exit anyway, so we won't bother.
  293.          */
  294.         tfnames[i] = 0;
  295.         }
  296. }
  297.  
  298.  
  299.     static char const *
  300. bindex(sp, c)
  301.     register char const *sp;
  302.     register int c;
  303. /* Function: Finds the last occurrence of character c in string sp
  304.  * and returns a pointer to the character just beyond it. If the
  305.  * character doesn't occur in the string, sp is returned.
  306.  */
  307. {
  308.     register char const *r;
  309.         r = sp;
  310.         while (*sp) {
  311.                 if (*sp++ == c) r=sp;
  312.         }
  313.         return r;
  314. }
  315.  
  316.  
  317.  
  318.     static int
  319. suffix_matches(suffix, pattern)
  320.     register char const *suffix, *pattern;
  321. {
  322.     register int c;
  323.     if (!pattern)
  324.         return true;
  325.     for (;;)
  326.         switch (*suffix++ - (c = *pattern++)) {
  327.             case 0:
  328.             if (!c)
  329.                 return true;
  330.             break;
  331.  
  332.             case 'A'-'a':
  333.             if (ctab[c] == Letter)
  334.                 break;
  335.             /* fall into */
  336.             default:
  337.             return false;
  338.         }
  339. }
  340.  
  341.  
  342.     static void
  343. InitAdmin()
  344. /* function: initializes an admin node */
  345. {
  346.     register char const *Suffix;
  347.         register int i;
  348.  
  349.     Head=nil; Dbranch=nil; AccessList=nil; Symbols=nil; Locks=nil;
  350.         StrictLocks=STRICT_LOCKING;
  351.  
  352.         /* guess the comment leader from the suffix*/
  353.         Suffix=bindex(workfilename, '.');
  354.         if (Suffix==workfilename) Suffix= ""; /* empty suffix; will get default*/
  355.     for (i=0; !suffix_matches(Suffix,comtable[i].suffix); i++)
  356.         continue;
  357.     Comment.string = comtable[i].comlead;
  358.     Comment.size = strlen(comtable[i].comlead);
  359.     Expand = KEYVAL_EXPAND;
  360.     Ignored.string = 0;
  361.     Ignored.size = 0;
  362.     Lexinit(); /* note: if !finptr, reads nothing; only initializes */
  363. }
  364.  
  365.  
  366. #if defined(_POSIX_NO_TRUNC) && _POSIX_NO_TRUNC!=-1
  367. #    define LONG_NAMES_MAY_BE_TRUNCATED 0
  368. #else
  369. #    define LONG_NAMES_MAY_BE_TRUNCATED 1
  370. #endif
  371.  
  372. #if LONG_NAMES_MAY_BE_TRUNCATED
  373. /* Long pathnames may be silently truncated, so we first check their length.  */
  374. #ifdef NAME_MAX
  375. #    define filenametoolong(path) (NAME_MAX < strlen(basename(path)))
  376. #else
  377.     static int
  378. filenametoolong(path)
  379.     char *path;
  380. /* Yield true if the last file name in PATH is too long. */
  381. {
  382.     static unsigned long dot_namemax;
  383.  
  384.     register size_t namelen;
  385.     register char *base;
  386.     register unsigned long namemax;
  387.  
  388.     base = path + dirlen(path);
  389.     namelen = strlen(base);
  390.     if (namelen <= _POSIX_NAME_MAX) /* fast check for shorties */
  391.         return false;
  392.     if (base != path) {
  393.         *--base = 0;
  394.         namemax = pathconf(path, _PC_NAME_MAX);
  395.         *base = SLASH;
  396.     } else {
  397.         /* Cache the results for the working directory, for speed. */
  398.         if (!dot_namemax)
  399.             dot_namemax = pathconf(".", _PC_NAME_MAX);
  400.         namemax = dot_namemax;
  401.     }
  402.     /* If pathconf() yielded -1, namemax is now ULONG_MAX.  */
  403.     return namemax<namelen;
  404. }
  405. #endif
  406. #endif
  407.  
  408.     void
  409. bufalloc(b, size)
  410.     register struct buf *b;
  411.     size_t size;
  412. /* Ensure *B is a name buffer of at least SIZE bytes.
  413.  * *B's old contents can be freed; *B's new contents are undefined.
  414.  */
  415. {
  416.     if (b->size < size) {
  417.         if (b->size)
  418.             tfree(b->string);
  419.         else
  420.             b->size = sizeof(malloc_type);
  421.         while (b->size < size)
  422.             b->size <<= 1;
  423.         b->string = tnalloc(char, b->size);
  424.     }
  425. }
  426.  
  427.     void
  428. bufrealloc(b, size)
  429.     register struct buf *b;
  430.     size_t size;
  431. /* like bufalloc, except *B's old contents, if any, are preserved */
  432. {
  433.     if (b->size < size) {
  434.         if (!b->size)
  435.             bufalloc(b, size);
  436.         else {
  437.             while ((b->size <<= 1)  <  size)
  438.                 continue;
  439.             b->string = trealloc(char, b->string, b->size);
  440.         }
  441.     }
  442. }
  443.  
  444.     void
  445. bufautoend(b)
  446.     struct buf *b;
  447. /* Free an auto buffer at block exit. */
  448. {
  449.     if (b->size)
  450.         tfree(b->string);
  451. }
  452.  
  453.     struct cbuf
  454. bufremember(b, s)
  455.     struct buf *b;
  456.     size_t s;
  457. /*
  458.  * Free the buffer B with used size S.
  459.  * Yield a cbuf with identical contents.
  460.  * The cbuf will be reclaimed when this input file is finished.
  461.  */
  462. {
  463.     struct cbuf cb;
  464.  
  465.     if ((cb.size = s))
  466.         cb.string = fremember(trealloc(char, b->string, s));
  467.     else {
  468.         bufautoend(b); /* not really auto */
  469.         cb.string = "";
  470.     }
  471.     return cb;
  472. }
  473.  
  474.     char *
  475. bufenlarge(b, alim)
  476.     register struct buf *b;
  477.     char const **alim;
  478. /* Make *B larger.  Set *ALIM to its new limit, and yield the relocated value
  479.  * of its old limit.
  480.  */
  481. {
  482.     size_t s = b->size;
  483.     bufrealloc(b, s + 1);
  484.     *alim = b->string + b->size;
  485.     return b->string + s;
  486. }
  487.  
  488.     void
  489. bufscat(b, s)
  490.     struct buf *b;
  491.     char const *s;
  492. /* Concatenate S to B's end. */
  493. {
  494.     size_t blen  =  b->string ? strlen(b->string) : 0;
  495.     bufrealloc(b, blen+strlen(s)+1);
  496.     VOID strcpy(b->string+blen, s);
  497. }
  498.  
  499.     void
  500. bufscpy(b, s)
  501.     struct buf *b;
  502.     char const *s;
  503. /* Copy S into B. */
  504. {
  505.     bufalloc(b, strlen(s)+1);
  506.     VOID strcpy(b->string, s);
  507. }
  508.  
  509.  
  510.     char const *
  511. basename(p)
  512.     char const *p;
  513. /* Yield the address of the base filename of the pathname P.  */
  514. {
  515.     register char const *b = p, *q = p;
  516.     for (;;)
  517.         switch (*q++) {
  518.         case SLASHes: b = q; break;
  519.         case 0: return b;
  520.         }
  521. }
  522.  
  523.     size_t
  524. dirlen(p)
  525.     char const *p;
  526. /* Yield the length of P's directory, including its trailing SLASH.  */
  527. {
  528.     return basename(p) - p;
  529. }
  530.  
  531.  
  532.     static size_t
  533. suffixlen(x)
  534.     char const *x;
  535. /* Yield the length of X, an RCS filename suffix.  */
  536. {
  537.     register char const *p;
  538.  
  539.     p = x;
  540.     for (;;)
  541.         switch (*p) {
  542.         case 0: case SLASHes:
  543.             return p - x;
  544.  
  545.         default:
  546.             ++p;
  547.             continue;
  548.         }
  549. }
  550.  
  551.     char const *
  552. rcssuffix(name)
  553.     char const *name;
  554. /* Yield the suffix of NAME if it is an RCS filename, 0 otherwise.  */
  555. {
  556.     char const *x, *p, *nz;
  557.     int d;
  558.     size_t nl, xl;
  559.  
  560.     nl = strlen(name);
  561.     nz = name + nl;
  562.     x = suffixes;
  563.     do {
  564.         if ((xl = suffixlen(x))) {
  565.         if (xl <= nl  &&  memcmp(p = nz-xl, x, xl) == 0)
  566.             return p;
  567.         } else
  568.         for (p = name, d = true;  p < nz - rcslen;  d = isSLASH(*p++))
  569.             if (d && memcmp(p,rcsdir,rcslen)==0 && isSLASH(p[rcslen]))
  570.             return nz;
  571.         x += xl;
  572.     } while (*x++);
  573.     return 0;
  574. }
  575.  
  576.     /*ARGSUSED*/ RILE *
  577. rcsreadopen(RCSname, status, mustread)
  578.     struct buf *RCSname;
  579.     struct stat *status;
  580.     int mustread;
  581. /* Open RCSNAME for reading and yield its FILE* descriptor.
  582.  * If successful, set *STATUS to its status.
  583.  * Pass this routine to pairfilenames() for read-only access to the file.  */
  584. {
  585.     return Iopen(RCSname->string, FOPEN_R, status);
  586. }
  587.  
  588.     static int
  589. finopen(rcsopen, mustread)
  590.     RILE *(*rcsopen)P((struct buf*,struct stat*,int));
  591.     int mustread;
  592. /*
  593.  * Use RCSOPEN to open an RCS file; MUSTREAD is set if the file must be read.
  594.  * Set finptr to the result and yield true if successful.
  595.  * RCSb holds the file's name.
  596.  * Set RCSbuf to the best RCS name found so far, and RCSerrno to its errno.
  597.  * Yield true if successful or if an unusual failure.
  598.  */
  599. {
  600.     int interesting, preferold;
  601.  
  602.     /*
  603.      * We prefer an old name to that of a nonexisting new RCS file,
  604.      * unless we tried locking the old name and failed.
  605.      */
  606.     preferold  =  RCSbuf.string[0] && (mustread||0<=fdlock);
  607.  
  608.     finptr = (*rcsopen)(&RCSb, &RCSstat, mustread);
  609.     interesting = finptr || errno!=ENOENT;
  610.     if (interesting || !preferold) {
  611.         /* Use the new name.  */
  612.         RCSerrno = errno;
  613.         bufscpy(&RCSbuf, RCSb.string);
  614.     }
  615.     return interesting;
  616. }
  617.  
  618.     static int
  619. fin2open(d, dlen, base, baselen, x, xlen, rcsopen, mustread)
  620.     char const *d, *base, *x;
  621.     size_t dlen, baselen, xlen;
  622.     RILE *(*rcsopen)P((struct buf*,struct stat*,int));
  623.     int mustread;
  624. /*
  625.  * D is a directory name with length DLEN (including trailing slash).
  626.  * BASE is a filename with length BASELEN.
  627.  * X is an RCS filename suffix with length XLEN.
  628.  * Use RCSOPEN to open an RCS file; MUSTREAD is set if the file must be read.
  629.  * Yield true if successful.
  630.  * Try dRCS/basex first; if that fails and x is nonempty, try dbasex.
  631.  * Put these potential names in RCSb.
  632.  * Set RCSbuf to the best RCS name found so far, and RCSerrno to its errno.
  633.  * Yield true if successful or if an unusual failure.
  634.  */
  635. {
  636.     register char *p;
  637.  
  638.     bufalloc(&RCSb, dlen + rcslen + 1 + baselen + xlen + 1);
  639.  
  640.     /* Try dRCS/basex.  */
  641.     VOID memcpy(p = RCSb.string, d, dlen);
  642.     VOID memcpy(p += dlen, rcsdir, rcslen);
  643.     p += rcslen;
  644.     *p++ = SLASH;
  645.     VOID memcpy(p, base, baselen);
  646.     VOID memcpy(p += baselen, x, xlen);
  647.     p[xlen] = 0;
  648.     if (xlen) {
  649.         if (finopen(rcsopen, mustread))
  650.         return true;
  651.  
  652.         /* Try dbasex.  */
  653.         /* Start from scratch, because finopen() may have changed RCSb.  */
  654.         VOID memcpy(p = RCSb.string, d, dlen);
  655.         VOID memcpy(p += dlen, base, baselen);
  656.         VOID memcpy(p += baselen, x, xlen);
  657.         p[xlen] = 0;
  658.     }
  659.     return finopen(rcsopen, mustread);
  660. }
  661.  
  662.     int
  663. pairfilenames(argc, argv, rcsopen, mustread, quiet)
  664.     int argc;
  665.     char **argv;
  666.     RILE *(*rcsopen)P((struct buf*,struct stat*,int));
  667.     int mustread, quiet;
  668. /* Function: Pairs the filenames pointed to by argv; argc indicates
  669.  * how many there are.
  670.  * Places a pointer to the RCS filename into RCSfilename,
  671.  * and a pointer to the name of the working file into workfilename.
  672.  * If both the workfilename and the RCS filename are given, and workstdout
  673.  * is set, a warning is printed.
  674.  *
  675.  * If the RCS file exists, places its status into RCSstat.
  676.  *
  677.  * If the RCS file exists, it is RCSOPENed for reading, the file pointer
  678.  * is placed into finptr, and the admin-node is read in; returns 1.
  679.  * If the RCS file does not exist and MUSTREAD,
  680.  * print an error unless QUIET and return 0.
  681.  * Otherwise, initialize the admin node and return -1.
  682.  *
  683.  * 0 is returned on all errors, e.g. files that are not regular files.
  684.  */
  685. {
  686.     static struct buf tempbuf;
  687.  
  688.     register char *p, *arg, *RCS1;
  689.     char const *purefname, *pureRCSname, *x;
  690.     int paired;
  691.     size_t arglen, dlen, baselen, xlen;
  692.  
  693.     if (!(arg = *argv)) return 0; /* already paired filename */
  694.     if (*arg == '-') {
  695.         error("%s option is ignored after file names", arg);
  696.         return 0;
  697.     }
  698.  
  699.     purefname = basename(arg);
  700.  
  701.     /* Allocate buffer temporary to hold the default paired file name. */
  702.     p = arg;
  703.     for (;;) {
  704.         switch (*p++) {
  705.             /* Beware characters that cause havoc with ci -k. */
  706.             case KDELIM:
  707.             error("RCS file name `%s' contains %c", arg, KDELIM);
  708.             return 0;
  709.             case ' ': case '\n': case '\t':
  710.             error("RCS file name `%s' contains white space", arg);
  711.             return 0;
  712.             default:
  713.             continue;
  714.             case 0:
  715.             break;
  716.         }
  717.         break;
  718.     }
  719.  
  720.     paired = false;
  721.  
  722.         /* first check suffix to see whether it is an RCS file or not */
  723.     if ((x = rcssuffix(arg)))
  724.     {
  725.                 /* RCS file name given*/
  726.         RCS1 = arg;
  727.         pureRCSname = purefname;
  728.         baselen = x - purefname;
  729.         if (
  730.             1 < argc  &&
  731.             !rcssuffix(workfilename = p = argv[1])  &&
  732.             baselen <= (arglen = strlen(p))  &&
  733.             ((p+=arglen-baselen) == workfilename  ||  isSLASH(p[-1])) &&
  734.             memcmp(purefname, p, baselen) == 0
  735.         ) {
  736.             argv[1] = 0;
  737.             paired = true;
  738.         } else {
  739.             bufscpy(&tempbuf, purefname);
  740.             workfilename = p = tempbuf.string;
  741.             p[baselen] = 0;
  742.         }
  743.         } else {
  744.                 /* working file given; now try to find RCS file */
  745.         workfilename = arg;
  746.         baselen = p - purefname - 1;
  747.                 /* derive RCS file name*/
  748.         if (
  749.             1 < argc  &&
  750.             (x = rcssuffix(RCS1 = argv[1]))  &&
  751.             baselen  <=  x - RCS1  &&
  752.             ((pureRCSname=x-baselen)==RCS1 || isSLASH(pureRCSname[-1])) &&
  753.             memcmp(purefname, pureRCSname, baselen) == 0
  754.         ) {
  755.             argv[1] = 0;
  756.             paired = true;
  757.         } else
  758.             pureRCSname = RCS1 = 0;
  759.         }
  760.         /* now we have a (tentative) RCS filename in RCS1 and workfilename  */
  761.         /* Second, try to find the right RCS file */
  762.     fdlock = -1;
  763.         if (pureRCSname!=RCS1) {
  764.                 /* a path for RCSfile is given; single RCS file to look for */
  765.         bufscpy(&RCSbuf, RCS1);
  766.         finptr = (*rcsopen)(&RCSbuf, &RCSstat, mustread);
  767.         RCSerrno = errno;
  768.         } else {
  769.         bufscpy(&RCSbuf, "");
  770.         if (RCS1)
  771.             /* RCS file name was given without path.  */
  772.             VOID fin2open(arg, (size_t)0, pureRCSname, baselen,
  773.                 x, strlen(x), rcsopen, mustread
  774.             );
  775.         else {
  776.             /* No RCS file name was given.  */
  777.             /* Try each suffix in turn.  */
  778.             dlen = purefname-arg;
  779.             x = suffixes;
  780.             while (! fin2open(arg, dlen, purefname, baselen,
  781.                     x, xlen=suffixlen(x), rcsopen, mustread
  782.             )) {
  783.                 x += xlen;
  784.                 if (!*x++)
  785.                     break;
  786.             }
  787.         }
  788.         }
  789.     RCSfilename = p = RCSbuf.string;
  790.     if (finptr) {
  791.         if (!S_ISREG(RCSstat.st_mode)) {
  792.             error("%s isn't a regular file -- ignored", p);
  793.                         return 0;
  794.                 }
  795.                 Lexinit(); getadmin();
  796.     } else {
  797.         if (RCSerrno!=ENOENT || mustread || fdlock<0) {
  798.             if (RCSerrno == EEXIST)
  799.                 error("RCS file %s is in use", p);
  800.             else if (!quiet || RCSerrno!=ENOENT)
  801.                 enerror(RCSerrno, p);
  802.             return 0;
  803.         }
  804.                 InitAdmin();
  805.         };
  806. #    if LONG_NAMES_MAY_BE_TRUNCATED
  807.         if (filenametoolong(p)) {
  808.         error("RCS file name %s is too long", p);
  809.         return 0;
  810.         }
  811. #        ifndef NAME_MAX
  812.         /*
  813.          * Check workfilename too, even though it cannot be longer,
  814.          * because it may reside on a different filesystem.
  815.          */
  816.         if (filenametoolong(workfilename)) {
  817.             error("working file name %s is too long", workfilename);
  818.             return 0;
  819.         }
  820. #        endif
  821. #    endif
  822.  
  823.     if (paired && workstdout)
  824.                 warn("Option -p is set; ignoring output file %s",workfilename);
  825.  
  826.     prevkeys = false;
  827.     return finptr ? 1 : -1;
  828. }
  829.  
  830.  
  831.     char const *
  832. getfullRCSname()
  833. /* Function: returns a pointer to the full path name of the RCS file.
  834.  * Gets the working directory's name at most once.
  835.  * Removes leading "../" and "./".
  836.  */
  837. {
  838.     static char const *wdptr;
  839.     static struct buf rcsbuf, wdbuf;
  840.     static size_t pathlength;
  841.  
  842.     register char const *realname;
  843.     register size_t parentdirlength;
  844.     register unsigned dotdotcounter;
  845.     register char *d;
  846.     register char const *wd;
  847.  
  848.     if (ROOTPATH(RCSfilename)) {
  849.                 return(RCSfilename);
  850.         } else {
  851.         if (!(wd = wdptr)) {
  852.             /* Get working directory for the first time.  */
  853.             if (!(d = cgetenv("PWD"))) {
  854.             bufalloc(&wdbuf, SIZEABLE_PATH + 1);
  855. #            if !has_getcwd && has_getwd
  856.                 d = getwd(wdbuf.string);
  857. #            else
  858.                 while (
  859.                     !(d = getcwd(wdbuf.string, wdbuf.size))
  860.                 &&  errno==ERANGE
  861.                 )
  862.                 bufalloc(&wdbuf, wdbuf.size<<1);
  863. #            endif
  864.             if (!d)
  865.                 efaterror("working directory");
  866.             }
  867.             parentdirlength = strlen(d);
  868.             while (parentdirlength && isSLASH(d[parentdirlength-1])) {
  869.             d[--parentdirlength] = 0;
  870.                         /* Check needed because some getwd implementations */
  871.                         /* generate "/" for the root.                      */
  872.                     }
  873.             wdptr = wd = d;
  874.             pathlength = parentdirlength;
  875.                 }
  876.                 /*the following must be redone since RCSfilename may change*/
  877.         /* Find how many `../'s to remove from RCSfilename.  */
  878.                 dotdotcounter =0;
  879.                 realname = RCSfilename;
  880.         while (realname[0]=='.') {
  881.             if (isSLASH(realname[1])) {
  882.                             /* drop leading ./ */
  883.                             realname += 2;
  884.             } else if (realname[1]=='.' && isSLASH(realname[2])) {
  885.                             /* drop leading ../ and remember */
  886.                             dotdotcounter++;
  887.                             realname += 3;
  888.             } else
  889.                 break;
  890.                 }
  891.         /* Now remove dotdotcounter trailing directories from wd. */
  892.         parentdirlength = pathlength;
  893.         while (dotdotcounter && parentdirlength) {
  894.                     /* move pointer backwards over trailing directory */
  895.             if (isSLASH(wd[--parentdirlength])) {
  896.                         dotdotcounter--;
  897.                     }
  898.                 }
  899.         /* build full path name */
  900.         bufalloc(&rcsbuf, parentdirlength+strlen(realname)+2);
  901.         d = rcsbuf.string;
  902.         VOID memcpy(d, wd, parentdirlength);
  903.         d += parentdirlength;
  904.         *d++ = SLASH;
  905.         VOID strcpy(d, realname);
  906.         return rcsbuf.string;
  907.         }
  908. }
  909.  
  910. #ifndef isSLASH
  911.     int
  912. isSLASH(c)
  913.     int c;
  914. {
  915.     switch (c) {
  916.         case SLASHes:
  917.         return true;
  918.         default:
  919.         return false;
  920.     }
  921. }
  922. #endif
  923.  
  924.  
  925. #if !has_getcwd && !has_getwd
  926.  
  927.     char *
  928. getcwd(path, size)
  929.     char *path;
  930.     size_t size;
  931. {
  932.     static char const usrbinpwd[] = "/usr/bin/pwd";
  933. #    define binpwd (usrbinpwd+4)
  934.  
  935.     register FILE *fp;
  936.     register int c;
  937.     register char *p, *lim;
  938.     int closeerrno, closeerror, e, fd[2], readerror, toolong, wstatus;
  939.     pid_t child;
  940. #    if !has_waitpid
  941.         pid_t w;
  942. #    endif
  943.  
  944.     if (!size) {
  945.         errno = EINVAL;
  946.         return 0;
  947.     }
  948.     if (pipe(fd) != 0)
  949.         return 0;
  950.     if (!(child = vfork())) {
  951.         if (
  952.             close(fd[0]) == 0 &&
  953.             (fd[1] == STDOUT_FILENO ||
  954. #                ifdef F_DUPFD
  955.                     (VOID close(STDOUT_FILENO),
  956.                     fcntl(fd[1], F_DUPFD, STDOUT_FILENO))
  957. #                else
  958.                     dup2(fd[1], STDOUT_FILENO)
  959. #                endif
  960.                 == STDOUT_FILENO &&
  961.                 close(fd[1]) == 0
  962.             )
  963.         ) {
  964.             VOID close(STDERR_FILENO);
  965.             VOID execl(binpwd, binpwd, (char *)0);
  966.             VOID execl(usrbinpwd, usrbinpwd, (char *)0);
  967.         }
  968.         _exit(EXIT_FAILURE);
  969.     }
  970.     e = errno;
  971.     closeerror = close(fd[1]);
  972.     closeerrno = errno;
  973.     fp = 0;
  974.     readerror = toolong = wstatus = 0;
  975.     p = path;
  976.     if (0 <= child) {
  977.         fp = fdopen(fd[0], "r");
  978.         e = errno;
  979.         if (fp) {
  980.             lim = p + size;
  981.             for (p = path;  ;  *p++ = c) {
  982.                 if ((c=getc(fp)) < 0) {
  983.                     if (feof(fp))
  984.                         break;
  985.                     if (ferror(fp)) {
  986.                         readerror = 1;
  987.                         e = errno;
  988.                         break;
  989.                     }
  990.                 }
  991.                 if (p == lim) {
  992.                     toolong = 1;
  993.                     break;
  994.                 }
  995.             }
  996.         }
  997. #        if has_waitpid
  998.             if (waitpid(child, &wstatus, 0) < 0)
  999.                 wstatus = 1;
  1000. #        else
  1001.             do {
  1002.                 if ((w = wait(&wstatus)) < 0) {
  1003.                     wstatus = 1;
  1004.                     break;
  1005.                 }
  1006.             } while (w != child);
  1007. #        endif
  1008.     }
  1009.     if (!fp) {
  1010.         VOID close(fd[0]);
  1011.         errno = e;
  1012.         return 0;
  1013.     }
  1014.     if (fclose(fp) != 0)
  1015.         return 0;
  1016.     if (readerror) {
  1017.         errno = e;
  1018.         return 0;
  1019.     }
  1020.     if (closeerror) {
  1021.         errno = closeerrno;
  1022.         return 0;
  1023.     }
  1024.     if (toolong) {
  1025.         errno = ERANGE;
  1026.         return 0;
  1027.     }
  1028.     if (wstatus  ||  p == path  ||  *--p != '\n') {
  1029.         errno = EACCES;
  1030.         return 0;
  1031.     }
  1032.     *p = '\0';
  1033.     return path;
  1034. }
  1035. #endif
  1036.  
  1037.  
  1038. #ifdef PAIRTEST
  1039. /* test program for pairfilenames() and getfullRCSname() */
  1040.  
  1041. char const cmdid[] = "pair";
  1042.  
  1043. main(argc, argv)
  1044. int argc; char *argv[];
  1045. {
  1046.         int result;
  1047.     int initflag;
  1048.     quietflag = initflag = false;
  1049.  
  1050.         while(--argc, ++argv, argc>=1 && ((*argv)[0] == '-')) {
  1051.                 switch ((*argv)[1]) {
  1052.  
  1053.         case 'p':       workstdout = stdout;
  1054.                                 break;
  1055.                 case 'i':       initflag=true;
  1056.                                 break;
  1057.                 case 'q':       quietflag=true;
  1058.                                 break;
  1059.                 default:        error("unknown option: %s", *argv);
  1060.                                 break;
  1061.                 }
  1062.         }
  1063.  
  1064.         do {
  1065.                 RCSfilename=workfilename=nil;
  1066.         result = pairfilenames(argc,argv,rcsreadopen,!initflag,quietflag);
  1067.                 if (result!=0) {
  1068.             diagnose("RCS file: %s; working file: %s\nFull RCS file name: %s\n",
  1069.                  RCSfilename,workfilename,getfullRCSname()
  1070.             );
  1071.                 }
  1072.                 switch (result) {
  1073.                         case 0: continue; /* already paired file */
  1074.  
  1075.                         case 1: if (initflag) {
  1076.                                     error("RCS file %s exists already",RCSfilename);
  1077.                                 } else {
  1078.                     diagnose("RCS file %s exists\n",RCSfilename);
  1079.                                 }
  1080.                 Ifclose(finptr);
  1081.                                 break;
  1082.  
  1083.             case -1:diagnose("RCS file doesn't exist\n");
  1084.                                 break;
  1085.                 }
  1086.  
  1087.         } while (++argv, --argc>=1);
  1088.  
  1089. }
  1090.  
  1091.     exiting void
  1092. exiterr()
  1093. {
  1094.     dirtempunlink();
  1095.     tempunlink();
  1096.     _exit(EXIT_FAILURE);
  1097. }
  1098. #endif
  1099.