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

  1. /*
  2.  *                     RCS stream editor
  3.  */
  4. /**********************************************************************************
  5.  *                       edits the input file according to a
  6.  *                       script from stdin, generated by diff -n
  7.  *                       performs keyword expansion
  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. /* $Log: rcsedit.c,v $
  39.  * Revision 5.14  1992/02/17  23:02:24  eggert
  40.  * Add -T support.
  41.  *
  42.  * Revision 5.13  1992/01/24  18:44:19  eggert
  43.  * Add support for bad_chmod_close, bad_creat0.
  44.  *
  45.  * Revision 5.12  1992/01/06  02:42:34  eggert
  46.  * Add setmode parameter to chnamemod.  addsymbol now reports changes.
  47.  * while (E) ; -> while (E) continue;
  48.  *
  49.  * Revision 5.11  1991/11/03  01:11:44  eggert
  50.  * Move the warning about link breaking to where they're actually being broken.
  51.  *
  52.  * Revision 5.10  1991/10/07  17:32:46  eggert
  53.  * Support piece tables even if !has_mmap.  Fix rare NFS bugs.
  54.  *
  55.  * Revision 5.9  1991/09/17  19:07:40  eggert
  56.  * SGI readlink() yields ENXIO, not EINVAL, for nonlinks.
  57.  *
  58.  * Revision 5.8  1991/08/19  03:13:55  eggert
  59.  * Add piece tables, NFS bug workarounds.  Catch odd filenames.  Tune.
  60.  *
  61.  * Revision 5.7  1991/04/21  11:58:21  eggert
  62.  * Fix errno bugs.  Add -x, RCSINIT, MS-DOS support.
  63.  *
  64.  * Revision 5.6  1991/02/25  07:12:40  eggert
  65.  * Fix setuid bug.  Support new link behavior.  Work around broken "w+" fopen.
  66.  *
  67.  * Revision 5.5  1990/12/30  05:07:35  eggert
  68.  * Fix report of busy RCS files when !defined(O_CREAT) | !defined(O_EXCL).
  69.  *
  70.  * Revision 5.4  1990/11/01  05:03:40  eggert
  71.  * Permit arbitrary data in comment leaders.
  72.  *
  73.  * Revision 5.3  1990/09/11  02:41:13  eggert
  74.  * Tune expandline().
  75.  *
  76.  * Revision 5.2  1990/09/04  08:02:21  eggert
  77.  * Count RCS lines better.  Improve incomplete line handling.
  78.  *
  79.  * Revision 5.1  1990/08/29  07:13:56  eggert
  80.  * Add -kkvl.
  81.  * Fix bug when getting revisions to files ending in incomplete lines.
  82.  * Fix bug in comment leader expansion.
  83.  *
  84.  * Revision 5.0  1990/08/22  08:12:47  eggert
  85.  * Don't require final newline.
  86.  * Don't append "checked in with -k by " to logs,
  87.  * so that checking in a program with -k doesn't change it.
  88.  * Don't generate trailing white space for empty comment leader.
  89.  * Remove compile-time limits; use malloc instead.  Add -k, -V.
  90.  * Permit dates past 1999/12/31.  Make lock and temp files faster and safer.
  91.  * Ansify and Posixate.  Check diff's output.
  92.  *
  93.  * Revision 4.8  89/05/01  15:12:35  narten
  94.  * changed copyright header to reflect current distribution rules
  95.  *
  96.  * Revision 4.7  88/11/08  13:54:14  narten
  97.  * misplaced semicolon caused infinite loop
  98.  *
  99.  * Revision 4.6  88/08/09  19:12:45  eggert
  100.  * Shrink stdio code size; allow cc -R.
  101.  *
  102.  * Revision 4.5  87/12/18  11:38:46  narten
  103.  * Changes from the 43. version. Don't know the significance of the
  104.  * first change involving "rewind". Also, additional "lint" cleanup.
  105.  * (Guy Harris)
  106.  *
  107.  * Revision 4.4  87/10/18  10:32:21  narten
  108.  * Updating version numbers. Changes relative to version 1.1 actually
  109.  * relative to 4.1
  110.  *
  111.  * Revision 1.4  87/09/24  13:59:29  narten
  112.  * Sources now pass through lint (if you ignore printf/sprintf/fprintf
  113.  * warnings)
  114.  *
  115.  * Revision 1.3  87/09/15  16:39:39  shepler
  116.  * added an initializatin of the variables editline and linecorr
  117.  * this will be done each time a file is processed.
  118.  * (there was an obscure bug where if co was used to retrieve multiple files
  119.  *  it would dump)
  120.  * fix attributed to  Roy Morris @FileNet Corp ...!felix!roy
  121.  *
  122.  * Revision 1.2  87/03/27  14:22:17  jenkins
  123.  * Port to suns
  124.  *
  125.  * Revision 4.1  83/05/12  13:10:30  wft
  126.  * Added new markers Id and RCSfile; added locker to Header and Id.
  127.  * Overhauled expandline completely() (problem with $01234567890123456789@).
  128.  * Moved trymatch() and marker table to rcskeys.c.
  129.  *
  130.  * Revision 3.7  83/05/12  13:04:39  wft
  131.  * Added retry to expandline to resume after failed match which ended in $.
  132.  * Fixed truncation problem for $19chars followed by@@.
  133.  * Log no longer expands full path of RCS file.
  134.  *
  135.  * Revision 3.6  83/05/11  16:06:30  wft
  136.  * added retry to expandline to resume after failed match which ended in $.
  137.  * Fixed truncation problem for $19chars followed by@@.
  138.  *
  139.  * Revision 3.5  82/12/04  13:20:56  wft
  140.  * Added expansion of keyword Locker.
  141.  *
  142.  * Revision 3.4  82/12/03  12:26:54  wft
  143.  * Added line number correction in case editing does not start at the
  144.  * beginning of the file.
  145.  * Changed keyword expansion to always print a space before closing KDELIM;
  146.  * Expansion for Header shortened.
  147.  *
  148.  * Revision 3.3  82/11/14  14:49:30  wft
  149.  * removed Suffix from keyword expansion. Replaced fclose with ffclose.
  150.  * keyreplace() gets log message from delta, not from curlogmsg.
  151.  * fixed expression overflow in while(c=putc(GETC....
  152.  * checked nil printing.
  153.  *
  154.  * Revision 3.2  82/10/18  21:13:39  wft
  155.  * I added checks for write errors during the co process, and renamed
  156.  * expandstring() to xpandstring().
  157.  *
  158.  * Revision 3.1  82/10/13  15:52:55  wft
  159.  * changed type of result of getc() from char to int.
  160.  * made keyword expansion loop in expandline() portable to machines
  161.  * without sign-extension.
  162.  */
  163.  
  164.  
  165. #include "rcsbase.h"
  166.  
  167. libId(editId, "$Id: rcsedit.c,v 5.14 1992/02/17 23:02:24 eggert Exp $")
  168.  
  169. static void keyreplace P((enum markers,struct hshentry const*,FILE*));
  170.  
  171. FILE *fcopy;         /* result file descriptor                */
  172. char const *resultfile;  /* result file name                    */
  173. int locker_expansion;     /* should the locker name be appended to Id val?   */
  174. #if !large_memory
  175.     static RILE *fedit; /* edit file descriptor */
  176.     static char const *editfile; /* edit pathname */
  177. #endif
  178. static unsigned long editline; /* edit line counter; #lines before cursor   */
  179. static long linecorr; /* #adds - #deletes in each edit run.            */
  180.                /*used to correct editline in case file is not rewound after */
  181.                /* applying one delta                                        */
  182.  
  183. /* indexes into dirtfname */
  184. #define lockdirtf_index 0
  185. #define newRCSdirtf_index bad_creat0
  186. #define newworkdirtf_index (newRCSdirtf_index+1)
  187. #define DIRTEMPNAMES (newworkdirtf_index + 1)
  188.  
  189. enum maker {notmade, real, effective};
  190. struct buf dirtfname[DIRTEMPNAMES];        /* unlink these when done */
  191. static enum maker volatile dirtfmaker[DIRTEMPNAMES];    /* if these are set */
  192. #define lockfilename (dirtfname[lockdirtf_index].string)
  193. #define newRCSfilename (dirtfname[newRCSdirtf_index].string)
  194.  
  195.  
  196. #if has_NFS || bad_unlink
  197.     int
  198. un_link(s)
  199.     char const *s;
  200. /*
  201.  * Remove S, even if it is unwritable.
  202.  * Ignore unlink() ENOENT failures; NFS generates bogus ones.
  203.  */
  204. {
  205. #    if bad_unlink
  206.         int e;
  207.         if (unlink(s) == 0)
  208.             return 0;
  209.         e = errno;
  210. #        if has_NFS
  211.             if (e == ENOENT)
  212.                 return 0;
  213. #        endif
  214.         if (chmod(s, S_IWUSR) != 0) {
  215.             errno = e;
  216.             return -1;
  217.         }
  218. #    endif
  219. #    if has_NFS
  220.         return unlink(s)==0 || errno==ENOENT  ?  0  :  -1;
  221. #    else
  222.         return unlink(s);
  223. #    endif
  224. }
  225. #endif
  226.  
  227. #if !has_rename
  228. #  if !has_NFS
  229. #    define do_link(s,t) link(s,t)
  230. #  else
  231.     static int
  232. do_link(s, t)
  233.     char const *s, *t;
  234. /* Link S to T, ignoring bogus EEXIST problems due to NFS failures.  */
  235. {
  236.     struct stat sb, tb;
  237.  
  238.     if (link(s,t) == 0)
  239.         return 0;
  240.     if (errno != EEXIST)
  241.         return -1;
  242.     if (
  243.         stat(s, &sb) == 0  &&
  244.         stat(t, &tb) == 0  &&
  245.         sb.st_ino == tb.st_ino  &&
  246.         sb.st_dev == tb.st_dev
  247.     )
  248.         return 0;
  249.     errno = EEXIST;
  250.     return -1;
  251. }
  252. #  endif
  253. #endif
  254.  
  255.  
  256.     static exiting void
  257. editEndsPrematurely()
  258. {
  259.     fatserror("edit script ends prematurely");
  260. }
  261.  
  262.     static exiting void
  263. editLineNumberOverflow()
  264. {
  265.     fatserror("edit script refers to line past end of file");
  266. }
  267.  
  268.  
  269. #if large_memory
  270.  
  271. #if has_memmove
  272. #    define movelines(s1, s2, n) VOID memmove(s1, s2, (n)*sizeof(Iptr_type))
  273. #else
  274.     static void
  275. movelines(s1, s2, n)
  276.     register Iptr_type *s1;
  277.     register Iptr_type const *s2;
  278.     register unsigned long n;
  279. {
  280.     if (s1 < s2)
  281.         do {
  282.             *s1++ = *s2++;
  283.         } while (--n);
  284.     else {
  285.         s1 += n;
  286.         s2 += n;
  287.         do {
  288.             *--s1 = *--s2;
  289.         } while (--n);
  290.     }
  291. }
  292. #endif
  293.  
  294. /*
  295.  * `line' contains pointers to the lines in the currently `edited' file.
  296.  * It is a 0-origin array that represents linelim-gapsize lines.
  297.  * line[0 .. gap-1] and line[gap+gapsize .. linelim-1] hold pointers to lines.
  298.  * line[gap .. gap+gapsize-1] contains garbage.
  299.  *
  300.  * Any @s in lines are duplicated.
  301.  * Lines are terminated by \n, or (for a last partial line only) by single @.
  302.  */
  303. static Iptr_type *line;
  304. static unsigned long gap, gapsize, linelim;
  305.  
  306.  
  307.     static void
  308. insertline(n, l)
  309.     unsigned long n;
  310.     Iptr_type l;
  311. /* Before line N, insert line L.  N is 0-origin.  */
  312. {
  313.     if (linelim-gapsize < n)
  314.         editLineNumberOverflow();
  315.     if (!gapsize)
  316.         line =
  317.         !linelim ?
  318.             tnalloc(Iptr_type, linelim = gapsize = 1024)
  319.         : (
  320.             gap = gapsize = linelim,
  321.             trealloc(Iptr_type, line, linelim <<= 1)
  322.         );
  323.     if (n < gap)
  324.         movelines(line+n+gapsize, line+n, gap-n);
  325.     else if (gap < n)
  326.         movelines(line+gap, line+gap+gapsize, n-gap);
  327.  
  328.     line[n] = l;
  329.     gap = n + 1;
  330.     gapsize--;
  331. }
  332.  
  333.     static void
  334. deletelines(n, nlines)
  335.     unsigned long n, nlines;
  336. /* Delete lines N through N+NLINES-1.  N is 0-origin.  */
  337. {
  338.     unsigned long l = n + nlines;
  339.     if (linelim-gapsize < l  ||  l < n)
  340.         editLineNumberOverflow();
  341.     if (l < gap)
  342.         movelines(line+l+gapsize, line+l, gap-l);
  343.     else if (gap < n)
  344.         movelines(line+gap, line+gap+gapsize, n-gap);
  345.  
  346.     gap = n;
  347.     gapsize += nlines;
  348. }
  349.  
  350.     static void
  351. snapshotline(f, l)
  352.     register FILE *f;
  353.     register Iptr_type l;
  354. {
  355.     register int c;
  356.     do {
  357.         if ((c = *l++) == SDELIM  &&  *l++ != SDELIM)
  358.             return;
  359.         aputc(c, f);
  360.     } while (c != '\n');
  361. }
  362.  
  363.     void
  364. snapshotedit(f)
  365.     FILE *f;
  366. /* Copy the current state of the edits to F.  */
  367. {
  368.     register Iptr_type *p, *lim, *l=line;
  369.     for (p=l, lim=l+gap;  p<lim;  )
  370.         snapshotline(f, *p++);
  371.     for (p+=gapsize, lim=l+linelim;  p<lim;  )
  372.         snapshotline(f, *p++);
  373. }
  374.  
  375.     static void
  376. finisheditline(fin, fout, l, delta)
  377.     RILE *fin;
  378.     FILE *fout;
  379.     Iptr_type l;
  380.     struct hshentry const *delta;
  381. {
  382.     Iseek(fin, l);
  383.     if (expandline(fin, fout, delta, true, (FILE*)0)  <  0)
  384.         faterror("finisheditline internal error");
  385. }
  386.  
  387.     void
  388. finishedit(delta, outfile, done)
  389.     struct hshentry const *delta;
  390.     FILE *outfile;
  391.     int done;
  392. /*
  393.  * Doing expansion if DELTA is set, output the state of the edits to OUTFILE.
  394.  * But do nothing unless DONE is set (which means we are on the last pass).
  395.  */
  396. {
  397.     if (done) {
  398.         openfcopy(outfile);
  399.         outfile = fcopy;
  400.         if (!delta)
  401.             snapshotedit(outfile);
  402.         else {
  403.             register Iptr_type *p, *lim, *l = line;
  404.             register RILE *fin = finptr;
  405.             Iptr_type here = Itell(fin);
  406.             for (p=l, lim=l+gap;  p<lim;  )
  407.                 finisheditline(fin, outfile, *p++, delta);
  408.             for (p+=gapsize, lim=l+linelim;  p<lim;  )
  409.                 finisheditline(fin, outfile, *p++, delta);
  410.             Iseek(fin, here);
  411.         }
  412.     }
  413. }
  414.  
  415. /* Open a temporary FILENAME for output, truncating any previous contents.  */
  416. #   define fopen_update_truncate(filename) fopen(filename, FOPEN_W_WORK)
  417. #else /* !large_memory */
  418.     static FILE *
  419. fopen_update_truncate(filename)
  420.     char const *filename;
  421. {
  422. #    if bad_fopen_wplus
  423.         if (un_link(filename) != 0)
  424.             efaterror(filename);
  425. #    endif
  426.     return fopen(filename, FOPEN_WPLUS_WORK);
  427. }
  428. #endif
  429.  
  430.  
  431.     void
  432. openfcopy(f)
  433.     FILE *f;
  434. {
  435.     if (!(fcopy = f)) {
  436.         if (!resultfile)
  437.             resultfile = maketemp(2);
  438.         if (!(fcopy = fopen_update_truncate(resultfile)))
  439.             efaterror(resultfile);
  440.     }
  441. }
  442.  
  443.  
  444. #if !large_memory
  445.  
  446.     static void
  447. swapeditfiles(outfile)
  448.     FILE *outfile;
  449. /* Function: swaps resultfile and editfile, assigns fedit=fcopy,
  450.  * and rewinds fedit for reading.  Set fcopy to outfile if nonnull;
  451.  * otherwise, set fcopy to be resultfile opened for reading and writing.
  452.  */
  453. {
  454.     char const *tmpptr;
  455.  
  456.     editline = 0;  linecorr = 0;
  457.     if (fseek(fcopy, 0L, SEEK_SET) != 0)
  458.         Oerror();
  459.     fedit = fcopy;
  460.         tmpptr=editfile; editfile=resultfile; resultfile=tmpptr;
  461.     openfcopy(outfile);
  462. }
  463.  
  464.     void
  465. snapshotedit(f)
  466.     FILE *f;
  467. /* Copy the current state of the edits to F.  */
  468. {
  469.     finishedit((struct hshentry *)nil, (FILE*)0, false);
  470.     fastcopy(fedit, f);
  471.     Irewind(fedit);
  472. }
  473.  
  474.     void
  475. finishedit(delta, outfile, done)
  476.     struct hshentry const *delta;
  477.     FILE *outfile;
  478.     int done;
  479. /* copy the rest of the edit file and close it (if it exists).
  480.  * if delta!=nil, perform keyword substitution at the same time.
  481.  * If DONE is set, we are finishing the last pass.
  482.  */
  483. {
  484.     register RILE *fe;
  485.     register FILE *fc;
  486.  
  487.     fe = fedit;
  488.     if (fe) {
  489.         fc = fcopy;
  490.                 if (delta!=nil) {
  491.             while (1 < expandline(fe,fc,delta,false,(FILE*)0))
  492.                 ;
  493.                 } else {
  494.             fastcopy(fe,fc);
  495.                 }
  496.         Ifclose(fe);
  497.         }
  498.     if (!done)
  499.         swapeditfiles(outfile);
  500. }
  501. #endif
  502.  
  503.  
  504.  
  505. #if large_memory
  506. #    define copylines(upto,delta) (editline = (upto))
  507. #else
  508.     static void
  509. copylines(upto,delta)
  510.     register unsigned long upto;
  511.     struct hshentry const *delta;
  512. /*
  513.  * Copy input lines editline+1..upto from fedit to fcopy.
  514.  * If delta != nil, keyword expansion is done simultaneously.
  515.  * editline is updated. Rewinds a file only if necessary.
  516.  */
  517. {
  518.     register int c;
  519.     declarecache;
  520.     register FILE *fc;
  521.     register RILE *fe;
  522.  
  523.     if (upto < editline) {
  524.                 /* swap files */
  525.         finishedit((struct hshentry *)nil, (FILE*)0, false);
  526.                 /* assumes edit only during last pass, from the beginning*/
  527.         }
  528.     fe = fedit;
  529.     fc = fcopy;
  530.     if (editline < upto)
  531.         if (delta)
  532.         do {
  533.             if (expandline(fe,fc,delta,false,(FILE*)0) <= 1)
  534.                 editLineNumberOverflow();
  535.         } while (++editline < upto);
  536.         else {
  537.         setupcache(fe); cache(fe);
  538.         do {
  539.             do {
  540.                 cachegeteof(c, editLineNumberOverflow(););
  541.                 aputc(c, fc);
  542.             } while (c != '\n');
  543.         } while (++editline < upto);
  544.         uncache(fe);
  545.         }
  546. }
  547. #endif
  548.  
  549.  
  550.  
  551.     void
  552. xpandstring(delta)
  553.     struct hshentry const *delta;
  554. /* Function: Reads a string terminated by SDELIM from finptr and writes it
  555.  * to fcopy. Double SDELIM is replaced with single SDELIM.
  556.  * Keyword expansion is performed with data from delta.
  557.  * If foutptr is nonnull, the string is also copied unchanged to foutptr.
  558.  */
  559. {
  560.     while (1 < expandline(finptr,fcopy,delta,true,foutptr))
  561.         continue;
  562. }
  563.  
  564.  
  565.     void
  566. copystring()
  567. /* Function: copies a string terminated with a single SDELIM from finptr to
  568.  * fcopy, replacing all double SDELIM with a single SDELIM.
  569.  * If foutptr is nonnull, the string also copied unchanged to foutptr.
  570.  * editline is incremented by the number of lines copied.
  571.  * Assumption: next character read is first string character.
  572.  */
  573. {    register c;
  574.     declarecache;
  575.     register FILE *frew, *fcop;
  576.     register int amidline;
  577.     register RILE *fin;
  578.  
  579.     fin = finptr;
  580.     setupcache(fin); cache(fin);
  581.     frew = foutptr;
  582.     fcop = fcopy;
  583.     amidline = false;
  584.     for (;;) {
  585.         GETC(frew,c);
  586.         switch (c) {
  587.             case '\n':
  588.             ++editline;
  589.             ++rcsline;
  590.             amidline = false;
  591.             break;
  592.             case SDELIM:
  593.             GETC(frew,c);
  594.             if (c != SDELIM) {
  595.                 /* end of string */
  596.                 nextc = c;
  597.                 editline += amidline;
  598.                 uncache(fin);
  599.                 return;
  600.             }
  601.             /* fall into */
  602.             default:
  603.             amidline = true;
  604.             break;
  605.                 }
  606.         aputc(c,fcop);
  607.         }
  608. }
  609.  
  610.  
  611.     void
  612. enterstring()
  613. /* Like copystring, except the string is put into the edit data structure.  */
  614. {
  615. #if !large_memory
  616.     editfile = 0;
  617.     fedit = 0;
  618.     editline = linecorr = 0;
  619.     resultfile = maketemp(1);
  620.     if (!(fcopy = fopen_update_truncate(resultfile)))
  621.         efaterror(resultfile);
  622.     copystring();
  623. #else
  624.     register int c;
  625.     declarecache;
  626.     register FILE *frew;
  627.     register unsigned long e, oe;
  628.     register int amidline, oamidline;
  629.     register Iptr_type optr;
  630.     register RILE *fin;
  631.  
  632.     e = 0;
  633.     gap = 0;
  634.     gapsize = linelim;
  635.     fin = finptr;
  636.     setupcache(fin); cache(fin);
  637.     advise_access(fin, MADV_NORMAL);
  638.     frew = foutptr;
  639.     amidline = false;
  640.     for (;;) {
  641.         optr = cachetell();
  642.         GETC(frew,c);
  643.         oamidline = amidline;
  644.         oe = e;
  645.         switch (c) {
  646.             case '\n':
  647.             ++e;
  648.             ++rcsline;
  649.             amidline = false;
  650.             break;
  651.             case SDELIM:
  652.             GETC(frew,c);
  653.             if (c != SDELIM) {
  654.                 /* end of string */
  655.                 nextc = c;
  656.                 editline = e + amidline;
  657.                 linecorr = 0;
  658.                 uncache(fin);
  659.                 return;
  660.             }
  661.             /* fall into */
  662.             default:
  663.             amidline = true;
  664.             break;
  665.         }
  666.         if (!oamidline)
  667.             insertline(oe, optr);
  668.     }
  669. #endif
  670. }
  671.  
  672.  
  673.  
  674.  
  675.     void
  676. #if large_memory
  677. edit_string()
  678. #else
  679.   editstring(delta)
  680.     struct hshentry const *delta;
  681. #endif
  682. /*
  683.  * Read an edit script from finptr and applies it to the edit file.
  684. #if !large_memory
  685.  * The result is written to fcopy.
  686.  * If delta!=nil, keyword expansion is performed simultaneously.
  687.  * If running out of lines in fedit, fedit and fcopy are swapped.
  688.  * editfile is the name of the file that goes with fedit.
  689. #endif
  690.  * If foutptr is set, the edit script is also copied verbatim to foutptr.
  691.  * Assumes that all these files are open.
  692.  * resultfile is the name of the file that goes with fcopy.
  693.  * Assumes the next input character from finptr is the first character of
  694.  * the edit script. Resets nextc on exit.
  695.  */
  696. {
  697.         int ed; /* editor command */
  698.         register int c;
  699.     declarecache;
  700.     register FILE *frew;
  701. #    if !large_memory
  702.         register FILE *f;
  703.         unsigned long line_lim = ULONG_MAX;
  704.         register RILE *fe;
  705. #    endif
  706.     register unsigned long i;
  707.     register RILE *fin;
  708. #    if large_memory
  709.         register unsigned long j;
  710. #    endif
  711.     struct diffcmd dc;
  712.  
  713.         editline += linecorr; linecorr=0; /*correct line number*/
  714.     frew = foutptr;
  715.     fin = finptr;
  716.     setupcache(fin);
  717.     initdiffcmd(&dc);
  718.     while (0  <=  (ed = getdiffcmd(fin,true,frew,&dc)))
  719. #if !large_memory
  720.         if (line_lim <= dc.line1)
  721.             editLineNumberOverflow();
  722.         else
  723. #endif
  724.         if (!ed) {
  725.             copylines(dc.line1-1, delta);
  726.                         /* skip over unwanted lines */
  727.             i = dc.nlines;
  728.             linecorr -= i;
  729.             editline += i;
  730. #            if large_memory
  731.                 deletelines(editline+linecorr, i);
  732. #            else
  733.                 fe = fedit;
  734.                 do {
  735.                                 /*skip next line*/
  736.                 do {
  737.                     Igeteof(fe, c, { if (i!=1) editLineNumberOverflow(); line_lim = dc.dafter; break; } );
  738.                 } while (c != '\n');
  739.                 } while (--i);
  740. #            endif
  741.         } else {
  742.             copylines(dc.line1, delta); /*copy only; no delete*/
  743.             i = dc.nlines;
  744. #            if large_memory
  745.                 j = editline+linecorr;
  746. #            endif
  747.             linecorr += i;
  748. #if !large_memory
  749.             f = fcopy;
  750.             if (delta)
  751.                 do {
  752.                 switch (expandline(fin,f,delta,true,frew)) {
  753.                     case 0: case 1:
  754.                     if (i==1)
  755.                         return;
  756.                     /* fall into */
  757.                     case -1:
  758.                     editEndsPrematurely();
  759.                 }
  760.                 } while (--i);
  761.             else
  762. #endif
  763.             {
  764.                 cache(fin);
  765.                 do {
  766. #                if large_memory
  767.                     insertline(j++, cachetell());
  768. #                endif
  769.                 for (;;) {
  770.                     GETC(frew, c);
  771. #                    if !large_memory
  772.                     aputc(c, f);
  773. #                    endif
  774.                     if (c == '\n')
  775.                     break;
  776.                     if (c==SDELIM) {
  777.                     GETC(frew, c);
  778.                     if (c!=SDELIM) {
  779.                         if (--i)
  780.                         editEndsPrematurely();
  781.                         nextc = c;
  782.                         uncache(fin);
  783.                         return;
  784.                     }
  785.                     }
  786.                 }
  787.                 ++rcsline;
  788.                 } while (--i);
  789.                 uncache(fin);
  790.             }
  791.                 }
  792. }
  793.  
  794.  
  795.  
  796. /* The rest is for keyword expansion */
  797.  
  798.  
  799.  
  800.     int
  801. expandline(infile, outfile, delta, delimstuffed, frewfile)
  802.     RILE *infile;
  803.     FILE *outfile, *frewfile;
  804.     struct hshentry const *delta;
  805.     int delimstuffed;
  806. /*
  807.  * Read a line from INFILE and write it to OUTFILE.
  808.  * If DELIMSTUFFED is true, double SDELIM is replaced with single SDELIM.
  809.  * Keyword expansion is performed with data from delta.
  810.  * If FREWFILE is set, copy the line unchanged to FREWFILE.
  811.  * DELIMSTUFFED must be true if FREWFILE is set.
  812.  * Yields -1 if no data is copied, 0 if an incomplete line is copied,
  813.  * 2 if a complete line is copied; adds 1 to yield if expansion occurred.
  814.  */
  815. {
  816.     register c;
  817.     declarecache;
  818.     register FILE *out, *frew;
  819.     register char * tp;
  820.     register int e, ds, r;
  821.     char const *tlim;
  822.     static struct buf keyval;
  823.         enum markers matchresult;
  824.  
  825.     setupcache(infile); cache(infile);
  826.     out = outfile;
  827.     frew = frewfile;
  828.     ds = delimstuffed;
  829.     bufalloc(&keyval, keylength+3);
  830.     e = 0;
  831.     r = -1;
  832.  
  833.         for (;;) {
  834.         if (ds) {
  835.         GETC(frew, c);
  836.         } else
  837.         cachegeteof(c, goto uncache_exit;);
  838.         for (;;) {
  839.         switch (c) {
  840.             case SDELIM:
  841.             if (ds) {
  842.                 GETC(frew, c);
  843.                 if (c != SDELIM) {
  844.                                 /* end of string */
  845.                                 nextc=c;
  846.                 goto uncache_exit;
  847.                 }
  848.             }
  849.             /* fall into */
  850.             default:
  851.             aputc(c,out);
  852.             r = 0;
  853.             break;
  854.  
  855.             case '\n':
  856.             rcsline += ds;
  857.             aputc(c,out);
  858.             r = 2;
  859.             goto uncache_exit;
  860.  
  861.             case KDELIM:
  862.             r = 0;
  863.                         /* check for keyword */
  864.                         /* first, copy a long enough string into keystring */
  865.             tp = keyval.string;
  866.             *tp++ = KDELIM;
  867.             for (;;) {
  868.                 if (ds) {
  869.                 GETC(frew, c);
  870.                 } else
  871.                 cachegeteof(c, goto keystring_eof;);
  872.                 if (tp < keyval.string+keylength+1)
  873.                 switch (ctab[c]) {
  874.                     case LETTER: case Letter:
  875.                     *tp++ = c;
  876.                     continue;
  877.                     default:
  878.                     break;
  879.                 }
  880.                 break;
  881.                         }
  882.             *tp++ = c; *tp = '\0';
  883.             matchresult = trymatch(keyval.string+1);
  884.             if (matchresult==Nomatch) {
  885.                 tp[-1] = 0;
  886.                 aputs(keyval.string, out);
  887.                 continue;   /* last c handled properly */
  888.             }
  889.  
  890.             /* Now we have a keyword terminated with a K/VDELIM */
  891.             if (c==VDELIM) {
  892.                   /* try to find closing KDELIM, and replace value */
  893.                   tlim = keyval.string + keyval.size;
  894.                   for (;;) {
  895.                       if (ds) {
  896.                     GETC(frew, c);
  897.                       } else
  898.                     cachegeteof(c, goto keystring_eof;);
  899.                       if (c=='\n' || c==KDELIM)
  900.                     break;
  901.                       *tp++ =c;
  902.                       if (tlim <= tp)
  903.                       tp = bufenlarge(&keyval, &tlim);
  904.                       if (c==SDELIM && ds) { /*skip next SDELIM */
  905.                         GETC(frew, c);
  906.                         if (c != SDELIM) {
  907.                             /* end of string before closing KDELIM or newline */
  908.                             nextc = c;
  909.                             goto keystring_eof;
  910.                         }
  911.                       }
  912.                   }
  913.                   if (c!=KDELIM) {
  914.                     /* couldn't find closing KDELIM -- give up */
  915.                     *tp = 0;
  916.                     aputs(keyval.string, out);
  917.                     continue;   /* last c handled properly */
  918.                   }
  919.             }
  920.             /* now put out the new keyword value */
  921.             keyreplace(matchresult,delta,out);
  922.             e = 1;
  923.             break;
  924.                 }
  925.         break;
  926.         }
  927.         }
  928.  
  929.     keystring_eof:
  930.     *tp = 0;
  931.     aputs(keyval.string, out);
  932.     uncache_exit:
  933.     uncache(infile);
  934.     return r + e;
  935. }
  936.  
  937.  
  938. char const ciklog[ciklogsize] = "checked in with -k by ";
  939.  
  940.     static void
  941. keyreplace(marker,delta,out)
  942.     enum markers marker;
  943.     register struct hshentry const *delta;
  944.     register FILE *out;
  945. /* function: outputs the keyword value(s) corresponding to marker.
  946.  * Attributes are derived from delta.
  947.  */
  948. {
  949.     register char const *sp, *cp, *date;
  950.     register char c;
  951.     register size_t cs, cw, ls;
  952.     char const *sp1;
  953.     char datebuf[datesize];
  954.     int RCSv;
  955.  
  956.     sp = Keyword[(int)marker];
  957.  
  958.     if (Expand == KEY_EXPAND) {
  959.         aprintf(out, "%c%s%c", KDELIM, sp, KDELIM);
  960.         return;
  961.     }
  962.  
  963.         date= delta->date;
  964.     RCSv = RCSversion;
  965.  
  966.     if (Expand == KEYVAL_EXPAND  ||  Expand == KEYVALLOCK_EXPAND)
  967.         aprintf(out, "%c%s%c%c", KDELIM, sp, VDELIM,
  968.             marker==Log && RCSv<VERSION(5)  ?  '\t'  :  ' '
  969.         );
  970.  
  971.         switch (marker) {
  972.         case Author:
  973.         aputs(delta->author, out);
  974.                 break;
  975.         case Date:
  976.         aputs(date2str(date,datebuf), out);
  977.                 break;
  978.         case Id:
  979.     case Header:
  980.         aprintf(out, "%s %s %s %s %s",
  981.               marker==Id || RCSv<VERSION(4)
  982.             ? basename(RCSfilename)
  983.             : getfullRCSname(),
  984.             delta->num,
  985.             date2str(date, datebuf),
  986.             delta->author,
  987.               RCSv==VERSION(3) && delta->lockedby ? "Locked"
  988.             : delta->state
  989.         );
  990.         if (delta->lockedby!=nil)
  991.             if (VERSION(5) <= RCSv) {
  992.             if (locker_expansion || Expand==KEYVALLOCK_EXPAND)
  993.                 aprintf(out, " %s", delta->lockedby);
  994.             } else if (RCSv == VERSION(4))
  995.             aprintf(out, " Locker: %s", delta->lockedby);
  996.                 break;
  997.         case Locker:
  998.         if (delta->lockedby)
  999.             if (
  1000.                 locker_expansion
  1001.             ||    Expand == KEYVALLOCK_EXPAND
  1002.             ||    RCSv <= VERSION(4)
  1003.             )
  1004.             aputs(delta->lockedby, out);
  1005.                 break;
  1006.         case Log:
  1007.         case RCSfile:
  1008.         aputs(basename(RCSfilename), out);
  1009.                 break;
  1010.         case Revision:
  1011.         aputs(delta->num, out);
  1012.                 break;
  1013.         case Source:
  1014.         aputs(getfullRCSname(), out);
  1015.                 break;
  1016.         case State:
  1017.         aputs(delta->state, out);
  1018.                 break;
  1019.     default:
  1020.         break;
  1021.         }
  1022.     if (Expand == KEYVAL_EXPAND  ||  Expand == KEYVALLOCK_EXPAND) {
  1023.         afputc(' ', out);
  1024.         afputc(KDELIM, out);
  1025.     }
  1026.     if (marker == Log) {
  1027.         sp = delta->log.string;
  1028.         ls = delta->log.size;
  1029.         if (sizeof(ciklog)-1<=ls && !memcmp(sp,ciklog,sizeof(ciklog)-1))
  1030.             return;
  1031.         afputc('\n', out);
  1032.         cp = Comment.string;
  1033.         cw = cs = Comment.size;
  1034.         awrite(cp, cs, out);
  1035.         /* oddity: 2 spaces between date and time, not 1 as usual */
  1036.         sp1 = strchr(date2str(date,datebuf), ' ');
  1037.         aprintf(out, "Revision %s  %.*s %s  %s",
  1038.             delta->num, (int)(sp1-datebuf), datebuf, sp1, delta->author
  1039.         );
  1040.         /* Do not include state: it may change and is not updated.  */
  1041.         /* Comment is the comment leader.  */
  1042.         if (VERSION(5) <= RCSv)
  1043.             for (;  cw && (cp[cw-1]==' ' || cp[cw-1]=='\t');  --cw)
  1044.             continue;
  1045.         for (;;) {
  1046.             afputc('\n', out);
  1047.             awrite(cp, cw, out);
  1048.             if (!ls)
  1049.             break;
  1050.             --ls;
  1051.             c = *sp++;
  1052.             if (c != '\n') {
  1053.             awrite(cp+cw, cs-cw, out);
  1054.             do {
  1055.                 afputc(c,out);
  1056.                 if (!ls)
  1057.                 break;
  1058.                 --ls;
  1059.                 c = *sp++;
  1060.             } while (c != '\n');
  1061.             }
  1062.         }
  1063.     }
  1064. }
  1065.  
  1066. #if has_readlink
  1067.     static int
  1068. resolve_symlink(L)
  1069.     struct buf *L;
  1070. /*
  1071.  * If L is a symbolic link, resolve it to the name that it points to.
  1072.  * If unsuccessful, set errno and yield -1.
  1073.  * If it points to an existing file, yield 1.
  1074.  * Otherwise, set errno=ENOENT and yield 0.
  1075.  */
  1076. {
  1077.     char *b, a[SIZEABLE_PATH];
  1078.     int e;
  1079.     size_t s;
  1080.     ssize_t r;
  1081.     struct buf bigbuf;
  1082.     unsigned linkcount = MAXSYMLINKS + 1;
  1083.  
  1084.     b = a;
  1085.     s = sizeof(a);
  1086.     bufautobegin(&bigbuf);
  1087.     while ((r = readlink(L->string,b,s))  !=  -1)
  1088.         if (r == s) {
  1089.         bufalloc(&bigbuf, s<<1);
  1090.         b = bigbuf.string;
  1091.         s = bigbuf.size;
  1092.         } else if (!--linkcount) {
  1093.         errno = ELOOP;
  1094.         return -1;
  1095.         } else {
  1096.         /* Splice symbolic link into L.  */
  1097.         b[r] = '\0';
  1098.         L->string[ROOTPATH(b) ? (size_t)0 : dirlen(L->string)]  =  '\0';
  1099.         bufscat(L, b);
  1100.         }
  1101.     e = errno;
  1102.     bufautoend(&bigbuf);
  1103.     errno = e;
  1104.     switch (e) {
  1105.         case ENXIO:
  1106.         case EINVAL: return 1;
  1107.         case ENOENT: return 0;
  1108.         default: return -1;
  1109.     }
  1110. }
  1111. #endif
  1112.  
  1113.     RILE *
  1114. rcswriteopen(RCSbuf, status, mustread)
  1115.     struct buf *RCSbuf;
  1116.     struct stat *status;
  1117.     int mustread;
  1118. /*
  1119.  * Create the lock file corresponding to RCSBUF.
  1120.  * Then try to open RCSBUF for reading and yield its RILE* descriptor.
  1121.  * Put its status into *STATUS too.
  1122.  * MUSTREAD is true if the file must already exist, too.
  1123.  * If all goes well, discard any previously acquired locks,
  1124.  * and set fdlock to the file descriptor of the RCS lockfile.
  1125.  */
  1126. {
  1127.     register char *tp;
  1128.     register char const *sp, *RCSname, *x;
  1129.     RILE *f;
  1130.     size_t l;
  1131.     int e, exists, fdesc, r, waslocked;
  1132.     struct buf *dirt;
  1133.     struct stat statbuf;
  1134.  
  1135.     waslocked  =  0 <= fdlock;
  1136.     exists =
  1137. #        if has_readlink
  1138.             resolve_symlink(RCSbuf);
  1139. #        else
  1140.                 stat(RCSbuf->string, &statbuf) == 0  ?  1
  1141.             :   errno==ENOENT ? 0 : -1;
  1142. #        endif
  1143.     if (exists < (mustread|waslocked))
  1144.         /*
  1145.          * There's an unusual problem with the RCS file;
  1146.          * or the RCS file doesn't exist,
  1147.          * and we must read or we already have a lock elsewhere.
  1148.          */
  1149.         return 0;
  1150.  
  1151.     RCSname = RCSbuf->string;
  1152.     sp = basename(RCSname);
  1153.     l = sp - RCSname;
  1154.     dirt = &dirtfname[waslocked];
  1155.     bufscpy(dirt, RCSname);
  1156.     tp = dirt->string + l;
  1157.     x = rcssuffix(RCSname);
  1158. #    if has_readlink
  1159.         if (!x) {
  1160.         error("symbolic link to non RCS filename `%s'", RCSname);
  1161.         errno = EINVAL;
  1162.         return 0;
  1163.         }
  1164. #    endif
  1165.     if (*sp == *x) {
  1166.         error("RCS filename `%s' incompatible with suffix `%s'", sp, x);
  1167.         errno = EINVAL;
  1168.         return 0;
  1169.     }
  1170.     /* Create a lock file whose name is a function of the RCS filename.  */
  1171.     if (*x) {
  1172.         /*
  1173.          * The suffix is nonempty.
  1174.          * The lock filename is the first char of of the suffix,
  1175.          * followed by the RCS filename with last char removed.  E.g.:
  1176.          *    foo,v    RCS filename with suffix ,v
  1177.          *    ,foo,    lock filename
  1178.          */
  1179.         *tp++ = *x;
  1180.         while (*sp)
  1181.             *tp++ = *sp++;
  1182.         *--tp = 0;
  1183.     } else {
  1184.         /*
  1185.          * The suffix is empty.
  1186.          * The lock filename is the RCS filename
  1187.          * with last char replaced by '_'.
  1188.          */
  1189.         while ((*tp++ = *sp++))
  1190.             continue;
  1191.         tp -= 2;
  1192.         if (*tp == '_') {
  1193.             error("RCS filename `%s' ends with `%c'", RCSname, *tp);
  1194.             errno = EINVAL;
  1195.             return 0;
  1196.         }
  1197.         *tp = '_';
  1198.     }
  1199.  
  1200.     sp = dirt->string;
  1201.  
  1202.     f = 0;
  1203.  
  1204.     /*
  1205.     * good news:
  1206.     *    open(f, O_CREAT|O_EXCL|O_TRUNC|O_WRONLY, READONLY) is atomic
  1207.     *    according to Posix 1003.1-1990.
  1208.     * bad news:
  1209.     *    NFS ignores O_EXCL and doesn't comply with Posix 1003.1-1990.
  1210.     * good news:
  1211.     *    (O_TRUNC,READONLY) normally guarantees atomicity even with NFS.
  1212.     * bad news:
  1213.     *    If you're root, (O_TRUNC,READONLY) doesn't guarantee atomicity.
  1214.     * good news:
  1215.     *    Root-over-the-wire NFS access is rare for security reasons.
  1216.     *    This bug has never been reported in practice with RCS.
  1217.     * So we don't worry about this bug.
  1218.     *
  1219.     * An even rarer NFS bug can occur when clients retry requests.
  1220.     * Suppose client A renames the lock file ",f," to "f,v"
  1221.     * at about the same time that client B creates ",f,",
  1222.     * and suppose A's first rename request is delayed, so A reissues it.
  1223.     * The sequence of events might be:
  1224.     *    A sends rename(",f,", "f,v")
  1225.     *    B sends create(",f,")
  1226.     *    A sends retry of rename(",f,", "f,v")
  1227.     *    server receives, does, and acknowledges A's first rename()
  1228.     *    A receives acknowledgment, and its RCS program exits
  1229.     *    server receives, does, and acknowledges B's create()
  1230.     *    server receives, does, and acknowledges A's retry of rename()
  1231.     * This not only wrongly deletes B's lock, it removes the RCS file!
  1232.     * Most NFS implementations have idempotency caches that usually prevent
  1233.     * this scenario, but such caches are finite and can be overrun.
  1234.     * This problem afflicts programs that use the traditional
  1235.     * Unix method of using link() and unlink() to get and release locks,
  1236.     * as well as RCS's method of using open() and rename().
  1237.     * There is no easy workaround for either link-unlink or open-rename.
  1238.     * Any new method based on lockf() seemingly would be incompatible with
  1239.     * the old methods; besides, lockf() is notoriously buggy under NFS.
  1240.     * Since this problem afflicts scads of Unix programs, but is so rare
  1241.     * that nobody seems to be worried about it, we won't worry either.
  1242.     */
  1243. #    define READONLY (S_IRUSR|S_IRGRP|S_IROTH)
  1244. #    if !open_can_creat
  1245. #        define create(f) creat(f, READONLY)
  1246. #    else
  1247. #        define create(f) open(f, OPEN_O_BINARY|O_CREAT|O_EXCL|O_TRUNC|O_WRONLY, READONLY)
  1248. #    endif
  1249.  
  1250.     catchints();
  1251.     ignoreints();
  1252.  
  1253.     /*
  1254.      * Create a lock file for an RCS file.  This should be atomic, i.e.
  1255.      * if two processes try it simultaneously, at most one should succeed.
  1256.      */
  1257.     seteid();
  1258.     fdesc = create(sp);
  1259.     e = errno;
  1260.     setrid();
  1261.  
  1262.     if (fdesc < 0) {
  1263.         if (e == EACCES  &&  stat(sp,&statbuf) == 0)
  1264.             /* The RCS file is busy.  */
  1265.             e = EEXIST;
  1266.     } else {
  1267.         dirtfmaker[0] = effective;
  1268.         e = ENOENT;
  1269.         if (exists) {
  1270.             f = Iopen(RCSname, FOPEN_R, status);
  1271.             e = errno;
  1272.             if (f && waslocked) {
  1273.             /* Discard the previous lock in favor of this one.  */
  1274.             ORCSclose();
  1275.             seteid();
  1276.             r = un_link(lockfilename);
  1277.             e = errno;
  1278.             setrid();
  1279.             if (r != 0)
  1280.                 enfaterror(e, lockfilename);
  1281.             bufscpy(&dirtfname[lockdirtf_index], sp);
  1282.             }
  1283.         }
  1284.         fdlock = fdesc;
  1285.     }
  1286.  
  1287.     restoreints();
  1288.  
  1289.     errno = e;
  1290.     return f;
  1291. }
  1292.  
  1293.     void
  1294. keepdirtemp(name)
  1295.     char const *name;
  1296. /* Do not unlink name, either because it's not there any more,
  1297.  * or because it has already been unlinked.
  1298.  */
  1299. {
  1300.     register int i;
  1301.     for (i=DIRTEMPNAMES; 0<=--i; )
  1302.         if (dirtfname[i].string == name) {
  1303.             dirtfmaker[i] = notmade;
  1304.             return;
  1305.         }
  1306.     faterror("keepdirtemp");
  1307. }
  1308.  
  1309.     char const *
  1310. makedirtemp(isworkfile)
  1311.     int isworkfile;
  1312. /*
  1313.  * Create a unique filename and store it into dirtfname.
  1314.  * Because of storage in tfnames, dirtempunlink() can unlink the file later.
  1315.  * Return a pointer to the filename created.
  1316.  * If ISWORKFILE is 1, put it into the working file's directory;
  1317.  * if 0, put the unique file in RCSfile's directory.
  1318.  */
  1319. {
  1320.     register char *tp, *np;
  1321.     register size_t dl;
  1322.     register struct buf *bn;
  1323.     register char const *name = isworkfile ? workfilename : RCSfilename;
  1324.  
  1325.     dl = dirlen(name);
  1326.     bn = &dirtfname[newRCSdirtf_index + isworkfile];
  1327.     bufalloc(bn,
  1328. #        if has_mktemp
  1329.             dl + 9
  1330. #        else
  1331.             strlen(name) + 3
  1332. #        endif
  1333.     );
  1334.     bufscpy(bn, name);
  1335.     np = tp = bn->string;
  1336.     tp += dl;
  1337.     *tp++ = '_';
  1338.     *tp++ = '0'+isworkfile;
  1339.     catchints();
  1340. #    if has_mktemp
  1341.         VOID strcpy(tp, "XXXXXX");
  1342.         if (!mktemp(np) || !*np)
  1343.             faterror("can't make temporary file name `%.*s%c_%cXXXXXX'",
  1344.             (int)dl, name, SLASH, '0'+isworkfile
  1345.             );
  1346. #    else
  1347.         /*
  1348.          * Posix 1003.1-1990 has no reliable way
  1349.          * to create a unique file in a named directory.
  1350.          * We fudge here.  If the file name is abcde,
  1351.          * the temp filename is _Ncde where N is a digit.
  1352.          */
  1353.         name += dl;
  1354.         if (*name) name++;
  1355.         if (*name) name++;
  1356.         VOID strcpy(tp, name);
  1357. #    endif
  1358.     dirtfmaker[newRCSdirtf_index + isworkfile] = real;
  1359.     return np;
  1360. }
  1361.  
  1362.     void
  1363. dirtempunlink()
  1364. /* Clean up makedirtemp() files.  May be invoked by signal handler. */
  1365. {
  1366.     register int i;
  1367.     enum maker m;
  1368.  
  1369.     for (i = DIRTEMPNAMES;  0 <= --i;  )
  1370.         if ((m = dirtfmaker[i]) != notmade) {
  1371.         if (m == effective)
  1372.             seteid();
  1373.         VOID un_link(dirtfname[i].string);
  1374.         if (m == effective)
  1375.             setrid();
  1376.         dirtfmaker[i] = notmade;
  1377.         }
  1378. }
  1379.  
  1380.  
  1381.     int
  1382. #if has_prototypes
  1383. chnamemod(FILE **fromp,char const *from,char const *to,int setmode,mode_t mode)
  1384.   /* The `#if has_prototypes' is needed because mode_t might promote to int.  */
  1385. #else
  1386.   chnamemod(fromp,from,to,setmode,mode)
  1387.     FILE **fromp; char const *from,*to; int setmode; mode_t mode;
  1388. #endif
  1389. /*
  1390.  * Rename a file (with stream pointer *FROMP) from FROM to TO.
  1391.  * FROM already exists.
  1392.  * If SETMODE is positive, change the mode to MODE, before renaming if possible.
  1393.  * Close and clear *FROMP before renaming it.
  1394.  * Unlink TO if it already exists.
  1395.  * Return -1 on error (setting errno), 0 otherwise.
  1396.  */
  1397. {
  1398. #    if bad_a_rename
  1399.         /*
  1400.          * This host is brain damaged.  A race condition is possible
  1401.          * while the lock file is temporarily writable.
  1402.          * There doesn't seem to be a workaround.
  1403.          */
  1404.         mode_t mode_while_renaming;
  1405.         if (setmode <= 0) {
  1406.             struct stat st;
  1407.             if (stat(from, &st) != 0)
  1408.             return -1;
  1409.             mode = st.st_mode;
  1410.         }
  1411.         mode_while_renaming = mode|S_IWUSR;
  1412.         if (mode != mode_while_renaming)
  1413.             setmode = 1;
  1414. #    else
  1415. #        define mode_while_renaming mode
  1416. #    endif
  1417.  
  1418. #    if has_fchmod
  1419.         if (0<setmode  &&  fchmod(fileno(*fromp),mode_while_renaming) != 0)
  1420.         return -1;
  1421.         Ozclose(fromp);
  1422. #    else
  1423.         /* If bad_chmod_close, we must close before chmod.  */
  1424.         Ozclose(fromp);
  1425.         if (0<setmode  &&  chmod(from, mode_while_renaming) != 0)
  1426.         return -1;
  1427. #    endif
  1428.  
  1429. #    if !has_rename || bad_b_rename
  1430.         VOID un_link(to);
  1431.         /*
  1432.          * We need not check the result;
  1433.          * link() or rename() will catch it.
  1434.          * No harm is done if TO does not exist.
  1435.          * However, there's a short window of inconsistency
  1436.          * during which TO does not exist.
  1437.          */
  1438. #    endif
  1439.  
  1440.     return
  1441. #        if !has_rename
  1442.         do_link(from,to) != 0  ?  -1  :  un_link(from)
  1443. #        else
  1444.             rename(from, to) != 0
  1445. #            if has_NFS
  1446.             && errno != ENOENT
  1447. #            endif
  1448.         ?  -1
  1449. #        if bad_a_rename
  1450.         :  0<setmode  ?  chmod(to, mode)
  1451. #        endif
  1452.         :  0
  1453. #        endif
  1454.     ;
  1455.  
  1456. #    undef mode_while_renaming
  1457. }
  1458.  
  1459.  
  1460.  
  1461.     int
  1462. findlock(delete, target)
  1463.     int delete;
  1464.     struct hshentry **target;
  1465. /*
  1466.  * Find the first lock held by caller and return a pointer
  1467.  * to the locked delta; also removes the lock if DELETE.
  1468.  * If one lock, put it into *TARGET.
  1469.  * Return 0 for no locks, 1 for one, 2 for two or more.
  1470.  */
  1471. {
  1472.     register struct lock *next, **trail, **found;
  1473.  
  1474.     found = 0;
  1475.     for (trail = &Locks;  (next = *trail);  trail = &next->nextlock)
  1476.         if (strcmp(getcaller(), next->login)  ==  0) {
  1477.             if (found) {
  1478.                 error("multiple revisions locked by %s; please specify one", getcaller());
  1479.                 return 2;
  1480.             }
  1481.             found = trail;
  1482.         }
  1483.     if (!found)
  1484.         return 0;
  1485.     next = *found;
  1486.     *target = next->delta;
  1487.     if (delete) {
  1488.         next->delta->lockedby = nil;
  1489.         *found = next->nextlock;
  1490.     }
  1491.     return 1;
  1492. }
  1493.  
  1494.     int
  1495. addlock(delta)
  1496.     struct hshentry * delta;
  1497. /*
  1498.  * Add a lock held by caller to DELTA and yield 1 if successful.
  1499.  * Print an error message and yield -1 if no lock is added because
  1500.  * DELTA is locked by somebody other than caller.
  1501.  * Return 0 if the caller already holds the lock.
  1502.  */
  1503. {
  1504.     register struct lock *next;
  1505.  
  1506.     next=Locks;
  1507.     for (next = Locks;  next;  next = next->nextlock)
  1508.         if (cmpnum(delta->num, next->delta->num) == 0)
  1509.             if (strcmp(getcaller(), next->login) == 0)
  1510.                 return 0;
  1511.             else {
  1512.                 error("revision %s already locked by %s",
  1513.                       delta->num, next->login
  1514.                 );
  1515.                 return -1;
  1516.             }
  1517.     next = ftalloc(struct lock);
  1518.     delta->lockedby = next->login = getcaller();
  1519.     next->delta = delta;
  1520.     next->nextlock = Locks;
  1521.     Locks = next;
  1522.     return 1;
  1523. }
  1524.  
  1525.  
  1526.     int
  1527. addsymbol(num, name, rebind)
  1528.     char const *num, *name;
  1529.     int rebind;
  1530. /*
  1531.  * Associate with revision NUM the new symbolic NAME.
  1532.  * If NAME already exists and REBIND is set, associate NAME with NUM;
  1533.  * otherwise, print an error message and return false;
  1534.  * Return -1 if unsuccessful, 0 if no change, 1 if change.
  1535.  */
  1536. {
  1537.     register struct assoc *next;
  1538.  
  1539.     for (next = Symbols;  next;  next = next->nextassoc)
  1540.         if (strcmp(name, next->symbol)  ==  0)
  1541.             if (strcmp(next->num,num) == 0)
  1542.                 return 0;
  1543.             else if (rebind) {
  1544.                 next->num = num;
  1545.                 return 1;
  1546.             } else {
  1547.                 error("symbolic name %s already bound to %s",
  1548.                     name, next->num
  1549.                 );
  1550.                 return -1;
  1551.             }
  1552.     next = ftalloc(struct assoc);
  1553.     next->symbol = name;
  1554.     next->num = num;
  1555.     next->nextassoc = Symbols;
  1556.     Symbols = next;
  1557.     return 1;
  1558. }
  1559.  
  1560.  
  1561.  
  1562.     char const *
  1563. getcaller()
  1564. /* Get the caller's login name.  */
  1565. {
  1566. #    if has_setuid
  1567.         return getusername(euid()!=ruid());
  1568. #    else
  1569.         return getusername(false);
  1570. #    endif
  1571. }
  1572.  
  1573.  
  1574.     int
  1575. checkaccesslist()
  1576. /*
  1577.  * Return true if caller is the superuser, the owner of the
  1578.  * file, the access list is empty, or caller is on the access list.
  1579.  * Otherwise, print an error message and return false.
  1580.  */
  1581. {
  1582.     register struct access const *next;
  1583.  
  1584.     if (!AccessList || myself(RCSstat.st_uid) || strcmp(getcaller(),"root")==0)
  1585.         return true;
  1586.  
  1587.     next = AccessList;
  1588.     do {
  1589.         if (strcmp(getcaller(), next->login)  ==  0)
  1590.             return true;
  1591.     } while ((next = next->nextaccess));
  1592.  
  1593.     error("user %s not on the access list", getcaller());
  1594.     return false;
  1595. }
  1596.  
  1597.  
  1598.     int
  1599. dorewrite(lockflag, changed)
  1600.     int lockflag, changed;
  1601. /*
  1602.  * Do nothing if LOCKFLAG is zero.
  1603.  * Prepare to rewrite an RCS file if CHANGED is positive.
  1604.  * Stop rewriting if CHANGED is zero, because there won't be any changes.
  1605.  * Fail if CHANGED is negative.
  1606.  * Return 0 on success, -1 on failure.
  1607.  */
  1608. {
  1609.     int r = 0, e;
  1610.  
  1611.     if (lockflag)
  1612.         if (changed) {
  1613.             if (changed < 0)
  1614.                 return -1;
  1615.             putadmin();
  1616.             puttree(Head, frewrite);
  1617.             aprintf(frewrite, "\n\n%s%c", Kdesc, nextc);
  1618.             foutptr = frewrite;
  1619.         } else {
  1620. #            if bad_creat0
  1621.                 int nr = !!frewrite, ne = 0;
  1622. #            endif
  1623.             ORCSclose();
  1624.             seteid();
  1625.             ignoreints();
  1626. #            if bad_creat0
  1627.                 if (nr) {
  1628.                     nr = un_link(newRCSfilename);
  1629.                     ne = errno;
  1630.                     keepdirtemp(newRCSfilename);
  1631.                 }
  1632. #            endif
  1633.             r = un_link(lockfilename);
  1634.             e = errno;
  1635.             keepdirtemp(lockfilename);
  1636.             restoreints();
  1637.             setrid();
  1638.             if (r != 0)
  1639.                 enerror(e, lockfilename);
  1640. #            if bad_creat0
  1641.                 if (nr != 0) {
  1642.                     enerror(ne, newRCSfilename);
  1643.                     r = -1;
  1644.                 }
  1645. #            endif
  1646.         }
  1647.     return r;
  1648. }
  1649.  
  1650.     int
  1651. donerewrite(changed, keepRCStime)
  1652.     int changed, keepRCStime;
  1653. /*
  1654.  * Finish rewriting an RCS file if CHANGED is nonzero.
  1655.  * Set its mode if CHANGED is positive.
  1656.  * Keep its original modification time if keepRCStime is set.
  1657.  * Return 0 on success, -1 on failure.
  1658.  */
  1659. {
  1660.     int r = 0, e;
  1661. #    if bad_creat0
  1662.         int lr, le;
  1663. #    endif
  1664.  
  1665.     if (changed && !nerror) {
  1666.         if (finptr) {
  1667.             fastcopy(finptr, frewrite);
  1668.             Izclose(&finptr);
  1669.         }
  1670.         if (1 < RCSstat.st_nlink)
  1671.             warn("breaking hard link to %s", RCSfilename);
  1672.         seteid();
  1673.         ignoreints();
  1674.         if (keepRCStime) {
  1675.             r = setmtime(newRCSfilename, RCSstat.st_mtime);
  1676.             e = errno;
  1677.         }
  1678.         if (r == 0) {
  1679.             r = chnamemod(
  1680.             &frewrite, newRCSfilename, RCSfilename, changed,
  1681.             RCSstat.st_mode & ~(S_IWUSR|S_IWGRP|S_IWOTH)
  1682.             );
  1683.             e = errno;
  1684.         }
  1685.         keepdirtemp(newRCSfilename);
  1686. #        if bad_creat0
  1687.             lr = un_link(lockfilename);
  1688.             le = errno;
  1689.             keepdirtemp(lockfilename);
  1690. #        endif
  1691.         restoreints();
  1692.         setrid();
  1693.         if (r != 0) {
  1694.             enerror(e, RCSfilename);
  1695.             error("saved in %s", newRCSfilename);
  1696.         }
  1697. #        if bad_creat0
  1698.             if (lr != 0) {
  1699.                 enerror(le, lockfilename);
  1700.                 r = -1;
  1701.             }
  1702. #        endif
  1703.     }
  1704.     return r;
  1705. }
  1706.  
  1707.     void
  1708. aflush(f)
  1709.     FILE *f;
  1710. {
  1711.     if (fflush(f) != 0)
  1712.         Oerror();
  1713. }
  1714.  
  1715.     void
  1716. ORCSclose()
  1717. {
  1718.     if (0 <= fdlock) {
  1719.         if (close(fdlock) != 0)
  1720.             efaterror(lockfilename);
  1721.         fdlock = -1;
  1722.     }
  1723.     Ozclose(&frewrite);
  1724. }
  1725.