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