We omit copying any user-space rsync.%FOO attributes unless the
[rsync/rsync.git] / util.c
CommitLineData
0f78b815
WD
1/*
2 * Utility routines used in rsync.
5cb37436 3 *
0f78b815
WD
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
ba2133d6 7 * Copyright (C) 2003-2007 Wayne Davison
5cb37436 8 *
0ecfbf27 9 * This program is free software; you can redistribute it and/or modify
ba2133d6
WD
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
5cb37436 12 *
0ecfbf27
MP
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.
5cb37436 17 *
e7c67065
WD
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.
0ecfbf27 21 */
c627d613 22
c627d613
AT
23#include "rsync.h"
24
c7c11a0d 25extern int verbose;
bc6ebcd2
WD
26extern int dry_run;
27extern int module_id;
28extern int modify_window;
7e43da81 29extern int relative_paths;
e175fb07 30extern int human_readable;
a8167c66 31extern unsigned int module_dirlen;
e9357a2d 32extern mode_t orig_umask;
a7260c40 33extern char *partial_dir;
7842418b 34extern struct filter_list_struct server_filter_list;
c7c11a0d 35
0ecfbf27
MP
36int sanitize_paths = 0;
37
a8167c66
WD
38char curr_dir[MAXPATHLEN];
39unsigned int curr_dir_len;
40int curr_dir_depth; /* This is only set for a sanitizing daemon. */
41
0f78b815 42/* Set a fd into nonblocking mode. */
f0359dd0
AT
43void set_nonblocking(int fd)
44{
45 int val;
46
ff530f04 47 if ((val = fcntl(fd, F_GETFL)) == -1)
f0359dd0
AT
48 return;
49 if (!(val & NONBLOCK_FLAG)) {
50 val |= NONBLOCK_FLAG;
51 fcntl(fd, F_SETFL, val);
52 }
53}
54
0f78b815 55/* Set a fd into blocking mode. */
36349ea0
AT
56void set_blocking(int fd)
57{
58 int val;
59
ff530f04 60 if ((val = fcntl(fd, F_GETFL)) == -1)
36349ea0
AT
61 return;
62 if (val & NONBLOCK_FLAG) {
63 val &= ~NONBLOCK_FLAG;
64 fcntl(fd, F_SETFL, val);
65 }
66}
67
ac13ad10 68/**
0ecfbf27
MP
69 * Create a file descriptor pair - like pipe() but use socketpair if
70 * possible (because of blocking issues on pipes).
5cb37436 71 *
0ecfbf27 72 * Always set non-blocking.
f0359dd0 73 */
08f15335
AT
74int fd_pair(int fd[2])
75{
f0359dd0
AT
76 int ret;
77
4f5b0756 78#ifdef HAVE_SOCKETPAIR
f0359dd0 79 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
08f15335 80#else
f0359dd0 81 ret = pipe(fd);
08f15335 82#endif
f0359dd0
AT
83
84 if (ret == 0) {
85 set_nonblocking(fd[0]);
86 set_nonblocking(fd[1]);
87 }
0ecfbf27 88
f0359dd0 89 return ret;
08f15335
AT
90}
91
0ecfbf27 92void print_child_argv(char **cmd)
5ad0e46f 93{
a3f6dbdf 94 rprintf(FCLIENT, "opening connection using ");
5ad0e46f
MP
95 for (; *cmd; cmd++) {
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"
101 "0123456789"
102 ",.-_=+@/") != strlen(*cmd)) {
a3f6dbdf 103 rprintf(FCLIENT, "\"%s\" ", *cmd);
5ad0e46f 104 } else {
a3f6dbdf 105 rprintf(FCLIENT, "%s ", *cmd);
5ad0e46f
MP
106 }
107 }
a3f6dbdf 108 rprintf(FCLIENT, "\n");
5ad0e46f
MP
109}
110
4a19c3b2 111NORETURN void out_of_memory(const char *str)
c627d613 112{
2cd421d8 113 rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
c284f34a 114 exit_cleanup(RERR_MALLOC);
575f2fca
AT
115}
116
4a19c3b2 117NORETURN void overflow_exit(const char *str)
575f2fca 118{
2cd421d8 119 rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
c284f34a 120 exit_cleanup(RERR_MALLOC);
c627d613
AT
121}
122
4a19c3b2 123int set_modtime(const char *fname, time_t modtime, mode_t mode)
c627d613 124{
25007999
WD
125#if !defined HAVE_LUTIMES || !defined HAVE_UTIMES
126 if (S_ISLNK(mode))
127 return 1;
128#endif
129
404e813c
MP
130 if (verbose > 2) {
131 rprintf(FINFO, "set modtime of %s to (%ld) %s",
785abd48 132 fname, (long)modtime,
404e813c
MP
133 asctime(localtime(&modtime)));
134 }
5cb37436 135
15778afb
WD
136 if (dry_run)
137 return 0;
138
31e12522 139 {
25007999
WD
140#ifdef HAVE_UTIMES
141 struct timeval t[2];
142 t[0].tv_sec = time(NULL);
143 t[0].tv_usec = 0;
144 t[1].tv_sec = modtime;
145 t[1].tv_usec = 0;
146# ifdef HAVE_LUTIMES
149a78e3
WD
147 if (S_ISLNK(mode)) {
148 lutimes(fname, t);
149 return 0; /* ignore errors */
150 }
25007999
WD
151# endif
152 return utimes(fname, t);
153#elif defined HAVE_UTIMBUF
5cb37436 154 struct utimbuf tbuf;
31e12522
AT
155 tbuf.actime = time(NULL);
156 tbuf.modtime = modtime;
157 return utime(fname,&tbuf);
4f5b0756 158#elif defined HAVE_UTIME
31e12522
AT
159 time_t t[2];
160 t[0] = time(NULL);
161 t[1] = modtime;
162 return utime(fname,t);
c627d613 163#else
25007999 164#error No file-time-modification routine found!
c627d613 165#endif
31e12522 166 }
c627d613 167}
94481d91 168
e9357a2d
WD
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(). */
172int mkdir_defmode(char *fname)
173{
174 int ret;
175
176 umask(orig_umask);
177 ret = do_mkdir(fname, ACCESSPERMS);
178 umask(0);
179
180 return ret;
181}
182
85c41757
WD
183/* Create any necessary directories in fname. Any missing directories are
184 * created with default permissions. */
e9357a2d 185int create_directory_path(char *fname)
6574b4f7 186{
6574b4f7 187 char *p;
85c41757 188 int ret = 0;
6574b4f7 189
c284f34a
WD
190 while (*fname == '/')
191 fname++;
192 while (strncmp(fname, "./", 2) == 0)
193 fname += 2;
6574b4f7 194
85c41757 195 umask(orig_umask);
6574b4f7 196 p = fname;
c284f34a 197 while ((p = strchr(p,'/')) != NULL) {
85c41757
WD
198 *p = '\0';
199 if (do_mkdir(fname, ACCESSPERMS) < 0 && errno != EEXIST)
200 ret = -1;
201 *p++ = '/';
6574b4f7 202 }
85c41757
WD
203 umask(0);
204
205 return ret;
6574b4f7 206}
950ab32d 207
ac13ad10
MP
208/**
209 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
210 * interrupted.
211 *
212 * @retval len upon success
213 *
214 * @retval <0 write's (negative) error code
215 *
216 * Derived from GNU C's cccp.c.
217 */
4a19c3b2 218int full_write(int desc, const char *ptr, size_t len)
950ab32d
AT
219{
220 int total_written;
5cb37436 221
950ab32d
AT
222 total_written = 0;
223 while (len > 0) {
5c1b7bfd 224 int written = write(desc, ptr, len);
950ab32d 225 if (written < 0) {
950ab32d
AT
226 if (errno == EINTR)
227 continue;
950ab32d
AT
228 return written;
229 }
230 total_written += written;
231 ptr += written;
232 len -= written;
233 }
234 return total_written;
235}
236
ac13ad10
MP
237/**
238 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
239 * interrupted.
240 *
241 * @retval >0 the actual number of bytes read
242 *
243 * @retval 0 for EOF
244 *
245 * @retval <0 for an error.
246 *
247 * Derived from GNU C's cccp.c. */
9dd891bb 248static int safe_read(int desc, char *ptr, size_t len)
950ab32d
AT
249{
250 int n_chars;
5cb37436 251
9dd891bb 252 if (len == 0)
950ab32d 253 return len;
5cb37436 254
950ab32d
AT
255 do {
256 n_chars = read(desc, ptr, len);
257 } while (n_chars < 0 && errno == EINTR);
5cb37436 258
950ab32d
AT
259 return n_chars;
260}
261
ac13ad10
MP
262/** Copy a file.
263 *
3e13004b
WD
264 * This is used in conjunction with the --temp-dir, --backup, and
265 * --copy-dest options. */
63cf5ae7 266int copy_file(const char *source, const char *dest, mode_t mode)
950ab32d
AT
267{
268 int ifd;
269 int ofd;
270 char buf[1024 * 8];
271 int len; /* Number of bytes read into `buf'. */
272
8c9fd200 273 ifd = do_open(source, O_RDONLY, 0);
950ab32d 274 if (ifd == -1) {
d62bcc17 275 rsyserr(FERROR, errno, "open %s", full_fname(source));
950ab32d
AT
276 return -1;
277 }
278
c7c11a0d 279 if (robust_unlink(dest) && errno != ENOENT) {
d62bcc17 280 rsyserr(FERROR, errno, "unlink %s", full_fname(dest));
950ab32d
AT
281 return -1;
282 }
283
31e12522 284 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
c46ded46 285 if (ofd == -1) {
d62bcc17 286 rsyserr(FERROR, errno, "open %s", full_fname(dest));
950ab32d
AT
287 close(ifd);
288 return -1;
289 }
290
5cb37436 291 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
950ab32d 292 if (full_write(ofd, buf, len) < 0) {
d62bcc17 293 rsyserr(FERROR, errno, "write %s", full_fname(dest));
950ab32d
AT
294 close(ifd);
295 close(ofd);
296 return -1;
297 }
298 }
299
8b602edd 300 if (len < 0) {
d62bcc17 301 rsyserr(FERROR, errno, "read %s", full_fname(source));
8b602edd
WD
302 close(ifd);
303 close(ofd);
304 return -1;
305 }
306
9f27cd8c 307 if (close(ifd) < 0) {
d62bcc17
WD
308 rsyserr(FINFO, errno, "close failed on %s",
309 full_fname(source));
9f27cd8c
WD
310 }
311
312 if (close(ofd) < 0) {
d62bcc17
WD
313 rsyserr(FERROR, errno, "close failed on %s",
314 full_fname(dest));
9f27cd8c
WD
315 return -1;
316 }
950ab32d 317
950ab32d
AT
318 return 0;
319}
feaa89c4 320
c7c11a0d
DD
321/* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
322#define MAX_RENAMES_DIGITS 3
323#define MAX_RENAMES 1000
324
ac13ad10 325/**
b4235b31
MP
326 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
327 * rename to <path>/.rsyncNNN instead.
328 *
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
333 * each time.
334 **/
63cf5ae7 335int robust_unlink(const char *fname)
c7c11a0d
DD
336{
337#ifndef ETXTBSY
338 return do_unlink(fname);
339#else
340 static int counter = 1;
341 int rc, pos, start;
342 char path[MAXPATHLEN];
343
344 rc = do_unlink(fname);
c284f34a 345 if (rc == 0 || errno != ETXTBSY)
c7c11a0d
DD
346 return rc;
347
c284f34a
WD
348 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
349 pos = MAXPATHLEN - 1;
c7c11a0d 350
c284f34a
WD
351 while (pos > 0 && path[pos-1] != '/')
352 pos--;
5cb37436 353 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
c7c11a0d
DD
354
355 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
356 errno = ETXTBSY;
357 return -1;
358 }
359
360 /* start where the last one left off to reduce chance of clashes */
361 start = counter;
362 do {
434c4098 363 snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
c7c11a0d
DD
364 if (++counter >= MAX_RENAMES)
365 counter = 1;
c284f34a 366 } while ((rc = access(path, 0)) == 0 && counter != start);
c7c11a0d 367
4791825d 368 if (verbose > 0) {
c7c11a0d 369 rprintf(FINFO,"renaming %s to %s because of text busy\n",
785abd48 370 fname, path);
4791825d 371 }
c7c11a0d
DD
372
373 /* maybe we should return rename()'s exit status? Nah. */
374 if (do_rename(fname, path) != 0) {
375 errno = ETXTBSY;
376 return -1;
377 }
378 return 0;
379#endif
380}
381
630f548f 382/* Returns 0 on successful rename, 1 if we successfully copied the file
3ed8eafc
WD
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. */
4a19c3b2 386int robust_rename(const char *from, const char *to, const char *partialptr,
3ed8eafc 387 int mode)
c7c11a0d 388{
62c9e6b3
WD
389 int tries = 4;
390
391 while (tries--) {
392 if (do_rename(from, to) == 0)
393 return 0;
394
395 switch (errno) {
396#ifdef ETXTBSY
397 case ETXTBSY:
398 if (robust_unlink(to) != 0)
399 return -1;
400 break;
c7c11a0d 401#endif
62c9e6b3 402 case EXDEV:
3ed8eafc
WD
403 if (partialptr) {
404 if (!handle_partial_dir(partialptr,PDIR_CREATE))
405 return -1;
406 to = partialptr;
407 }
62c9e6b3
WD
408 if (copy_file(from, to, mode) != 0)
409 return -2;
410 do_unlink(from);
630f548f 411 return 1;
62c9e6b3
WD
412 default:
413 return -1;
414 }
415 }
416 return -1;
feaa89c4 417}
3ba62a83 418
3ba62a83
AT
419static pid_t all_pids[10];
420static int num_pids;
421
4cf64834 422/** Fork and record the pid of the child. **/
3ba62a83
AT
423pid_t do_fork(void)
424{
425 pid_t newpid = fork();
5cb37436 426
4cf64834 427 if (newpid != 0 && newpid != -1) {
3ba62a83
AT
428 all_pids[num_pids++] = newpid;
429 }
430 return newpid;
431}
432
4cf64834
MP
433/**
434 * Kill all children.
435 *
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.
442 **/
3ba62a83
AT
443void kill_all(int sig)
444{
445 int i;
4cf64834
MP
446
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];
452
453 if (p == getpid())
454 continue;
455 if (p <= 0)
456 continue;
457
458 kill(p, sig);
3ba62a83
AT
459 }
460}
9486289c 461
ac13ad10 462/** Turn a user name into a uid */
4a19c3b2 463int name_to_uid(const char *name, uid_t *uid)
8ef4ffd6
AT
464{
465 struct passwd *pass;
b5bd5542
WD
466 if (!name || !*name)
467 return 0;
8ef4ffd6
AT
468 pass = getpwnam(name);
469 if (pass) {
470 *uid = pass->pw_uid;
471 return 1;
472 }
473 return 0;
474}
475
ac13ad10 476/** Turn a group name into a gid */
4a19c3b2 477int name_to_gid(const char *name, gid_t *gid)
8ef4ffd6
AT
478{
479 struct group *grp;
b5bd5542
WD
480 if (!name || !*name)
481 return 0;
8ef4ffd6
AT
482 grp = getgrnam(name);
483 if (grp) {
484 *gid = grp->gr_gid;
485 return 1;
486 }
487 return 0;
488}
489
ac13ad10 490/** Lock a byte range in a open file */
31593dd6 491int lock_range(int fd, int offset, int len)
0c515f17 492{
31593dd6 493 struct flock lock;
0c515f17 494
31593dd6
AT
495 lock.l_type = F_WRLCK;
496 lock.l_whence = SEEK_SET;
497 lock.l_start = offset;
498 lock.l_len = len;
499 lock.l_pid = 0;
5cb37436 500
31593dd6 501 return fcntl(fd,F_SETLK,&lock) == 0;
0c515f17 502}
874895d5 503
7842418b 504static int filter_server_path(char *arg)
4791825d
WD
505{
506 char *s;
4791825d 507
7842418b 508 if (server_filter_list.head) {
4791825d
WD
509 for (s = arg; (s = strchr(s, '/')) != NULL; ) {
510 *s = '\0';
7842418b 511 if (check_filter(&server_filter_list, arg, 1) < 0) {
4791825d
WD
512 /* We must leave arg truncated! */
513 return 1;
514 }
515 *s++ = '/';
516 }
517 }
518 return 0;
519}
874895d5 520
b7061c82
WD
521static void glob_expand_one(char *s, char ***argv_ptr, int *argc_ptr,
522 int *maxargs_ptr)
874895d5 523{
b7061c82 524 char **argv = *argv_ptr;
b5bd5542 525 int argc = *argc_ptr;
b7061c82 526 int maxargs = *maxargs_ptr;
4f5b0756 527#if !defined HAVE_GLOB || !defined HAVE_GLOB_H
b7061c82
WD
528 if (argc == maxargs) {
529 maxargs += MAX_ARGS;
530 if (!(argv = realloc_array(argv, char *, maxargs)))
531 out_of_memory("glob_expand_one");
532 *argv_ptr = argv;
533 *maxargs_ptr = maxargs;
534 }
4135d091
WD
535 if (!*s)
536 s = ".";
b5bd5542 537 s = argv[argc++] = strdup(s);
7842418b 538 filter_server_path(s);
874895d5
AT
539#else
540 glob_t globbuf;
874895d5 541
b5bd5542
WD
542 if (maxargs <= argc)
543 return;
4135d091
WD
544 if (!*s)
545 s = ".";
e42c9458 546
4135d091 547 if (sanitize_paths)
a8167c66 548 s = sanitize_path(NULL, s, "", 0, NULL);
84a63795
WD
549 else
550 s = strdup(s);
087bf010 551
5cb37436 552 memset(&globbuf, 0, sizeof globbuf);
7842418b 553 if (!filter_server_path(s))
4791825d 554 glob(s, 0, NULL, &globbuf);
b7061c82
WD
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");
559 *argv_ptr = argv;
560 *maxargs_ptr = maxargs;
561 }
b5bd5542
WD
562 if (globbuf.gl_pathc == 0)
563 argv[argc++] = s;
564 else {
c8933031 565 int i;
b5bd5542 566 free(s);
c8933031 567 for (i = 0; i < (int)globbuf.gl_pathc; i++) {
b5bd5542
WD
568 if (!(argv[argc++] = strdup(globbuf.gl_pathv[i])))
569 out_of_memory("glob_expand_one");
570 }
874895d5
AT
571 }
572 globfree(&globbuf);
874895d5 573#endif
b5bd5542 574 *argc_ptr = argc;
874895d5 575}
5a96ee05 576
4791825d 577/* This routine is only used in daemon mode. */
b7061c82 578void glob_expand(char *base1, char ***argv_ptr, int *argc_ptr, int *maxargs_ptr)
087bf010 579{
b7061c82 580 char *s = (*argv_ptr)[*argc_ptr];
087bf010 581 char *p, *q;
ba5e128d 582 char *base = base1;
4791825d 583 int base_len = strlen(base);
087bf010 584
b5bd5542
WD
585 if (!s || !*s)
586 return;
087bf010 587
4791825d
WD
588 if (strncmp(s, base, base_len) == 0)
589 s += base_len;
e42c9458 590
b5bd5542
WD
591 if (!(s = strdup(s)))
592 out_of_memory("glob_expand");
087bf010 593
b5bd5542
WD
594 if (asprintf(&base," %s/", base1) <= 0)
595 out_of_memory("glob_expand");
4791825d 596 base_len++;
ba5e128d 597
b5bd5542
WD
598 for (q = s; *q; q = p + base_len) {
599 if ((p = strstr(q, base)) != NULL)
600 *p = '\0'; /* split it at this point */
b7061c82 601 glob_expand_one(q, argv_ptr, argc_ptr, maxargs_ptr);
b5bd5542
WD
602 if (!p)
603 break;
087bf010
AT
604 }
605
087bf010 606 free(s);
ba5e128d 607 free(base);
087bf010 608}
5a96ee05 609
ac13ad10
MP
610/**
611 * Convert a string to lower case
612 **/
5a96ee05
AT
613void strlower(char *s)
614{
615 while (*s) {
2dc7b8bd
WD
616 if (isUpper(s))
617 *s = toLower(s);
5a96ee05
AT
618 s++;
619 }
620}
e42c9458 621
368ad70e
WD
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
a8f7e4b8
WD
624 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
625 * string fits into destsize. */
368ad70e
WD
626size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
627{
628 size_t len = strlcpy(dest, p1, destsize);
629 if (len < destsize - 1) {
630 if (!len || dest[len-1] != '/')
631 dest[len++] = '/';
632 if (len < destsize - 1)
633 len += strlcpy(dest + len, p2, destsize - len);
634 else {
635 dest[len] = '\0';
636 len += strlen(p2);
637 }
638 }
639 else
640 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
641 return len;
642}
643
644/* Join any number of strings together, putting them in "dest". The return
a8f7e4b8
WD
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. */
368ad70e
WD
648size_t stringjoin(char *dest, size_t destsize, ...)
649{
5cb37436 650 va_list ap;
368ad70e
WD
651 size_t len, ret = 0;
652 const char *src;
653
654 va_start(ap, destsize);
655 while (1) {
656 if (!(src = va_arg(ap, const char *)))
657 break;
658 len = strlen(src);
659 ret += len;
660 if (destsize > 1) {
661 if (len >= destsize)
662 len = destsize - 1;
663 memcpy(dest, src, len);
664 destsize -= len;
665 dest += len;
666 }
667 }
668 *dest = '\0';
669 va_end(ap);
670
671 return ret;
672}
673
1d6b8f9a
WD
674int count_dir_elements(const char *p)
675{
676 int cnt = 0, new_component = 1;
677 while (*p) {
678 if (*p++ == '/')
a8167c66 679 new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
1d6b8f9a
WD
680 else if (new_component) {
681 new_component = 0;
682 cnt++;
683 }
684 }
685 return cnt;
686}
687
b92693da
WD
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 ".". */
692unsigned int clean_fname(char *name, BOOL collapse_dot_dot)
5243c216 693{
e012b94f 694 char *limit = name - 1, *t = name, *f = name;
ebdd24d6 695 int anchored;
5243c216 696
b5bd5542 697 if (!name)
3104620c 698 return 0;
5243c216 699
ebdd24d6
WD
700 if ((anchored = *f == '/') != 0)
701 *t++ = *f++;
702 while (*f) {
703 /* discard extra slashes */
704 if (*f == '/') {
705 f++;
706 continue;
5243c216 707 }
ebdd24d6
WD
708 if (*f == '.') {
709 /* discard "." dirs (but NOT a trailing '.'!) */
710 if (f[1] == '/') {
e012b94f 711 f += 2;
ebdd24d6
WD
712 continue;
713 }
714 /* collapse ".." dirs */
b92693da
WD
715 if (collapse_dot_dot
716 && f[1] == '.' && (f[2] == '/' || !f[2])) {
ebdd24d6
WD
717 char *s = t - 1;
718 if (s == name && anchored) {
719 f += 2;
720 continue;
721 }
722 while (s > limit && *--s != '/') {}
e012b94f 723 if (s != t - 1 && (s < name || *s == '/')) {
ebdd24d6
WD
724 t = s + 1;
725 f += 2;
726 continue;
727 }
f55c2dfc 728 limit = t + 2;
5243c216
AT
729 }
730 }
ebdd24d6 731 while (*f && (*t++ = *f++) != '/') {}
5243c216 732 }
ebdd24d6
WD
733
734 if (t > name+anchored && t[-1] == '/')
735 t--;
736 if (t == name)
737 *t++ = '.';
738 *t = '\0';
3104620c
WD
739
740 return t - name;
5243c216
AT
741}
742
84a63795
WD
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.
b4235b31 746 *
1d6b8f9a
WD
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.
b4235b31 750 *
1d6b8f9a
WD
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).
ac13ad10 753 *
a8167c66
WD
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**.
ac13ad10 757 *
b92693da 758 * We also clean the path in a manner similar to clean_fname() but with a
0f78b815 759 * few differences:
b92693da
WD
760 *
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 ".". */
a8167c66
WD
766char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
767 const char *symlink)
1b8e662a 768{
a8167c66 769 char *start, *sanp, *save_dest = dest;
7e43da81 770 int rlen = 0, leave_one_dotdir = relative_paths;
84a63795 771
a8167c66
WD
772 if (symlink && *symlink == '/') {
773 p = symlink;
774 symlink = "";
775 }
776
84a63795
WD
777 if (dest != p) {
778 int plen = strlen(p);
1d6b8f9a
WD
779 if (*p == '/') {
780 if (!rootdir)
781 rootdir = lp_path(module_id);
782 rlen = strlen(rootdir);
783 depth = 0;
84a63795
WD
784 p++;
785 }
786 if (dest) {
787 if (rlen + plen + 1 >= MAXPATHLEN)
788 return NULL;
789 } else if (!(dest = new_array(char, rlen + plen + 1)))
790 out_of_memory("sanitize_path");
791 if (rlen) {
1d6b8f9a 792 memcpy(dest, rootdir, rlen);
84a63795
WD
793 if (rlen > 1)
794 dest[rlen++] = '/';
795 }
796 }
cb13abfe 797
84a63795 798 start = sanp = dest + rlen;
a8167c66
WD
799 while (1) {
800 if (*p == '\0') {
801 if (!symlink || !*symlink)
802 break;
803 while (sanp != start && sanp[-1] != '/') {
804 /* strip last element */
805 sanp--;
806 }
807 /* Append a relative symlink */
808 p = symlink;
809 symlink = "";
810 }
2d41264e
WD
811 /* discard leading or extra slashes */
812 if (*p == '/') {
813 p++;
814 continue;
815 }
b5f9e67d 816 /* this loop iterates once per filename component in p.
44e2e578 817 * both p (and sanp if the original had a slash) should
b5f9e67d
DD
818 * always be left pointing after a slash
819 */
c284f34a 820 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
35812ea1 821 if (leave_one_dotdir && p[1])
7e43da81
WD
822 leave_one_dotdir = 0;
823 else {
824 /* skip "." component */
825 p++;
826 continue;
827 }
cb13abfe 828 }
c284f34a 829 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
cb13abfe 830 /* ".." component followed by slash or end */
8e5f029e 831 if (depth <= 0 || sanp != start) {
a8167c66
WD
832 if (symlink && sanp == start) {
833 if (!save_dest)
834 free(dest);
835 return NULL;
836 }
8e5f029e
WD
837 p += 2;
838 if (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 */
843 sanp--;
844 }
b5f9e67d 845 }
8e5f029e 846 continue;
1b8e662a 847 }
8e5f029e
WD
848 /* allow depth levels of .. at the beginning */
849 depth--;
850 /* move the virtual beginning to leave the .. alone */
851 start = sanp + 3;
1b8e662a 852 }
2d41264e
WD
853 /* copy one component through next slash */
854 while (*p && (*sanp++ = *p++) != '/') {}
1b8e662a 855 }
84a63795 856 if (sanp == dest) {
b5f9e67d 857 /* ended up with nothing, so put in "." component */
44e2e578 858 *sanp++ = '.';
b5f9e67d 859 }
44e2e578 860 *sanp = '\0';
1b8e662a 861
84a63795 862 return dest;
14b61c63 863}
5243c216 864
a8167c66 865/* Like chdir(), but it keeps track of the current directory (in the
a16d8f2b 866 * global "curr_dir"), and ensures that the path size doesn't overflow.
a8167c66 867 * Also cleans the path using the clean_fname() function. */
2c708476 868int push_dir(const char *dir, int set_path_only)
5243c216 869{
5243c216 870 static int initialised;
4af8fe4e 871 unsigned int len;
5243c216
AT
872
873 if (!initialised) {
874 initialised = 1;
5cb37436 875 getcwd(curr_dir, sizeof curr_dir - 1);
4af8fe4e 876 curr_dir_len = strlen(curr_dir);
5243c216
AT
877 }
878
4af8fe4e
WD
879 if (!dir) /* this call was probably just to initialize */
880 return 0;
c226b7c2 881
4af8fe4e
WD
882 len = strlen(dir);
883 if (len == 1 && *dir == '.')
884 return 1;
5243c216 885
4af8fe4e
WD
886 if ((*dir == '/' ? len : curr_dir_len + 1 + len) >= sizeof curr_dir)
887 return 0;
888
ba081be3 889 if (!set_path_only && chdir(dir))
4af8fe4e 890 return 0;
5243c216
AT
891
892 if (*dir == '/') {
4af8fe4e
WD
893 memcpy(curr_dir, dir, len + 1);
894 curr_dir_len = len;
895 } else {
896 curr_dir[curr_dir_len++] = '/';
897 memcpy(curr_dir + curr_dir_len, dir, len + 1);
898 curr_dir_len += len;
5243c216
AT
899 }
900
b92693da 901 curr_dir_len = clean_fname(curr_dir, 1);
a8167c66
WD
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);
906 }
5243c216 907
4af8fe4e 908 return 1;
5243c216
AT
909}
910
a16d8f2b
WD
911/**
912 * Reverse a push_dir() call. You must pass in an absolute path
913 * that was copied from a prior value of "curr_dir".
914 **/
2c708476 915int pop_dir(const char *dir)
5243c216 916{
4af8fe4e
WD
917 if (chdir(dir))
918 return 0;
5243c216 919
4af8fe4e
WD
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;
a8167c66
WD
923 if (sanitize_paths)
924 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
5243c216 925
4af8fe4e 926 return 1;
5243c216 927}
aa9b77a5 928
eb61be19
WD
929/**
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.
933 **/
9a5ade18 934char *full_fname(const char *fn)
eb61be19 935{
eb61be19
WD
936 static char *result = NULL;
937 char *m1, *m2, *m3;
938 char *p1, *p2;
939
940 if (result)
941 free(result);
942
943 if (*fn == '/')
944 p1 = p2 = "";
945 else {
4cff5fa4 946 p1 = curr_dir + module_dirlen;
bc83274a
WD
947 for (p2 = p1; *p2 == '/'; p2++) {}
948 if (*p2)
949 p2 = "/";
eb61be19
WD
950 }
951 if (module_id >= 0) {
952 m1 = " (in ";
953 m2 = lp_name(module_id);
954 m3 = ")";
eb61be19
WD
955 } else
956 m1 = m2 = m3 = "";
957
c98ad3df
WD
958 if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
959 out_of_memory("full_fname");
eb61be19
WD
960
961 return result;
962}
963
a7260c40
WD
964static char partial_fname[MAXPATHLEN];
965
966char *partial_dir_fname(const char *fname)
967{
968 char *t = partial_fname;
969 int sz = sizeof partial_fname;
970 const char *fn;
971
972 if ((fn = strrchr(fname, '/')) != NULL) {
973 fn++;
974 if (*partial_dir != '/') {
975 int len = fn - fname;
976 strncpy(t, fname, len); /* safe */
977 t += len;
978 sz -= len;
979 }
980 } else
981 fn = fname;
982 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
983 return NULL;
5aa7b20a 984 if (server_filter_list.head) {
89363676
WD
985 t = strrchr(partial_fname, '/');
986 *t = '\0';
5aa7b20a
WD
987 if (check_filter(&server_filter_list, partial_fname, 1) < 0)
988 return NULL;
89363676 989 *t = '/';
5aa7b20a
WD
990 if (check_filter(&server_filter_list, partial_fname, 0) < 0)
991 return NULL;
992 }
a7260c40
WD
993
994 return partial_fname;
995}
996
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. */
999int handle_partial_dir(const char *fname, int create)
1000{
1001 char *fn, *dir;
1002
1003 if (fname != partial_fname)
1004 return 1;
1005 if (!create && *partial_dir == '/')
1006 return 1;
1007 if (!(fn = strrchr(partial_fname, '/')))
1008 return 1;
1009
1010 *fn = '\0';
1011 dir = partial_fname;
1012 if (create) {
1013 STRUCT_STAT st;
a7260c40 1014 int statret = do_lstat(dir, &st);
a7260c40
WD
1015 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1016 if (do_unlink(dir) < 0)
1017 return 0;
1018 statret = -1;
1019 }
1020 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1021 return 0;
1022 } else
1023 do_rmdir(dir);
1024 *fn = '/';
1025
1026 return 1;
1027}
1028
ac13ad10
MP
1029/**
1030 * Determine if a symlink points outside the current directory tree.
036e70b0
MP
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.
1034 *
4e5db0ad
MP
1035 * Null symlinks and absolute symlinks are always unsafe.
1036 *
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
1040 * reenter.
1041 *
036e70b0
MP
1042 * @param dest Target of the symlink in question.
1043 *
25d34a5c 1044 * @param src Top source directory currently applicable. Basically this
036e70b0 1045 * is the first parameter to rsync in a simple invocation, but it's
25d34a5c 1046 * modified by flist.c in slightly complex ways.
036e70b0
MP
1047 *
1048 * @retval True if unsafe
1049 * @retval False is unsafe
4e5db0ad
MP
1050 *
1051 * @sa t_unsafe.c
ac13ad10 1052 **/
7afa3a4a 1053int unsafe_symlink(const char *dest, const char *src)
4b957c22 1054{
7afa3a4a 1055 const char *name, *slash;
4b957c22
AT
1056 int depth = 0;
1057
1058 /* all absolute and null symlinks are unsafe */
b5bd5542
WD
1059 if (!dest || !*dest || *dest == '/')
1060 return 1;
4b957c22
AT
1061
1062 /* find out what our safety margin is */
7afa3a4a
WD
1063 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1064 if (strncmp(name, "../", 3) == 0) {
c284f34a 1065 depth = 0;
7afa3a4a 1066 } else if (strncmp(name, "./", 2) == 0) {
4b957c22
AT
1067 /* nothing */
1068 } else {
1069 depth++;
1070 }
1071 }
7afa3a4a
WD
1072 if (strcmp(name, "..") == 0)
1073 depth = 0;
4b957c22 1074
7afa3a4a
WD
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 */
1079 if (--depth < 0)
1080 return 1;
1081 } else if (strncmp(name, "./", 2) == 0) {
4b957c22
AT
1082 /* nothing */
1083 } else {
1084 depth++;
1085 }
4b957c22 1086 }
7afa3a4a
WD
1087 if (strcmp(name, "..") == 0)
1088 depth--;
4b957c22 1089
4b957c22
AT
1090 return (depth < 0);
1091}
375a4556 1092
e175fb07
WD
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. */
1096char *human_num(int64 num)
1097{
1098 static char bufs[4][128]; /* more than enough room */
1099 static unsigned int n;
1100 char *s;
1101
1102 n = (n + 1) % (sizeof bufs / sizeof bufs[0]);
1103
1104 if (human_readable) {
1105 char units = '\0';
7794db7c 1106 int mult = human_readable == 1 ? 1000 : 1024;
e175fb07
WD
1107 double dnum = 0;
1108 if (num > mult*mult*mult) {
1109 dnum = (double)num / (mult*mult*mult);
1110 units = 'G';
1111 } else if (num > mult*mult) {
1112 dnum = (double)num / (mult*mult);
1113 units = 'M';
1114 } else if (num > mult) {
1115 dnum = (double)num / mult;
1116 units = 'K';
1117 }
1118 if (units) {
83078af5 1119 snprintf(bufs[n], sizeof bufs[0], "%.2f%c", dnum, units);
e175fb07
WD
1120 return bufs[n];
1121 }
1122 }
1123
1124 s = bufs[n] + sizeof bufs[0] - 1;
1125 *s = '\0';
1126
1127 if (!num)
1128 *--s = '0';
1129 while (num) {
26404276 1130 *--s = (char)(num % 10) + '0';
e175fb07
WD
1131 num /= 10;
1132 }
1133 return s;
1134}
1135
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. */
1139char *human_dnum(double dnum, int decimal_digits)
1140{
1141 char *buf = human_num(dnum);
1142 int len = strlen(buf);
2dc7b8bd 1143 if (isDigit(buf + len - 1)) {
e175fb07
WD
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);
1147 }
1148 return buf;
1149}
f7632fc6 1150
4a19c3b2 1151/* Return the date and time as a string. Some callers tweak returned buf. */
f7632fc6
AT
1152char *timestring(time_t t)
1153{
1154 static char TimeBuf[200];
1155 struct tm *tm = localtime(&t);
afa73c75 1156 char *p;
f7632fc6 1157
4f5b0756 1158#ifdef HAVE_STRFTIME
5cb37436 1159 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
f7632fc6 1160#else
5cb37436 1161 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
f7632fc6
AT
1162#endif
1163
afa73c75
WD
1164 if ((p = strchr(TimeBuf, '\n')) != NULL)
1165 *p = '\0';
f7632fc6 1166
afa73c75 1167 return TimeBuf;
f7632fc6
AT
1168}
1169
e1bd49d6
MP
1170/**
1171 * Sleep for a specified number of milliseconds.
1172 *
1173 * Always returns TRUE. (In the future it might return FALSE if
1174 * interrupted.)
1175 **/
1176int msleep(int t)
9ec16c83 1177{
c284f34a
WD
1178 int tdiff = 0;
1179 struct timeval tval, t1, t2;
9ec16c83
AT
1180
1181 gettimeofday(&t1, NULL);
5cb37436 1182
9ec16c83
AT
1183 while (tdiff < t) {
1184 tval.tv_sec = (t-tdiff)/1000;
1185 tval.tv_usec = 1000*((t-tdiff)%1000);
5cb37436 1186
9ec16c83
AT
1187 errno = 0;
1188 select(0,NULL,NULL, NULL, &tval);
1189
1190 gettimeofday(&t2, NULL);
5cb37436 1191 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
9ec16c83
AT
1192 (t2.tv_usec - t1.tv_usec)/1000;
1193 }
e1bd49d6
MP
1194
1195 return True;
9ec16c83
AT
1196}
1197
c2b54076
WD
1198/* Determine if two time_t values are equivalent (either exact, or in
1199 * the modification timestamp window established by --modify-window).
ac13ad10
MP
1200 *
1201 * @retval 0 if the times should be treated as the same
1202 *
1203 * @retval +1 if the first is later
1204 *
1205 * @retval -1 if the 2nd is later
1206 **/
c2b54076 1207int cmp_time(time_t file1, time_t file2)
5b56cc19 1208{
5b56cc19 1209 if (file2 > file1) {
bc6ebcd2
WD
1210 if (file2 - file1 <= modify_window)
1211 return 0;
5b56cc19
AT
1212 return -1;
1213 }
bc6ebcd2
WD
1214 if (file1 - file2 <= modify_window)
1215 return 0;
5b56cc19
AT
1216 return 1;
1217}
1218
1219
1220#ifdef __INSURE__XX
0f8f98c8
AT
1221#include <dlfcn.h>
1222
ac13ad10
MP
1223/**
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.
1227**/
0f8f98c8
AT
1228int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1229{
1230 static int (*fn)();
1231 int ret;
8950ac03 1232 char *cmd;
0f8f98c8 1233
5cb37436 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'",
0f8f98c8
AT
1235 getpid(), getpid(), getpid());
1236
1237 if (!fn) {
1238 static void *h;
1239 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1240 fn = dlsym(h, "_Insure_trap_error");
1241 }
1242
1243 ret = fn(a1, a2, a3, a4, a5, a6);
1244
1245 system(cmd);
1246
8950ac03
AT
1247 free(cmd);
1248
0f8f98c8
AT
1249 return ret;
1250}
1251#endif
58cadc86 1252
58cadc86
WD
1253#define MALLOC_MAX 0x40000000
1254
1255void *_new_array(unsigned int size, unsigned long num)
1256{
1257 if (num >= MALLOC_MAX/size)
1258 return NULL;
1259 return malloc(size * num);
1260}
1261
1262void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
1263{
1264 if (num >= MALLOC_MAX/size)
1265 return NULL;
58cadc86
WD
1266 if (!ptr)
1267 return malloc(size * num);
1268 return realloc(ptr, size * num);
1269}
e64ae6d7
WD
1270
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. */
1274const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1275{
1276 const char *suf, *s;
1277 BOOL had_tilde;
1278 int s_len;
1279
1280 /* One or more dots at the start aren't a suffix. */
1281 while (fn_len && *fn == '.') fn++, fn_len--;
1282
1283 /* Ignore the ~ in a "foo~" filename. */
1284 if (fn_len > 1 && fn[fn_len-1] == '~')
1285 fn_len--, had_tilde = True;
1286 else
1287 had_tilde = False;
1288
1289 /* Assume we don't find an suffix. */
1290 suf = "";
1291 *len_ptr = 0;
1292
1293 /* Find the last significant suffix. */
1294 for (s = fn + fn_len; fn_len > 1; ) {
1295 while (*--s != '.' && s != fn) {}
1296 if (s == fn)
1297 break;
1298 s_len = fn_len - (s - fn);
1299 fn_len = s - fn;
6012eaa1 1300 if (s_len == 4) {
e64ae6d7
WD
1301 if (strcmp(s+1, "bak") == 0
1302 || strcmp(s+1, "old") == 0)
1303 continue;
6012eaa1 1304 } else if (s_len == 5) {
e64ae6d7
WD
1305 if (strcmp(s+1, "orig") == 0)
1306 continue;
1307 } else if (s_len > 2 && had_tilde
2dc7b8bd 1308 && s[1] == '~' && isDigit(s + 2))
e64ae6d7
WD
1309 continue;
1310 *len_ptr = s_len;
1311 suf = s;
1312 if (s_len == 1)
1313 break;
1314 /* Determine if the suffix is all digits. */
1315 for (s++, s_len--; s_len > 0; s++, s_len--) {
2dc7b8bd 1316 if (!isDigit(s))
e64ae6d7
WD
1317 return suf;
1318 }
1319 /* An all-digit suffix may not be that signficant. */
1320 s = suf;
1321 }
1322
1323 return suf;
1324}
1325
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". */
1332
1333#define UNIT (1 << 16)
1334
1335uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1336{
1337 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1338 int32 cost;
1339 int i1, i2;
1340
1341 if (!len1 || !len2) {
1342 if (!len1) {
1343 s1 = s2;
1344 len1 = len2;
1345 }
1346 for (i1 = 0, cost = 0; i1 < len1; i1++)
1347 cost += s1[i1];
1348 return (int32)len1 * UNIT + cost;
1349 }
1350
1351 for (i2 = 0; i2 < len2; i2++)
1352 a[i2] = (i2+1) * UNIT;
1353
1354 for (i1 = 0; i1 < len1; i1++) {
1355 diag = i1 * UNIT;
1356 above = (i1+1) * UNIT;
1357 for (i2 = 0; i2 < len2; i2++) {
1358 left = a[i2];
1359 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1360 if (cost < 0)
1361 cost = UNIT - cost;
1362 else
1363 cost = UNIT + cost;
1364 }
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);
1371 diag = left;
1372 }
1373 }
1374
1375 return a[len2-1];
1376}
c2b54076
WD
1377
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 */
1381
1382struct bitbag {
1383 uint32 **bits;
1384 int slot_cnt;
1385};
1386
1387struct bitbag *bitbag_create(int max_ndx)
1388{
1389 struct bitbag *bb = new(struct bitbag);
1390 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1391
1392 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1393 out_of_memory("bitbag_create");
1394
1395 return bb;
1396}
1397
1398void bitbag_set_bit(struct bitbag *bb, int ndx)
1399{
1400 int slot = ndx / BB_PER_SLOT_BITS;
1401 ndx %= BB_PER_SLOT_BITS;
1402
1403 if (!bb->bits[slot]) {
1404 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1405 out_of_memory("bitbag_set_bit");
1406 }
1407
1408 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1409}
1410
1411#if 0 /* not needed yet */
1412void bitbag_clear_bit(struct bitbag *bb, int ndx)
1413{
1414 int slot = ndx / BB_PER_SLOT_BITS;
1415 ndx %= BB_PER_SLOT_BITS;
1416
1417 if (!bb->bits[slot])
1418 return;
1419
1420 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1421}
1422
1423int bitbag_check_bit(struct bitbag *bb, int ndx)
1424{
1425 int slot = ndx / BB_PER_SLOT_BITS;
1426 ndx %= BB_PER_SLOT_BITS;
1427
1428 if (!bb->bits[slot])
1429 return 0;
1430
1431 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1432}
1433#endif
1434
1435/* Call this with -1 to start checking from 0. Returns -1 at the end. */
1436int bitbag_next_bit(struct bitbag *bb, int after)
1437{
1438 uint32 bits, mask;
1439 int i, ndx = after + 1;
1440 int slot = ndx / BB_PER_SLOT_BITS;
1441 ndx %= BB_PER_SLOT_BITS;
1442
1443 mask = (1u << (ndx % 32)) - 1;
1444 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1445 if (!bb->bits[slot])
1446 continue;
1447 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1448 if (!(bits = bb->bits[slot][i] & ~mask))
1449 continue;
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);
1462 }
1463 return -1; /* impossible... */
1464 }
1465 }
1466
1467 return -1;
1468}
1c3344a1
WD
1469
1470void *expand_item_list(item_list *lp, size_t item_size,
1471 const char *desc, int incr)
1472{
1473 /* First time through, 0 <= 0, so list is expanded. */
1474 if (lp->malloced <= lp->count) {
1475 void *new_ptr;
1476 size_t new_size = lp->malloced;
1477 if (incr < 0)
1478 new_size -= incr; /* increase slowly */
1479 else if (new_size < (size_t)incr)
1480 new_size += incr;
1481 else
1482 new_size *= 2;
1483 new_ptr = realloc_array(lp->items, char, new_size * item_size);
1484 if (verbose >= 4) {
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" : "");
1488 }
1489 if (!new_ptr)
1490 out_of_memory("expand_item_list");
1491
1492 lp->items = new_ptr;
1493 lp->malloced = new_size;
1494 }
1495 return (char*)lp->items + (lp->count++ * item_size);
1496}