Debian Codegraph @

util1.c

raw symbols SCIP
1 /*
2 * Utility routines used in rsync.
3 *
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <[email protected]>
7 * Copyright (C) 2003-2022 Wayne Davison
8 *
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 3 of the License, or
12 * (at your option) any later version.
13 *
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.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
21 */
22
23 #include "rsync.h"
24 #include "ifuncs.h"
25 #include "itypes.h"
26 #include "inums.h"
27
28 extern int dry_run;
29 extern int module_id;
30 extern int do_fsync;
31 extern int protect_args;
32 extern int modify_window;
33 extern int relative_paths;
34 extern int preserve_xattrs;
35 extern int omit_link_times;
36 extern int preallocate_files;
37 extern int operator_path_resolve;
38 extern char *module_dir;
39 extern unsigned int module_dirlen;
40 extern char *partial_dir;
41 extern filter_rule_list daemon_filter_list;
42
43 int sanitize_paths = 0;
44
45 extern char curr_dir[MAXPATHLEN]; /* defined in syscall.c */
46 extern unsigned int curr_dir_len;
47 int curr_dir_depth; /* This is only set for a sanitizing daemon. */
48
49 /* Set a fd into nonblocking mode. */
50 void set_nonblocking(int fd)
51 {
52 int val;
53
54 if ((val = fcntl(fd, F_GETFL)) == -1)
55 return;
56 if (!(val & NONBLOCK_FLAG)) {
57 val |= NONBLOCK_FLAG;
58 fcntl(fd, F_SETFL, val);
59 }
60 }
61
62 /* Set a fd into blocking mode. */
63 void set_blocking(int fd)
64 {
65 int val;
66
67 if ((val = fcntl(fd, F_GETFL)) == -1)
68 return;
69 if (val & NONBLOCK_FLAG) {
70 val &= ~NONBLOCK_FLAG;
71 fcntl(fd, F_SETFL, val);
72 }
73 }
74
75 /**
76 * Create a file descriptor pair - like pipe() but use socketpair if
77 * possible (because of blocking issues on pipes).
78 *
79 * Always set non-blocking.
80 */
81 int fd_pair(int fd[2])
82 {
83 int ret;
84
85 #ifdef HAVE_SOCKETPAIR
86 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
87 #else
88 ret = pipe(fd);
89 #endif
90
91 if (ret == 0) {
92 set_nonblocking(fd[0]);
93 set_nonblocking(fd[1]);
94 }
95
96 return ret;
97 }
98
99 void print_child_argv(const char *prefix, char **cmd)
100 {
101 int cnt = 0;
102 rprintf(FCLIENT, "%s ", prefix);
103 for (; *cmd; cmd++) {
104 /* Look for characters that ought to be quoted. This
105 * is not a great quoting algorithm, but it's
106 * sufficient for a log message. */
107 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
108 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
109 "0123456789"
110 ",.-_=+@/") != strlen(*cmd)) {
111 rprintf(FCLIENT, "\"%s\" ", *cmd);
112 } else {
113 rprintf(FCLIENT, "%s ", *cmd);
114 }
115 cnt++;
116 }
117 rprintf(FCLIENT, " (%d args)\n", cnt);
118 }
119
120 /* This returns 0 for success, 1 for a symlink if symlink time-setting
121 * is not possible, or -1 for any other error. */
122 int set_times(const char *fname, STRUCT_STAT *stp)
123 {
124 static int switch_step = 0;
125
126 if (DEBUG_GTE(TIME, 1)) {
127 rprintf(FINFO,
128 "set modtime, atime of %s to (%ld) %s, (%ld) %s\n",
129 fname, (long)stp->st_mtime,
130 timestring(stp->st_mtime), (long)stp->st_atime, timestring(stp->st_atime));
131 }
132
133 switch (switch_step) {
134 #ifdef HAVE_SETATTRLIST
135 #include "case_N.h"
136 if (do_setattrlist_times(fname, stp) == 0)
137 break;
138 if (errno != ENOSYS)
139 return -1;
140 switch_step++;
141 #endif
142
143 #ifdef HAVE_UTIMENSAT
144 #include "case_N.h"
145 if (do_utimensat_at(fname, stp) == 0)
146 break;
147 if (errno != ENOSYS)
148 return -1;
149 switch_step++;
150 #endif
151
152 #ifdef HAVE_LUTIMES
153 #include "case_N.h"
154 if (do_lutimes(fname, stp) == 0)
155 break;
156 if (errno != ENOSYS)
157 return -1;
158 switch_step++;
159 #endif
160
161 #include "case_N.h"
162 switch_step++;
163 if (!omit_link_times) {
164 omit_link_times = 1;
165 if (S_ISLNK(stp->st_mode))
166 return 1;
167 }
168
169 #include "case_N.h"
170 #ifdef HAVE_UTIMES
171 if (do_utimes(fname, stp) == 0)
172 break;
173 #else
174 if (do_utime(fname, stp) == 0)
175 break;
176 #endif
177
178 return -1;
179 }
180
181 return 0;
182 }
183
184 /* Held-dirfd variant of set_times(): set `name`'s times relative to dir fd
185 * `dfd`. Returns 0/-1 like set_times(), or -2 when this platform's active
186 * time-setting tier has no dfd-relative form (caller must fall back to
187 * set_times(fname, stp)). Only the utimensat tier has an at-on-dfd form, so
188 * macOS (setattrlist) and pre-utimensat systems take the -2 path. */
189 int set_times_at(int dfd, const char *name, STRUCT_STAT *stp)
190 {
191 #if defined HAVE_UTIMENSAT && !defined HAVE_SETATTRLIST
192 int r = do_utimensat_atfd(dfd, name, stp);
193 if (r == 0)
194 return 0;
195 if (errno == ENOSYS)
196 return -2; /* fall back to the full set_times() tier walk */
197 return -1;
198 #else
199 (void)dfd; (void)name; (void)stp;
200 return -2;
201 #endif
202 }
203
204 /* Create any necessary directories in fname. Any missing directories are
205 * created with default permissions. Returns < 0 on error, or the number
206 * of directories created. */
207 int make_path(char *fname, int flags)
208 {
209 char *end, *p;
210 int ret = 0;
211
212 if (flags & MKP_SKIP_SLASH) {
213 while (*fname == '/')
214 fname++;
215 }
216
217 while (*fname == '.' && fname[1] == '/')
218 fname += 2;
219
220 if (flags & MKP_DROP_NAME) {
221 end = strrchr(fname, '/');
222 if (!end || end == fname)
223 return 0;
224 *end = '\0';
225 } else
226 end = fname + strlen(fname);
227
228 /* Try to find an existing dir, starting from the deepest dir. */
229 for (p = end; ; ) {
230 if (dry_run) {
231 STRUCT_STAT st;
232 if (do_stat(fname, &st) == 0) {
233 if (S_ISDIR(st.st_mode))
234 errno = EEXIST;
235 else
236 errno = ENOTDIR;
237 }
238 } else if (do_mkdir_at(fname, ACCESSPERMS) == 0) {
239 ret++;
240 break;
241 }
242
243 if (errno != ENOENT) {
244 STRUCT_STAT st;
245 if (errno != EEXIST || (do_stat(fname, &st) == 0 && !S_ISDIR(st.st_mode)))
246 ret = -ret - 1;
247 break;
248 }
249 while (1) {
250 if (p == fname) {
251 /* We got a relative path that doesn't exist, so assume that '.'
252 * is there and just break out and create the whole thing. */
253 p = NULL;
254 goto double_break;
255 }
256 if (*--p == '/') {
257 if (p == fname) {
258 /* We reached the "/" dir, which we assume is there. */
259 goto double_break;
260 }
261 *p = '\0';
262 break;
263 }
264 }
265 }
266 double_break:
267
268 /* Make all the dirs that we didn't find on the way here. */
269 while (p != end) {
270 if (p)
271 *p = '/';
272 else
273 p = fname;
274 p += strlen(p);
275 if (ret < 0) /* Skip mkdir on error, but keep restoring the path. */
276 continue;
277 if (do_mkdir_at(fname, ACCESSPERMS) < 0)
278 ret = -ret - 1;
279 else
280 ret++;
281 }
282
283 if (flags & MKP_DROP_NAME)
284 *end = '/';
285
286 return ret;
287 }
288
289 /**
290 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
291 * interrupted.
292 *
293 * @retval len upon success
294 *
295 * @retval <0 write's (negative) error code
296 *
297 * Derived from GNU C's cccp.c.
298 */
299 int full_write(int desc, const char *ptr, size_t len)
300 {
301 int total_written;
302
303 total_written = 0;
304 while (len > 0) {
305 int written = write(desc, ptr, len);
306 if (written < 0) {
307 if (errno == EINTR)
308 continue;
309 return written;
310 }
311 total_written += written;
312 ptr += written;
313 len -= written;
314 }
315 return total_written;
316 }
317
318 /**
319 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
320 * interrupted.
321 *
322 * @retval >0 the actual number of bytes read
323 *
324 * @retval 0 for EOF
325 *
326 * @retval <0 for an error.
327 *
328 * Derived from GNU C's cccp.c. */
329 static int safe_read(int desc, char *ptr, size_t len)
330 {
331 int n_chars;
332
333 if (len == 0)
334 return len;
335
336 do {
337 n_chars = read(desc, ptr, len);
338 } while (n_chars < 0 && errno == EINTR);
339
340 return n_chars;
341 }
342
343 /* Remove existing file @dest and reopen, creating a new file with @mode */
344 static int unlink_and_reopen(const char *dest, mode_t mode)
345 {
346 int ofd;
347
348 if (robust_unlink(dest) && errno != ENOENT) {
349 int save_errno = errno;
350 rsyserr(FERROR_XFER, errno, "unlink %s", full_fname(dest));
351 errno = save_errno;
352 return -1;
353 }
354
355 #ifdef SUPPORT_XATTRS
356 if (preserve_xattrs)
357 mode |= S_IWUSR;
358 #endif
359 mode &= INITACCESSPERMS;
360 /* Use do_open_at so the create/truncate goes through a secure
361 * parent dirfd in the daemon-no-chroot deployment. Otherwise
362 * an attacker could swap a parent component with a symlink in
363 * the window between robust_unlink (which uses do_unlink_at,
364 * already secure) and the create here, and redirect the new
365 * file outside the module. */
366 if ((ofd = do_open_at(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode)) < 0) {
367 int save_errno = errno;
368 rsyserr(FERROR_XFER, save_errno, "open %s", full_fname(dest));
369 errno = save_errno;
370 return -1;
371 }
372 return ofd;
373 }
374
375 /* Copy contents of file @source to file @dest with mode @mode.
376 *
377 * If @tmpfilefd is < 0, copy_file unlinks @dest and then opens a new
378 * file with name @dest.
379 *
380 * Otherwise, copy_file writes to and closes the provided file
381 * descriptor.
382 *
383 * In either case, if --xattrs are being preserved, the dest file will
384 * have its xattrs set from the source file.
385 *
386 * This is used in conjunction with the --temp-dir, --backup, and
387 * --copy-dest options. */
388 int copy_file(const char *source, const char *dest, int tmpfilefd, mode_t mode)
389 {
390 int ifd, ofd;
391 char buf[1024 * 8];
392 int len; /* Number of bytes read into `buf'. */
393 OFF_T prealloc_len = 0, offset = 0;
394
395 /* For any hardened (non-chrooted) receiver, route the source open through
396 * secure_relative_open so a parent-symlink on the source path (e.g.
397 * --copy-dest=cd where cd is a symlink to an outside directory) cannot
398 * redirect the read to a file the attacker should not see. Plain
399 * do_open_nofollow only refuses a final-component symlink; parents are
400 * still followed. An ABSOLUTE source is an operator basis (e.g. an absolute
401 * --copy-dest): confine its parents via the ownership walk -- a foreign-owned
402 * parent symlink is refused, the operator's own dirs/uid0/euid symlinks
403 * followed -- so a flipped parent can't redirect the basis read out of tree.
404 * operator_path_resolve is set only across the walk (so module-exclude is
405 * enforced) and restored, leaving the caller's value for the dest side -- this
406 * is why confining the source here does not re-open the copy_xattrs dest
407 * race the way wrapping the whole copy_altdest_file would. */
408 if (secure_relpath_active() && source && *source && source[0] != '/')
409 ifd = secure_relative_open(NULL, source, O_RDONLY | O_NOFOLLOW, 0);
410 #if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY
411 else if (secure_relpath_active() && source && source[0] == '/'
412 && !symlink_optout_allowed()) {
413 int save = operator_path_resolve, dfd, e;
414 const char *leaf;
415 operator_path_resolve = 1;
416 dfd = owner_walk_parent(source, &leaf);
417 operator_path_resolve = save;
418 if (dfd < 0)
419 ifd = -1;
420 else {
421 ifd = openat(dfd, leaf, O_RDONLY | O_NOFOLLOW);
422 e = errno;
423 close(dfd);
424 errno = e;
425 }
426 }
427 #endif
428 else
429 ifd = do_open_nofollow(source, O_RDONLY);
430 if (ifd < 0) {
431 int save_errno = errno;
432 rsyserr(FERROR_XFER, errno, "open %s", full_fname(source));
433 errno = save_errno;
434 return -1;
435 }
436
437 if (tmpfilefd >= 0) {
438 ofd = tmpfilefd;
439 } else {
440 ofd = unlink_and_reopen(dest, mode);
441 if (ofd < 0) {
442 int save_errno = errno;
443 close(ifd);
444 errno = save_errno;
445 return -1;
446 }
447 }
448
449 #ifdef SUPPORT_PREALLOCATION
450 if (preallocate_files) {
451 STRUCT_STAT srcst;
452
453 /* Try to preallocate enough space for file's eventual length. Can
454 * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
455 if (do_fstat(ifd, &srcst) < 0)
456 rsyserr(FWARNING, errno, "fstat %s", full_fname(source));
457 else if (srcst.st_size > 0) {
458 prealloc_len = do_fallocate(ofd, 0, srcst.st_size);
459 if (prealloc_len < 0)
460 rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest));
461 }
462 }
463 #endif
464
465 while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
466 if (full_write(ofd, buf, len) < 0) {
467 int save_errno = errno;
468 rsyserr(FERROR_XFER, errno, "write %s", full_fname(dest));
469 close(ifd);
470 close(ofd);
471 errno = save_errno;
472 return -1;
473 }
474 offset += len;
475 }
476
477 if (len < 0) {
478 int save_errno = errno;
479 rsyserr(FERROR_XFER, errno, "read %s", full_fname(source));
480 close(ifd);
481 close(ofd);
482 errno = save_errno;
483 return -1;
484 }
485
486 /* Source file might have shrunk since we fstatted it.
487 * Cut off any extra preallocated zeros from dest file. */
488 if (offset < prealloc_len) {
489 #ifdef HAVE_FTRUNCATE
490 /* If we fail to truncate, the dest file may be wrong, so we
491 * must trigger the "partial transfer" error. */
492 if (do_ftruncate(ofd, offset) < 0)
493 rsyserr(FERROR_XFER, errno, "ftruncate %s", full_fname(dest));
494 #else
495 rprintf(FERROR_XFER, "no ftruncate for over-long pre-alloc: %s", full_fname(dest));
496 #endif
497 }
498
499 if (do_fsync && fsync(ofd) < 0) {
500 int save_errno = errno;
501 rsyserr(FERROR, errno, "fsync failed on %s", full_fname(dest));
502 close(ofd);
503 close(ifd); /* ifd is held open until after the xattr copy below */
504 errno = save_errno;
505 return -1;
506 }
507
508 #ifdef SUPPORT_XATTRS
509 /* Read the source xattrs through the held source fd (ifd) and set them
510 * through ofd while both are still held, so a parent-symlink race can't
511 * redirect the read out of tree or the write onto a file outside it. */
512 if (preserve_xattrs)
513 copy_xattrs(source, ifd, dest, ofd);
514 #endif
515
516 if (close(ifd) < 0) {
517 rsyserr(FWARNING, errno, "close failed on %s",
518 full_fname(source));
519 }
520
521 if (close(ofd) < 0) {
522 int save_errno = errno;
523 rsyserr(FERROR_XFER, errno, "close failed on %s", full_fname(dest));
524 errno = save_errno;
525 return -1;
526 }
527
528 return 0;
529 }
530
531 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
532 #define MAX_RENAMES_DIGITS 3
533 #define MAX_RENAMES 1000
534
535 /**
536 * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
537 * rename to <path>/.rsyncNNN instead.
538 *
539 * Note that successive rsync runs will shuffle the filenames around a
540 * bit as long as the file is still busy; this is because this function
541 * does not know if the unlink call is due to a new file coming in, or
542 * --delete trying to remove old .rsyncNNN files, hence it renames it
543 * each time.
544 **/
545 int robust_unlink(const char *fname)
546 {
547 #ifndef ETXTBSY
548 return do_unlink_at(fname);
549 #else
550 static int counter = 1;
551 int rc, pos, start;
552 char path[MAXPATHLEN];
553
554 rc = do_unlink_at(fname);
555 if (rc == 0 || errno != ETXTBSY)
556 return rc;
557
558 if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
559 pos = MAXPATHLEN - 1;
560
561 while (pos > 0 && path[pos-1] != '/')
562 pos--;
563 pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
564
565 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
566 errno = ETXTBSY;
567 return -1;
568 }
569
570 /* start where the last one left off to reduce chance of clashes */
571 start = counter;
572 do {
573 snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
574 if (++counter >= MAX_RENAMES)
575 counter = 1;
576 } while (access(path, 0) == 0 && counter != start);
577
578 if (INFO_GTE(MISC, 1)) {
579 rprintf(FWARNING, "renaming %s to %s because of text busy\n",
580 fname, path);
581 }
582
583 /* maybe we should return rename()'s exit status? Nah. */
584 if (do_rename_at(fname, path) != 0) {
585 errno = ETXTBSY;
586 return -1;
587 }
588 return 0;
589 #endif
590 }
591
592 /* Returns 0 on successful rename, 1 if we successfully copied the file
593 * across filesystems, -2 if copy_file() failed, and -1 on other errors.
594 * If partialptr is not NULL and we need to do a copy, copy the file into
595 * the active partial-dir instead of over the destination file. */
596 int robust_rename(const char *from, const char *to, const char *partialptr,
597 int mode, struct file_struct *file)
598 {
599 int tries = 4;
600
601 /* A resumed in-place partial-dir transfer might call us with from and
602 * to pointing to the same buf if the transfer failed yet again. */
603 if (from == to)
604 return 0;
605
606 while (tries--) {
607 /* tmp -> final usually live in the entry's own dir: rename via the
608 * held dir fd when both do, else the full-path wrapper. */
609 int ofd = held_dfd_for(from, file);
610 int nfd = held_dfd_for(to, file);
611 int rr;
612 if (ofd >= 0 && nfd >= 0) {
613 const char *os = strrchr(from, '/');
614 const char *ns = strrchr(to, '/');
615 rr = do_rename_atfd(ofd, os ? os + 1 : from, nfd, ns ? ns + 1 : to);
616 } else
617 rr = do_rename_at(from, to);
618 if (rr == 0)
619 return 0;
620
621 switch (errno) {
622 #ifdef ETXTBSY
623 case ETXTBSY:
624 if (robust_unlink(to) != 0) {
625 errno = ETXTBSY;
626 return -1;
627 }
628 errno = ETXTBSY;
629 break;
630 #endif
631 case EXDEV: {
632 int save = operator_path_resolve, rc;
633 if (partialptr) {
634 if (!handle_partial_dir(partialptr,PDIR_CREATE))
635 return -2;
636 to = partialptr;
637 }
638 /* Cross-fs fallback: copy then unlink. An absolute --temp-dir
639 * source / --partial-dir dest is an operator path whose parents
640 * do_open_at()/do_unlink_at() would otherwise follow via plain libc
641 * -- confine them through the ownership walk so a raced parent
642 * symlink can't redirect the dest-write or the source-unlink out of
643 * the module. copy_file already confines the source READ; a
644 * relative in-module path stays on the secure_relative_open arm, so
645 * only flip the flag for an absolute (operator) path. */
646 if (*to == '/')
647 operator_path_resolve = 1;
648 rc = copy_file(from, to, -1, mode);
649 operator_path_resolve = save;
650 if (rc != 0)
651 return -2;
652 if (*from == '/')
653 operator_path_resolve = 1;
654 do_unlink_at(from);
655 operator_path_resolve = save;
656 return 1;
657 }
658 default:
659 return -1;
660 }
661 }
662 return -1;
663 }
664
665 static pid_t all_pids[10];
666 static int num_pids;
667
668 /** Fork and record the pid of the child. **/
669 pid_t do_fork(void)
670 {
671 pid_t newpid = fork();
672
673 if (newpid != 0 && newpid != -1) {
674 all_pids[num_pids++] = newpid;
675 }
676 return newpid;
677 }
678
679 /**
680 * Kill all children.
681 *
682 * @todo It would be kind of nice to make sure that they are actually
683 * all our children before we kill them, because their pids may have
684 * been recycled by some other process. Perhaps when we wait for a
685 * child, we should remove it from this array. Alternatively we could
686 * perhaps use process groups, but I think that would not work on
687 * ancient Unix versions that don't support them.
688 **/
689 void kill_all(int sig)
690 {
691 int i;
692
693 for (i = 0; i < num_pids; i++) {
694 /* Let's just be a little careful where we
695 * point that gun, hey? See kill(2) for the
696 * magic caused by negative values. */
697 pid_t p = all_pids[i];
698
699 if (p == getpid())
700 continue;
701 if (p <= 0)
702 continue;
703
704 kill(p, sig);
705 }
706 }
707
708 /** Lock a byte range in a open file */
709 int lock_range(int fd, int offset, int len)
710 {
711 struct flock lock;
712
713 lock.l_type = F_WRLCK;
714 lock.l_whence = SEEK_SET;
715 lock.l_start = offset;
716 lock.l_len = len;
717 lock.l_pid = 0;
718
719 return fcntl(fd,F_SETLK,&lock) == 0;
720 }
721
722 #define ENSURE_MEMSPACE(buf, type, sz, req) \
723 do { if ((req) > sz) buf = realloc_array(buf, type, sz = MAX(sz * 2, req)); } while(0)
724
725 static inline void call_glob_match(const char *name, int len, int from_glob,
726 char *arg, int abpos, int fbpos);
727
728 static struct glob_data {
729 char *arg_buf, *filt_buf, **argv;
730 int absize, fbsize, maxargs, argc;
731 } glob;
732
733 static void glob_match(char *arg, int abpos, int fbpos)
734 {
735 int len;
736 char *slash;
737
738 while (*arg == '.' && arg[1] == '/') {
739 if (fbpos < 0) {
740 ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, glob.absize);
741 memcpy(glob.filt_buf, glob.arg_buf, abpos + 1);
742 fbpos = abpos;
743 }
744 ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + 3);
745 glob.arg_buf[abpos++] = *arg++;
746 glob.arg_buf[abpos++] = *arg++;
747 glob.arg_buf[abpos] = '\0';
748 }
749 if ((slash = strchr(arg, '/')) != NULL) {
750 *slash = '\0';
751 len = slash - arg;
752 } else
753 len = strlen(arg);
754 if (strpbrk(arg, "*?[")) {
755 struct dirent *di;
756 DIR *d;
757
758 if (!(d = opendir(abpos ? glob.arg_buf : ".")))
759 return;
760 while ((di = readdir(d)) != NULL) {
761 char *dname = d_name(di);
762 if (dname[0] == '.' && (dname[1] == '\0'
763 || (dname[1] == '.' && dname[2] == '\0')))
764 continue;
765 if (!wildmatch(arg, dname))
766 continue;
767 call_glob_match(dname, strlen(dname), 1,
768 slash ? arg + len + 1 : NULL,
769 abpos, fbpos);
770 }
771 closedir(d);
772 } else {
773 call_glob_match(arg, len, 0,
774 slash ? arg + len + 1 : NULL,
775 abpos, fbpos);
776 }
777 if (slash)
778 *slash = '/';
779 }
780
781 static inline void call_glob_match(const char *name, int len, int from_glob,
782 char *arg, int abpos, int fbpos)
783 {
784 char *use_buf;
785
786 ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + len + 2);
787 memcpy(glob.arg_buf + abpos, name, len);
788 abpos += len;
789 glob.arg_buf[abpos] = '\0';
790
791 if (fbpos >= 0) {
792 ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, fbpos + len + 2);
793 memcpy(glob.filt_buf + fbpos, name, len);
794 fbpos += len;
795 glob.filt_buf[fbpos] = '\0';
796 use_buf = glob.filt_buf;
797 } else
798 use_buf = glob.arg_buf;
799
800 if (from_glob || (arg && len)) {
801 STRUCT_STAT st;
802 int is_dir;
803
804 if (do_stat(glob.arg_buf, &st) != 0)
805 return;
806 is_dir = S_ISDIR(st.st_mode) != 0;
807 if (arg && !is_dir)
808 return;
809
810 if (daemon_filter_list.head
811 && check_filter(&daemon_filter_list, FLOG, use_buf, is_dir) < 0)
812 return;
813 }
814
815 if (arg) {
816 glob.arg_buf[abpos++] = '/';
817 glob.arg_buf[abpos] = '\0';
818 if (fbpos >= 0) {
819 glob.filt_buf[fbpos++] = '/';
820 glob.filt_buf[fbpos] = '\0';
821 }
822 glob_match(arg, abpos, fbpos);
823 } else {
824 ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
825 glob.argv[glob.argc++] = strdup(glob.arg_buf);
826 }
827 }
828
829 /* This routine performs wild-card expansion of the pathname in "arg". Any
830 * daemon-excluded files/dirs will not be matched by the wildcards. Returns 0
831 * if a wild-card string is the only returned item (due to matching nothing). */
832 int glob_expand(const char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
833 {
834 int ret, save_argc;
835 char *s;
836
837 if (!arg) {
838 if (glob.filt_buf)
839 free(glob.filt_buf);
840 free(glob.arg_buf);
841 memset(&glob, 0, sizeof glob);
842 return -1;
843 }
844
845 if (sanitize_paths)
846 s = sanitize_path(NULL, arg, "", 0, SP_KEEP_DOT_DIRS);
847 else {
848 s = strdup(arg);
849 clean_fname(s, CFN_KEEP_DOT_DIRS | CFN_KEEP_TRAILING_SLASH | CFN_COLLAPSE_DOT_DOT_DIRS);
850 }
851
852 ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, MAXPATHLEN);
853 *glob.arg_buf = '\0';
854
855 glob.argc = save_argc = *argc_p;
856 glob.argv = *argv_p;
857 glob.maxargs = *maxargs_p;
858
859 ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, 100);
860
861 glob_match(s, 0, -1);
862
863 /* The arg didn't match anything, so add the failed arg to the list. */
864 if (glob.argc == save_argc) {
865 ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
866 glob.argv[glob.argc++] = s;
867 ret = 0;
868 } else {
869 free(s);
870 ret = 1;
871 }
872
873 *maxargs_p = glob.maxargs;
874 *argv_p = glob.argv;
875 *argc_p = glob.argc;
876
877 return ret;
878 }
879
880 /* This routine is only used in daemon mode. */
881 void glob_expand_module(char *base1, char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
882 {
883 char *p, *s;
884 char *base = base1;
885 int base_len = strlen(base);
886
887 if (!arg || !*arg)
888 return;
889
890 if (strncmp(arg, base, base_len) == 0)
891 arg += base_len;
892
893 if (protect_args) {
894 glob_expand(arg, argv_p, argc_p, maxargs_p);
895 return;
896 }
897
898 arg = strdup(arg);
899
900 if (asprintf(&base," %s/", base1) < 0)
901 out_of_memory("glob_expand_module");
902 base_len++;
903
904 for (s = arg; *s; s = p + base_len) {
905 if ((p = strstr(s, base)) != NULL)
906 *p = '\0'; /* split it at this point */
907 glob_expand(s, argv_p, argc_p, maxargs_p);
908 if (!p)
909 break;
910 }
911
912 free(arg);
913 free(base);
914 }
915
916 /**
917 * Convert a string to lower case
918 **/
919 void strlower(char *s)
920 {
921 while (*s) {
922 if (isUpper(s))
923 *s = toLower(s);
924 s++;
925 }
926 }
927
928 /**
929 * Split a string into tokens based (usually) on whitespace & commas. If the
930 * string starts with a comma (after skipping any leading whitespace), then
931 * splitting is done only on commas. No empty tokens are ever returned. */
932 char *conf_strtok(char *str)
933 {
934 static int commas_only = 0;
935
936 if (str) {
937 while (isSpace(str)) str++;
938 if (*str == ',') {
939 commas_only = 1;
940 str++;
941 } else
942 commas_only = 0;
943 }
944
945 while (commas_only) {
946 char *end, *tok = strtok(str, ",");
947 if (!tok)
948 return NULL;
949 /* Trim just leading and trailing whitespace. */
950 while (isSpace(tok))
951 tok++;
952 end = tok + strlen(tok);
953 while (end > tok && isSpace(end-1))
954 *--end = '\0';
955 if (*tok)
956 return tok;
957 str = NULL;
958 }
959
960 return strtok(str, " ,\t\r\n");
961 }
962
963 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If
964 * p1 ends with a '/', no extra '/' is inserted.) Returns the length of both
965 * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
966 * string fits into destsize. */
967 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
968 {
969 size_t len = strlcpy(dest, p1, destsize);
970 if (len < destsize - 1) {
971 if (!len || dest[len-1] != '/')
972 dest[len++] = '/';
973 if (len < destsize - 1)
974 len += strlcpy(dest + len, p2, destsize - len);
975 else {
976 dest[len] = '\0';
977 len += strlen(p2);
978 }
979 }
980 else
981 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
982 return len;
983 }
984
985 /* Join any number of strings together, putting them in "dest". The return
986 * value is the length of all the strings, regardless of whether the null-
987 * terminated whole fits in destsize. Your list of string pointers must end
988 * with a NULL to indicate the end of the list. */
989 size_t stringjoin(char *dest, size_t destsize, ...)
990 {
991 va_list ap;
992 size_t len, ret = 0;
993 const char *src;
994
995 va_start(ap, destsize);
996 while (1) {
997 if (!(src = va_arg(ap, const char *)))
998 break;
999 len = strlen(src);
1000 ret += len;
1001 if (destsize > 1) {
1002 if (len >= destsize)
1003 len = destsize - 1;
1004 memcpy(dest, src, len);
1005 destsize -= len;
1006 dest += len;
1007 }
1008 }
1009 *dest = '\0';
1010 va_end(ap);
1011
1012 return ret;
1013 }
1014
1015 int count_dir_elements(const char *p)
1016 {
1017 int cnt = 0, new_component = 1;
1018 while (*p) {
1019 if (*p++ == '/')
1020 new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
1021 else if (new_component) {
1022 new_component = 0;
1023 cnt++;
1024 }
1025 }
1026 return cnt;
1027 }
1028
1029 /* Turns multiple adjacent slashes into a single slash (possible exception:
1030 * the preserving of two leading slashes at the start), drops all leading or
1031 * interior "." elements unless CFN_KEEP_DOT_DIRS is flagged. Will also drop
1032 * a trailing '.' after a '/' if CFN_DROP_TRAILING_DOT_DIR is flagged, removes
1033 * a trailing slash (perhaps after removing the aforementioned dot) unless
1034 * CFN_KEEP_TRAILING_SLASH is flagged, and will also collapse ".." elements
1035 * (except at the start) if CFN_COLLAPSE_DOT_DOT_DIRS is flagged. If the
1036 * resulting name would be empty, returns ".". */
1037 int clean_fname(char *name, int flags)
1038 {
1039 char *limit = name, *t = name, *f = name;
1040 int anchored;
1041
1042 if (!name)
1043 return 0;
1044
1045 #define DOT_IS_DOT_DOT_DIR(bp) (bp[1] == '.' && (bp[2] == '/' || !bp[2]))
1046
1047 if ((anchored = *f == '/') != 0) {
1048 *t++ = *f++;
1049 #ifdef __CYGWIN__
1050 /* If there are exactly 2 slashes at the start, preserve
1051 * them. Would break daemon excludes unless the paths are
1052 * really treated differently, so used this sparingly. */
1053 if (*f == '/' && f[1] != '/')
1054 *t++ = *f++;
1055 #endif
1056 } else if (flags & CFN_KEEP_DOT_DIRS && *f == '.' && f[1] == '/') {
1057 *t++ = *f++;
1058 *t++ = *f++;
1059 } else if (flags & CFN_REFUSE_DOT_DOT_DIRS && *f == '.' && DOT_IS_DOT_DOT_DIR(f))
1060 return -1;
1061 while (*f) {
1062 /* discard extra slashes */
1063 if (*f == '/') {
1064 f++;
1065 continue;
1066 }
1067 if (*f == '.') {
1068 /* discard interior "." dirs */
1069 if (f[1] == '/' && !(flags & CFN_KEEP_DOT_DIRS)) {
1070 f += 2;
1071 continue;
1072 }
1073 if (f[1] == '\0' && flags & CFN_DROP_TRAILING_DOT_DIR)
1074 break;
1075 /* collapse ".." dirs */
1076 if (flags & (CFN_COLLAPSE_DOT_DOT_DIRS|CFN_REFUSE_DOT_DOT_DIRS) && DOT_IS_DOT_DOT_DIR(f)) {
1077 char *s = t - 1;
1078 if (flags & CFN_REFUSE_DOT_DOT_DIRS)
1079 return -1;
1080 if (s == name && anchored) {
1081 f += 2;
1082 continue;
1083 }
1084 /* backing up for ".." — avoid reading before 'name' */
1085 while (s > limit && s[-1] != '/')
1086 s--;
1087
1088 /* If found prior '/', or we reached the start, adjust t.
1089 * After the backward walk, s points at the first char of the
1090 * prior component and s[-1] is its leading '/' -- so test
1091 * s[-1] (not *s) and reset t to s (not s+1) to actually drop
1092 * the component; the old off-by-one left CFN_COLLAPSE_DOT_DOT_DIRS
1093 * dead for multi-component and absolute paths. */
1094 if (s != t - 1 && (s <= name || s[-1] == '/')) {
1095 t = (s == name) ? name : s;
1096 f += 2;
1097 continue;
1098 }
1099 limit = t + 2;
1100 }
1101 }
1102 while (*f && (*t++ = *f++) != '/') {}
1103 }
1104
1105 if (t > name+anchored && t[-1] == '/' && !(flags & CFN_KEEP_TRAILING_SLASH))
1106 t--;
1107 if (t == name)
1108 *t++ = '.';
1109 *t = '\0';
1110
1111 #undef DOT_IS_DOT_DOT_DIR
1112
1113 return t - name;
1114 }
1115
1116 /* Make path appear as if a chroot had occurred. This handles a leading
1117 * "/" (either removing it or expanding it) and any leading or embedded
1118 * ".." components that attempt to escape past the module's top dir.
1119 *
1120 * If dest is NULL, a buffer is allocated to hold the result. It is legal
1121 * to call with the dest and the path (p) pointing to the same buffer, but
1122 * rootdir will be ignored to avoid expansion of the string.
1123 *
1124 * The rootdir string contains a value to use in place of a leading slash.
1125 * Specify NULL to get the default of "module_dir".
1126 *
1127 * The depth var is a count of how many '..'s to allow at the start of the
1128 * path.
1129 *
1130 * We also clean the path in a manner similar to clean_fname() but with a
1131 * few differences:
1132 *
1133 * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
1134 * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
1135 * ALWAYS collapses ".." elements (except for those at the start of the
1136 * string up to "depth" deep). If the resulting name would be empty,
1137 * change it into a ".". */
1138 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth, int flags)
1139 {
1140 char *start, *sanp;
1141 int rlen = 0, drop_dot_dirs = !relative_paths || !(flags & SP_KEEP_DOT_DIRS);
1142
1143 if (dest != p) {
1144 int plen = strlen(p); /* the path len INCLUDING any separating slash */
1145 if (*p == '/') {
1146 if (!rootdir)
1147 rootdir = module_dir;
1148 rlen = strlen(rootdir);
1149 depth = 0;
1150 p++;
1151 }
1152 if (!dest)
1153 dest = new_array(char, MAX(rlen + plen + 1, 2));
1154 else if (rlen + plen + 1 >= MAXPATHLEN)
1155 return NULL;
1156 if (rlen) { /* only true if p previously started with a slash */
1157 memcpy(dest, rootdir, rlen);
1158 if (rlen > 1) /* a rootdir of len 1 is "/", so this avoids a 2nd slash */
1159 dest[rlen++] = '/';
1160 }
1161 }
1162
1163 if (drop_dot_dirs) {
1164 while (*p == '.' && p[1] == '/')
1165 p += 2;
1166 }
1167
1168 start = sanp = dest + rlen;
1169 /* This loop iterates once per filename component in p, pointing at
1170 * the start of the name (past any prior slash) for each iteration. */
1171 while (*p) {
1172 /* discard leading or extra slashes */
1173 if (*p == '/') {
1174 p++;
1175 continue;
1176 }
1177 if (drop_dot_dirs) {
1178 if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
1179 /* skip "." component */
1180 p++;
1181 continue;
1182 }
1183 }
1184 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
1185 /* ".." component followed by slash or end */
1186 if (depth <= 0 || sanp != start) {
1187 p += 2;
1188 if (sanp != start) {
1189 /* back up sanp one level */
1190 --sanp; /* now pointing at slash */
1191 while (sanp > start && sanp[-1] != '/')
1192 sanp--;
1193 }
1194 continue;
1195 }
1196 /* allow depth levels of .. at the beginning */
1197 depth--;
1198 /* move the virtual beginning to leave the .. alone */
1199 start = sanp + 3;
1200 }
1201 /* copy one component through next slash */
1202 while (*p && (*sanp++ = *p++) != '/') {}
1203 }
1204 if (sanp == dest) {
1205 /* ended up with nothing, so put in "." component */
1206 *sanp++ = '.';
1207 }
1208 *sanp = '\0';
1209
1210 return dest;
1211 }
1212
1213 /* Like chdir(), but it keeps track of the current directory (in the
1214 * global "curr_dir"), and ensures that the path size doesn't overflow.
1215 * Also cleans the path using the clean_fname() function. */
1216 int change_dir(const char *dir, int set_path_only)
1217 {
1218 extern int am_daemon, am_chrooted, am_sender, insecure_links;
1219 static int initialised, skipped_chdir;
1220 unsigned int len;
1221
1222 if (!initialised) {
1223 initialised = 1;
1224 if (getcwd(curr_dir, sizeof curr_dir - 1) == NULL) {
1225 rsyserr(FERROR, errno, "getcwd()");
1226 exit_cleanup(RERR_FILESELECT);
1227 }
1228 curr_dir_len = strlen(curr_dir);
1229 }
1230
1231 if (!dir) /* this call was probably just to initialize */
1232 return 0;
1233
1234 len = strlen(dir);
1235 if (len == 1 && *dir == '.' && (!skipped_chdir || set_path_only))
1236 return 1;
1237
1238 if (*dir == '/') {
1239 if (len >= sizeof curr_dir) {
1240 errno = ENAMETOOLONG;
1241 return 0;
1242 }
1243 if (!set_path_only) {
1244 /* The destination is operator-supplied (like --log-file et al.), so
1245 * resolve it with open_no_attacker_symlinks: walk each component
1246 * refusing a symlink not owned by uid 0 or our euid, then fchdir to
1247 * the result. This still follows the operator's/root's own symlinked
1248 * dest -- the `/backup -> /mnt/disk` / `/var/www -> /srv/www` admin
1249 * pattern -- but refuses one an attacker raced in from another uid,
1250 * closing the dest chdir TOCTOU (the daemon `use chroot = no` module
1251 * path is the same class). The daemon is always confined; a
1252 * non-daemon receiver can opt back into the legacy plain chdir with
1253 * --insecure-links. */
1254 if (am_daemon && !am_chrooted) {
1255 int dfd = open_no_attacker_symlinks(dir, O_RDONLY | O_DIRECTORY, 0);
1256 if (dfd < 0)
1257 return 0;
1258 if (fchdir(dfd) != 0) {
1259 int e = errno;
1260 close(dfd);
1261 errno = e;
1262 return 0;
1263 }
1264 close(dfd);
1265 #if defined O_NOFOLLOW && defined O_DIRECTORY
1266 } else if (!am_chrooted && !am_sender && !insecure_links) {
1267 /* Strip the trailing slash: a symlink opened as "name/" is
1268 * always followed, so safe_open's final-component O_NOFOLLOW
1269 * must see the bare name to refuse an attacker's symlink. */
1270 char nf[MAXPATHLEN];
1271 unsigned int nl = len;
1272 int dfd;
1273 if (nl >= sizeof nf) {
1274 errno = ENAMETOOLONG;
1275 return 0;
1276 }
1277 memcpy(nf, dir, nl + 1);
1278 while (nl > 1 && nf[nl-1] == '/')
1279 nf[--nl] = '\0';
1280 /* Follow a symlinked dest only when it is owned by uid 0 or our
1281 * euid (the admin `/backup -> /mnt/disk` pattern and the
1282 * operator's own symlinks); refuse one an attacker raced in from
1283 * another uid. A real dir is opened directly. This closes the
1284 * destination chdir TOCTOU; --insecure-links keeps the plain
1285 * chdir for an operator whose dest is a foreign-owned symlink. */
1286 dfd = open_no_attacker_symlinks(nf, O_RDONLY | O_DIRECTORY, 0);
1287 if (dfd < 0)
1288 return 0;
1289 if (fchdir(dfd) != 0) {
1290 int e = errno;
1291 close(dfd);
1292 errno = e;
1293 return 0;
1294 }
1295 close(dfd);
1296 #endif
1297 } else if (chdir(dir)) {
1298 return 0;
1299 }
1300 }
1301 skipped_chdir = set_path_only;
1302 memcpy(curr_dir, dir, len + 1);
1303 } else {
1304 unsigned int save_dir_len = curr_dir_len;
1305 if (curr_dir_len + 1 + len >= sizeof curr_dir) {
1306 errno = ENAMETOOLONG;
1307 return 0;
1308 }
1309 if (!(curr_dir_len && curr_dir[curr_dir_len-1] == '/'))
1310 curr_dir[curr_dir_len++] = '/';
1311 memcpy(curr_dir + curr_dir_len, dir, len + 1);
1312
1313 if (!set_path_only) {
1314 int chdir_failed;
1315 /* In the daemon-without-chroot deployment we must not
1316 * follow a symlink in any component of the chdir
1317 * target -- otherwise CWD escapes the module and
1318 * every subsequent path-relative syscall (open,
1319 * chmod, lchown, ...) inherits the escape, which
1320 * defeats secure_relative_open's RESOLVE_BENEATH
1321 * anchor and re-opens the CVE-2026-29518 class of
1322 * symlink TOCTOU attacks. Use the secure resolver
1323 * to get a confined dirfd, then fchdir() to it.
1324 *
1325 * If skipped_chdir is set, a previous CD_SKIP_CHDIR
1326 * call buffered an absolute prefix in curr_dir
1327 * (e.g. change_pathname's CD_SKIP_CHDIR to orig_dir)
1328 * without syncing the kernel's CWD. Resolve `dir`
1329 * relative to that prefix as basedir so the secure
1330 * branch still anchors at the operator-trusted
1331 * directory rather than wherever the kernel CWD
1332 * happens to be. */
1333 if (am_daemon && (!am_chrooted || module_dirlen) && !symlink_optout_allowed()) {
1334 const char *basedir = NULL;
1335 char prefix[MAXPATHLEN];
1336 int dfd;
1337 if (skipped_chdir) {
1338 if (save_dir_len >= sizeof prefix) {
1339 errno = ENAMETOOLONG;
1340 chdir_failed = 1;
1341 goto chdir_cleanup;
1342 }
1343 memcpy(prefix, curr_dir, save_dir_len);
1344 prefix[save_dir_len] = '\0';
1345 basedir = prefix;
1346 }
1347 dfd = secure_relative_open(basedir, dir,
1348 O_RDONLY | O_DIRECTORY, 0);
1349 if (dfd < 0) {
1350 chdir_failed = 1;
1351 } else {
1352 chdir_failed = fchdir(dfd) != 0;
1353 close(dfd);
1354 }
1355 } else if (am_daemon && symlink_optout_allowed()) {
1356 /* "insecure links = yes": restore the 3.2.7 follow-any-symlink
1357 * traversal with a plain chdir to the accumulated path, the same
1358 * legacy behaviour the per-operation sites grant under the opt-out. */
1359 chdir_failed = chdir(curr_dir) != 0;
1360 } else if (!am_chrooted && !am_sender && !insecure_links) {
1361 /* Non-daemon receiver: confine the operator-named relative
1362 * destination like the absolute case above -- refuse a component
1363 * symlink not owned by uid 0 or our euid, closing the
1364 * relative-dest chdir TOCTOU while still following the operator's
1365 * own symlinks. --insecure-links keeps the plain chdir. */
1366 int dfd = open_no_attacker_symlinks(curr_dir,
1367 O_RDONLY | O_DIRECTORY, 0);
1368 if (dfd < 0)
1369 chdir_failed = 1;
1370 else {
1371 chdir_failed = fchdir(dfd) != 0;
1372 close(dfd);
1373 }
1374 } else {
1375 chdir_failed = chdir(curr_dir) != 0;
1376 }
1377 chdir_cleanup:
1378 if (chdir_failed) {
1379 curr_dir_len = save_dir_len;
1380 curr_dir[curr_dir_len] = '\0';
1381 return 0;
1382 }
1383 }
1384 skipped_chdir = set_path_only;
1385 }
1386
1387 curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
1388 if (sanitize_paths) {
1389 if (module_dirlen > curr_dir_len)
1390 module_dirlen = curr_dir_len;
1391 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
1392 }
1393
1394 if (!set_path_only) /* a real chdir invalidates the cwd-relative dir-fd stack */
1395 reset_dir_fd_cache();
1396
1397 if (DEBUG_GTE(CHDIR, 1) && !set_path_only)
1398 rprintf(FINFO, "[%s] change_dir(%s)\n", who_am_i(), curr_dir);
1399
1400 return 1;
1401 }
1402
1403 /* This will make a relative path absolute and clean it up via clean_fname().
1404 * Returns the string, which might be newly allocated, or NULL on error. */
1405 char *normalize_path(char *path, BOOL force_newbuf, unsigned int *len_ptr)
1406 {
1407 unsigned int len;
1408
1409 if (*path != '/') { /* Make path absolute. */
1410 int len = strlen(path);
1411 if (curr_dir_len + 1 + len >= sizeof curr_dir)
1412 return NULL;
1413 curr_dir[curr_dir_len] = '/';
1414 memcpy(curr_dir + curr_dir_len + 1, path, len + 1);
1415 path = strdup(curr_dir);
1416 curr_dir[curr_dir_len] = '\0';
1417 } else if (force_newbuf)
1418 path = strdup(path);
1419
1420 len = clean_fname(path, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
1421
1422 if (len_ptr)
1423 *len_ptr = len;
1424
1425 return path;
1426 }
1427
1428 /**
1429 * Return a quoted string with the full pathname of the indicated filename.
1430 * The string " (in MODNAME)" may also be appended. The returned pointer
1431 * remains valid until the next time full_fname() is called.
1432 **/
1433 char *full_fname(const char *fn)
1434 {
1435 static char *result = NULL;
1436 char *m1, *m2, *m3;
1437 char *p1, *p2;
1438
1439 if (result)
1440 free(result);
1441
1442 if (!fn)
1443 fn = "(null)";
1444
1445 if (*fn == '/')
1446 p1 = p2 = "";
1447 else {
1448 p1 = curr_dir + module_dirlen;
1449 for (p2 = p1; *p2 == '/'; p2++) {}
1450 if (*p2)
1451 p2 = "/";
1452 }
1453 if (module_id >= 0) {
1454 m1 = " (in ";
1455 m2 = lp_name(module_id);
1456 m3 = ")";
1457 } else
1458 m1 = m2 = m3 = "";
1459
1460 if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) < 0)
1461 out_of_memory("full_fname");
1462
1463 return result;
1464 }
1465
1466 static char partial_fname[MAXPATHLEN];
1467
1468 char *partial_dir_fname(const char *fname)
1469 {
1470 char *t = partial_fname;
1471 int sz = sizeof partial_fname;
1472 const char *fn;
1473
1474 if ((fn = strrchr(fname, '/')) != NULL) {
1475 fn++;
1476 if (*partial_dir != '/') {
1477 int len = fn - fname;
1478 strncpy(t, fname, len); /* safe */
1479 t += len;
1480 sz -= len;
1481 }
1482 } else
1483 fn = fname;
1484 if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
1485 return NULL;
1486 if (daemon_filter_list.head) {
1487 t = strrchr(partial_fname, '/');
1488 *t = '\0';
1489 if (check_filter(&daemon_filter_list, FLOG, partial_fname, 1) < 0)
1490 return NULL;
1491 *t = '/';
1492 if (check_filter(&daemon_filter_list, FLOG, partial_fname, 0) < 0)
1493 return NULL;
1494 }
1495
1496 return partial_fname;
1497 }
1498
1499 /* If no --partial-dir option was specified, we don't need to do anything
1500 * (the partial-dir is essentially '.'), so just return success. */
1501 int handle_partial_dir(const char *fname, int create)
1502 {
1503 char *fn, *dir;
1504
1505 if (fname != partial_fname)
1506 return 1;
1507 if (!create && *partial_dir == '/')
1508 return 1;
1509 if (!(fn = strrchr(partial_fname, '/')))
1510 return 1;
1511
1512 *fn = '\0';
1513 dir = partial_fname;
1514 /* The --partial-dir is an operator-supplied path (an absolute one may point
1515 * outside the tree): resolve it with the ownership walk -- follow a
1516 * uid0/euid-owned symlink, refuse a foreign one, absolute and relative alike.
1517 * --insecure-links (or a daemon module's "insecure links =") opts out. */
1518 operator_path_resolve = 1;
1519 if (create) {
1520 STRUCT_STAT st;
1521 int statret = do_lstat_at(dir, &st);
1522 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1523 if (do_unlink_at(dir) < 0) {
1524 operator_path_resolve = 0;
1525 *fn = '/';
1526 return 0;
1527 }
1528 statret = -1;
1529 }
1530 if (statret < 0 && do_mkdir_at(dir, 0700) < 0) {
1531 operator_path_resolve = 0;
1532 *fn = '/';
1533 return 0;
1534 }
1535 } else
1536 do_rmdir_at(dir);
1537 operator_path_resolve = 0;
1538 *fn = '/';
1539
1540 return 1;
1541 }
1542
1543 /* Determine if a symlink points outside the current directory tree.
1544 * This is considered "unsafe" because e.g. when mirroring somebody
1545 * else's machine it might allow them to establish a symlink to
1546 * /etc/passwd, and then read it through a web server.
1547 *
1548 * Returns 1 if unsafe, 0 if safe.
1549 *
1550 * Null symlinks and absolute symlinks are always unsafe.
1551 *
1552 * Basically here we are concerned with symlinks whose target contains
1553 * "..", because this might cause us to walk back up out of the
1554 * transferred directory. We are not allowed to go back up and
1555 * reenter.
1556 *
1557 * "dest" is the target of the symlink in question.
1558 *
1559 * "src" is the top source directory currently applicable at the level
1560 * of the referenced symlink. This is usually the symlink's full path
1561 * (including its name), as referenced from the root of the transfer.
1562 *
1563 * NOTE: this also rejects dest names with a .. component in other
1564 * than the first component of the name ie. it rejects names such as
1565 * a/b/../x/y. This needs to be done as the leading subpaths 'a' or
1566 * 'b' could later be replaced with symlinks such as a link to '.'
1567 * resulting in the link being transferred now becoming unsafe
1568 */
1569 int unsafe_symlink(const char *dest, const char *src)
1570 {
1571 const char *name, *slash;
1572 int depth = 0;
1573
1574 /* all absolute and null symlinks are unsafe */
1575 if (!dest || !*dest || *dest == '/')
1576 return 1;
1577
1578 // reject destinations with /../ in the name other than at the start of the name
1579 const char *dest2 = dest;
1580 while (strncmp(dest2, "../", 3) == 0) {
1581 dest2 += 3;
1582 while (*dest2 == '/') {
1583 // allow for ..//..///../foo
1584 dest2++;
1585 }
1586 }
1587 if (strstr(dest2, "/../"))
1588 return 1;
1589
1590 // reject if the destination ends in /..
1591 const size_t dlen = strlen(dest);
1592 if (dlen > 3 && strcmp(&dest[dlen-3], "/..") == 0)
1593 return 1;
1594
1595 /* find out what our safety margin is */
1596 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1597 /* ".." segment starts the count over. "." segment is ignored. */
1598 if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
1599 if (name[1] == '.')
1600 depth = 0;
1601 } else
1602 depth++;
1603 while (slash[1] == '/') slash++; /* just in case src isn't clean */
1604 }
1605 if (*name == '.' && name[1] == '.' && name[2] == '\0')
1606 depth = 0;
1607
1608 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1609 if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
1610 if (name[1] == '.') {
1611 /* if at any point we go outside the current directory
1612 then stop - it is unsafe */
1613 if (--depth < 0)
1614 return 1;
1615 }
1616 } else
1617 depth++;
1618 while (slash[1] == '/') slash++;
1619 }
1620 if (*name == '.' && name[1] == '.' && name[2] == '\0')
1621 depth--;
1622
1623 return depth < 0;
1624 }
1625
1626 /* Return the date and time as a string. Some callers tweak returned buf. */
1627 char *timestring(time_t t)
1628 {
1629 static int ndx = 0;
1630 static char buffers[4][20]; /* We support 4 simultaneous timestring results. */
1631 char *TimeBuf = buffers[ndx = (ndx + 1) % 4];
1632 struct tm tmp, *tm = localtime_r(&t, &tmp);
1633 int len;
1634 if (!tm) {
1635 strlcpy(TimeBuf, "(time out of range)", sizeof buffers[0]);
1636 return TimeBuf;
1637 }
1638 len = snprintf(TimeBuf, sizeof buffers[0], "%4d/%02d/%02d %02d:%02d:%02d",
1639 (int)tm->tm_year + 1900, (int)tm->tm_mon + 1, (int)tm->tm_mday,
1640 (int)tm->tm_hour, (int)tm->tm_min, (int)tm->tm_sec);
1641 assert(len > 0); /* Silence gcc warning */
1642
1643 return TimeBuf;
1644 }
1645
1646 /* Determine if two time_t values are equivalent (either exact, or in
1647 * the modification timestamp window established by --modify-window).
1648 * Returns 1 if the times the "same", or 0 if they are different. */
1649 int same_time(time_t f1_sec, unsigned long f1_nsec, time_t f2_sec, unsigned long f2_nsec)
1650 {
1651 if (modify_window == 0)
1652 return f1_sec == f2_sec;
1653 if (modify_window < 0)
1654 return f1_sec == f2_sec && f1_nsec == f2_nsec;
1655 /* The nanoseconds do not figure into these checks -- time windows don't care about that. */
1656 if (f2_sec > f1_sec)
1657 return f2_sec - f1_sec <= modify_window;
1658 return f1_sec - f2_sec <= modify_window;
1659 }
1660
1661 #ifdef __INSURE__XX
1662 #include <dlfcn.h>
1663
1664 /**
1665 This routine is a trick to immediately catch errors when debugging
1666 with insure. A xterm with a gdb is popped up when insure catches
1667 a error. It is Linux specific.
1668 **/
1669 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1670 {
1671 static int (*fn)();
1672 int ret, pid_int = getpid();
1673 char *cmd;
1674
1675 if (asprintf(&cmd,
1676 "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; "
1677 "gdb /proc/%d/exe %d'", pid_int, pid_int, pid_int) < 0)
1678 return -1;
1679
1680 if (!fn) {
1681 static void *h;
1682 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1683 fn = dlsym(h, "_Insure_trap_error");
1684 }
1685
1686 ret = fn(a1, a2, a3, a4, a5, a6);
1687
1688 system(cmd);
1689
1690 free(cmd);
1691
1692 return ret;
1693 }
1694 #endif
1695
1696 /* Take a filename and filename length and return the most significant
1697 * filename suffix we can find. This ignores suffixes such as "~",
1698 * ".bak", ".orig", ".~1~", etc. */
1699 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1700 {
1701 const char *suf, *s;
1702 BOOL had_tilde;
1703 int s_len;
1704
1705 /* One or more dots at the start aren't a suffix. */
1706 while (fn_len && *fn == '.') fn++, fn_len--;
1707
1708 /* Ignore the ~ in a "foo~" filename. */
1709 if (fn_len > 1 && fn[fn_len-1] == '~')
1710 fn_len--, had_tilde = True;
1711 else
1712 had_tilde = False;
1713
1714 /* Assume we don't find an suffix. */
1715 suf = "";
1716 *len_ptr = 0;
1717
1718 /* Find the last significant suffix. */
1719 for (s = fn + fn_len; fn_len > 1; ) {
1720 while (*--s != '.' && s != fn) {}
1721 if (s == fn)
1722 break;
1723 s_len = fn_len - (s - fn);
1724 fn_len = s - fn;
1725 if (s_len == 4) {
1726 if (strcmp(s+1, "bak") == 0
1727 || strcmp(s+1, "old") == 0)
1728 continue;
1729 } else if (s_len == 5) {
1730 if (strcmp(s+1, "orig") == 0)
1731 continue;
1732 } else if (s_len > 2 && had_tilde && s[1] == '~' && isDigit(s + 2))
1733 continue;
1734 *len_ptr = s_len;
1735 suf = s;
1736 if (s_len == 1)
1737 break;
1738 /* Determine if the suffix is all digits. */
1739 for (s++, s_len--; s_len > 0; s++, s_len--) {
1740 if (!isDigit(s))
1741 return suf;
1742 }
1743 /* An all-digit suffix may not be that significant. */
1744 s = suf;
1745 }
1746
1747 return suf;
1748 }
1749
1750 /* This is an implementation of the Levenshtein distance algorithm. It
1751 * was implemented to avoid needing a two-dimensional matrix (to save
1752 * memory). It was also tweaked to try to factor in the ASCII distance
1753 * between changed characters as a minor distance quantity. The normal
1754 * Levenshtein units of distance (each signifying a single change between
1755 * the two strings) are defined as a "UNIT". */
1756
1757 #define UNIT (1 << 16)
1758
1759 uint32 fuzzy_distance(const char *s1, unsigned len1, const char *s2, unsigned len2, uint32 upperlimit)
1760 {
1761 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1762 int32 cost;
1763 unsigned i1, i2;
1764
1765 /* Check to see if the Levenshtein distance must be greater than the
1766 * upper limit defined by the previously found lowest distance using
1767 * the heuristic that the Levenshtein distance is greater than the
1768 * difference in length of the two strings */
1769 if ((len1 > len2 ? len1 - len2 : len2 - len1) * UNIT > upperlimit)
1770 return 0xFFFFU * UNIT + 1;
1771
1772 if (!len1 || !len2) {
1773 if (!len1) {
1774 s1 = s2;
1775 len1 = len2;
1776 }
1777 for (i1 = 0, cost = 0; i1 < len1; i1++)
1778 cost += s1[i1];
1779 return (int32)len1 * UNIT + cost;
1780 }
1781
1782 for (i2 = 0; i2 < len2; i2++)
1783 a[i2] = (i2+1) * UNIT;
1784
1785 for (i1 = 0; i1 < len1; i1++) {
1786 diag = i1 * UNIT;
1787 above = (i1+1) * UNIT;
1788 for (i2 = 0; i2 < len2; i2++) {
1789 left = a[i2];
1790 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1791 if (cost < 0)
1792 cost = UNIT - cost;
1793 else
1794 cost = UNIT + cost;
1795 }
1796 diag_inc = diag + cost;
1797 left_inc = left + UNIT + *((uchar*)s1+i1);
1798 above_inc = above + UNIT + *((uchar*)s2+i2);
1799 a[i2] = above = left < above
1800 ? (left_inc < diag_inc ? left_inc : diag_inc)
1801 : (above_inc < diag_inc ? above_inc : diag_inc);
1802 diag = left;
1803 }
1804 }
1805
1806 return a[len2-1];
1807 }
1808
1809 #define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1810 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1811 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1812
1813 struct bitbag {
1814 uint32 **bits;
1815 int slot_cnt;
1816 };
1817
1818 struct bitbag *bitbag_create(int max_ndx)
1819 {
1820 struct bitbag *bb = new(struct bitbag);
1821 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1822
1823 bb->bits = new_array0(uint32*, bb->slot_cnt);
1824
1825 return bb;
1826 }
1827
1828 void bitbag_set_bit(struct bitbag *bb, int ndx)
1829 {
1830 int slot = ndx / BB_PER_SLOT_BITS;
1831 ndx %= BB_PER_SLOT_BITS;
1832
1833 if (!bb->bits[slot])
1834 bb->bits[slot] = new_array0(uint32, BB_PER_SLOT_INTS);
1835
1836 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1837 }
1838
1839 #if 0 /* not needed yet */
1840 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1841 {
1842 int slot = ndx / BB_PER_SLOT_BITS;
1843 ndx %= BB_PER_SLOT_BITS;
1844
1845 if (!bb->bits[slot])
1846 return;
1847
1848 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1849 }
1850
1851 int bitbag_check_bit(struct bitbag *bb, int ndx)
1852 {
1853 int slot = ndx / BB_PER_SLOT_BITS;
1854 ndx %= BB_PER_SLOT_BITS;
1855
1856 if (!bb->bits[slot])
1857 return 0;
1858
1859 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1860 }
1861 #endif
1862
1863 /* Call this with -1 to start checking from 0. Returns -1 at the end. */
1864 int bitbag_next_bit(struct bitbag *bb, int after)
1865 {
1866 uint32 bits, mask;
1867 int i, ndx = after + 1;
1868 int slot = ndx / BB_PER_SLOT_BITS;
1869 ndx %= BB_PER_SLOT_BITS;
1870
1871 mask = (1u << (ndx % 32)) - 1;
1872 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1873 if (!bb->bits[slot])
1874 continue;
1875 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1876 if (!(bits = bb->bits[slot][i] & ~mask))
1877 continue;
1878 /* The xor magic figures out the lowest enabled bit in
1879 * bits, and the switch quickly computes log2(bit). */
1880 switch (bits ^ (bits & (bits-1))) {
1881 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1882 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1883 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1884 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1885 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1886 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1887 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1888 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1889 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1890 }
1891 return -1; /* impossible... */
1892 }
1893 }
1894
1895 return -1;
1896 }
1897
1898 void flist_ndx_push(flist_ndx_list *lp, int ndx)
1899 {
1900 struct flist_ndx_item *item;
1901
1902 item = new(struct flist_ndx_item);
1903 item->next = NULL;
1904 item->ndx = ndx;
1905 if (lp->tail)
1906 lp->tail->next = item;
1907 else
1908 lp->head = item;
1909 lp->tail = item;
1910 }
1911
1912 int flist_ndx_pop(flist_ndx_list *lp)
1913 {
1914 struct flist_ndx_item *next;
1915 int ndx;
1916
1917 if (!lp->head)
1918 return -1;
1919
1920 ndx = lp->head->ndx;
1921 next = lp->head->next;
1922 free(lp->head);
1923 lp->head = next;
1924 if (!next)
1925 lp->tail = NULL;
1926
1927 return ndx;
1928 }
1929
1930 /* Make sure there is room for one more item in the item list. If there
1931 * is not, expand the list as indicated by the value of "incr":
1932 * - if incr < 0 then increase the malloced size by -1 * incr
1933 * - if incr >= 0 then either make the malloced size equal to "incr"
1934 * or (if that's not large enough) double the malloced size
1935 * After the size check, the list's count is incremented by 1 and a pointer
1936 * to the "new" list item is returned.
1937 */
1938 void *expand_item_list(item_list *lp, size_t item_size, const char *desc, int incr)
1939 {
1940 /* First time through, 0 <= 0, so list is expanded. */
1941 if (lp->malloced <= lp->count) {
1942 void *new_ptr;
1943 size_t expand_size;
1944 if (incr < 0)
1945 expand_size = -incr; /* increase slowly */
1946 else if (lp->malloced < (size_t)incr)
1947 expand_size = incr - lp->malloced;
1948 else if (lp->malloced)
1949 expand_size = lp->malloced; /* double in size */
1950 else
1951 expand_size = 1;
1952 if (SIZE_MAX/item_size - expand_size < lp->malloced)
1953 overflow_exit("expand_item_list");
1954 expand_size += lp->malloced;
1955 new_ptr = realloc_buf(lp->items, expand_size * item_size);
1956 if (DEBUG_GTE(FLIST, 3)) {
1957 rprintf(FINFO, "[%s] expand %s to %s bytes, did%s move\n",
1958 who_am_i(), desc, big_num(expand_size * item_size),
1959 new_ptr == lp->items ? " not" : "");
1960 }
1961
1962 lp->items = new_ptr;
1963 lp->malloced = expand_size;
1964 }
1965 return (char*)lp->items + (lp->count++ * item_size);
1966 }
1967
1968 /* This zeroing of memory won't be optimized away by the compiler. */
1969 void force_memzero(void *buf, size_t len)
1970 {
1971 volatile uchar *z = buf;
1972 while (len-- > 0)
1973 *z++ = '\0';
1974 }