2 * Utility routines used in rsync.
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7 * Copyright (C) 2003-2007 Wayne Davison
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
28 extern int modify_window;
29 extern int relative_paths;
30 extern int human_readable;
31 extern unsigned int module_dirlen;
32 extern mode_t orig_umask;
33 extern char *partial_dir;
34 extern struct filter_list_struct server_filter_list;
36 int sanitize_paths = 0;
38 char curr_dir[MAXPATHLEN];
39 unsigned int curr_dir_len;
40 int curr_dir_depth; /* This is only set for a sanitizing daemon. */
42 /* Set a fd into nonblocking mode. */
43 void set_nonblocking(int fd)
47 if ((val = fcntl(fd, F_GETFL)) == -1)
49 if (!(val & NONBLOCK_FLAG)) {
51 fcntl(fd, F_SETFL, val);
55 /* Set a fd into blocking mode. */
56 void set_blocking(int fd)
60 if ((val = fcntl(fd, F_GETFL)) == -1)
62 if (val & NONBLOCK_FLAG) {
63 val &= ~NONBLOCK_FLAG;
64 fcntl(fd, F_SETFL, val);
69 * Create a file descriptor pair - like pipe() but use socketpair if
70 * possible (because of blocking issues on pipes).
72 * Always set non-blocking.
74 int fd_pair(int fd[2])
78 #ifdef HAVE_SOCKETPAIR
79 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
85 set_nonblocking(fd[0]);
86 set_nonblocking(fd[1]);
92 void print_child_argv(char **cmd)
94 rprintf(FCLIENT, "opening connection using ");
96 /* Look for characters that ought to be quoted. This
97 * is not a great quoting algorithm, but it's
98 * sufficient for a log message. */
99 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
100 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
102 ",.-_=+@/") != strlen(*cmd)) {
103 rprintf(FCLIENT, "\"%s\" ", *cmd);
105 rprintf(FCLIENT, "%s ", *cmd);
108 rprintf(FCLIENT, "\n");
111 NORETURN void out_of_memory(const char *str)
113 rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
114 exit_cleanup(RERR_MALLOC);
117 NORETURN void overflow_exit(const char *str)
119 rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
120 exit_cleanup(RERR_MALLOC);
123 int set_modtime(const char *fname, time_t modtime, mode_t mode)
125 #if !defined HAVE_LUTIMES || !defined HAVE_UTIMES
131 rprintf(FINFO, "set modtime of %s to (%ld) %s",
132 fname, (long)modtime,
133 asctime(localtime(&modtime)));
142 t[0].tv_sec = time(NULL);
144 t[1].tv_sec = modtime;
149 return 0; /* ignore errors */
152 return utimes(fname, t);
153 #elif defined HAVE_UTIMBUF
155 tbuf.actime = time(NULL);
156 tbuf.modtime = modtime;
157 return utime(fname,&tbuf);
158 #elif defined HAVE_UTIME
162 return utime(fname,t);
164 #error No file-time-modification routine found!
169 /* This creates a new directory with default permissions. Since there
170 * might be some directory-default permissions affecting this, we can't
171 * force the permissions directly using the original umask and mkdir(). */
172 int mkdir_defmode(char *fname)
177 ret = do_mkdir(fname, ACCESSPERMS);
183 /* Create any necessary directories in fname. Any missing directories are
184 * created with default permissions. */
185 int create_directory_path(char *fname)
190 while (*fname == '/')
192 while (strncmp(fname, "./", 2) == 0)
197 while ((p = strchr(p,'/')) != NULL) {
199 if (do_mkdir(fname, ACCESSPERMS) < 0 && errno != EEXIST)
209 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
212 * @retval len upon success
214 * @retval <0 write's (negative) error code
216 * Derived from GNU C's cccp.c.
218 int full_write(int desc, const char *ptr, size_t len)
224 int written = write(desc, ptr, len);
230 total_written += written;
234 return total_written;
238 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
241 * @retval >0 the actual number of bytes read
245 * @retval <0 for an error.
247 * Derived from GNU C's cccp.c. */
248 static int safe_read(int desc, char *ptr, size_t len)
256 n_chars = read(desc, ptr, len);
257 } while (n_chars < 0 && errno == EINTR);
264 * This is used in conjunction with the --temp-dir, --backup, and
265 * --copy-dest options. */
266 int copy_file(const char *source, const char *dest, mode_t mode)
271 int len; /* Number of bytes read into `buf'. */
273 ifd = do_open(source, O_RDONLY, 0);
275 rsyserr(FERROR, errno, "open %s", full_fname(source));
279 if (robust_unlink(dest) && errno != ENOENT) {
280 rsyserr(FERROR, errno, "unlink %s", full_fname(dest));
284 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
286 rsyserr(FERROR, errno, "open %s", full_fname(dest));
291 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
292 if (full_write(ofd, buf, len) < 0) {
293 rsyserr(FERROR, errno, "write %s", full_fname(dest));
301 rsyserr(FERROR, errno, "read %s", full_fname(source));
307 if (close(ifd) < 0) {
308 rsyserr(FINFO, errno, "close failed on %s",
312 if (close(ofd) < 0) {
313 rsyserr(FERROR, errno, "close failed on %s",
321 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
322 #define MAX_RENAMES_DIGITS 3
323 #define MAX_RENAMES 1000
326 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
327 * rename to <path>/.rsyncNNN instead.
329 * Note that successive rsync runs will shuffle the filenames around a
330 * bit as long as the file is still busy; this is because this function
331 * does not know if the unlink call is due to a new file coming in, or
332 * --delete trying to remove old .rsyncNNN files, hence it renames it
335 int robust_unlink(const char *fname)
338 return do_unlink(fname);
340 static int counter = 1;
342 char path[MAXPATHLEN];
344 rc = do_unlink(fname);
345 if (rc == 0 || errno != ETXTBSY)
348 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
349 pos = MAXPATHLEN - 1;
351 while (pos > 0 && path[pos-1] != '/')
353 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
355 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
360 /* start where the last one left off to reduce chance of clashes */
363 snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
364 if (++counter >= MAX_RENAMES)
366 } while ((rc = access(path, 0)) == 0 && counter != start);
369 rprintf(FINFO,"renaming %s to %s because of text busy\n",
373 /* maybe we should return rename()'s exit status? Nah. */
374 if (do_rename(fname, path) != 0) {
382 /* Returns 0 on successful rename, 1 if we successfully copied the file
383 * across filesystems, -2 if copy_file() failed, and -1 on other errors.
384 * If partialptr is not NULL and we need to do a copy, copy the file into
385 * the active partial-dir instead of over the destination file. */
386 int robust_rename(const char *from, const char *to, const char *partialptr,
392 if (do_rename(from, to) == 0)
398 if (robust_unlink(to) != 0)
404 if (!handle_partial_dir(partialptr,PDIR_CREATE))
408 if (copy_file(from, to, mode) != 0)
419 static pid_t all_pids[10];
422 /** Fork and record the pid of the child. **/
425 pid_t newpid = fork();
427 if (newpid != 0 && newpid != -1) {
428 all_pids[num_pids++] = newpid;
436 * @todo It would be kind of nice to make sure that they are actually
437 * all our children before we kill them, because their pids may have
438 * been recycled by some other process. Perhaps when we wait for a
439 * child, we should remove it from this array. Alternatively we could
440 * perhaps use process groups, but I think that would not work on
441 * ancient Unix versions that don't support them.
443 void kill_all(int sig)
447 for (i = 0; i < num_pids; i++) {
448 /* Let's just be a little careful where we
449 * point that gun, hey? See kill(2) for the
450 * magic caused by negative values. */
451 pid_t p = all_pids[i];
462 /** Turn a user name into a uid */
463 int name_to_uid(const char *name, uid_t *uid)
468 pass = getpwnam(name);
476 /** Turn a group name into a gid */
477 int name_to_gid(const char *name, gid_t *gid)
482 grp = getgrnam(name);
490 /** Lock a byte range in a open file */
491 int lock_range(int fd, int offset, int len)
495 lock.l_type = F_WRLCK;
496 lock.l_whence = SEEK_SET;
497 lock.l_start = offset;
501 return fcntl(fd,F_SETLK,&lock) == 0;
504 static int filter_server_path(char *arg)
508 if (server_filter_list.head) {
509 for (s = arg; (s = strchr(s, '/')) != NULL; ) {
511 if (check_filter(&server_filter_list, arg, 1) < 0) {
512 /* We must leave arg truncated! */
521 static void glob_expand_one(char *s, char ***argv_ptr, int *argc_ptr,
524 char **argv = *argv_ptr;
525 int argc = *argc_ptr;
526 int maxargs = *maxargs_ptr;
527 #if !defined HAVE_GLOB || !defined HAVE_GLOB_H
528 if (argc == maxargs) {
530 if (!(argv = realloc_array(argv, char *, maxargs)))
531 out_of_memory("glob_expand_one");
533 *maxargs_ptr = maxargs;
537 s = argv[argc++] = strdup(s);
538 filter_server_path(s);
548 s = sanitize_path(NULL, s, "", 0, NULL);
552 memset(&globbuf, 0, sizeof globbuf);
553 if (!filter_server_path(s))
554 glob(s, 0, NULL, &globbuf);
555 if (MAX((int)globbuf.gl_pathc, 1) > maxargs - argc) {
556 maxargs += globbuf.gl_pathc + MAX_ARGS;
557 if (!(argv = realloc_array(argv, char *, maxargs)))
558 out_of_memory("glob_expand_one");
560 *maxargs_ptr = maxargs;
562 if (globbuf.gl_pathc == 0)
567 for (i = 0; i < (int)globbuf.gl_pathc; i++) {
568 if (!(argv[argc++] = strdup(globbuf.gl_pathv[i])))
569 out_of_memory("glob_expand_one");
577 /* This routine is only used in daemon mode. */
578 void glob_expand(char *base1, char ***argv_ptr, int *argc_ptr, int *maxargs_ptr)
580 char *s = (*argv_ptr)[*argc_ptr];
583 int base_len = strlen(base);
588 if (strncmp(s, base, base_len) == 0)
591 if (!(s = strdup(s)))
592 out_of_memory("glob_expand");
594 if (asprintf(&base," %s/", base1) <= 0)
595 out_of_memory("glob_expand");
598 for (q = s; *q; q = p + base_len) {
599 if ((p = strstr(q, base)) != NULL)
600 *p = '\0'; /* split it at this point */
601 glob_expand_one(q, argv_ptr, argc_ptr, maxargs_ptr);
611 * Convert a string to lower case
613 void strlower(char *s)
622 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
623 * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
624 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
625 * string fits into destsize. */
626 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
628 size_t len = strlcpy(dest, p1, destsize);
629 if (len < destsize - 1) {
630 if (!len || dest[len-1] != '/')
632 if (len < destsize - 1)
633 len += strlcpy(dest + len, p2, destsize - len);
640 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
644 /* Join any number of strings together, putting them in "dest". The return
645 * value is the length of all the strings, regardless of whether the null-
646 * terminated whole fits in destsize. Your list of string pointers must end
647 * with a NULL to indicate the end of the list. */
648 size_t stringjoin(char *dest, size_t destsize, ...)
654 va_start(ap, destsize);
656 if (!(src = va_arg(ap, const char *)))
663 memcpy(dest, src, len);
674 int count_dir_elements(const char *p)
676 int cnt = 0, new_component = 1;
679 new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
680 else if (new_component) {
688 /* Turns multiple adjacent slashes into a single slash, gets rid of "./"
689 * elements (but not a trailing dot dir), removes a trailing slash, and
690 * optionally collapses ".." elements (except for those at the start of the
691 * string). If the resulting name would be empty, change it into a ".". */
692 unsigned int clean_fname(char *name, BOOL collapse_dot_dot)
694 char *limit = name - 1, *t = name, *f = name;
700 if ((anchored = *f == '/') != 0)
703 /* discard extra slashes */
709 /* discard "." dirs (but NOT a trailing '.'!) */
714 /* collapse ".." dirs */
716 && f[1] == '.' && (f[2] == '/' || !f[2])) {
718 if (s == name && anchored) {
722 while (s > limit && *--s != '/') {}
723 if (s != t - 1 && (s < name || *s == '/')) {
731 while (*f && (*t++ = *f++) != '/') {}
734 if (t > name+anchored && t[-1] == '/')
743 /* Make path appear as if a chroot had occurred. This handles a leading
744 * "/" (either removing it or expanding it) and any leading or embedded
745 * ".." components that attempt to escape past the module's top dir.
747 * If dest is NULL, a buffer is allocated to hold the result. It is legal
748 * to call with the dest and the path (p) pointing to the same buffer, but
749 * rootdir will be ignored to avoid expansion of the string.
751 * The rootdir string contains a value to use in place of a leading slash.
752 * Specify NULL to get the default of lp_path(module_id).
754 * The depth var is a count of how many '..'s to allow at the start of the
755 * path. If symlink is set, combine its value with the "p" value to get
756 * the target path, and **return NULL if any '..'s try to escape**.
758 * We also clean the path in a manner similar to clean_fname() but with a
761 * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
762 * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
763 * ALWAYS collapses ".." elements (except for those at the start of the
764 * string up to "depth" deep). If the resulting name would be empty,
765 * change it into a ".". */
766 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
769 char *start, *sanp, *save_dest = dest;
770 int rlen = 0, leave_one_dotdir = relative_paths;
772 if (symlink && *symlink == '/') {
778 int plen = strlen(p);
781 rootdir = lp_path(module_id);
782 rlen = strlen(rootdir);
787 if (rlen + plen + 1 >= MAXPATHLEN)
789 } else if (!(dest = new_array(char, rlen + plen + 1)))
790 out_of_memory("sanitize_path");
792 memcpy(dest, rootdir, rlen);
798 start = sanp = dest + rlen;
801 if (!symlink || !*symlink)
803 while (sanp != start && sanp[-1] != '/') {
804 /* strip last element */
807 /* Append a relative symlink */
811 /* discard leading or extra slashes */
816 /* this loop iterates once per filename component in p.
817 * both p (and sanp if the original had a slash) should
818 * always be left pointing after a slash
820 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
821 if (leave_one_dotdir && p[1])
822 leave_one_dotdir = 0;
824 /* skip "." component */
829 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
830 /* ".." component followed by slash or end */
831 if (depth <= 0 || sanp != start) {
832 if (symlink && sanp == start) {
839 /* back up sanp one level */
840 --sanp; /* now pointing at slash */
841 while (sanp > start && sanp[-1] != '/') {
842 /* skip back up to slash */
848 /* allow depth levels of .. at the beginning */
850 /* move the virtual beginning to leave the .. alone */
853 /* copy one component through next slash */
854 while (*p && (*sanp++ = *p++) != '/') {}
857 /* ended up with nothing, so put in "." component */
865 /* Like chdir(), but it keeps track of the current directory (in the
866 * global "curr_dir"), and ensures that the path size doesn't overflow.
867 * Also cleans the path using the clean_fname() function. */
868 int push_dir(const char *dir, int set_path_only)
870 static int initialised;
875 getcwd(curr_dir, sizeof curr_dir - 1);
876 curr_dir_len = strlen(curr_dir);
879 if (!dir) /* this call was probably just to initialize */
883 if (len == 1 && *dir == '.')
886 if ((*dir == '/' ? len : curr_dir_len + 1 + len) >= sizeof curr_dir)
889 if (!set_path_only && chdir(dir))
893 memcpy(curr_dir, dir, len + 1);
896 curr_dir[curr_dir_len++] = '/';
897 memcpy(curr_dir + curr_dir_len, dir, len + 1);
901 curr_dir_len = clean_fname(curr_dir, 1);
902 if (sanitize_paths) {
903 if (module_dirlen > curr_dir_len)
904 module_dirlen = curr_dir_len;
905 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
912 * Reverse a push_dir() call. You must pass in an absolute path
913 * that was copied from a prior value of "curr_dir".
915 int pop_dir(const char *dir)
920 curr_dir_len = strlcpy(curr_dir, dir, sizeof curr_dir);
921 if (curr_dir_len >= sizeof curr_dir)
922 curr_dir_len = sizeof curr_dir - 1;
924 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
930 * Return a quoted string with the full pathname of the indicated filename.
931 * The string " (in MODNAME)" may also be appended. The returned pointer
932 * remains valid until the next time full_fname() is called.
934 char *full_fname(const char *fn)
936 static char *result = NULL;
946 p1 = curr_dir + module_dirlen;
947 for (p2 = p1; *p2 == '/'; p2++) {}
951 if (module_id >= 0) {
953 m2 = lp_name(module_id);
958 if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
959 out_of_memory("full_fname");
964 static char partial_fname[MAXPATHLEN];
966 char *partial_dir_fname(const char *fname)
968 char *t = partial_fname;
969 int sz = sizeof partial_fname;
972 if ((fn = strrchr(fname, '/')) != NULL) {
974 if (*partial_dir != '/') {
975 int len = fn - fname;
976 strncpy(t, fname, len); /* safe */
982 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
984 if (server_filter_list.head) {
985 t = strrchr(partial_fname, '/');
987 if (check_filter(&server_filter_list, partial_fname, 1) < 0)
990 if (check_filter(&server_filter_list, partial_fname, 0) < 0)
994 return partial_fname;
997 /* If no --partial-dir option was specified, we don't need to do anything
998 * (the partial-dir is essentially '.'), so just return success. */
999 int handle_partial_dir(const char *fname, int create)
1003 if (fname != partial_fname)
1005 if (!create && *partial_dir == '/')
1007 if (!(fn = strrchr(partial_fname, '/')))
1011 dir = partial_fname;
1014 int statret = do_lstat(dir, &st);
1015 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1016 if (do_unlink(dir) < 0)
1020 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1030 * Determine if a symlink points outside the current directory tree.
1031 * This is considered "unsafe" because e.g. when mirroring somebody
1032 * else's machine it might allow them to establish a symlink to
1033 * /etc/passwd, and then read it through a web server.
1035 * Null symlinks and absolute symlinks are always unsafe.
1037 * Basically here we are concerned with symlinks whose target contains
1038 * "..", because this might cause us to walk back up out of the
1039 * transferred directory. We are not allowed to go back up and
1042 * @param dest Target of the symlink in question.
1044 * @param src Top source directory currently applicable. Basically this
1045 * is the first parameter to rsync in a simple invocation, but it's
1046 * modified by flist.c in slightly complex ways.
1048 * @retval True if unsafe
1049 * @retval False is unsafe
1053 int unsafe_symlink(const char *dest, const char *src)
1055 const char *name, *slash;
1058 /* all absolute and null symlinks are unsafe */
1059 if (!dest || !*dest || *dest == '/')
1062 /* find out what our safety margin is */
1063 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1064 if (strncmp(name, "../", 3) == 0) {
1066 } else if (strncmp(name, "./", 2) == 0) {
1072 if (strcmp(name, "..") == 0)
1075 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1076 if (strncmp(name, "../", 3) == 0) {
1077 /* if at any point we go outside the current directory
1078 then stop - it is unsafe */
1081 } else if (strncmp(name, "./", 2) == 0) {
1087 if (strcmp(name, "..") == 0)
1093 /* Return the int64 number as a string. If the --human-readable option was
1094 * specified, we may output the number in K, M, or G units. We can return
1095 * up to 4 buffers at a time. */
1096 char *human_num(int64 num)
1098 static char bufs[4][128]; /* more than enough room */
1099 static unsigned int n;
1102 n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
1104 if (human_readable) {
1106 int mult = human_readable == 1 ? 1000 : 1024;
1108 if (num > mult*mult*mult) {
1109 dnum = (double)num / (mult*mult*mult);
1111 } else if (num > mult*mult) {
1112 dnum = (double)num / (mult*mult);
1114 } else if (num > mult) {
1115 dnum = (double)num / mult;
1119 snprintf(bufs[n], sizeof bufs[0], "%.2f%c", dnum, units);
1124 s = bufs[n] + sizeof bufs[0] - 1;
1130 *--s = (char)(num % 10) + '0';
1136 /* Return the double number as a string. If the --human-readable option was
1137 * specified, we may output the number in K, M, or G units. We use a buffer
1138 * from human_num() to return our result. */
1139 char *human_dnum(double dnum, int decimal_digits)
1141 char *buf = human_num(dnum);
1142 int len = strlen(buf);
1143 if (isDigit(buf + len - 1)) {
1144 /* There's extra room in buf prior to the start of the num. */
1145 buf -= decimal_digits + 1;
1146 snprintf(buf, len + decimal_digits + 2, "%.*f", decimal_digits, dnum);
1151 /* Return the date and time as a string. Some callers tweak returned buf. */
1152 char *timestring(time_t t)
1154 static char TimeBuf[200];
1155 struct tm *tm = localtime(&t);
1158 #ifdef HAVE_STRFTIME
1159 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
1161 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
1164 if ((p = strchr(TimeBuf, '\n')) != NULL)
1171 * Sleep for a specified number of milliseconds.
1173 * Always returns TRUE. (In the future it might return FALSE if
1179 struct timeval tval, t1, t2;
1181 gettimeofday(&t1, NULL);
1184 tval.tv_sec = (t-tdiff)/1000;
1185 tval.tv_usec = 1000*((t-tdiff)%1000);
1188 select(0,NULL,NULL, NULL, &tval);
1190 gettimeofday(&t2, NULL);
1191 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1192 (t2.tv_usec - t1.tv_usec)/1000;
1198 /* Determine if two time_t values are equivalent (either exact, or in
1199 * the modification timestamp window established by --modify-window).
1201 * @retval 0 if the times should be treated as the same
1203 * @retval +1 if the first is later
1205 * @retval -1 if the 2nd is later
1207 int cmp_time(time_t file1, time_t file2)
1209 if (file2 > file1) {
1210 if (file2 - file1 <= modify_window)
1214 if (file1 - file2 <= modify_window)
1224 This routine is a trick to immediately catch errors when debugging
1225 with insure. A xterm with a gdb is popped up when insure catches
1226 a error. It is Linux specific.
1228 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1234 asprintf(&cmd, "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'",
1235 getpid(), getpid(), getpid());
1239 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1240 fn = dlsym(h, "_Insure_trap_error");
1243 ret = fn(a1, a2, a3, a4, a5, a6);
1253 #define MALLOC_MAX 0x40000000
1255 void *_new_array(unsigned int size, unsigned long num)
1257 if (num >= MALLOC_MAX/size)
1259 return malloc(size * num);
1262 void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
1264 if (num >= MALLOC_MAX/size)
1267 return malloc(size * num);
1268 return realloc(ptr, size * num);
1271 /* Take a filename and filename length and return the most significant
1272 * filename suffix we can find. This ignores suffixes such as "~",
1273 * ".bak", ".orig", ".~1~", etc. */
1274 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1276 const char *suf, *s;
1280 /* One or more dots at the start aren't a suffix. */
1281 while (fn_len && *fn == '.') fn++, fn_len--;
1283 /* Ignore the ~ in a "foo~" filename. */
1284 if (fn_len > 1 && fn[fn_len-1] == '~')
1285 fn_len--, had_tilde = True;
1289 /* Assume we don't find an suffix. */
1293 /* Find the last significant suffix. */
1294 for (s = fn + fn_len; fn_len > 1; ) {
1295 while (*--s != '.' && s != fn) {}
1298 s_len = fn_len - (s - fn);
1301 if (strcmp(s+1, "bak") == 0
1302 || strcmp(s+1, "old") == 0)
1304 } else if (s_len == 5) {
1305 if (strcmp(s+1, "orig") == 0)
1307 } else if (s_len > 2 && had_tilde
1308 && s[1] == '~' && isDigit(s + 2))
1314 /* Determine if the suffix is all digits. */
1315 for (s++, s_len--; s_len > 0; s++, s_len--) {
1319 /* An all-digit suffix may not be that signficant. */
1326 /* This is an implementation of the Levenshtein distance algorithm. It
1327 * was implemented to avoid needing a two-dimensional matrix (to save
1328 * memory). It was also tweaked to try to factor in the ASCII distance
1329 * between changed characters as a minor distance quantity. The normal
1330 * Levenshtein units of distance (each signifying a single change between
1331 * the two strings) are defined as a "UNIT". */
1333 #define UNIT (1 << 16)
1335 uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1337 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1341 if (!len1 || !len2) {
1346 for (i1 = 0, cost = 0; i1 < len1; i1++)
1348 return (int32)len1 * UNIT + cost;
1351 for (i2 = 0; i2 < len2; i2++)
1352 a[i2] = (i2+1) * UNIT;
1354 for (i1 = 0; i1 < len1; i1++) {
1356 above = (i1+1) * UNIT;
1357 for (i2 = 0; i2 < len2; i2++) {
1359 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1365 diag_inc = diag + cost;
1366 left_inc = left + UNIT + *((uchar*)s1+i1);
1367 above_inc = above + UNIT + *((uchar*)s2+i2);
1368 a[i2] = above = left < above
1369 ? (left_inc < diag_inc ? left_inc : diag_inc)
1370 : (above_inc < diag_inc ? above_inc : diag_inc);
1378 #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1379 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1380 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1387 struct bitbag *bitbag_create(int max_ndx)
1389 struct bitbag *bb = new(struct bitbag);
1390 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1392 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1393 out_of_memory("bitbag_create");
1398 void bitbag_set_bit(struct bitbag *bb, int ndx)
1400 int slot = ndx / BB_PER_SLOT_BITS;
1401 ndx %= BB_PER_SLOT_BITS;
1403 if (!bb->bits[slot]) {
1404 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1405 out_of_memory("bitbag_set_bit");
1408 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1411 #if 0 /* not needed yet */
1412 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1414 int slot = ndx / BB_PER_SLOT_BITS;
1415 ndx %= BB_PER_SLOT_BITS;
1417 if (!bb->bits[slot])
1420 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1423 int bitbag_check_bit(struct bitbag *bb, int ndx)
1425 int slot = ndx / BB_PER_SLOT_BITS;
1426 ndx %= BB_PER_SLOT_BITS;
1428 if (!bb->bits[slot])
1431 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1435 /* Call this with -1 to start checking from 0. Returns -1 at the end. */
1436 int bitbag_next_bit(struct bitbag *bb, int after)
1439 int i, ndx = after + 1;
1440 int slot = ndx / BB_PER_SLOT_BITS;
1441 ndx %= BB_PER_SLOT_BITS;
1443 mask = (1u << (ndx % 32)) - 1;
1444 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1445 if (!bb->bits[slot])
1447 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1448 if (!(bits = bb->bits[slot][i] & ~mask))
1450 /* The xor magic figures out the lowest enabled bit in
1451 * bits, and the switch quickly computes log2(bit). */
1452 switch (bits ^ (bits & (bits-1))) {
1453 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1454 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1455 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1456 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1457 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1458 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1459 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1460 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1461 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1463 return -1; /* impossible... */
1470 void *expand_item_list(item_list *lp, size_t item_size,
1471 const char *desc, int incr)
1473 /* First time through, 0 <= 0, so list is expanded. */
1474 if (lp->malloced <= lp->count) {
1476 size_t new_size = lp->malloced;
1478 new_size -= incr; /* increase slowly */
1479 else if (new_size < (size_t)incr)
1483 new_ptr = realloc_array(lp->items, char, new_size * item_size);
1485 rprintf(FINFO, "[%s] expand %s to %.0f bytes, did%s move\n",
1486 who_am_i(), desc, (double)new_size * item_size,
1487 new_ptr == lp->items ? " not" : "");
1490 out_of_memory("expand_item_list");
1492 lp->items = new_ptr;
1493 lp->malloced = new_size;
1495 return (char*)lp->items + (lp->count++ * item_size);