PageRenderTime 89ms CodeModel.GetById 12ms app.highlight 68ms RepoModel.GetById 2ms app.codeStats 0ms

/contrib/cvs/src/subr.c

https://bitbucket.org/freebsd/freebsd-head/
C | 968 lines | 638 code | 117 blank | 213 comment | 173 complexity | ea91409b66d4d9233d9e88e461d817bc MD5 | raw file
  1/*
  2 * Copyright (C) 1986-2005 The Free Software Foundation, Inc.
  3 *
  4 * Portions Copyright (C) 1998-2005 Derek Price, Ximbiot <http://ximbiot.com>,
  5 *                                  and others.
  6 *
  7 * Portions Copyright (C) 1992, Brian Berliner and Jeff Polk
  8 * Portions Copyright (C) 1989-1992, Brian Berliner
  9 * 
 10 * You may distribute under the terms of the GNU General Public License as
 11 * specified in the README file that comes with the CVS source distribution.
 12 * 
 13 * Various useful functions for the CVS support code.
 14 */
 15
 16#include <assert.h>
 17#include "cvs.h"
 18#include "getline.h"
 19
 20#ifdef HAVE_NANOSLEEP
 21# include "xtime.h"
 22#else /* HAVE_NANOSLEEP */
 23# if !defined HAVE_USLEEP && defined HAVE_SELECT
 24    /* use select as a workaround */
 25#   include "xselect.h"
 26# endif /* !defined HAVE_USLEEP && defined HAVE_SELECT */
 27#endif /* !HAVE_NANOSLEEP */
 28
 29extern char *getlogin ();
 30
 31/*
 32 * malloc some data and die if it fails
 33 */
 34void *
 35xmalloc (bytes)
 36    size_t bytes;
 37{
 38    char *cp;
 39
 40    /* Parts of CVS try to xmalloc zero bytes and then free it.  Some
 41       systems have a malloc which returns NULL for zero byte
 42       allocations but a free which can't handle NULL, so compensate. */
 43    if (bytes == 0)
 44	bytes = 1;
 45
 46    cp = malloc (bytes);
 47    if (cp == NULL)
 48    {
 49	char buf[80];
 50	sprintf (buf, "out of memory; can not allocate %lu bytes",
 51		 (unsigned long) bytes);
 52	error (1, 0, buf);
 53    }
 54    return (cp);
 55}
 56
 57/*
 58 * realloc data and die if it fails [I've always wanted to have "realloc" do
 59 * a "malloc" if the argument is NULL, but you can't depend on it.  Here, I
 60 * can *force* it.]
 61 */
 62void *
 63xrealloc (ptr, bytes)
 64    void *ptr;
 65    size_t bytes;
 66{
 67    char *cp;
 68
 69    if (!ptr)
 70	cp = malloc (bytes);
 71    else
 72	cp = realloc (ptr, bytes);
 73
 74    if (cp == NULL)
 75    {
 76	char buf[80];
 77	sprintf (buf, "out of memory; can not reallocate %lu bytes",
 78		 (unsigned long) bytes);
 79	error (1, 0, buf);
 80    }
 81    return (cp);
 82}
 83
 84/* Two constants which tune expand_string.  Having MIN_INCR as large
 85   as 1024 might waste a bit of memory, but it shouldn't be too bad
 86   (CVS used to allocate arrays of, say, 3000, PATH_MAX (8192, often),
 87   or other such sizes).  Probably anything which is going to allocate
 88   memory which is likely to get as big as MAX_INCR shouldn't be doing
 89   it in one block which must be contiguous, but since getrcskey does
 90   so, we might as well limit the wasted memory to MAX_INCR or so
 91   bytes.
 92
 93   MIN_INCR and MAX_INCR should both be powers of two and we generally
 94   try to keep our allocations to powers of two for the most part.
 95   Most malloc implementations these days tend to like that.  */
 96
 97#define MIN_INCR 1024
 98#define MAX_INCR (2*1024*1024)
 99
100/* *STRPTR is a pointer returned from malloc (or NULL), pointing to *N
101   characters of space.  Reallocate it so that points to at least
102   NEWSIZE bytes of space.  Gives a fatal error if out of memory;
103   if it returns it was successful.  */
104void
105expand_string (strptr, n, newsize)
106    char **strptr;
107    size_t *n;
108    size_t newsize;
109{
110    if (*n < newsize)
111    {
112	while (*n < newsize)
113	{
114	    if (*n < MIN_INCR)
115		*n = MIN_INCR;
116	    else if (*n >= MAX_INCR)
117		*n += MAX_INCR;
118	    else
119	    {
120		*n *= 2;
121		if (*n > MAX_INCR)
122		    *n = MAX_INCR;
123	    }
124	}
125	*strptr = xrealloc (*strptr, *n);
126    }
127}
128
129/* *STR is a pointer to a malloc'd string.  *LENP is its allocated
130   length.  Add SRC to the end of it, reallocating if necessary.  */
131void
132xrealloc_and_strcat (str, lenp, src)
133    char **str;
134    size_t *lenp;
135    const char *src;
136{
137
138    expand_string (str, lenp, strlen (*str) + strlen (src) + 1);
139    strcat (*str, src);
140}
141
142/*
143 * Duplicate a string, calling xmalloc to allocate some dynamic space
144 */
145char *
146xstrdup (str)
147    const char *str;
148{
149    char *s;
150
151    if (str == NULL)
152	return ((char *) NULL);
153    s = xmalloc (strlen (str) + 1);
154    (void) strcpy (s, str);
155    return (s);
156}
157
158
159
160/* Remove trailing newlines from STRING, destructively.
161 *
162 * RETURNS
163 *
164 *   True if any newlines were removed, false otherwise.
165 */
166int
167strip_trailing_newlines (str)
168    char *str;
169{
170    size_t index, origlen;
171    index = origlen = strlen (str);
172
173    while (index > 0 && str[index-1] == '\n')
174	str[--index] = '\0';
175
176    return index != origlen;
177}
178
179
180
181/* Return the number of levels that PATH ascends above where it starts.
182 * For example:
183 *
184 *   "../../foo" -> 2
185 *   "foo/../../bar" -> 1
186 */
187int
188pathname_levels (p)
189    const char *p;
190{
191    int level;
192    int max_level;
193
194    if (p == NULL) return 0;
195
196    max_level = 0;
197    level = 0;
198    do
199    {
200	/* Now look for pathname level-ups.  */
201	if (p[0] == '.' && p[1] == '.' && (p[2] == '\0' || ISDIRSEP (p[2])))
202	{
203	    --level;
204	    if (-level > max_level)
205		max_level = -level;
206	}
207	else if (p[0] == '\0' || ISDIRSEP (p[0]) ||
208		 (p[0] == '.' && (p[1] == '\0' || ISDIRSEP (p[1]))))
209	    ;
210	else
211	    ++level;
212
213	/* q = strchr (p, '/'); but sub ISDIRSEP() for '/': */
214	while (*p != '\0' && !ISDIRSEP (*p)) p++;
215	if (*p != '\0') p++;
216    } while (*p != '\0');
217    return max_level;
218}
219
220
221
222/* Free a vector, where (*ARGV)[0], (*ARGV)[1], ... (*ARGV)[*PARGC - 1]
223   are malloc'd and so is *ARGV itself.  Such a vector is allocated by
224   line2argv or expand_wild, for example.  */
225void
226free_names (pargc, argv)
227    int *pargc;
228    char **argv;
229{
230    register int i;
231
232    for (i = 0; i < *pargc; i++)
233    {					/* only do through *pargc */
234	free (argv[i]);
235    }
236    free (argv);
237    *pargc = 0;				/* and set it to zero when done */
238}
239
240/* Convert LINE into arguments separated by SEPCHARS.  Set *ARGC
241   to the number of arguments found, and (*ARGV)[0] to the first argument,
242   (*ARGV)[1] to the second, etc.  *ARGV is malloc'd and so are each of
243   (*ARGV)[0], (*ARGV)[1], ...  Use free_names() to return the memory
244   allocated here back to the free pool.  */
245void
246line2argv (pargc, argv, line, sepchars)
247    int *pargc;
248    char ***argv;
249    char *line;
250    char *sepchars;
251{
252    char *cp;
253    /* Could make a case for size_t or some other unsigned type, but
254       we'll stick with int to avoid signed/unsigned warnings when
255       comparing with *pargc.  */
256    int argv_allocated;
257
258    /* Small for testing.  */
259    argv_allocated = 1;
260    *argv = (char **) xmalloc (argv_allocated * sizeof (**argv));
261
262    *pargc = 0;
263    for (cp = strtok (line, sepchars); cp; cp = strtok ((char *) NULL, sepchars))
264    {
265	if (*pargc == argv_allocated)
266	{
267	    argv_allocated *= 2;
268	    *argv = xrealloc (*argv, argv_allocated * sizeof (**argv));
269	}
270	(*argv)[*pargc] = xstrdup (cp);
271	(*pargc)++;
272    }
273}
274
275/*
276 * Returns the number of dots ('.') found in an RCS revision number
277 */
278int
279numdots (s)
280    const char *s;
281{
282    int dots = 0;
283
284    for (; *s; s++)
285    {
286	if (*s == '.')
287	    dots++;
288    }
289    return (dots);
290}
291
292/* Compare revision numbers REV1 and REV2 by consecutive fields.
293   Return negative, zero, or positive in the manner of strcmp.  The
294   two revision numbers must have the same number of fields, or else
295   compare_revnums will return an inaccurate result. */
296int
297compare_revnums (rev1, rev2)
298    const char *rev1;
299    const char *rev2;
300{
301    const char *sp, *tp;
302    char *snext, *tnext;
303    int result = 0;
304
305    sp = rev1;
306    tp = rev2;
307    while (result == 0)
308    {
309	result = strtoul (sp, &snext, 10) - strtoul (tp, &tnext, 10);
310	if (*snext == '\0' || *tnext == '\0')
311	    break;
312	sp = snext + 1;
313	tp = tnext + 1;
314    }
315
316    return result;
317}
318
319/* Increment a revision number.  Working on the string is a bit awkward,
320   but it avoid problems with integer overflow should the revision numbers
321   get really big.  */
322char *
323increment_revnum (rev)
324    const char *rev;
325{
326    char *newrev, *p;
327    size_t len = strlen (rev);
328
329    newrev = xmalloc (len + 2);
330    memcpy (newrev, rev, len + 1);
331    for (p = newrev + len; p != newrev; )
332    {
333	--p;
334	if (!isdigit(*p))
335	{
336	    ++p;
337	    break;
338	}
339	if (*p != '9')
340	{
341	    ++*p;
342	    return newrev;
343	}
344	*p = '0';
345    }
346    /* The number was all 9s, so change the first character to 1 and add
347       a 0 to the end.  */
348    *p = '1';
349    p = newrev + len;
350    *p++ = '0';
351    *p = '\0';
352    return newrev;
353}
354
355/* Return the username by which the caller should be identified in
356   CVS, in contexts such as the author field of RCS files, various
357   logs, etc.  */
358char *
359getcaller ()
360{
361#ifndef SYSTEM_GETCALLER
362    static char *cache;
363    struct passwd *pw;
364    uid_t uid;
365#endif
366
367    /* If there is a CVS username, return it.  */
368#ifdef AUTH_SERVER_SUPPORT
369    if (CVS_Username != NULL)
370	return CVS_Username;
371#endif
372
373#ifdef SYSTEM_GETCALLER
374    return SYSTEM_GETCALLER ();
375#else
376    /* Get the caller's login from his uid.  If the real uid is "root"
377       try LOGNAME USER or getlogin(). If getlogin() and getpwuid()
378       both fail, return the uid as a string.  */
379
380    if (cache != NULL)
381	return cache;
382
383    uid = getuid ();
384    if (uid == (uid_t) 0)
385    {
386	char *name;
387
388	/* super-user; try getlogin() to distinguish */
389	if (((name = getlogin ()) || (name = getenv("LOGNAME")) ||
390	     (name = getenv("USER"))) && *name)
391	{
392	    cache = xstrdup (name);
393	    return cache;
394	}
395    }
396    if ((pw = (struct passwd *) getpwuid (uid)) == NULL)
397    {
398	char uidname[20];
399
400	(void) sprintf (uidname, "uid%lu", (unsigned long) uid);
401	cache = xstrdup (uidname);
402	return cache;
403    }
404    cache = xstrdup (pw->pw_name);
405    return cache;
406#endif
407}
408
409#ifdef lint
410#ifndef __GNUC__
411/* ARGSUSED */
412time_t
413get_date (date, now)
414    char *date;
415    struct timeb *now;
416{
417    time_t foo = 0;
418
419    return (foo);
420}
421#endif
422#endif
423
424
425
426/* Given some revision, REV, return the first prior revision that exists in the
427 * RCS file, RCS.
428 *
429 * ASSUMPTIONS
430 *   REV exists.
431 *
432 * INPUTS
433 *   RCS	The RCS node pointer.
434 *   REV	An existing revision in the RCS file referred to by RCS.
435 *
436 * RETURNS
437 *   The first prior revision that exists in the RCS file, or NULL if no prior
438 *   revision exists.  The caller is responsible for disposing of this string.
439 *
440 * NOTES
441 *   This function currently neglects the case where we are on the trunk with
442 *   rev = X.1, where X != 1.  If rev = X.Y, where X != 1 and Y > 1, then this
443 *   function should work fine, as revision X.1 must exist, due to RCS rules.
444 */
445char *
446previous_rev (rcs, rev)
447    RCSNode *rcs;
448    const char *rev;
449{
450    char *p;
451    char *tmp = xstrdup (rev);
452    long r1;
453    char *retval;
454
455    /* Our retval can have no more digits and dots than our input revision.  */
456    retval = xmalloc (strlen (rev) + 1);
457    p = strrchr (tmp, '.');
458    *p = '\0';
459    r1 = strtol (p+1, NULL, 10);
460    do {
461	if (--r1 == 0)
462	{
463		/* If r1 == 0, then we must be on a branch and our parent must
464		 * exist, or we must be on the trunk with a REV like X.1.
465		 * We are neglecting the X.1 with X != 1 case by assuming that
466		 * there is no previous revision when we discover we were on
467		 * the trunk.
468		 */
469		p = strrchr (tmp, '.');
470		if (p == NULL)
471		    /* We are on the trunk.  */
472		    retval = NULL;
473		else
474		{
475		    *p = '\0';
476		    sprintf (retval, "%s", tmp);
477		}
478		break;
479	}
480	sprintf (retval, "%s.%ld", tmp, r1);
481    } while (!RCS_exist_rev (rcs, retval));
482
483    free (tmp);
484    return retval;
485}
486
487
488
489/* Given two revisions, find their greatest common ancestor.  If the
490   two input revisions exist, then rcs guarantees that the gca will
491   exist.  */
492
493char *
494gca (rev1, rev2)
495    const char *rev1;
496    const char *rev2;
497{
498    int dots;
499    char *gca, *g;
500    const char *p1, *p2;
501    int r1, r2;
502    char *retval;
503
504    if (rev1 == NULL || rev2 == NULL)
505    {
506	error (0, 0, "sanity failure in gca");
507	abort();
508    }
509
510    /* The greatest common ancestor will have no more dots, and numbers
511       of digits for each component no greater than the arguments.  Therefore
512       this string will be big enough.  */
513    g = gca = xmalloc (strlen (rev1) + strlen (rev2) + 100);
514
515    /* walk the strings, reading the common parts. */
516    p1 = rev1;
517    p2 = rev2;
518    do
519    {
520	r1 = strtol (p1, (char **) &p1, 10);
521	r2 = strtol (p2, (char **) &p2, 10);
522	
523	/* use the lowest. */
524	(void) sprintf (g, "%d.", r1 < r2 ? r1 : r2);
525	g += strlen (g);
526	if (*p1 == '.') ++p1;
527	else break;
528	if (*p2 == '.') ++p2;
529	else break;
530    } while (r1 == r2);
531
532    /* erase that last dot. */
533    *--g = '\0';
534
535    /* numbers differ, or we ran out of strings.  we're done with the
536       common parts.  */
537
538    dots = numdots (gca);
539    if (dots == 0)
540    {
541	/* revisions differ in trunk major number.  */
542
543	if (r2 < r1) p1 = p2;
544	if (*p1 == '\0')
545	{
546	    /* we only got one number.  this is strange.  */
547	    error (0, 0, "bad revisions %s or %s", rev1, rev2);
548	    abort();
549	}
550	else
551	{
552	    /* we have a minor number.  use it.  */
553	    *g++ = '.';
554	    while (*p1 != '.' && *p1 != '\0')
555		*g++ = *p1++;
556	    *g = '\0';
557	}
558    }
559    else if ((dots & 1) == 0)
560    {
561	/* if we have an even number of dots, then we have a branch.
562	   remove the last number in order to make it a revision.  */
563	
564	g = strrchr (gca, '.');
565	*g = '\0';
566    }
567
568    retval = xstrdup (gca);
569    free (gca);
570    return retval;
571}
572
573/* Give fatal error if REV is numeric and ARGC,ARGV imply we are
574   planning to operate on more than one file.  The current directory
575   should be the working directory.  Note that callers assume that we
576   will only be checking the first character of REV; it need not have
577   '\0' at the end of the tag name and other niceties.  Right now this
578   is only called from admin.c, but if people like the concept it probably
579   should also be called from diff -r, update -r, get -r, and log -r.  */
580
581void
582check_numeric (rev, argc, argv)
583    const char *rev;
584    int argc;
585    char **argv;
586{
587    if (rev == NULL || !isdigit ((unsigned char) *rev))
588	return;
589
590    /* Note that the check for whether we are processing more than one
591       file is (basically) syntactic; that is, we don't behave differently
592       depending on whether a directory happens to contain only a single
593       file or whether it contains more than one.  I strongly suspect this
594       is the least confusing behavior.  */
595    if (argc != 1
596	|| (!wrap_name_has (argv[0], WRAP_TOCVS) && isdir (argv[0])))
597    {
598	error (0, 0, "while processing more than one file:");
599	error (1, 0, "attempt to specify a numeric revision");
600    }
601}
602
603/*
604 *  Sanity checks and any required fix-up on message passed to RCS via '-m'.
605 *  RCS 5.7 requires that a non-total-whitespace, non-null message be provided
606 *  with '-m'.  Returns a newly allocated, non-empty buffer with whitespace
607 *  stripped from end of lines and end of buffer.
608 *
609 *  TODO: We no longer use RCS to manage repository files, so maybe this
610 *  nonsense about non-empty log fields can be dropped.
611 */
612char *
613make_message_rcslegal (message)
614     const char *message;
615{
616    char *dst, *dp;
617    const char *mp;
618
619    if (message == NULL) message = "";
620
621    /* Strip whitespace from end of lines and end of string. */
622    dp = dst = (char *) xmalloc (strlen (message) + 1);
623    for (mp = message; *mp != '\0'; ++mp)
624    {
625	if (*mp == '\n')
626	{
627	    /* At end-of-line; backtrack to last non-space. */
628	    while (dp > dst && (dp[-1] == ' ' || dp[-1] == '\t'))
629		--dp;
630	}
631	*dp++ = *mp;
632    }
633
634    /* Backtrack to last non-space at end of string, and truncate. */
635    while (dp > dst && isspace ((unsigned char) dp[-1]))
636	--dp;
637    *dp = '\0';
638
639    /* After all that, if there was no non-space in the string,
640       substitute a non-empty message. */
641    if (*dst == '\0')
642    {
643	free (dst);
644	dst = xstrdup ("*** empty log message ***");
645    }
646
647    return dst;
648}
649
650
651
652/* Does the file FINFO contain conflict markers?  The whole concept
653   of looking at the contents of the file to figure out whether there are
654   unresolved conflicts is kind of bogus (people do want to manage files
655   which contain those patterns not as conflict markers), but for now it
656   is what we do.  */
657int
658file_has_markers (finfo)
659    const struct file_info *finfo;
660{
661    FILE *fp;
662    char *line = NULL;
663    size_t line_allocated = 0;
664    int result;
665
666    result = 0;
667    fp = CVS_FOPEN (finfo->file, "r");
668    if (fp == NULL)
669	error (1, errno, "cannot open %s", finfo->fullname);
670    while (getline (&line, &line_allocated, fp) > 0)
671    {
672	if (strncmp (line, RCS_MERGE_PAT_1, sizeof RCS_MERGE_PAT_1 - 1) == 0 ||
673	    strncmp (line, RCS_MERGE_PAT_2, sizeof RCS_MERGE_PAT_2 - 1) == 0 ||
674	    strncmp (line, RCS_MERGE_PAT_3, sizeof RCS_MERGE_PAT_3 - 1) == 0)
675	{
676	    result = 1;
677	    goto out;
678	}
679    }
680    if (ferror (fp))
681	error (0, errno, "cannot read %s", finfo->fullname);
682out:
683    if (fclose (fp) < 0)
684	error (0, errno, "cannot close %s", finfo->fullname);
685    if (line != NULL)
686	free (line);
687    return result;
688}
689
690/* Read the entire contents of the file NAME into *BUF.
691   If NAME is NULL, read from stdin.  *BUF
692   is a pointer returned from malloc (or NULL), pointing to *BUFSIZE
693   bytes of space.  The actual size is returned in *LEN.  On error,
694   give a fatal error.  The name of the file to use in error messages
695   (typically will include a directory if we have changed directory)
696   is FULLNAME.  MODE is "r" for text or "rb" for binary.  */
697
698void
699get_file (name, fullname, mode, buf, bufsize, len)
700    const char *name;
701    const char *fullname;
702    const char *mode;
703    char **buf;
704    size_t *bufsize;
705    size_t *len;
706{
707    struct stat s;
708    size_t nread;
709    char *tobuf;
710    FILE *e;
711    size_t filesize;
712
713    if (name == NULL)
714    {
715	e = stdin;
716	filesize = 100;	/* force allocation of minimum buffer */
717    }
718    else
719    {
720	/* Although it would be cleaner in some ways to just read
721	   until end of file, reallocating the buffer, this function
722	   does get called on files in the working directory which can
723	   be of arbitrary size, so I think we better do all that
724	   extra allocation.  */
725
726	if (CVS_STAT (name, &s) < 0)
727	    error (1, errno, "can't stat %s", fullname);
728
729	/* Convert from signed to unsigned.  */
730	filesize = s.st_size;
731
732	e = open_file (name, mode);
733    }
734
735    if (*buf == NULL || *bufsize <= filesize)
736    {
737	*bufsize = filesize + 1;
738	*buf = xrealloc (*buf, *bufsize);
739    }
740
741    tobuf = *buf;
742    nread = 0;
743    while (1)
744    {
745	size_t got;
746
747	got = fread (tobuf, 1, *bufsize - (tobuf - *buf), e);
748	if (ferror (e))
749	    error (1, errno, "can't read %s", fullname);
750	nread += got;
751	tobuf += got;
752
753	if (feof (e))
754	    break;
755
756	/* Allocate more space if needed.  */
757	if (tobuf == *buf + *bufsize)
758	{
759	    int c;
760	    long off;
761
762	    c = getc (e);
763	    if (c == EOF)
764		break;
765	    off = tobuf - *buf;
766	    expand_string (buf, bufsize, *bufsize + 100);
767	    tobuf = *buf + off;
768	    *tobuf++ = c;
769	    ++nread;
770	}
771    }
772
773    if (e != stdin && fclose (e) < 0)
774	error (0, errno, "cannot close %s", fullname);
775
776    *len = nread;
777
778    /* Force *BUF to be large enough to hold a null terminator. */
779    if (nread == *bufsize)
780	expand_string (buf, bufsize, *bufsize + 1);
781    (*buf)[nread] = '\0';
782}
783
784
785/* Follow a chain of symbolic links to its destination.  FILENAME
786   should be a handle to a malloc'd block of memory which contains the
787   beginning of the chain.  This routine will replace the contents of
788   FILENAME with the destination (a real file).  */
789
790void
791resolve_symlink (filename)
792     char **filename;
793{
794    if (filename == NULL || *filename == NULL)
795	return;
796
797    while (islink (*filename))
798    {
799#ifdef HAVE_READLINK
800	/* The clean thing to do is probably to have each filesubr.c
801	   implement this (with an error if not supported by the
802	   platform, in which case islink would presumably return 0).
803	   But that would require editing each filesubr.c and so the
804	   expedient hack seems to be looking at HAVE_READLINK.  */
805	char *newname = xreadlink (*filename);
806	
807	if (isabsolute (newname))
808	{
809	    free (*filename);
810	    *filename = newname;
811	}
812	else
813	{
814	    const char *oldname = last_component (*filename);
815	    int dirlen = oldname - *filename;
816	    char *fullnewname = xmalloc (dirlen + strlen (newname) + 1);
817	    strncpy (fullnewname, *filename, dirlen);
818	    strcpy (fullnewname + dirlen, newname);
819	    free (newname);
820	    free (*filename);
821	    *filename = fullnewname;
822	}
823#else
824	error (1, 0, "internal error: islink doesn't like readlink");
825#endif
826    }
827}
828
829/*
830 * Rename a file to an appropriate backup name based on BAKPREFIX.
831 * If suffix non-null, then ".<suffix>" is appended to the new name.
832 *
833 * Returns the new name, which caller may free() if desired.
834 */
835char *
836backup_file (filename, suffix)
837     const char *filename;
838     const char *suffix;
839{
840    char *backup_name;
841
842    if (suffix == NULL)
843    {
844        backup_name = xmalloc (sizeof (BAKPREFIX) + strlen (filename) + 1);
845        sprintf (backup_name, "%s%s", BAKPREFIX, filename);
846    }
847    else
848    {
849        backup_name = xmalloc (sizeof (BAKPREFIX)
850                               + strlen (filename)
851                               + strlen (suffix)
852                               + 2);  /* one for dot, one for trailing '\0' */
853        sprintf (backup_name, "%s%s.%s", BAKPREFIX, filename, suffix);
854    }
855
856    if (isfile (filename))
857        copy_file (filename, backup_name);
858
859    return backup_name;
860}
861
862/*
863 * Copy a string into a buffer escaping any shell metacharacters.  The
864 * buffer should be at least twice as long as the string.
865 *
866 * Returns a pointer to the terminating NUL byte in buffer.
867 */
868
869char *
870shell_escape(buf, str)
871    char *buf;
872    const char *str;
873{
874    static const char meta[] = "$`\\\"";
875    const char *p;
876
877    for (;;)
878    {
879	p = strpbrk(str, meta);
880	if (!p) p = str + strlen(str);
881	if (p > str)
882	{
883	    memcpy(buf, str, p - str);
884	    buf += p - str;
885	}
886	if (!*p) break;
887	*buf++ = '\\';
888	*buf++ = *p++;
889	str = p;
890    }
891    *buf = '\0';
892    return buf;
893}
894
895
896
897/*
898 * We can only travel forwards in time, not backwards.  :)
899 */
900void
901sleep_past (desttime)
902    time_t desttime;
903{
904    time_t t;
905    long s;
906    long us;
907
908    while (time (&t) <= desttime)
909    {
910#ifdef HAVE_GETTIMEOFDAY
911	struct timeval tv;
912	gettimeofday (&tv, NULL);
913	if (tv.tv_sec > desttime)
914	    break;
915	s = desttime - tv.tv_sec;
916	if (tv.tv_usec > 0)
917	    us = 1000000 - tv.tv_usec;
918	else
919	{
920	    s++;
921	    us = 0;
922	}
923#else
924	/* default to 20 ms increments */
925	s = desttime - t;
926	us = 20000;
927#endif
928
929#if defined(HAVE_NANOSLEEP)
930	{
931	    struct timespec ts;
932	    ts.tv_sec = s;
933	    ts.tv_nsec = us * 1000;
934	    (void)nanosleep (&ts, NULL);
935	}
936#elif defined(HAVE_USLEEP)
937	if (s > 0)
938	    (void)sleep (s);
939	else
940	    (void)usleep (us);
941#elif defined(HAVE_SELECT)
942	{
943	    /* use select instead of sleep since it is a fairly portable way of
944	     * sleeping for ms.
945	     */
946	    struct timeval tv;
947	    tv.tv_sec = s;
948	    tv.tv_usec = us;
949	    (void)select (0, (fd_set *)NULL, (fd_set *)NULL, (fd_set *)NULL,
950                          &tv);
951	}
952#else
953	if (us > 0) s++;
954	(void)sleep(s);
955#endif
956    }
957}
958
959
960
961/* Return non-zero iff FILENAME is absolute.
962   Trivial under Unix, but more complicated under other systems.  */
963int
964isabsolute (filename)
965    const char *filename;
966{
967    return ISABSOLUTE (filename);
968}