home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / rcs567s.zip / rcs / src / rcsedit.c < prev    next >
C/C++ Source or Header  |  1994-08-01  |  48KB  |  1,891 lines

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