1 /* -*- c-file-style: "linux" -*-
3 * Copyright (C) 1996-2000 by Andrew Tridgell
4 * Copyright (C) Paul Mackerras 1996
5 * Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 * Utilities used in rsync
33 extern int modify_window;
34 extern int relative_paths;
35 extern int human_readable;
36 extern mode_t orig_umask;
37 extern char *partial_dir;
38 extern struct filter_list_struct server_filter_list;
40 int sanitize_paths = 0;
45 * Set a fd into nonblocking mode
47 void set_nonblocking(int fd)
51 if ((val = fcntl(fd, F_GETFL, 0)) == -1)
53 if (!(val & NONBLOCK_FLAG)) {
55 fcntl(fd, F_SETFL, val);
60 * Set a fd into blocking mode
62 void set_blocking(int fd)
66 if ((val = fcntl(fd, F_GETFL, 0)) == -1)
68 if (val & NONBLOCK_FLAG) {
69 val &= ~NONBLOCK_FLAG;
70 fcntl(fd, F_SETFL, val);
75 * Create a file descriptor pair - like pipe() but use socketpair if
76 * possible (because of blocking issues on pipes).
78 * Always set non-blocking.
80 int fd_pair(int fd[2])
84 #ifdef HAVE_SOCKETPAIR
85 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
91 set_nonblocking(fd[0]);
92 set_nonblocking(fd[1]);
98 void print_child_argv(char **cmd)
100 rprintf(FINFO, "opening connection using ");
101 for (; *cmd; cmd++) {
102 /* Look for characters that ought to be quoted. This
103 * is not a great quoting algorithm, but it's
104 * sufficient for a log message. */
105 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
106 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
108 ",.-_=+@/") != strlen(*cmd)) {
109 rprintf(FINFO, "\"%s\" ", *cmd);
111 rprintf(FINFO, "%s ", *cmd);
114 rprintf(FINFO, "\n");
117 void out_of_memory(char *str)
119 rprintf(FERROR, "ERROR: out of memory in %s\n", str);
120 exit_cleanup(RERR_MALLOC);
123 void overflow_exit(char *str)
125 rprintf(FERROR, "ERROR: buffer overflow in %s\n", str);
126 exit_cleanup(RERR_MALLOC);
129 int set_modtime(char *fname, time_t modtime, mode_t mode)
131 #if !defined HAVE_LUTIMES || !defined HAVE_UTIMES
137 rprintf(FINFO, "set modtime of %s to (%ld) %s",
138 fname, (long)modtime,
139 asctime(localtime(&modtime)));
148 t[0].tv_sec = time(NULL);
150 t[1].tv_sec = modtime;
154 return lutimes(fname, t);
156 return utimes(fname, t);
157 #elif defined HAVE_UTIMBUF
159 tbuf.actime = time(NULL);
160 tbuf.modtime = modtime;
161 return utime(fname,&tbuf);
162 #elif defined HAVE_UTIME
166 return utime(fname,t);
168 #error No file-time-modification routine found!
173 /* This creates a new directory with default permissions. Since there
174 * might be some directory-default permissions affecting this, we can't
175 * force the permissions directly using the original umask and mkdir(). */
176 int mkdir_defmode(char *fname)
181 ret = do_mkdir(fname, ACCESSPERMS);
188 Create any necessary directories in fname. Unfortunately we don't know
189 what perms to give the directory when this is called so we need to rely
192 int create_directory_path(char *fname)
196 while (*fname == '/')
198 while (strncmp(fname, "./", 2) == 0)
202 while ((p = strchr(p,'/')) != NULL) {
204 mkdir_defmode(fname);
212 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
215 * @retval len upon success
217 * @retval <0 write's (negative) error code
219 * Derived from GNU C's cccp.c.
221 int full_write(int desc, char *ptr, size_t len)
227 int written = write(desc, ptr, len);
233 total_written += written;
237 return total_written;
241 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
244 * @retval >0 the actual number of bytes read
248 * @retval <0 for an error.
250 * Derived from GNU C's cccp.c. */
251 static int safe_read(int desc, char *ptr, size_t len)
259 n_chars = read(desc, ptr, len);
260 } while (n_chars < 0 && errno == EINTR);
267 * This is used in conjunction with the --temp-dir, --backup, and
268 * --copy-dest options. */
269 int copy_file(const char *source, const char *dest, mode_t mode)
274 int len; /* Number of bytes read into `buf'. */
276 ifd = do_open(source, O_RDONLY, 0);
278 rsyserr(FERROR, errno, "open %s", full_fname(source));
282 if (robust_unlink(dest) && errno != ENOENT) {
283 rsyserr(FERROR, errno, "unlink %s", full_fname(dest));
287 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
289 rsyserr(FERROR, errno, "open %s", full_fname(dest));
294 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
295 if (full_write(ofd, buf, len) < 0) {
296 rsyserr(FERROR, errno, "write %s", full_fname(dest));
304 rsyserr(FERROR, errno, "read %s", full_fname(source));
310 if (close(ifd) < 0) {
311 rsyserr(FINFO, errno, "close failed on %s",
315 if (close(ofd) < 0) {
316 rsyserr(FERROR, errno, "close failed on %s",
324 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
325 #define MAX_RENAMES_DIGITS 3
326 #define MAX_RENAMES 1000
329 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
330 * rename to <path>/.rsyncNNN instead.
332 * Note that successive rsync runs will shuffle the filenames around a
333 * bit as long as the file is still busy; this is because this function
334 * does not know if the unlink call is due to a new file coming in, or
335 * --delete trying to remove old .rsyncNNN files, hence it renames it
338 int robust_unlink(const char *fname)
341 return do_unlink(fname);
343 static int counter = 1;
345 char path[MAXPATHLEN];
347 rc = do_unlink(fname);
348 if (rc == 0 || errno != ETXTBSY)
351 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
352 pos = MAXPATHLEN - 1;
354 while (pos > 0 && path[pos-1] != '/')
356 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
358 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
363 /* start where the last one left off to reduce chance of clashes */
366 sprintf(&path[pos], "%03d", counter);
367 if (++counter >= MAX_RENAMES)
369 } while ((rc = access(path, 0)) == 0 && counter != start);
372 rprintf(FINFO,"renaming %s to %s because of text busy\n",
376 /* maybe we should return rename()'s exit status? Nah. */
377 if (do_rename(fname, path) != 0) {
385 /* Returns 0 on successful rename, 1 if we successfully copied the file
386 * across filesystems, -2 if copy_file() failed, and -1 on other errors.
387 * If partialptr is not NULL and we need to do a copy, copy the file into
388 * the active partial-dir instead of over the destination file. */
389 int robust_rename(char *from, char *to, char *partialptr,
395 if (do_rename(from, to) == 0)
401 if (robust_unlink(to) != 0)
407 if (!handle_partial_dir(partialptr,PDIR_CREATE))
411 if (copy_file(from, to, mode) != 0)
422 static pid_t all_pids[10];
425 /** Fork and record the pid of the child. **/
428 pid_t newpid = fork();
430 if (newpid != 0 && newpid != -1) {
431 all_pids[num_pids++] = newpid;
439 * @todo It would be kind of nice to make sure that they are actually
440 * all our children before we kill them, because their pids may have
441 * been recycled by some other process. Perhaps when we wait for a
442 * child, we should remove it from this array. Alternatively we could
443 * perhaps use process groups, but I think that would not work on
444 * ancient Unix versions that don't support them.
446 void kill_all(int sig)
450 for (i = 0; i < num_pids; i++) {
451 /* Let's just be a little careful where we
452 * point that gun, hey? See kill(2) for the
453 * magic caused by negative values. */
454 pid_t p = all_pids[i];
465 /** Turn a user name into a uid */
466 int name_to_uid(char *name, uid_t *uid)
471 pass = getpwnam(name);
479 /** Turn a group name into a gid */
480 int name_to_gid(char *name, gid_t *gid)
485 grp = getgrnam(name);
493 /** Lock a byte range in a open file */
494 int lock_range(int fd, int offset, int len)
498 lock.l_type = F_WRLCK;
499 lock.l_whence = SEEK_SET;
500 lock.l_start = offset;
504 return fcntl(fd,F_SETLK,&lock) == 0;
507 static int filter_server_path(char *arg)
511 if (server_filter_list.head) {
512 for (s = arg; (s = strchr(s, '/')) != NULL; ) {
514 if (check_filter(&server_filter_list, arg, 1) < 0) {
515 /* We must leave arg truncated! */
524 static void glob_expand_one(char *s, char ***argv_ptr, int *argc_ptr,
527 char **argv = *argv_ptr;
528 int argc = *argc_ptr;
529 int maxargs = *maxargs_ptr;
530 #if !defined HAVE_GLOB || !defined HAVE_GLOB_H
531 if (argc == maxargs) {
533 if (!(argv = realloc_array(argv, char *, maxargs)))
534 out_of_memory("glob_expand_one");
536 *maxargs_ptr = maxargs;
540 s = argv[argc++] = strdup(s);
541 filter_server_path(s);
551 s = sanitize_path(NULL, s, "", 0);
555 memset(&globbuf, 0, sizeof globbuf);
556 if (!filter_server_path(s))
557 glob(s, 0, NULL, &globbuf);
558 if (MAX((int)globbuf.gl_pathc, 1) > maxargs - argc) {
559 maxargs += globbuf.gl_pathc + MAX_ARGS;
560 if (!(argv = realloc_array(argv, char *, maxargs)))
561 out_of_memory("glob_expand_one");
563 *maxargs_ptr = maxargs;
565 if (globbuf.gl_pathc == 0)
570 for (i = 0; i < (int)globbuf.gl_pathc; i++) {
571 if (!(argv[argc++] = strdup(globbuf.gl_pathv[i])))
572 out_of_memory("glob_expand_one");
580 /* This routine is only used in daemon mode. */
581 void glob_expand(char *base1, char ***argv_ptr, int *argc_ptr, int *maxargs_ptr)
583 char *s = (*argv_ptr)[*argc_ptr];
586 int base_len = strlen(base);
591 if (strncmp(s, base, base_len) == 0)
594 if (!(s = strdup(s)))
595 out_of_memory("glob_expand");
597 if (asprintf(&base," %s/", base1) <= 0)
598 out_of_memory("glob_expand");
601 for (q = s; *q; q = p + base_len) {
602 if ((p = strstr(q, base)) != NULL)
603 *p = '\0'; /* split it at this point */
604 glob_expand_one(q, argv_ptr, argc_ptr, maxargs_ptr);
614 * Convert a string to lower case
616 void strlower(char *s)
619 if (isupper(*(unsigned char *)s))
620 *s = tolower(*(unsigned char *)s);
625 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
626 * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
627 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
628 * string fits into destsize. */
629 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
631 size_t len = strlcpy(dest, p1, destsize);
632 if (len < destsize - 1) {
633 if (!len || dest[len-1] != '/')
635 if (len < destsize - 1)
636 len += strlcpy(dest + len, p2, destsize - len);
643 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
647 /* Join any number of strings together, putting them in "dest". The return
648 * value is the length of all the strings, regardless of whether the null-
649 * terminated whole fits in destsize. Your list of string pointers must end
650 * with a NULL to indicate the end of the list. */
651 size_t stringjoin(char *dest, size_t destsize, ...)
657 va_start(ap, destsize);
659 if (!(src = va_arg(ap, const char *)))
666 memcpy(dest, src, len);
677 int count_dir_elements(const char *p)
679 int cnt = 0, new_component = 1;
683 else if (new_component) {
691 /* Turns multiple adjacent slashes into a single slash, gets rid of "./"
692 * elements (but not a trailing dot dir), removes a trailing slash, and
693 * optionally collapses ".." elements (except for those at the start of the
694 * string). If the resulting name would be empty, change it into a ".". */
695 unsigned int clean_fname(char *name, BOOL collapse_dot_dot)
697 char *limit = name - 1, *t = name, *f = name;
703 if ((anchored = *f == '/') != 0)
706 /* discard extra slashes */
712 /* discard "." dirs (but NOT a trailing '.'!) */
717 /* collapse ".." dirs */
719 && f[1] == '.' && (f[2] == '/' || !f[2])) {
721 if (s == name && anchored) {
725 while (s > limit && *--s != '/') {}
726 if (s != t - 1 && (s < name || *s == '/')) {
734 while (*f && (*t++ = *f++) != '/') {}
737 if (t > name+anchored && t[-1] == '/')
746 /* Make path appear as if a chroot had occurred. This handles a leading
747 * "/" (either removing it or expanding it) and any leading or embedded
748 * ".." components that attempt to escape past the module's top dir.
750 * If dest is NULL, a buffer is allocated to hold the result. It is legal
751 * to call with the dest and the path (p) pointing to the same buffer, but
752 * rootdir will be ignored to avoid expansion of the string.
754 * The rootdir string contains a value to use in place of a leading slash.
755 * Specify NULL to get the default of lp_path(module_id).
757 * If depth is >= 0, it is a count of how many '..'s to allow at the start
758 * of the path. Use -1 to allow unlimited depth.
760 * We also clean the path in a manner similar to clean_fname() but with a
763 * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
764 * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
765 * ALWAYS collapses ".." elements (except for those at the start of the
766 * string up to "depth" deep). If the resulting name would be empty,
767 * change it into a ".". */
768 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth)
771 int rlen = 0, leave_one_dotdir = relative_paths;
774 int plen = strlen(p);
777 rootdir = lp_path(module_id);
778 rlen = strlen(rootdir);
783 if (rlen + plen + 1 >= MAXPATHLEN)
785 } else if (!(dest = new_array(char, rlen + plen + 1)))
786 out_of_memory("sanitize_path");
788 memcpy(dest, rootdir, rlen);
794 start = sanp = dest + rlen;
796 /* discard leading or extra slashes */
801 /* this loop iterates once per filename component in p.
802 * both p (and sanp if the original had a slash) should
803 * always be left pointing after a slash
805 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
806 if (leave_one_dotdir && p[1])
807 leave_one_dotdir = 0;
809 /* skip "." component */
814 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
815 /* ".." component followed by slash or end */
816 if (depth <= 0 || sanp != start) {
819 /* back up sanp one level */
820 --sanp; /* now pointing at slash */
821 while (sanp > start && sanp[-1] != '/') {
822 /* skip back up to slash */
828 /* allow depth levels of .. at the beginning */
830 /* move the virtual beginning to leave the .. alone */
833 /* copy one component through next slash */
834 while (*p && (*sanp++ = *p++) != '/') {}
837 /* ended up with nothing, so put in "." component */
845 char curr_dir[MAXPATHLEN];
846 unsigned int curr_dir_len;
849 * Like chdir(), but it keeps track of the current directory (in the
850 * global "curr_dir"), and ensures that the path size doesn't overflow.
851 * Also cleans the path using the clean_fname() function.
853 int push_dir(char *dir)
855 static int initialised;
860 getcwd(curr_dir, sizeof curr_dir - 1);
861 curr_dir_len = strlen(curr_dir);
864 if (!dir) /* this call was probably just to initialize */
868 if (len == 1 && *dir == '.')
871 if ((*dir == '/' ? len : curr_dir_len + 1 + len) >= sizeof curr_dir)
878 memcpy(curr_dir, dir, len + 1);
881 curr_dir[curr_dir_len++] = '/';
882 memcpy(curr_dir + curr_dir_len, dir, len + 1);
886 curr_dir_len = clean_fname(curr_dir, 1);
892 * Reverse a push_dir() call. You must pass in an absolute path
893 * that was copied from a prior value of "curr_dir".
895 int pop_dir(char *dir)
900 curr_dir_len = strlcpy(curr_dir, dir, sizeof curr_dir);
901 if (curr_dir_len >= sizeof curr_dir)
902 curr_dir_len = sizeof curr_dir - 1;
908 * Return a quoted string with the full pathname of the indicated filename.
909 * The string " (in MODNAME)" may also be appended. The returned pointer
910 * remains valid until the next time full_fname() is called.
912 char *full_fname(const char *fn)
914 static char *result = NULL;
925 for (p2 = p1; *p2 == '/'; p2++) {}
929 if (module_id >= 0) {
931 m2 = lp_name(module_id);
933 if (p1 == curr_dir) {
934 if (!lp_use_chroot(module_id)) {
935 char *p = lp_path(module_id);
936 if (*p != '/' || p[1])
943 asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3);
948 static char partial_fname[MAXPATHLEN];
950 char *partial_dir_fname(const char *fname)
952 char *t = partial_fname;
953 int sz = sizeof partial_fname;
956 if ((fn = strrchr(fname, '/')) != NULL) {
958 if (*partial_dir != '/') {
959 int len = fn - fname;
960 strncpy(t, fname, len); /* safe */
966 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
968 if (server_filter_list.head) {
971 len = strlen(partial_dir);
973 if (check_filter(&server_filter_list, partial_fname, 1) < 0)
976 if (check_filter(&server_filter_list, partial_fname, 0) < 0)
980 return partial_fname;
983 /* If no --partial-dir option was specified, we don't need to do anything
984 * (the partial-dir is essentially '.'), so just return success. */
985 int handle_partial_dir(const char *fname, int create)
989 if (fname != partial_fname)
991 if (!create && *partial_dir == '/')
993 if (!(fn = strrchr(partial_fname, '/')))
1000 int statret = do_lstat(dir, &st);
1001 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1002 if (do_unlink(dir) < 0)
1006 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1016 * Determine if a symlink points outside the current directory tree.
1017 * This is considered "unsafe" because e.g. when mirroring somebody
1018 * else's machine it might allow them to establish a symlink to
1019 * /etc/passwd, and then read it through a web server.
1021 * Null symlinks and absolute symlinks are always unsafe.
1023 * Basically here we are concerned with symlinks whose target contains
1024 * "..", because this might cause us to walk back up out of the
1025 * transferred directory. We are not allowed to go back up and
1028 * @param dest Target of the symlink in question.
1030 * @param src Top source directory currently applicable. Basically this
1031 * is the first parameter to rsync in a simple invocation, but it's
1032 * modified by flist.c in slightly complex ways.
1034 * @retval True if unsafe
1035 * @retval False is unsafe
1039 int unsafe_symlink(const char *dest, const char *src)
1041 const char *name, *slash;
1044 /* all absolute and null symlinks are unsafe */
1045 if (!dest || !*dest || *dest == '/')
1048 /* find out what our safety margin is */
1049 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1050 if (strncmp(name, "../", 3) == 0) {
1052 } else if (strncmp(name, "./", 2) == 0) {
1058 if (strcmp(name, "..") == 0)
1061 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1062 if (strncmp(name, "../", 3) == 0) {
1063 /* if at any point we go outside the current directory
1064 then stop - it is unsafe */
1067 } else if (strncmp(name, "./", 2) == 0) {
1073 if (strcmp(name, "..") == 0)
1079 /* Return the int64 number as a string. If the --human-readable option was
1080 * specified, we may output the number in K, M, or G units. We can return
1081 * up to 4 buffers at a time. */
1082 char *human_num(int64 num)
1084 static char bufs[4][128]; /* more than enough room */
1085 static unsigned int n;
1088 n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
1090 if (human_readable) {
1092 int mult = human_readable == 1 ? 1000 : 1024;
1094 if (num > mult*mult*mult) {
1095 dnum = (double)num / (mult*mult*mult);
1097 } else if (num > mult*mult) {
1098 dnum = (double)num / (mult*mult);
1100 } else if (num > mult) {
1101 dnum = (double)num / mult;
1105 sprintf(bufs[n], "%.2f%c", dnum, units);
1110 s = bufs[n] + sizeof bufs[0] - 1;
1116 *--s = (num % 10) + '0';
1122 /* Return the double number as a string. If the --human-readable option was
1123 * specified, we may output the number in K, M, or G units. We use a buffer
1124 * from human_num() to return our result. */
1125 char *human_dnum(double dnum, int decimal_digits)
1127 char *buf = human_num(dnum);
1128 int len = strlen(buf);
1129 if (isdigit(*(uchar*)(buf+len-1))) {
1130 /* There's extra room in buf prior to the start of the num. */
1131 buf -= decimal_digits + 1;
1132 snprintf(buf, len + decimal_digits + 2, "%.*f", decimal_digits, dnum);
1138 * Return the date and time as a string
1140 char *timestring(time_t t)
1142 static char TimeBuf[200];
1143 struct tm *tm = localtime(&t);
1146 #ifdef HAVE_STRFTIME
1147 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
1149 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
1152 if ((p = strchr(TimeBuf, '\n')) != NULL)
1159 * Sleep for a specified number of milliseconds.
1161 * Always returns TRUE. (In the future it might return FALSE if
1167 struct timeval tval, t1, t2;
1169 gettimeofday(&t1, NULL);
1172 tval.tv_sec = (t-tdiff)/1000;
1173 tval.tv_usec = 1000*((t-tdiff)%1000);
1176 select(0,NULL,NULL, NULL, &tval);
1178 gettimeofday(&t2, NULL);
1179 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1180 (t2.tv_usec - t1.tv_usec)/1000;
1186 /* Determine if two time_t values are equivalent (either exact, or in
1187 * the modification timestamp window established by --modify-window).
1189 * @retval 0 if the times should be treated as the same
1191 * @retval +1 if the first is later
1193 * @retval -1 if the 2nd is later
1195 int cmp_time(time_t file1, time_t file2)
1197 if (file2 > file1) {
1198 if (file2 - file1 <= modify_window)
1202 if (file1 - file2 <= modify_window)
1212 This routine is a trick to immediately catch errors when debugging
1213 with insure. A xterm with a gdb is popped up when insure catches
1214 a error. It is Linux specific.
1216 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1222 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'",
1223 getpid(), getpid(), getpid());
1227 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1228 fn = dlsym(h, "_Insure_trap_error");
1231 ret = fn(a1, a2, a3, a4, a5, a6);
1241 #define MALLOC_MAX 0x40000000
1243 void *_new_array(unsigned int size, unsigned long num)
1245 if (num >= MALLOC_MAX/size)
1247 return malloc(size * num);
1250 void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
1252 if (num >= MALLOC_MAX/size)
1254 /* No realloc should need this, but just in case... */
1256 return malloc(size * num);
1257 return realloc(ptr, size * num);
1260 /* Take a filename and filename length and return the most significant
1261 * filename suffix we can find. This ignores suffixes such as "~",
1262 * ".bak", ".orig", ".~1~", etc. */
1263 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1265 const char *suf, *s;
1269 /* One or more dots at the start aren't a suffix. */
1270 while (fn_len && *fn == '.') fn++, fn_len--;
1272 /* Ignore the ~ in a "foo~" filename. */
1273 if (fn_len > 1 && fn[fn_len-1] == '~')
1274 fn_len--, had_tilde = True;
1278 /* Assume we don't find an suffix. */
1282 /* Find the last significant suffix. */
1283 for (s = fn + fn_len; fn_len > 1; ) {
1284 while (*--s != '.' && s != fn) {}
1287 s_len = fn_len - (s - fn);
1290 if (strcmp(s+1, "bak") == 0
1291 || strcmp(s+1, "old") == 0)
1293 } else if (s_len == 5) {
1294 if (strcmp(s+1, "orig") == 0)
1296 } else if (s_len > 2 && had_tilde
1297 && s[1] == '~' && isdigit(*(uchar*)(s+2)))
1303 /* Determine if the suffix is all digits. */
1304 for (s++, s_len--; s_len > 0; s++, s_len--) {
1305 if (!isdigit(*(uchar*)s))
1308 /* An all-digit suffix may not be that signficant. */
1315 /* This is an implementation of the Levenshtein distance algorithm. It
1316 * was implemented to avoid needing a two-dimensional matrix (to save
1317 * memory). It was also tweaked to try to factor in the ASCII distance
1318 * between changed characters as a minor distance quantity. The normal
1319 * Levenshtein units of distance (each signifying a single change between
1320 * the two strings) are defined as a "UNIT". */
1322 #define UNIT (1 << 16)
1324 uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1326 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1330 if (!len1 || !len2) {
1335 for (i1 = 0, cost = 0; i1 < len1; i1++)
1337 return (int32)len1 * UNIT + cost;
1340 for (i2 = 0; i2 < len2; i2++)
1341 a[i2] = (i2+1) * UNIT;
1343 for (i1 = 0; i1 < len1; i1++) {
1345 above = (i1+1) * UNIT;
1346 for (i2 = 0; i2 < len2; i2++) {
1348 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1354 diag_inc = diag + cost;
1355 left_inc = left + UNIT + *((uchar*)s1+i1);
1356 above_inc = above + UNIT + *((uchar*)s2+i2);
1357 a[i2] = above = left < above
1358 ? (left_inc < diag_inc ? left_inc : diag_inc)
1359 : (above_inc < diag_inc ? above_inc : diag_inc);
1367 #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1368 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1369 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1376 struct bitbag *bitbag_create(int max_ndx)
1378 struct bitbag *bb = new(struct bitbag);
1379 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1381 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1382 out_of_memory("bitbag_create");
1387 void bitbag_set_bit(struct bitbag *bb, int ndx)
1389 int slot = ndx / BB_PER_SLOT_BITS;
1390 ndx %= BB_PER_SLOT_BITS;
1392 if (!bb->bits[slot]) {
1393 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1394 out_of_memory("bitbag_set_bit");
1397 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1400 #if 0 /* not needed yet */
1401 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1403 int slot = ndx / BB_PER_SLOT_BITS;
1404 ndx %= BB_PER_SLOT_BITS;
1406 if (!bb->bits[slot])
1409 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1412 int bitbag_check_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 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1424 /* Call this with -1 to start checking from 0. Returns -1 at the end. */
1425 int bitbag_next_bit(struct bitbag *bb, int after)
1428 int i, ndx = after + 1;
1429 int slot = ndx / BB_PER_SLOT_BITS;
1430 ndx %= BB_PER_SLOT_BITS;
1432 mask = (1u << (ndx % 32)) - 1;
1433 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1434 if (!bb->bits[slot])
1436 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1437 if (!(bits = bb->bits[slot][i] & ~mask))
1439 /* The xor magic figures out the lowest enabled bit in
1440 * bits, and the switch quickly computes log2(bit). */
1441 switch (bits ^ (bits & (bits-1))) {
1442 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1443 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1444 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1445 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1446 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1447 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1448 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1449 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1450 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1452 return -1; /* impossible... */