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