2 * Copyright (C) 1986-2005 The Free Software Foundation, Inc.
4 * Portions Copyright (C) 1998-2005 Derek Price, Ximbiot <http://ximbiot.com>,
7 * Portions Copyright (C) 1992, Brian Berliner and Jeff Polk
8 * Portions Copyright (C) 1989-1992, Brian Berliner
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.
13 * Various useful functions for the CVS support code.
22 #else /* HAVE_NANOSLEEP */
23 # if !defined HAVE_USLEEP && defined HAVE_SELECT
24 /* use select as a workaround */
26 # endif /* !defined HAVE_USLEEP && defined HAVE_SELECT */
27 #endif /* !HAVE_NANOSLEEP */
29 extern char *getlogin ();
32 * malloc some data and die if it fails
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. */
50 sprintf (buf, "out of memory; can not allocate %lu bytes",
51 (unsigned long) bytes);
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
72 cp = realloc (ptr, bytes);
77 sprintf (buf, "out of memory; can not reallocate %lu bytes",
78 (unsigned long) bytes);
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
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. */
98 #define MAX_INCR (2*1024*1024)
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. */
105 expand_string (strptr, n, newsize)
116 else if (*n >= MAX_INCR)
125 *strptr = xrealloc (*strptr, *n);
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. */
132 xrealloc_and_strcat (str, lenp, src)
138 expand_string (str, lenp, strlen (*str) + strlen (src) + 1);
143 * Duplicate a string, calling xmalloc to allocate some dynamic space
152 return ((char *) NULL);
153 s = xmalloc (strlen (str) + 1);
154 (void) strcpy (s, str);
160 /* Remove trailing newlines from STRING, destructively.
164 * True if any newlines were removed, false otherwise.
167 strip_trailing_newlines (str)
170 size_t index, origlen;
171 index = origlen = strlen (str);
173 while (index > 0 && str[index-1] == '\n')
176 return index != origlen;
181 /* Return the number of levels that PATH ascends above where it starts.
185 * "foo/../../bar" -> 1
194 if (p == NULL) return 0;
200 /* Now look for pathname level-ups. */
201 if (p[0] == '.' && p[1] == '.' && (p[2] == '\0' || ISDIRSEP (p[2])))
204 if (-level > max_level)
207 else if (p[0] == '\0' || ISDIRSEP (p[0]) ||
208 (p[0] == '.' && (p[1] == '\0' || ISDIRSEP (p[1]))))
213 /* q = strchr (p, '/'); but sub ISDIRSEP() for '/': */
214 while (*p != '\0' && !ISDIRSEP (*p)) p++;
216 } while (*p != '\0');
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. */
226 free_names (pargc, argv)
232 for (i = 0; i < *pargc; i++)
233 { /* only do through *pargc */
237 *pargc = 0; /* and set it to zero when done */
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. */
246 line2argv (pargc, argv, line, sepchars)
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. */
258 /* Small for testing. */
260 *argv = (char **) xmalloc (argv_allocated * sizeof (**argv));
263 for (cp = strtok (line, sepchars); cp; cp = strtok ((char *) NULL, sepchars))
265 if (*pargc == argv_allocated)
268 *argv = xrealloc (*argv, argv_allocated * sizeof (**argv));
270 (*argv)[*pargc] = xstrdup (cp);
276 * Returns the number of dots ('.') found in an RCS revision number
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. */
297 compare_revnums (rev1, rev2)
309 result = strtoul (sp, &snext, 10) - strtoul (tp, &tnext, 10);
310 if (*snext == '\0' || *tnext == '\0')
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
323 increment_revnum (rev)
327 size_t len = strlen (rev);
329 newrev = xmalloc (len + 2);
330 memcpy (newrev, rev, len + 1);
331 for (p = newrev + len; p != newrev; )
346 /* The number was all 9s, so change the first character to 1 and add
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
361 #ifndef SYSTEM_GETCALLER
367 /* If there is a CVS username, return it. */
368 #ifdef AUTH_SERVER_SUPPORT
369 if (CVS_Username != NULL)
373 #ifdef SYSTEM_GETCALLER
374 return SYSTEM_GETCALLER ();
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. */
384 if (uid == (uid_t) 0)
388 /* super-user; try getlogin() to distinguish */
389 if (((name = getlogin ()) || (name = getenv("LOGNAME")) ||
390 (name = getenv("USER"))) && *name)
392 cache = xstrdup (name);
396 if ((pw = (struct passwd *) getpwuid (uid)) == NULL)
400 (void) sprintf (uidname, "uid%lu", (unsigned long) uid);
401 cache = xstrdup (uidname);
404 cache = xstrdup (pw->pw_name);
426 /* Given some revision, REV, return the first prior revision that exists in the
433 * RCS The RCS node pointer.
434 * REV An existing revision in the RCS file referred to by RCS.
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.
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.
446 previous_rev (rcs, rev)
451 char *tmp = xstrdup (rev);
455 /* Our retval can have no more digits and dots than our input revision. */
456 retval = xmalloc (strlen (rev) + 1);
457 p = strrchr (tmp, '.');
459 r1 = strtol (p+1, NULL, 10);
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
469 p = strrchr (tmp, '.');
471 /* We are on the trunk. */
476 sprintf (retval, "%s", tmp);
480 sprintf (retval, "%s.%ld", tmp, r1);
481 } while (!RCS_exist_rev (rcs, retval));
489 /* Given two revisions, find their greatest common ancestor. If the
490 two input revisions exist, then rcs guarantees that the gca will
504 if (rev1 == NULL || rev2 == NULL)
506 error (0, 0, "sanity failure in gca");
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);
515 /* walk the strings, reading the common parts. */
520 r1 = strtol (p1, (char **) &p1, 10);
521 r2 = strtol (p2, (char **) &p2, 10);
523 /* use the lowest. */
524 (void) sprintf (g, "%d.", r1 < r2 ? r1 : r2);
526 if (*p1 == '.') ++p1;
528 if (*p2 == '.') ++p2;
532 /* erase that last dot. */
535 /* numbers differ, or we ran out of strings. we're done with the
538 dots = numdots (gca);
541 /* revisions differ in trunk major number. */
543 if (r2 < r1) p1 = p2;
546 /* we only got one number. this is strange. */
547 error (0, 0, "bad revisions %s or %s", rev1, rev2);
552 /* we have a minor number. use it. */
554 while (*p1 != '.' && *p1 != '\0')
559 else if ((dots & 1) == 0)
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. */
564 g = strrchr (gca, '.');
568 retval = xstrdup (gca);
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. */
582 check_numeric (rev, argc, argv)
587 if (rev == NULL || !isdigit ((unsigned char) *rev))
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. */
596 || (!wrap_name_has (argv[0], WRAP_TOCVS) && isdir (argv[0])))
598 error (0, 0, "while processing more than one file:");
599 error (1, 0, "attempt to specify a numeric revision");
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.
609 * TODO: We no longer use RCS to manage repository files, so maybe this
610 * nonsense about non-empty log fields can be dropped.
613 make_message_rcslegal (message)
619 if (message == NULL) message = "";
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)
627 /* At end-of-line; backtrack to last non-space. */
628 while (dp > dst && (dp[-1] == ' ' || dp[-1] == '\t'))
634 /* Backtrack to last non-space at end of string, and truncate. */
635 while (dp > dst && isspace ((unsigned char) dp[-1]))
639 /* After all that, if there was no non-space in the string,
640 substitute a non-empty message. */
644 dst = xstrdup ("*** empty log message ***");
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
658 file_has_markers (finfo)
659 const struct file_info *finfo;
663 size_t line_allocated = 0;
667 fp = CVS_FOPEN (finfo->file, "r");
669 error (1, errno, "cannot open %s", finfo->fullname);
670 while (getline (&line, &line_allocated, fp) > 0)
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)
681 error (0, errno, "cannot read %s", finfo->fullname);
684 error (0, errno, "cannot close %s", finfo->fullname);
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. */
699 get_file (name, fullname, mode, buf, bufsize, len)
701 const char *fullname;
716 filesize = 100; /* force allocation of minimum buffer */
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
726 if (CVS_STAT (name, &s) < 0)
727 error (1, errno, "can't stat %s", fullname);
729 /* Convert from signed to unsigned. */
730 filesize = s.st_size;
732 e = open_file (name, mode);
735 if (*buf == NULL || *bufsize <= filesize)
737 *bufsize = filesize + 1;
738 *buf = xrealloc (*buf, *bufsize);
747 got = fread (tobuf, 1, *bufsize - (tobuf - *buf), e);
749 error (1, errno, "can't read %s", fullname);
756 /* Allocate more space if needed. */
757 if (tobuf == *buf + *bufsize)
766 expand_string (buf, bufsize, *bufsize + 100);
773 if (e != stdin && fclose (e) < 0)
774 error (0, errno, "cannot close %s", fullname);
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';
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). */
791 resolve_symlink (filename)
794 if (filename == NULL || *filename == NULL)
797 while (islink (*filename))
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);
807 if (isabsolute (newname))
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);
821 *filename = fullnewname;
824 error (1, 0, "internal error: islink doesn't like readlink");
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.
833 * Returns the new name, which caller may free() if desired.
836 backup_file (filename, suffix)
837 const char *filename;
844 backup_name = xmalloc (sizeof (BAKPREFIX) + strlen (filename) + 1);
845 sprintf (backup_name, "%s%s", BAKPREFIX, filename);
849 backup_name = xmalloc (sizeof (BAKPREFIX)
852 + 2); /* one for dot, one for trailing '\0' */
853 sprintf (backup_name, "%s%s.%s", BAKPREFIX, filename, suffix);
856 if (isfile (filename))
857 copy_file (filename, backup_name);
863 * Copy a string into a buffer escaping any shell metacharacters. The
864 * buffer should be at least twice as long as the string.
866 * Returns a pointer to the terminating NUL byte in buffer.
870 shell_escape(buf, str)
874 static const char meta[] = "$`\\\"";
879 p = strpbrk(str, meta);
880 if (!p) p = str + strlen(str);
883 memcpy(buf, str, p - str);
898 * We can only travel forwards in time, not backwards. :)
901 sleep_past (desttime)
908 while (time (&t) <= desttime)
910 #ifdef HAVE_GETTIMEOFDAY
912 gettimeofday (&tv, NULL);
913 if (tv.tv_sec > desttime)
915 s = desttime - tv.tv_sec;
917 us = 1000000 - tv.tv_usec;
924 /* default to 20 ms increments */
929 #if defined(HAVE_NANOSLEEP)
933 ts.tv_nsec = us * 1000;
934 (void)nanosleep (&ts, NULL);
936 #elif defined(HAVE_USLEEP)
941 #elif defined(HAVE_SELECT)
943 /* use select instead of sleep since it is a fairly portable way of
949 (void)select (0, (fd_set *)NULL, (fd_set *)NULL, (fd_set *)NULL,
961 /* Return non-zero iff FILENAME is absolute.
962 Trivial under Unix, but more complicated under other systems. */
964 isabsolute (filename)
965 const char *filename;
967 return ISABSOLUTE (filename);