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, 2004, 2005, 2006 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 as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
29 extern int modify_window;
30 extern int relative_paths;
31 extern int human_readable;
32 extern unsigned int module_dirlen;
33 extern mode_t orig_umask;
34 extern char *partial_dir;
35 extern struct filter_list_struct server_filter_list;
37 int sanitize_paths = 0;
39 char curr_dir[MAXPATHLEN];
40 unsigned int curr_dir_len;
41 int curr_dir_depth; /* This is only set for a sanitizing daemon. */
43 /* Set a fd into nonblocking mode. */
44 void set_nonblocking(int fd)
48 if ((val = fcntl(fd, F_GETFL)) == -1)
50 if (!(val & NONBLOCK_FLAG)) {
52 fcntl(fd, F_SETFL, val);
56 /* Set a fd into blocking mode. */
57 void set_blocking(int fd)
61 if ((val = fcntl(fd, F_GETFL)) == -1)
63 if (val & NONBLOCK_FLAG) {
64 val &= ~NONBLOCK_FLAG;
65 fcntl(fd, F_SETFL, val);
70 * Create a file descriptor pair - like pipe() but use socketpair if
71 * possible (because of blocking issues on pipes).
73 * Always set non-blocking.
75 int fd_pair(int fd[2])
79 #ifdef HAVE_SOCKETPAIR
80 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
86 set_nonblocking(fd[0]);
87 set_nonblocking(fd[1]);
93 void print_child_argv(char **cmd)
95 rprintf(FCLIENT, "opening connection using ");
97 /* Look for characters that ought to be quoted. This
98 * is not a great quoting algorithm, but it's
99 * sufficient for a log message. */
100 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
101 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
103 ",.-_=+@/") != strlen(*cmd)) {
104 rprintf(FCLIENT, "\"%s\" ", *cmd);
106 rprintf(FCLIENT, "%s ", *cmd);
109 rprintf(FCLIENT, "\n");
112 NORETURN void out_of_memory(const char *str)
114 rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
115 exit_cleanup(RERR_MALLOC);
118 NORETURN void overflow_exit(const char *str)
120 rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
121 exit_cleanup(RERR_MALLOC);
124 int set_modtime(const char *fname, time_t modtime, mode_t mode)
126 #if !defined HAVE_LUTIMES || !defined HAVE_UTIMES
132 rprintf(FINFO, "set modtime of %s to (%ld) %s",
133 fname, (long)modtime,
134 asctime(localtime(&modtime)));
143 t[0].tv_sec = time(NULL);
145 t[1].tv_sec = modtime;
150 return 0; /* ignore errors */
153 return utimes(fname, t);
154 #elif defined HAVE_UTIMBUF
156 tbuf.actime = time(NULL);
157 tbuf.modtime = modtime;
158 return utime(fname,&tbuf);
159 #elif defined HAVE_UTIME
163 return utime(fname,t);
165 #error No file-time-modification routine found!
170 /* This creates a new directory with default permissions. Since there
171 * might be some directory-default permissions affecting this, we can't
172 * force the permissions directly using the original umask and mkdir(). */
173 int mkdir_defmode(char *fname)
178 ret = do_mkdir(fname, ACCESSPERMS);
184 /* Create any necessary directories in fname. Any missing directories are
185 * created with default permissions. */
186 int create_directory_path(char *fname)
191 while (*fname == '/')
193 while (strncmp(fname, "./", 2) == 0)
198 while ((p = strchr(p,'/')) != NULL) {
200 if (do_mkdir(fname, ACCESSPERMS) < 0 && errno != EEXIST)
210 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
213 * @retval len upon success
215 * @retval <0 write's (negative) error code
217 * Derived from GNU C's cccp.c.
219 int full_write(int desc, const char *ptr, size_t len)
225 int written = write(desc, ptr, len);
231 total_written += written;
235 return total_written;
239 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
242 * @retval >0 the actual number of bytes read
246 * @retval <0 for an error.
248 * Derived from GNU C's cccp.c. */
249 static int safe_read(int desc, char *ptr, size_t len)
257 n_chars = read(desc, ptr, len);
258 } while (n_chars < 0 && errno == EINTR);
265 * This is used in conjunction with the --temp-dir, --backup, and
266 * --copy-dest options. */
267 int copy_file(const char *source, const char *dest, mode_t mode)
272 int len; /* Number of bytes read into `buf'. */
274 ifd = do_open(source, O_RDONLY, 0);
276 rsyserr(FERROR, errno, "open %s", full_fname(source));
280 if (robust_unlink(dest) && errno != ENOENT) {
281 rsyserr(FERROR, errno, "unlink %s", full_fname(dest));
285 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
287 rsyserr(FERROR, errno, "open %s", full_fname(dest));
292 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
293 if (full_write(ofd, buf, len) < 0) {
294 rsyserr(FERROR, errno, "write %s", full_fname(dest));
302 rsyserr(FERROR, errno, "read %s", full_fname(source));
308 if (close(ifd) < 0) {
309 rsyserr(FINFO, errno, "close failed on %s",
313 if (close(ofd) < 0) {
314 rsyserr(FERROR, errno, "close failed on %s",
322 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
323 #define MAX_RENAMES_DIGITS 3
324 #define MAX_RENAMES 1000
327 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
328 * rename to <path>/.rsyncNNN instead.
330 * Note that successive rsync runs will shuffle the filenames around a
331 * bit as long as the file is still busy; this is because this function
332 * does not know if the unlink call is due to a new file coming in, or
333 * --delete trying to remove old .rsyncNNN files, hence it renames it
336 int robust_unlink(const char *fname)
339 return do_unlink(fname);
341 static int counter = 1;
343 char path[MAXPATHLEN];
345 rc = do_unlink(fname);
346 if (rc == 0 || errno != ETXTBSY)
349 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
350 pos = MAXPATHLEN - 1;
352 while (pos > 0 && path[pos-1] != '/')
354 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
356 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
361 /* start where the last one left off to reduce chance of clashes */
364 snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
365 if (++counter >= MAX_RENAMES)
367 } while ((rc = access(path, 0)) == 0 && counter != start);
370 rprintf(FINFO,"renaming %s to %s because of text busy\n",
374 /* maybe we should return rename()'s exit status? Nah. */
375 if (do_rename(fname, path) != 0) {
383 /* Returns 0 on successful rename, 1 if we successfully copied the file
384 * across filesystems, -2 if copy_file() failed, and -1 on other errors.
385 * If partialptr is not NULL and we need to do a copy, copy the file into
386 * the active partial-dir instead of over the destination file. */
387 int robust_rename(const char *from, const char *to, const char *partialptr,
393 if (do_rename(from, to) == 0)
399 if (robust_unlink(to) != 0)
405 if (!handle_partial_dir(partialptr,PDIR_CREATE))
409 if (copy_file(from, to, mode) != 0)
420 static pid_t all_pids[10];
423 /** Fork and record the pid of the child. **/
426 pid_t newpid = fork();
428 if (newpid != 0 && newpid != -1) {
429 all_pids[num_pids++] = newpid;
437 * @todo It would be kind of nice to make sure that they are actually
438 * all our children before we kill them, because their pids may have
439 * been recycled by some other process. Perhaps when we wait for a
440 * child, we should remove it from this array. Alternatively we could
441 * perhaps use process groups, but I think that would not work on
442 * ancient Unix versions that don't support them.
444 void kill_all(int sig)
448 for (i = 0; i < num_pids; i++) {
449 /* Let's just be a little careful where we
450 * point that gun, hey? See kill(2) for the
451 * magic caused by negative values. */
452 pid_t p = all_pids[i];
463 /** Turn a user name into a uid */
464 int name_to_uid(const char *name, uid_t *uid)
469 pass = getpwnam(name);
477 /** Turn a group name into a gid */
478 int name_to_gid(const char *name, gid_t *gid)
483 grp = getgrnam(name);
491 /** Lock a byte range in a open file */
492 int lock_range(int fd, int offset, int len)
496 lock.l_type = F_WRLCK;
497 lock.l_whence = SEEK_SET;
498 lock.l_start = offset;
502 return fcntl(fd,F_SETLK,&lock) == 0;
505 static int filter_server_path(char *arg)
509 if (server_filter_list.head) {
510 for (s = arg; (s = strchr(s, '/')) != NULL; ) {
512 if (check_filter(&server_filter_list, arg, 1) < 0) {
513 /* We must leave arg truncated! */
522 static void glob_expand_one(char *s, char ***argv_ptr, int *argc_ptr,
525 char **argv = *argv_ptr;
526 int argc = *argc_ptr;
527 int maxargs = *maxargs_ptr;
528 #if !defined HAVE_GLOB || !defined HAVE_GLOB_H
529 if (argc == maxargs) {
531 if (!(argv = realloc_array(argv, char *, maxargs)))
532 out_of_memory("glob_expand_one");
534 *maxargs_ptr = maxargs;
538 s = argv[argc++] = strdup(s);
539 filter_server_path(s);
549 s = sanitize_path(NULL, s, "", 0, NULL);
553 memset(&globbuf, 0, sizeof globbuf);
554 if (!filter_server_path(s))
555 glob(s, 0, NULL, &globbuf);
556 if (MAX((int)globbuf.gl_pathc, 1) > maxargs - argc) {
557 maxargs += globbuf.gl_pathc + MAX_ARGS;
558 if (!(argv = realloc_array(argv, char *, maxargs)))
559 out_of_memory("glob_expand_one");
561 *maxargs_ptr = maxargs;
563 if (globbuf.gl_pathc == 0)
568 for (i = 0; i < (int)globbuf.gl_pathc; i++) {
569 if (!(argv[argc++] = strdup(globbuf.gl_pathv[i])))
570 out_of_memory("glob_expand_one");
578 /* This routine is only used in daemon mode. */
579 void glob_expand(char *base1, char ***argv_ptr, int *argc_ptr, int *maxargs_ptr)
581 char *s = (*argv_ptr)[*argc_ptr];
584 int base_len = strlen(base);
589 if (strncmp(s, base, base_len) == 0)
592 if (!(s = strdup(s)))
593 out_of_memory("glob_expand");
595 if (asprintf(&base," %s/", base1) <= 0)
596 out_of_memory("glob_expand");
599 for (q = s; *q; q = p + base_len) {
600 if ((p = strstr(q, base)) != NULL)
601 *p = '\0'; /* split it at this point */
602 glob_expand_one(q, argv_ptr, argc_ptr, maxargs_ptr);
612 * Convert a string to lower case
614 void strlower(char *s)
623 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
624 * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
625 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
626 * string fits into destsize. */
627 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
629 size_t len = strlcpy(dest, p1, destsize);
630 if (len < destsize - 1) {
631 if (!len || dest[len-1] != '/')
633 if (len < destsize - 1)
634 len += strlcpy(dest + len, p2, destsize - len);
641 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
645 /* Join any number of strings together, putting them in "dest". The return
646 * value is the length of all the strings, regardless of whether the null-
647 * terminated whole fits in destsize. Your list of string pointers must end
648 * with a NULL to indicate the end of the list. */
649 size_t stringjoin(char *dest, size_t destsize, ...)
655 va_start(ap, destsize);
657 if (!(src = va_arg(ap, const char *)))
664 memcpy(dest, src, len);
675 int count_dir_elements(const char *p)
677 int cnt = 0, new_component = 1;
680 new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
681 else if (new_component) {
689 /* Turns multiple adjacent slashes into a single slash, gets rid of "./"
690 * elements (but not a trailing dot dir), removes a trailing slash, and
691 * optionally collapses ".." elements (except for those at the start of the
692 * string). If the resulting name would be empty, change it into a ".". */
693 unsigned int clean_fname(char *name, BOOL collapse_dot_dot)
695 char *limit = name - 1, *t = name, *f = name;
701 if ((anchored = *f == '/') != 0)
704 /* discard extra slashes */
710 /* discard "." dirs (but NOT a trailing '.'!) */
715 /* collapse ".." dirs */
717 && f[1] == '.' && (f[2] == '/' || !f[2])) {
719 if (s == name && anchored) {
723 while (s > limit && *--s != '/') {}
724 if (s != t - 1 && (s < name || *s == '/')) {
732 while (*f && (*t++ = *f++) != '/') {}
735 if (t > name+anchored && t[-1] == '/')
744 /* Make path appear as if a chroot had occurred. This handles a leading
745 * "/" (either removing it or expanding it) and any leading or embedded
746 * ".." components that attempt to escape past the module's top dir.
748 * If dest is NULL, a buffer is allocated to hold the result. It is legal
749 * to call with the dest and the path (p) pointing to the same buffer, but
750 * rootdir will be ignored to avoid expansion of the string.
752 * The rootdir string contains a value to use in place of a leading slash.
753 * Specify NULL to get the default of lp_path(module_id).
755 * The depth var is a count of how many '..'s to allow at the start of the
756 * path. If symlink is set, combine its value with the "p" value to get
757 * the target path, and **return NULL if any '..'s try to escape**.
759 * We also clean the path in a manner similar to clean_fname() but with a
762 * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
763 * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
764 * ALWAYS collapses ".." elements (except for those at the start of the
765 * string up to "depth" deep). If the resulting name would be empty,
766 * change it into a ".". */
767 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
770 char *start, *sanp, *save_dest = dest;
771 int rlen = 0, leave_one_dotdir = relative_paths;
773 if (symlink && *symlink == '/') {
779 int plen = strlen(p);
782 rootdir = lp_path(module_id);
783 rlen = strlen(rootdir);
788 if (rlen + plen + 1 >= MAXPATHLEN)
790 } else if (!(dest = new_array(char, rlen + plen + 1)))
791 out_of_memory("sanitize_path");
793 memcpy(dest, rootdir, rlen);
799 start = sanp = dest + rlen;
802 if (!symlink || !*symlink)
804 while (sanp != start && sanp[-1] != '/') {
805 /* strip last element */
808 /* Append a relative symlink */
812 /* discard leading or extra slashes */
817 /* this loop iterates once per filename component in p.
818 * both p (and sanp if the original had a slash) should
819 * always be left pointing after a slash
821 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
822 if (leave_one_dotdir && p[1])
823 leave_one_dotdir = 0;
825 /* skip "." component */
830 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
831 /* ".." component followed by slash or end */
832 if (depth <= 0 || sanp != start) {
833 if (symlink && sanp == start) {
840 /* back up sanp one level */
841 --sanp; /* now pointing at slash */
842 while (sanp > start && sanp[-1] != '/') {
843 /* skip back up to slash */
849 /* allow depth levels of .. at the beginning */
851 /* move the virtual beginning to leave the .. alone */
854 /* copy one component through next slash */
855 while (*p && (*sanp++ = *p++) != '/') {}
858 /* ended up with nothing, so put in "." component */
866 /* Like chdir(), but it keeps track of the current directory (in the
867 * global "curr_dir"), and ensures that the path size doesn't overflow.
868 * Also cleans the path using the clean_fname() function. */
869 int push_dir(const char *dir, int set_path_only)
871 static int initialised;
876 getcwd(curr_dir, sizeof curr_dir - 1);
877 curr_dir_len = strlen(curr_dir);
880 if (!dir) /* this call was probably just to initialize */
884 if (len == 1 && *dir == '.')
887 if ((*dir == '/' ? len : curr_dir_len + 1 + len) >= sizeof curr_dir)
890 if (!set_path_only && chdir(dir))
894 memcpy(curr_dir, dir, len + 1);
897 curr_dir[curr_dir_len++] = '/';
898 memcpy(curr_dir + curr_dir_len, dir, len + 1);
902 curr_dir_len = clean_fname(curr_dir, 1);
903 if (sanitize_paths) {
904 if (module_dirlen > curr_dir_len)
905 module_dirlen = curr_dir_len;
906 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
913 * Reverse a push_dir() call. You must pass in an absolute path
914 * that was copied from a prior value of "curr_dir".
916 int pop_dir(const char *dir)
921 curr_dir_len = strlcpy(curr_dir, dir, sizeof curr_dir);
922 if (curr_dir_len >= sizeof curr_dir)
923 curr_dir_len = sizeof curr_dir - 1;
925 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
931 * Return a quoted string with the full pathname of the indicated filename.
932 * The string " (in MODNAME)" may also be appended. The returned pointer
933 * remains valid until the next time full_fname() is called.
935 char *full_fname(const char *fn)
937 static char *result = NULL;
947 p1 = curr_dir + module_dirlen;
948 for (p2 = p1; *p2 == '/'; p2++) {}
952 if (module_id >= 0) {
954 m2 = lp_name(module_id);
959 if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
960 out_of_memory("full_fname");
965 static char partial_fname[MAXPATHLEN];
967 char *partial_dir_fname(const char *fname)
969 char *t = partial_fname;
970 int sz = sizeof partial_fname;
973 if ((fn = strrchr(fname, '/')) != NULL) {
975 if (*partial_dir != '/') {
976 int len = fn - fname;
977 strncpy(t, fname, len); /* safe */
983 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
985 if (server_filter_list.head) {
986 t = strrchr(partial_fname, '/');
988 if (check_filter(&server_filter_list, partial_fname, 1) < 0)
991 if (check_filter(&server_filter_list, partial_fname, 0) < 0)
995 return partial_fname;
998 /* If no --partial-dir option was specified, we don't need to do anything
999 * (the partial-dir is essentially '.'), so just return success. */
1000 int handle_partial_dir(const char *fname, int create)
1004 if (fname != partial_fname)
1006 if (!create && *partial_dir == '/')
1008 if (!(fn = strrchr(partial_fname, '/')))
1012 dir = partial_fname;
1015 int statret = do_lstat(dir, &st);
1016 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1017 if (do_unlink(dir) < 0)
1021 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1031 * Determine if a symlink points outside the current directory tree.
1032 * This is considered "unsafe" because e.g. when mirroring somebody
1033 * else's machine it might allow them to establish a symlink to
1034 * /etc/passwd, and then read it through a web server.
1036 * Null symlinks and absolute symlinks are always unsafe.
1038 * Basically here we are concerned with symlinks whose target contains
1039 * "..", because this might cause us to walk back up out of the
1040 * transferred directory. We are not allowed to go back up and
1043 * @param dest Target of the symlink in question.
1045 * @param src Top source directory currently applicable. Basically this
1046 * is the first parameter to rsync in a simple invocation, but it's
1047 * modified by flist.c in slightly complex ways.
1049 * @retval True if unsafe
1050 * @retval False is unsafe
1054 int unsafe_symlink(const char *dest, const char *src)
1056 const char *name, *slash;
1059 /* all absolute and null symlinks are unsafe */
1060 if (!dest || !*dest || *dest == '/')
1063 /* find out what our safety margin is */
1064 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1065 if (strncmp(name, "../", 3) == 0) {
1067 } else if (strncmp(name, "./", 2) == 0) {
1073 if (strcmp(name, "..") == 0)
1076 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1077 if (strncmp(name, "../", 3) == 0) {
1078 /* if at any point we go outside the current directory
1079 then stop - it is unsafe */
1082 } else if (strncmp(name, "./", 2) == 0) {
1088 if (strcmp(name, "..") == 0)
1094 /* Return the int64 number as a string. If the --human-readable option was
1095 * specified, we may output the number in K, M, or G units. We can return
1096 * up to 4 buffers at a time. */
1097 char *human_num(int64 num)
1099 static char bufs[4][128]; /* more than enough room */
1100 static unsigned int n;
1103 n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
1105 if (human_readable) {
1107 int mult = human_readable == 1 ? 1000 : 1024;
1109 if (num > mult*mult*mult) {
1110 dnum = (double)num / (mult*mult*mult);
1112 } else if (num > mult*mult) {
1113 dnum = (double)num / (mult*mult);
1115 } else if (num > mult) {
1116 dnum = (double)num / mult;
1120 snprintf(bufs[n], sizeof bufs[0], "%.2f%c", dnum, units);
1125 s = bufs[n] + sizeof bufs[0] - 1;
1131 *--s = (char)(num % 10) + '0';
1137 /* Return the double number as a string. If the --human-readable option was
1138 * specified, we may output the number in K, M, or G units. We use a buffer
1139 * from human_num() to return our result. */
1140 char *human_dnum(double dnum, int decimal_digits)
1142 char *buf = human_num(dnum);
1143 int len = strlen(buf);
1144 if (isDigit(buf + len - 1)) {
1145 /* There's extra room in buf prior to the start of the num. */
1146 buf -= decimal_digits + 1;
1147 snprintf(buf, len + decimal_digits + 2, "%.*f", decimal_digits, dnum);
1152 /* Return the date and time as a string. Some callers tweak returned buf. */
1153 char *timestring(time_t t)
1155 static char TimeBuf[200];
1156 struct tm *tm = localtime(&t);
1159 #ifdef HAVE_STRFTIME
1160 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
1162 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
1165 if ((p = strchr(TimeBuf, '\n')) != NULL)
1172 * Sleep for a specified number of milliseconds.
1174 * Always returns TRUE. (In the future it might return FALSE if
1180 struct timeval tval, t1, t2;
1182 gettimeofday(&t1, NULL);
1185 tval.tv_sec = (t-tdiff)/1000;
1186 tval.tv_usec = 1000*((t-tdiff)%1000);
1189 select(0,NULL,NULL, NULL, &tval);
1191 gettimeofday(&t2, NULL);
1192 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1193 (t2.tv_usec - t1.tv_usec)/1000;
1199 /* Determine if two time_t values are equivalent (either exact, or in
1200 * the modification timestamp window established by --modify-window).
1202 * @retval 0 if the times should be treated as the same
1204 * @retval +1 if the first is later
1206 * @retval -1 if the 2nd is later
1208 int cmp_time(time_t file1, time_t file2)
1210 if (file2 > file1) {
1211 if (file2 - file1 <= modify_window)
1215 if (file1 - file2 <= modify_window)
1225 This routine is a trick to immediately catch errors when debugging
1226 with insure. A xterm with a gdb is popped up when insure catches
1227 a error. It is Linux specific.
1229 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1235 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'",
1236 getpid(), getpid(), getpid());
1240 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1241 fn = dlsym(h, "_Insure_trap_error");
1244 ret = fn(a1, a2, a3, a4, a5, a6);
1254 #define MALLOC_MAX 0x40000000
1256 void *_new_array(unsigned int size, unsigned long num)
1258 if (num >= MALLOC_MAX/size)
1260 return malloc(size * num);
1263 void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
1265 if (num >= MALLOC_MAX/size)
1268 return malloc(size * num);
1269 return realloc(ptr, size * num);
1272 /* Take a filename and filename length and return the most significant
1273 * filename suffix we can find. This ignores suffixes such as "~",
1274 * ".bak", ".orig", ".~1~", etc. */
1275 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1277 const char *suf, *s;
1281 /* One or more dots at the start aren't a suffix. */
1282 while (fn_len && *fn == '.') fn++, fn_len--;
1284 /* Ignore the ~ in a "foo~" filename. */
1285 if (fn_len > 1 && fn[fn_len-1] == '~')
1286 fn_len--, had_tilde = True;
1290 /* Assume we don't find an suffix. */
1294 /* Find the last significant suffix. */
1295 for (s = fn + fn_len; fn_len > 1; ) {
1296 while (*--s != '.' && s != fn) {}
1299 s_len = fn_len - (s - fn);
1302 if (strcmp(s+1, "bak") == 0
1303 || strcmp(s+1, "old") == 0)
1305 } else if (s_len == 5) {
1306 if (strcmp(s+1, "orig") == 0)
1308 } else if (s_len > 2 && had_tilde
1309 && s[1] == '~' && isDigit(s + 2))
1315 /* Determine if the suffix is all digits. */
1316 for (s++, s_len--; s_len > 0; s++, s_len--) {
1320 /* An all-digit suffix may not be that signficant. */
1327 /* This is an implementation of the Levenshtein distance algorithm. It
1328 * was implemented to avoid needing a two-dimensional matrix (to save
1329 * memory). It was also tweaked to try to factor in the ASCII distance
1330 * between changed characters as a minor distance quantity. The normal
1331 * Levenshtein units of distance (each signifying a single change between
1332 * the two strings) are defined as a "UNIT". */
1334 #define UNIT (1 << 16)
1336 uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1338 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1342 if (!len1 || !len2) {
1347 for (i1 = 0, cost = 0; i1 < len1; i1++)
1349 return (int32)len1 * UNIT + cost;
1352 for (i2 = 0; i2 < len2; i2++)
1353 a[i2] = (i2+1) * UNIT;
1355 for (i1 = 0; i1 < len1; i1++) {
1357 above = (i1+1) * UNIT;
1358 for (i2 = 0; i2 < len2; i2++) {
1360 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1366 diag_inc = diag + cost;
1367 left_inc = left + UNIT + *((uchar*)s1+i1);
1368 above_inc = above + UNIT + *((uchar*)s2+i2);
1369 a[i2] = above = left < above
1370 ? (left_inc < diag_inc ? left_inc : diag_inc)
1371 : (above_inc < diag_inc ? above_inc : diag_inc);
1379 #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1380 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1381 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1388 struct bitbag *bitbag_create(int max_ndx)
1390 struct bitbag *bb = new(struct bitbag);
1391 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1393 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1394 out_of_memory("bitbag_create");
1399 void bitbag_set_bit(struct bitbag *bb, int ndx)
1401 int slot = ndx / BB_PER_SLOT_BITS;
1402 ndx %= BB_PER_SLOT_BITS;
1404 if (!bb->bits[slot]) {
1405 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1406 out_of_memory("bitbag_set_bit");
1409 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1412 #if 0 /* not needed yet */
1413 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1415 int slot = ndx / BB_PER_SLOT_BITS;
1416 ndx %= BB_PER_SLOT_BITS;
1418 if (!bb->bits[slot])
1421 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1424 int bitbag_check_bit(struct bitbag *bb, int ndx)
1426 int slot = ndx / BB_PER_SLOT_BITS;
1427 ndx %= BB_PER_SLOT_BITS;
1429 if (!bb->bits[slot])
1432 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1436 /* Call this with -1 to start checking from 0. Returns -1 at the end. */
1437 int bitbag_next_bit(struct bitbag *bb, int after)
1440 int i, ndx = after + 1;
1441 int slot = ndx / BB_PER_SLOT_BITS;
1442 ndx %= BB_PER_SLOT_BITS;
1444 mask = (1u << (ndx % 32)) - 1;
1445 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1446 if (!bb->bits[slot])
1448 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1449 if (!(bits = bb->bits[slot][i] & ~mask))
1451 /* The xor magic figures out the lowest enabled bit in
1452 * bits, and the switch quickly computes log2(bit). */
1453 switch (bits ^ (bits & (bits-1))) {
1454 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1455 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1456 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1457 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1458 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1459 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1460 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1461 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1462 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1464 return -1; /* impossible... */