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, 0)) == -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, 0)) == -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 void out_of_memory(char *str)
114 rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
115 exit_cleanup(RERR_MALLOC);
118 void overflow_exit(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(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;
149 return lutimes(fname, t);
151 return utimes(fname, t);
152 #elif defined HAVE_UTIMBUF
154 tbuf.actime = time(NULL);
155 tbuf.modtime = modtime;
156 return utime(fname,&tbuf);
157 #elif defined HAVE_UTIME
161 return utime(fname,t);
163 #error No file-time-modification routine found!
168 /* This creates a new directory with default permissions. Since there
169 * might be some directory-default permissions affecting this, we can't
170 * force the permissions directly using the original umask and mkdir(). */
171 int mkdir_defmode(char *fname)
176 ret = do_mkdir(fname, ACCESSPERMS);
182 /* Create any necessary directories in fname. Any missing directories are
183 * created with default permissions. */
184 int create_directory_path(char *fname)
189 while (*fname == '/')
191 while (strncmp(fname, "./", 2) == 0)
196 while ((p = strchr(p,'/')) != NULL) {
198 if (do_mkdir(fname, ACCESSPERMS) < 0 && errno != EEXIST)
208 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
211 * @retval len upon success
213 * @retval <0 write's (negative) error code
215 * Derived from GNU C's cccp.c.
217 int full_write(int desc, char *ptr, size_t len)
223 int written = write(desc, ptr, len);
229 total_written += written;
233 return total_written;
237 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
240 * @retval >0 the actual number of bytes read
244 * @retval <0 for an error.
246 * Derived from GNU C's cccp.c. */
247 static int safe_read(int desc, char *ptr, size_t len)
255 n_chars = read(desc, ptr, len);
256 } while (n_chars < 0 && errno == EINTR);
263 * This is used in conjunction with the --temp-dir, --backup, and
264 * --copy-dest options. */
265 int copy_file(const char *source, const char *dest, mode_t mode)
270 int len; /* Number of bytes read into `buf'. */
272 ifd = do_open(source, O_RDONLY, 0);
274 rsyserr(FERROR, errno, "open %s", full_fname(source));
278 if (robust_unlink(dest) && errno != ENOENT) {
279 rsyserr(FERROR, errno, "unlink %s", full_fname(dest));
283 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
285 rsyserr(FERROR, errno, "open %s", full_fname(dest));
290 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
291 if (full_write(ofd, buf, len) < 0) {
292 rsyserr(FERROR, errno, "write %s", full_fname(dest));
300 rsyserr(FERROR, errno, "read %s", full_fname(source));
306 if (close(ifd) < 0) {
307 rsyserr(FINFO, errno, "close failed on %s",
311 if (close(ofd) < 0) {
312 rsyserr(FERROR, errno, "close failed on %s",
320 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
321 #define MAX_RENAMES_DIGITS 3
322 #define MAX_RENAMES 1000
325 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
326 * rename to <path>/.rsyncNNN instead.
328 * Note that successive rsync runs will shuffle the filenames around a
329 * bit as long as the file is still busy; this is because this function
330 * does not know if the unlink call is due to a new file coming in, or
331 * --delete trying to remove old .rsyncNNN files, hence it renames it
334 int robust_unlink(const char *fname)
337 return do_unlink(fname);
339 static int counter = 1;
341 char path[MAXPATHLEN];
343 rc = do_unlink(fname);
344 if (rc == 0 || errno != ETXTBSY)
347 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
348 pos = MAXPATHLEN - 1;
350 while (pos > 0 && path[pos-1] != '/')
352 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
354 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
359 /* start where the last one left off to reduce chance of clashes */
362 sprintf(&path[pos], "%03d", counter);
363 if (++counter >= MAX_RENAMES)
365 } while ((rc = access(path, 0)) == 0 && counter != start);
368 rprintf(FINFO,"renaming %s to %s because of text busy\n",
372 /* maybe we should return rename()'s exit status? Nah. */
373 if (do_rename(fname, path) != 0) {
381 /* Returns 0 on successful rename, 1 if we successfully copied the file
382 * across filesystems, -2 if copy_file() failed, and -1 on other errors.
383 * If partialptr is not NULL and we need to do a copy, copy the file into
384 * the active partial-dir instead of over the destination file. */
385 int robust_rename(char *from, char *to, char *partialptr,
391 if (do_rename(from, to) == 0)
397 if (robust_unlink(to) != 0)
403 if (!handle_partial_dir(partialptr,PDIR_CREATE))
407 if (copy_file(from, to, mode) != 0)
418 static pid_t all_pids[10];
421 /** Fork and record the pid of the child. **/
424 pid_t newpid = fork();
426 if (newpid != 0 && newpid != -1) {
427 all_pids[num_pids++] = newpid;
435 * @todo It would be kind of nice to make sure that they are actually
436 * all our children before we kill them, because their pids may have
437 * been recycled by some other process. Perhaps when we wait for a
438 * child, we should remove it from this array. Alternatively we could
439 * perhaps use process groups, but I think that would not work on
440 * ancient Unix versions that don't support them.
442 void kill_all(int sig)
446 for (i = 0; i < num_pids; i++) {
447 /* Let's just be a little careful where we
448 * point that gun, hey? See kill(2) for the
449 * magic caused by negative values. */
450 pid_t p = all_pids[i];
461 /** Turn a user name into a uid */
462 int name_to_uid(char *name, uid_t *uid)
467 pass = getpwnam(name);
475 /** Turn a group name into a gid */
476 int name_to_gid(char *name, gid_t *gid)
481 grp = getgrnam(name);
489 /** Lock a byte range in a open file */
490 int lock_range(int fd, int offset, int len)
494 lock.l_type = F_WRLCK;
495 lock.l_whence = SEEK_SET;
496 lock.l_start = offset;
500 return fcntl(fd,F_SETLK,&lock) == 0;
503 static int filter_server_path(char *arg)
507 if (server_filter_list.head) {
508 for (s = arg; (s = strchr(s, '/')) != NULL; ) {
510 if (check_filter(&server_filter_list, arg, 1) < 0) {
511 /* We must leave arg truncated! */
520 static void glob_expand_one(char *s, char ***argv_ptr, int *argc_ptr,
523 char **argv = *argv_ptr;
524 int argc = *argc_ptr;
525 int maxargs = *maxargs_ptr;
526 #if !defined HAVE_GLOB || !defined HAVE_GLOB_H
527 if (argc == maxargs) {
529 if (!(argv = realloc_array(argv, char *, maxargs)))
530 out_of_memory("glob_expand_one");
532 *maxargs_ptr = maxargs;
536 s = argv[argc++] = strdup(s);
537 filter_server_path(s);
547 s = sanitize_path(NULL, s, "", 0, NULL);
551 memset(&globbuf, 0, sizeof globbuf);
552 if (!filter_server_path(s))
553 glob(s, 0, NULL, &globbuf);
554 if (MAX((int)globbuf.gl_pathc, 1) > maxargs - argc) {
555 maxargs += globbuf.gl_pathc + MAX_ARGS;
556 if (!(argv = realloc_array(argv, char *, maxargs)))
557 out_of_memory("glob_expand_one");
559 *maxargs_ptr = maxargs;
561 if (globbuf.gl_pathc == 0)
566 for (i = 0; i < (int)globbuf.gl_pathc; i++) {
567 if (!(argv[argc++] = strdup(globbuf.gl_pathv[i])))
568 out_of_memory("glob_expand_one");
576 /* This routine is only used in daemon mode. */
577 void glob_expand(char *base1, char ***argv_ptr, int *argc_ptr, int *maxargs_ptr)
579 char *s = (*argv_ptr)[*argc_ptr];
582 int base_len = strlen(base);
587 if (strncmp(s, base, base_len) == 0)
590 if (!(s = strdup(s)))
591 out_of_memory("glob_expand");
593 if (asprintf(&base," %s/", base1) <= 0)
594 out_of_memory("glob_expand");
597 for (q = s; *q; q = p + base_len) {
598 if ((p = strstr(q, base)) != NULL)
599 *p = '\0'; /* split it at this point */
600 glob_expand_one(q, argv_ptr, argc_ptr, maxargs_ptr);
610 * Convert a string to lower case
612 void strlower(char *s)
615 if (isupper(*(unsigned char *)s))
616 *s = tolower(*(unsigned char *)s);
621 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
622 * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
623 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
624 * string fits into destsize. */
625 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
627 size_t len = strlcpy(dest, p1, destsize);
628 if (len < destsize - 1) {
629 if (!len || dest[len-1] != '/')
631 if (len < destsize - 1)
632 len += strlcpy(dest + len, p2, destsize - len);
639 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
643 /* Join any number of strings together, putting them in "dest". The return
644 * value is the length of all the strings, regardless of whether the null-
645 * terminated whole fits in destsize. Your list of string pointers must end
646 * with a NULL to indicate the end of the list. */
647 size_t stringjoin(char *dest, size_t destsize, ...)
653 va_start(ap, destsize);
655 if (!(src = va_arg(ap, const char *)))
662 memcpy(dest, src, len);
673 int count_dir_elements(const char *p)
675 int cnt = 0, new_component = 1;
678 new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
679 else if (new_component) {
687 /* Turns multiple adjacent slashes into a single slash, gets rid of "./"
688 * elements (but not a trailing dot dir), removes a trailing slash, and
689 * optionally collapses ".." elements (except for those at the start of the
690 * string). If the resulting name would be empty, change it into a ".". */
691 unsigned int clean_fname(char *name, BOOL collapse_dot_dot)
693 char *limit = name - 1, *t = name, *f = name;
699 if ((anchored = *f == '/') != 0)
702 /* discard extra slashes */
708 /* discard "." dirs (but NOT a trailing '.'!) */
713 /* collapse ".." dirs */
715 && f[1] == '.' && (f[2] == '/' || !f[2])) {
717 if (s == name && anchored) {
721 while (s > limit && *--s != '/') {}
722 if (s != t - 1 && (s < name || *s == '/')) {
730 while (*f && (*t++ = *f++) != '/') {}
733 if (t > name+anchored && t[-1] == '/')
742 /* Make path appear as if a chroot had occurred. This handles a leading
743 * "/" (either removing it or expanding it) and any leading or embedded
744 * ".." components that attempt to escape past the module's top dir.
746 * If dest is NULL, a buffer is allocated to hold the result. It is legal
747 * to call with the dest and the path (p) pointing to the same buffer, but
748 * rootdir will be ignored to avoid expansion of the string.
750 * The rootdir string contains a value to use in place of a leading slash.
751 * Specify NULL to get the default of lp_path(module_id).
753 * The depth var is a count of how many '..'s to allow at the start of the
754 * path. If symlink is set, combine its value with the "p" value to get
755 * the target path, and **return NULL if any '..'s try to escape**.
757 * We also clean the path in a manner similar to clean_fname() but with a
760 * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
761 * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
762 * ALWAYS collapses ".." elements (except for those at the start of the
763 * string up to "depth" deep). If the resulting name would be empty,
764 * change it into a ".". */
765 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
768 char *start, *sanp, *save_dest = dest;
769 int rlen = 0, leave_one_dotdir = relative_paths;
771 if (symlink && *symlink == '/') {
777 int plen = strlen(p);
780 rootdir = lp_path(module_id);
781 rlen = strlen(rootdir);
786 if (rlen + plen + 1 >= MAXPATHLEN)
788 } else if (!(dest = new_array(char, rlen + plen + 1)))
789 out_of_memory("sanitize_path");
791 memcpy(dest, rootdir, rlen);
797 start = sanp = dest + rlen;
800 if (!symlink || !*symlink)
802 while (sanp != start && sanp[-1] != '/') {
803 /* strip last element */
806 /* Append a relative symlink */
810 /* discard leading or extra slashes */
815 /* this loop iterates once per filename component in p.
816 * both p (and sanp if the original had a slash) should
817 * always be left pointing after a slash
819 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
820 if (leave_one_dotdir && p[1])
821 leave_one_dotdir = 0;
823 /* skip "." component */
828 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
829 /* ".." component followed by slash or end */
830 if (depth <= 0 || sanp != start) {
831 if (symlink && sanp == start) {
838 /* back up sanp one level */
839 --sanp; /* now pointing at slash */
840 while (sanp > start && sanp[-1] != '/') {
841 /* skip back up to slash */
847 /* allow depth levels of .. at the beginning */
849 /* move the virtual beginning to leave the .. alone */
852 /* copy one component through next slash */
853 while (*p && (*sanp++ = *p++) != '/') {}
856 /* ended up with nothing, so put in "." component */
864 /* If sanitize_paths is not set, this works exactly the same as do_stat().
865 * Otherwise, we verify that no symlink takes us outside the module path.
866 * If we encounter an escape attempt, we return a symlink's stat info! */
867 int safe_stat(const char *fname, STRUCT_STAT *stp)
870 char tmpbuf[MAXPATHLEN], linkbuf[MAXPATHLEN], *mod_path;
871 int i, llen, mod_path_len;
874 return do_stat(fname, stp);
876 mod_path = lp_path(module_id);
877 mod_path_len = strlen(mod_path);
879 for (i = 0; i < 16; i++) {
882 assert(strncmp(fname, mod_path, mod_path_len) == 0 && fname[mod_path_len] == '/');
884 if (do_lstat(fname, stp) < 0)
886 if (!S_ISLNK(stp->st_mode))
888 if ((llen = readlink(fname, linkbuf, sizeof linkbuf - 1)) < 0)
890 linkbuf[llen] = '\0';
892 fname += mod_path_len;
893 if (!(fname = sanitize_path(tmpbuf, fname, mod_path, curr_dir_depth, linkbuf)))
897 return 0; /* Leave *stp set to the last symlink. */
899 return do_stat(fname, stp);
903 void die_on_unsafe_path(char *path, int strip_filename)
906 char *final_slash, *p;
911 if (strip_filename) {
912 if (!(final_slash = strrchr(path, '/')))
920 p += module_dirlen + 1;
922 if ((p = strchr(p, '/')) != NULL)
924 if (safe_stat(path, &st) < 0) {
929 if (S_ISLNK(st.st_mode)) {
930 rprintf(FERROR, "Unsafe path: %s\n", path);
931 exit_cleanup(RERR_SYNTAX);
944 /* Like chdir(), but it keeps track of the current directory (in the
945 * global "curr_dir"), and ensures that the path size doesn't overflow.
946 * Also cleans the path using the clean_fname() function. */
947 int push_dir(char *dir)
949 static int initialised;
954 getcwd(curr_dir, sizeof curr_dir - 1);
955 curr_dir_len = strlen(curr_dir);
958 if (!dir) /* this call was probably just to initialize */
962 if (len == 1 && *dir == '.')
965 if ((*dir == '/' ? len : curr_dir_len + 1 + len) >= sizeof curr_dir)
972 memcpy(curr_dir, dir, len + 1);
975 curr_dir[curr_dir_len++] = '/';
976 memcpy(curr_dir + curr_dir_len, dir, len + 1);
980 curr_dir_len = clean_fname(curr_dir, 1);
981 if (sanitize_paths) {
982 if (module_dirlen > curr_dir_len)
983 module_dirlen = curr_dir_len;
984 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
991 * Reverse a push_dir() call. You must pass in an absolute path
992 * that was copied from a prior value of "curr_dir".
994 int pop_dir(char *dir)
999 curr_dir_len = strlcpy(curr_dir, dir, sizeof curr_dir);
1000 if (curr_dir_len >= sizeof curr_dir)
1001 curr_dir_len = sizeof curr_dir - 1;
1003 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
1009 * Return a quoted string with the full pathname of the indicated filename.
1010 * The string " (in MODNAME)" may also be appended. The returned pointer
1011 * remains valid until the next time full_fname() is called.
1013 char *full_fname(const char *fn)
1015 static char *result = NULL;
1025 p1 = curr_dir + module_dirlen;
1026 for (p2 = p1; *p2 == '/'; p2++) {}
1030 if (module_id >= 0) {
1032 m2 = lp_name(module_id);
1037 if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
1038 out_of_memory("full_fname");
1043 static char partial_fname[MAXPATHLEN];
1045 char *partial_dir_fname(const char *fname)
1047 char *t = partial_fname;
1048 int sz = sizeof partial_fname;
1051 if ((fn = strrchr(fname, '/')) != NULL) {
1053 if (*partial_dir != '/') {
1054 int len = fn - fname;
1055 strncpy(t, fname, len); /* safe */
1061 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
1063 if (server_filter_list.head) {
1064 t = strrchr(partial_fname, '/');
1066 if (check_filter(&server_filter_list, partial_fname, 1) < 0)
1069 if (check_filter(&server_filter_list, partial_fname, 0) < 0)
1073 return partial_fname;
1076 /* If no --partial-dir option was specified, we don't need to do anything
1077 * (the partial-dir is essentially '.'), so just return success. */
1078 int handle_partial_dir(const char *fname, int create)
1082 if (fname != partial_fname)
1084 if (!create && *partial_dir == '/')
1086 if (!(fn = strrchr(partial_fname, '/')))
1090 dir = partial_fname;
1093 int statret = do_lstat(dir, &st);
1094 if (sanitize_paths && *partial_dir != '/')
1095 die_on_unsafe_path(dir, 1); /* lstat handles last element */
1096 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1097 if (do_unlink(dir) < 0)
1101 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1111 * Determine if a symlink points outside the current directory tree.
1112 * This is considered "unsafe" because e.g. when mirroring somebody
1113 * else's machine it might allow them to establish a symlink to
1114 * /etc/passwd, and then read it through a web server.
1116 * Null symlinks and absolute symlinks are always unsafe.
1118 * Basically here we are concerned with symlinks whose target contains
1119 * "..", because this might cause us to walk back up out of the
1120 * transferred directory. We are not allowed to go back up and
1123 * @param dest Target of the symlink in question.
1125 * @param src Top source directory currently applicable. Basically this
1126 * is the first parameter to rsync in a simple invocation, but it's
1127 * modified by flist.c in slightly complex ways.
1129 * @retval True if unsafe
1130 * @retval False is unsafe
1134 int unsafe_symlink(const char *dest, const char *src)
1136 const char *name, *slash;
1139 /* all absolute and null symlinks are unsafe */
1140 if (!dest || !*dest || *dest == '/')
1143 /* find out what our safety margin is */
1144 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1145 if (strncmp(name, "../", 3) == 0) {
1147 } else if (strncmp(name, "./", 2) == 0) {
1153 if (strcmp(name, "..") == 0)
1156 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1157 if (strncmp(name, "../", 3) == 0) {
1158 /* if at any point we go outside the current directory
1159 then stop - it is unsafe */
1162 } else if (strncmp(name, "./", 2) == 0) {
1168 if (strcmp(name, "..") == 0)
1174 /* Return the int64 number as a string. If the --human-readable option was
1175 * specified, we may output the number in K, M, or G units. We can return
1176 * up to 4 buffers at a time. */
1177 char *human_num(int64 num)
1179 static char bufs[4][128]; /* more than enough room */
1180 static unsigned int n;
1183 n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
1185 if (human_readable) {
1187 int mult = human_readable == 1 ? 1000 : 1024;
1189 if (num > mult*mult*mult) {
1190 dnum = (double)num / (mult*mult*mult);
1192 } else if (num > mult*mult) {
1193 dnum = (double)num / (mult*mult);
1195 } else if (num > mult) {
1196 dnum = (double)num / mult;
1200 sprintf(bufs[n], "%.2f%c", dnum, units);
1205 s = bufs[n] + sizeof bufs[0] - 1;
1211 *--s = (num % 10) + '0';
1217 /* Return the double number as a string. If the --human-readable option was
1218 * specified, we may output the number in K, M, or G units. We use a buffer
1219 * from human_num() to return our result. */
1220 char *human_dnum(double dnum, int decimal_digits)
1222 char *buf = human_num(dnum);
1223 int len = strlen(buf);
1224 if (isdigit(*(uchar*)(buf+len-1))) {
1225 /* There's extra room in buf prior to the start of the num. */
1226 buf -= decimal_digits + 1;
1227 snprintf(buf, len + decimal_digits + 2, "%.*f", decimal_digits, dnum);
1233 * Return the date and time as a string
1235 char *timestring(time_t t)
1237 static char TimeBuf[200];
1238 struct tm *tm = localtime(&t);
1241 #ifdef HAVE_STRFTIME
1242 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
1244 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
1247 if ((p = strchr(TimeBuf, '\n')) != NULL)
1254 * Sleep for a specified number of milliseconds.
1256 * Always returns TRUE. (In the future it might return FALSE if
1262 struct timeval tval, t1, t2;
1264 gettimeofday(&t1, NULL);
1267 tval.tv_sec = (t-tdiff)/1000;
1268 tval.tv_usec = 1000*((t-tdiff)%1000);
1271 select(0,NULL,NULL, NULL, &tval);
1273 gettimeofday(&t2, NULL);
1274 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1275 (t2.tv_usec - t1.tv_usec)/1000;
1281 /* Determine if two time_t values are equivalent (either exact, or in
1282 * the modification timestamp window established by --modify-window).
1284 * @retval 0 if the times should be treated as the same
1286 * @retval +1 if the first is later
1288 * @retval -1 if the 2nd is later
1290 int cmp_time(time_t file1, time_t file2)
1292 if (file2 > file1) {
1293 if (file2 - file1 <= modify_window)
1297 if (file1 - file2 <= modify_window)
1307 This routine is a trick to immediately catch errors when debugging
1308 with insure. A xterm with a gdb is popped up when insure catches
1309 a error. It is Linux specific.
1311 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1317 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'",
1318 getpid(), getpid(), getpid());
1322 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1323 fn = dlsym(h, "_Insure_trap_error");
1326 ret = fn(a1, a2, a3, a4, a5, a6);
1336 #define MALLOC_MAX 0x40000000
1338 void *_new_array(unsigned int size, unsigned long num)
1340 if (num >= MALLOC_MAX/size)
1342 return malloc(size * num);
1345 void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
1347 if (num >= MALLOC_MAX/size)
1349 /* No realloc should need this, but just in case... */
1351 return malloc(size * num);
1352 return realloc(ptr, size * num);
1355 /* Take a filename and filename length and return the most significant
1356 * filename suffix we can find. This ignores suffixes such as "~",
1357 * ".bak", ".orig", ".~1~", etc. */
1358 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1360 const char *suf, *s;
1364 /* One or more dots at the start aren't a suffix. */
1365 while (fn_len && *fn == '.') fn++, fn_len--;
1367 /* Ignore the ~ in a "foo~" filename. */
1368 if (fn_len > 1 && fn[fn_len-1] == '~')
1369 fn_len--, had_tilde = True;
1373 /* Assume we don't find an suffix. */
1377 /* Find the last significant suffix. */
1378 for (s = fn + fn_len; fn_len > 1; ) {
1379 while (*--s != '.' && s != fn) {}
1382 s_len = fn_len - (s - fn);
1385 if (strcmp(s+1, "bak") == 0
1386 || strcmp(s+1, "old") == 0)
1388 } else if (s_len == 5) {
1389 if (strcmp(s+1, "orig") == 0)
1391 } else if (s_len > 2 && had_tilde
1392 && s[1] == '~' && isdigit(*(uchar*)(s+2)))
1398 /* Determine if the suffix is all digits. */
1399 for (s++, s_len--; s_len > 0; s++, s_len--) {
1400 if (!isdigit(*(uchar*)s))
1403 /* An all-digit suffix may not be that signficant. */
1410 /* This is an implementation of the Levenshtein distance algorithm. It
1411 * was implemented to avoid needing a two-dimensional matrix (to save
1412 * memory). It was also tweaked to try to factor in the ASCII distance
1413 * between changed characters as a minor distance quantity. The normal
1414 * Levenshtein units of distance (each signifying a single change between
1415 * the two strings) are defined as a "UNIT". */
1417 #define UNIT (1 << 16)
1419 uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1421 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1425 if (!len1 || !len2) {
1430 for (i1 = 0, cost = 0; i1 < len1; i1++)
1432 return (int32)len1 * UNIT + cost;
1435 for (i2 = 0; i2 < len2; i2++)
1436 a[i2] = (i2+1) * UNIT;
1438 for (i1 = 0; i1 < len1; i1++) {
1440 above = (i1+1) * UNIT;
1441 for (i2 = 0; i2 < len2; i2++) {
1443 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1449 diag_inc = diag + cost;
1450 left_inc = left + UNIT + *((uchar*)s1+i1);
1451 above_inc = above + UNIT + *((uchar*)s2+i2);
1452 a[i2] = above = left < above
1453 ? (left_inc < diag_inc ? left_inc : diag_inc)
1454 : (above_inc < diag_inc ? above_inc : diag_inc);
1462 #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1463 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1464 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1471 struct bitbag *bitbag_create(int max_ndx)
1473 struct bitbag *bb = new(struct bitbag);
1474 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1476 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1477 out_of_memory("bitbag_create");
1482 void bitbag_set_bit(struct bitbag *bb, int ndx)
1484 int slot = ndx / BB_PER_SLOT_BITS;
1485 ndx %= BB_PER_SLOT_BITS;
1487 if (!bb->bits[slot]) {
1488 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1489 out_of_memory("bitbag_set_bit");
1492 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1495 #if 0 /* not needed yet */
1496 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1498 int slot = ndx / BB_PER_SLOT_BITS;
1499 ndx %= BB_PER_SLOT_BITS;
1501 if (!bb->bits[slot])
1504 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1507 int bitbag_check_bit(struct bitbag *bb, int ndx)
1509 int slot = ndx / BB_PER_SLOT_BITS;
1510 ndx %= BB_PER_SLOT_BITS;
1512 if (!bb->bits[slot])
1515 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1519 /* Call this with -1 to start checking from 0. Returns -1 at the end. */
1520 int bitbag_next_bit(struct bitbag *bb, int after)
1523 int i, ndx = after + 1;
1524 int slot = ndx / BB_PER_SLOT_BITS;
1525 ndx %= BB_PER_SLOT_BITS;
1527 mask = (1u << (ndx % 32)) - 1;
1528 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1529 if (!bb->bits[slot])
1531 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1532 if (!(bits = bb->bits[slot][i] & ~mask))
1534 /* The xor magic figures out the lowest enabled bit in
1535 * bits, and the switch quickly computes log2(bit). */
1536 switch (bits ^ (bits & (bits-1))) {
1537 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1538 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1539 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1540 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1541 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1542 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1543 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1544 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1545 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1547 return -1; /* impossible... */