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