diff --git a/.github/scripts/changes.py b/.github/scripts/changes.py index 6f223a9ac..485e2e1d4 100644 --- a/.github/scripts/changes.py +++ b/.github/scripts/changes.py @@ -107,7 +107,13 @@ def script(selected, name): enable(selected, 'linux', 'diagnostics') elif name == 'install-cygwin.ps1': enable(selected, 'other', 'diagnostics') - elif name == 'prepare-vm-host.sh': + elif name == 'prepare-macos.sh': + enable(selected, 'macos', 'interoperability', 'diagnostics') + elif name == 'prepare-manpages.sh': + enable(selected, 'linux', 'macos', 'diagnostics') + elif name == 'unpack-android-artifact.sh': + enable(selected, 'android', 'diagnostics') + elif name in ('prepare-vm-host.sh', 'vm-ssh.sh'): enable(selected, 'bsd', 'other', 'diagnostics', 'interoperability') elif name == 'ubuntu-apt.sh': enable(selected, 'linux', 'bsd', 'other', 'android', 'archive', 'diagnostics', 'versions', diff --git a/.github/scripts/install-cygwin.ps1 b/.github/scripts/install-cygwin.ps1 index 38a957e1e..fd0787f8c 100644 --- a/.github/scripts/install-cygwin.ps1 +++ b/.github/scripts/install-cygwin.ps1 @@ -31,3 +31,5 @@ if (-not (Test-Path -LiteralPath $bash)) { throw 'Cygwin setup did not install b & $bash -lc 'command -v make aclocal gcc /usr/bin/git python3 >/dev/null' if ($LASTEXITCODE -ne 0) { throw 'Cygwin setup did not install all required build tools' } 'C:/tools/cygwin/bin' >>$Env:GITHUB_PATH +# The version wrapper cannot infer an Autoconf version from rsync's handwritten configure script. +'WANT_AUTOCONF=latest' >>$Env:GITHUB_ENV diff --git a/.github/scripts/prepare-macos.sh b/.github/scripts/prepare-macos.sh new file mode 100644 index 000000000..9fc232905 --- /dev/null +++ b/.github/scripts/prepare-macos.sh @@ -0,0 +1,12 @@ +#!/bin/sh +set -eu + +set -- +for formula in automake openssl xxhash zstd lz4 libidn2; do + if ! brew --prefix --installed "$formula" >/dev/null; then + set -- "$@" "$formula" + fi +done +if [ "$#" -gt 0 ]; then + brew install "$@" +fi diff --git a/.github/scripts/prepare-manpages.sh b/.github/scripts/prepare-manpages.sh new file mode 100644 index 000000000..0751c510b --- /dev/null +++ b/.github/scripts/prepare-manpages.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +venv="${RUNNER_TEMP:?}/rsync-manpages" +python3 -m venv "$venv" +PATH="$venv/bin:$PATH" +export PATH +"$venv/bin/python3" -m pip install --no-cache-dir 'commonmark==0.9.2' +printf '%s\n' "$venv/bin" >>"${GITHUB_PATH:?}" diff --git a/.github/scripts/prepare-vm-host.sh b/.github/scripts/prepare-vm-host.sh index 27c21cb1b..dc080dcf2 100644 --- a/.github/scripts/prepare-vm-host.sh +++ b/.github/scripts/prepare-vm-host.sh @@ -18,11 +18,15 @@ esac if [ "$mode" = update-first ]; then sh .github/scripts/ubuntu-apt.sh update - exec sh .github/scripts/ubuntu-apt.sh install -y "$@" + sh .github/scripts/ubuntu-apt.sh install -y "$@" +elif ! sh .github/scripts/ubuntu-apt.sh install -y -q -o Acquire::Retries=3 --no-install-recommends "$@"; then + sh .github/scripts/ubuntu-apt.sh update -q + sh .github/scripts/ubuntu-apt.sh install -y -q -o Acquire::Retries=3 --no-install-recommends "$@" fi -if sh .github/scripts/ubuntu-apt.sh install -y -q -o Acquire::Retries=3 --no-install-recommends "$@"; then - exit 0 -fi -sh .github/scripts/ubuntu-apt.sh update -q -exec sh .github/scripts/ubuntu-apt.sh install -y -q -o Acquire::Retries=3 --no-install-recommends "$@" +real_ssh=$(command -v ssh) +bin="${RUNNER_TEMP:?}/rsync-vm-bin" +mkdir "$bin" +install -m 0755 .github/scripts/vm-ssh.sh "$bin/ssh" +printf 'RSYNC_VM_SSH=%s\n' "$real_ssh" >>"${GITHUB_ENV:?}" +printf '%s\n' "$bin" >>"${GITHUB_PATH:?}" diff --git a/.github/scripts/test-changes.py b/.github/scripts/test-changes.py index b21516faa..59906b5be 100644 --- a/.github/scripts/test-changes.py +++ b/.github/scripts/test-changes.py @@ -92,7 +92,11 @@ def test_ci_files_select_their_owner(self): '.github/scripts/changes.py': full_selection, '.github/scripts/test-changes.py': {'diagnostics'}, '.github/scripts/check-platform.py': {'linux', 'macos', 'other', 'diagnostics'}, + '.github/scripts/prepare-macos.sh': {'macos', 'interoperability', 'diagnostics'}, + '.github/scripts/prepare-manpages.sh': {'linux', 'macos', 'diagnostics'}, '.github/scripts/prepare-vm-host.sh': {'bsd', 'other', 'diagnostics', 'interoperability'}, + '.github/scripts/unpack-android-artifact.sh': {'android', 'diagnostics'}, + '.github/scripts/vm-ssh.sh': {'bsd', 'other', 'diagnostics', 'interoperability'}, '.github/scripts/ubuntu-apt.sh': full_selection - {'macos'}, '.github/actions/interoperability/action.yml': {'interoperability', 'diagnostics'}, '.github/actions/interop-upload/action.yml': {'interoperability', 'diagnostics'}, diff --git a/.github/scripts/test-diagnostics.py b/.github/scripts/test-diagnostics.py index 2cd9b4262..7a0820402 100644 --- a/.github/scripts/test-diagnostics.py +++ b/.github/scripts/test-diagnostics.py @@ -3,6 +3,8 @@ import os from pathlib import Path import runpy +import shutil +import subprocess import sys import tempfile import unittest @@ -13,6 +15,18 @@ class Diagnostics(unittest.TestCase): + @unittest.skipUnless(shutil.which('bash') and shutil.which('sh'), 'VM SSH test needs bash and sh') + def test_vm_ssh_preserves_binary_stdin(self): + wrapper = Path(__file__).with_name('vm-ssh.sh') + payload = b'rsync protocol\0\xff\n' + result = subprocess.run( + ['bash', str(wrapper), '-c', 'cat; printf "%s\\n" "transport diagnostic" >&2; exit 13'], + env=dict(os.environ, RSYNC_VM_SSH=shutil.which('sh')), + input=payload, capture_output=True, timeout=10) + self.assertEqual(result.returncode, 13) + self.assertEqual(result.stdout, payload) + self.assertEqual(result.stderr, b'transport diagnostic\n') + def test_helper_runner_covers_the_roster(self): with tempfile.TemporaryDirectory(prefix='rsync-helpers-') as directory: root = Path(directory) diff --git a/.github/scripts/unpack-android-artifact.sh b/.github/scripts/unpack-android-artifact.sh new file mode 100644 index 000000000..5b66e5e34 --- /dev/null +++ b/.github/scripts/unpack-android-artifact.sh @@ -0,0 +1,43 @@ +#!/bin/sh +set -eu + +if [ "$#" -ne 1 ]; then + echo 'usage: unpack-android-artifact.sh ' >&2 + exit 2 +fi +case "$1" in + /*) ;; + *) echo 'Expected an absolute artifact directory' >&2; exit 2 ;; +esac + +set -- "$1"/* +if [ "$#" -ne 1 ] || [ ! -f "$1" ] || [ -L "$1" ]; then + echo 'Expected exactly one downloaded Android archive' >&2 + exit 1 +fi +archive=$1 +members=$(LC_ALL=C unzip -Z -1 "$archive") +binary=$(printf '%s\n' "$members" | LC_ALL=C awk ' + /^rsync-[A-Za-z0-9.+-]+-android-x86_64$/ { binary = $0; next } + /^rsync-[A-Za-z0-9.+-]+-android-x86_64[.]sha256$/ { checksum = $0; next } + END { + if (NR != 2 || !binary || checksum != binary ".sha256") + exit 1 + print binary + } +') || { + echo 'Expected one x86-64 Android binary and its checksum in the archive' >&2 + exit 1 +} + +# Stream the expected members into a new directory without extracting archive paths. +umask 077 +mkdir dist +( + ulimit -f 131072 + unzip -p "$archive" "$binary" >"dist/$binary" +) +( + ulimit -f 2 + unzip -p "$archive" "$binary.sha256" >"dist/$binary.sha256" +) diff --git a/.github/scripts/vm-ssh.sh b/.github/scripts/vm-ssh.sh new file mode 100644 index 000000000..a152b80c2 --- /dev/null +++ b/.github/scripts/vm-ssh.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -u + +# OpenSSH writes host-key acceptance at info level and prefixes it with "Warning:". +# Normalise only that message for loopback VM connections. +: "${RSYNC_VM_SSH:?}" +command -v sed >/dev/null || exit 127 +coproc FILTER { + LC_ALL=C sed -u -E "s/^Warning: Permanently added '(\[127\.0\.0\.1\]:[0-9]+)' \(([A-Za-z0-9_-]+)\) to the list of known hosts\.$/VM SSH accepted the host key for \1 (\2)./" >&2 +} +filter_pid=$! +coproc_fd=${FILTER[1]} +exec {stderr_fd}>&"$coproc_fd" +# An asynchronous command would otherwise read from /dev/null. +"$RSYNC_VM_SSH" "$@" <&0 2>&"$stderr_fd" & +ssh_pid=$! +exec {coproc_fd}>&- +exec {stderr_fd}>&- + +trap ' + trap - INT TERM HUP + kill -TERM "$ssh_pid" 2>/dev/null || : + wait "$ssh_pid" 2>/dev/null || : + wait "$filter_pid" 2>/dev/null || : + exit 143 +' INT TERM HUP + +wait "$ssh_pid" +ssh_status=$? +wait "$filter_pid" +filter_status=$? +trap - INT TERM HUP +if (( ssh_status != 0 )); then + exit "$ssh_status" +fi +exit "$filter_status" diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 546a06dc8..f6e22d29f 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -137,10 +137,13 @@ jobs: uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: rsync-android-x86_64 - path: dist/ + path: ${{ runner.temp }}/rsync-android-artifact + skip-decompress: true - &restore name: Verify binary - run: python3 -S .github/scripts/android.py restore --abi x86_64 + run: | + sh .github/scripts/unpack-android-artifact.sh "$RUNNER_TEMP/rsync-android-artifact" && + python3 -S .github/scripts/android.py restore --abi x86_64 - name: Tests id: test run: python3 -S .github/scripts/android-emulator.py --termux --output test-results/termux diff --git a/.github/workflows/diagnostics.yml b/.github/workflows/diagnostics.yml index 67c4233c6..f7b78fe49 100644 --- a/.github/workflows/diagnostics.yml +++ b/.github/workflows/diagnostics.yml @@ -221,7 +221,7 @@ jobs: sh .github/scripts/ubuntu-apt.sh "$@" update sh .github/scripts/ubuntu-apt.sh "$@" install -y --no-install-recommends \ "clang-$LLVM_MAJOR" "clang-tools-$LLVM_MAJOR" cppcheck acl libacl1-dev attr libattr1-dev \ - liblz4-dev libidn2-dev libzstd-dev libxxhash-dev libpopt-dev libssl-dev openssl + liblz4-dev libidn2-dev libzstd-dev libxxhash-dev libssl-dev openssl - name: Tool versions run: | "clang-$LLVM_MAJOR" --version @@ -229,7 +229,13 @@ jobs: - name: Configure run: | "scan-build-$LLVM_MAJOR" --use-cc="clang-$LLVM_MAJOR" --use-c++="clang++-$LLVM_MAJOR" \ - ./configure --with-rrsync --disable-md2man + ./configure --with-rrsync --disable-md2man --with-included-popt + - name: Bundled popt hash + run: | + cc -std=c11 -O1 -g -Wall -Wextra -Werror \ + -fsanitize=address,undefined -fno-omit-frame-pointer \ + -o "$RUNNER_TEMP/t_popt_hash" t_popt_hash.c + "$RUNNER_TEMP/t_popt_hash" - name: Clang static analyser run: python3 -B -S .github/scripts/diagnostics.py scan "$LLVM_MAJOR" - name: Cppcheck diff --git a/.github/workflows/interoperability-tests.yml b/.github/workflows/interoperability-tests.yml index 797e7e052..8b71bb595 100644 --- a/.github/workflows/interoperability-tests.yml +++ b/.github/workflows/interoperability-tests.yml @@ -152,7 +152,7 @@ jobs: cache: false - name: Install dependencies run: | - brew install automake openssl xxhash zstd lz4 libidn2 + sh .github/scripts/prepare-macos.sh echo "$(brew --prefix openssl)/bin" >>"$GITHUB_PATH" - name: Configure run: | diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 7e66bb054..02c432d78 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -231,7 +231,7 @@ jobs: xxhash xxhash-devel \ libidn2 libidn2-devel alternatives --set python3 /usr/bin/python3.9 - pip3 install commonmark + sh .github/scripts/prepare-manpages.sh - name: Platform run: python3 -S .github/scripts/check-platform.py almalinux --release 8 --arch x86_64 - name: Configure diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 38a91457f..6c7a5870a 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -38,9 +38,9 @@ jobs: run: python3 -S .github/scripts/check-platform.py macos --release "${{ matrix.release }}" --arch "${{ matrix.arch }}" - name: Install dependencies run: | - brew install automake openssl xxhash zstd lz4 libidn2 - pip3 install --user --break-system-packages commonmark + sh .github/scripts/prepare-macos.sh echo "$(brew --prefix)/bin" >>"$GITHUB_PATH" + sh .github/scripts/prepare-manpages.sh mkdir -p test-results - name: Configure run: | diff --git a/Makefile.in b/Makefile.in index c0ee0e654..a52aa07f1 100644 --- a/Makefile.in +++ b/Makefile.in @@ -212,23 +212,23 @@ help-rsync.h help-rsyncd.h: rsync.1.md help-from-md.awk daemon-parm.h: daemon-parm.txt daemon-parm.awk $(AWK) -f $(srcdir)/daemon-parm.awk $(srcdir)/daemon-parm.txt -rounding.h: rounding.c rsync.h proto.h - @for r in 0 1 3; do \ - if $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o rounding -DEXTRA_ROUNDING=$$r -I. $(srcdir)/rounding.c >rounding.out 2>&1; then \ - echo "#define EXTRA_ROUNDING $$r" >rounding.h; \ +rounding.h: rounding.c $(HEADERS) + @set -e; \ + trap 'rm -f rounding.o rounding.out "$@.tmp"' 0; \ + for r in 0 1 3; do \ + if $(CC) $(CFLAGS) $(CPPFLAGS) -c -o rounding.o -DEXTRA_ROUNDING=$$r -I. $(srcdir)/rounding.c >rounding.out 2>&1; then \ + cat rounding.out >&2; \ + printf '#define EXTRA_ROUNDING %s\n' "$$r" >"$@.tmp"; \ + mv -f "$@.tmp" "$@"; \ if test -f "$$HOME/build_farm/build_test.fns"; then \ echo "EXTRA_ROUNDING is $$r" >&2; \ fi; \ - break; \ + exit 0; \ fi; \ - done - @rm -f rounding - @if test -f rounding.h; then : ; else \ - cat rounding.out 1>&2; \ - echo "Failed to create rounding.h!" 1>&2; \ - exit 1; \ - fi - @rm -f rounding.out + done; \ + cat rounding.out >&2; \ + echo "Failed to create $@!" >&2; \ + exit 1 git-version.h: ALWAYS_RUN $(srcdir)/mkgitver diff --git a/access.c b/access.c index b4db6b8ae..610aecdb8 100644 --- a/access.c +++ b/access.c @@ -329,12 +329,12 @@ enum unix_access { UNIX_ACCESS_NONE, UNIX_ACCESS_MODULE, UNIX_ACCESS_PROXY }; static int access_match(const char *list, const char *addr, const char **host_ptr, int deny, enum unix_access unix_access) { - char *tok; + char *tok, *save = NULL; char *list2 = strdup(list); strlower(list2); - for (tok = strtok(list2, " ,\t"); tok; tok = strtok(NULL, " ,\t")) { + for (tok = strtok_r(list2, " ,\t", &save); tok; tok = strtok_r(NULL, " ,\t", &save)) { int match; if (strcmp(tok, "unix:") == 0) match = unix_access != UNIX_ACCESS_NONE; diff --git a/authenticate.c b/authenticate.c index bf11343da..7ccf46774 100644 --- a/authenticate.c +++ b/authenticate.c @@ -252,7 +252,8 @@ static const char *check_secret(int module, const char *user, const char *group, /* Try to find a line that starts with the user (or @group) name and a ':'. */ err = "secret not found"; while ((user || group) && fgets(line, sizeof line, fh) != NULL) { - const char **ptr, *s = strtok(line, "\n\r"); + char *save = NULL; + const char **ptr, *s = strtok_r(line, "\n\r", &save); int len; if (!s) continue; @@ -361,6 +362,7 @@ char *auth_server(int f_in, int f_out, int module, const char *host, int group_match = -1; char *tok, *pass; char opt_ch = '\0'; + struct conf_token_state tokens = {0}; if (use_pam) { #ifndef SUPPORT_PAM @@ -428,7 +430,7 @@ char *auth_server(int f_in, int f_out, int module, const char *host, * on whitespace here tore such an entry apart, so the rule the admin wrote * never matched and a rule they never wrote appeared from its tail. The * daemon's gid field already uses this parser (clientserver.c). */ - for (tok = conf_strtok(users); tok; tok = conf_strtok(NULL)) { + for (tok = conf_strtok(users, &tokens); tok; tok = conf_strtok(NULL, &tokens)) { char *opts; /* See if the user appended :deny, :ro, or :rw. */ if ((opts = strchr(tok, ':')) != NULL) { diff --git a/clientserver.c b/clientserver.c index 993636120..ebce10803 100644 --- a/clientserver.c +++ b/clientserver.c @@ -792,6 +792,7 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char int save_munge_symlinks; pid_t pre_exec_pid = 0; char *request = NULL; + struct conf_token_state gid_tokens = {0}; set_env_str("RSYNC_MODULE_NAME", name); @@ -880,7 +881,7 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char } else set_uid = 0; - p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL; + p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id), &gid_tokens) : NULL; if (p) { /* The "*" gid must be the first item in the list. */ if (strcmp(p, "*") == 0) { @@ -897,7 +898,7 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char #endif } else if (add_a_group(f_out, p) < 0) return -1; - while ((p = conf_strtok(NULL)) != NULL) { + while ((p = conf_strtok(NULL, &gid_tokens)) != NULL) { #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST if (pw) { rprintf(FLOG, "This rsync cannot add groups after \"*\".\n"); diff --git a/configure.ac b/configure.ac index 988c33e42..44ba7a9f3 100644 --- a/configure.ac +++ b/configure.ac @@ -1920,17 +1920,6 @@ if test x"$samba_cv_HAVE_POSIX_ACLS" = x"yes"; then esac fi -if test x"$enable_acl_support" = x"no" || test x"$enable_xattr_support" = x"no" || test x"$enable_iconv" = x"no"; then - AC_MSG_CHECKING([whether $CC supports -Wno-unused-parameter]) - OLD_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS -Wno-unused-parameter" - AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[printf("hello\n");]])],[rsync_warn_flag=yes],[rsync_warn_flag=no]) - AC_MSG_RESULT([$rsync_warn_flag]) - if test x"$rsync_warn_flag" = x"no"; then - CFLAGS="$OLD_CFLAGS" - fi -fi - case "$CC" in ' checker'*|checker*) AC_DEFINE(FORCE_FD_ZERO_MEMSET, 1, [Used to make "checker" understand that FD_ZERO() clears memory.]) diff --git a/flist.c b/flist.c index e352c453a..7f2e75cf3 100644 --- a/flist.c +++ b/flist.c @@ -245,8 +245,10 @@ struct sender_source_root { }; static struct sender_source_root *sender_source_roots; +#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY static struct sender_source_root *sender_source_root_fd_owner; static int sender_source_root_fd = -1; +#endif static int sender_source_full_path(const char *path, char *full, size_t full_size) { @@ -402,12 +404,14 @@ int open_sender_source_path(const char *path, int flags, int *matched) void clear_sender_source_roots(void) { +#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY if (sender_source_root_fd >= 0) { reset_dir_fd_cache(); close(sender_source_root_fd); } sender_source_root_fd = -1; sender_source_root_fd_owner = NULL; +#endif while (sender_source_roots) { struct sender_source_root *root = sender_source_roots; sender_source_roots = root->next; diff --git a/generator.c b/generator.c index 8ad43bbfc..ab1f88e15 100644 --- a/generator.c +++ b/generator.c @@ -463,7 +463,7 @@ static BOOL destination_link_is_newer(const STRUCT_STAT *dest, const struct file } #ifdef ST_MTIME_NSEC if (dest->st_mtime == source->modtime && modify_window < 0 && protocol_version >= 31) - return dest->ST_MTIME_NSEC > F_MOD_NSEC_or_0(source); + return dest->ST_MTIME_NSEC > (int64)F_MOD_NSEC_or_0(source); #endif return False; } @@ -575,7 +575,7 @@ int unchanged_attrs(const char *fname, struct file_struct *file, stat_x *sxp) return 1; } -void itemize(const char *fnamecmp, struct file_struct *file, int ndx, int statret, +void itemize(UNUSED(const char *fnamecmp), struct file_struct *file, int ndx, int statret, stat_x *sxp, int32 iflags, uchar fnamecmp_type, const char *xname) { diff --git a/ifuncs.h b/ifuncs.h index 956fc22eb..7fe511c68 100644 --- a/ifuncs.h +++ b/ifuncs.h @@ -85,7 +85,7 @@ init_stat_x(stat_x *sx_p) } static inline void -free_stat_x(stat_x *sx_p) +free_stat_x(UNUSED(stat_x *sx_p)) { #ifdef SUPPORT_ACLS { diff --git a/lib/sysxattrs.c b/lib/sysxattrs.c index 094180c7a..649024a8c 100644 --- a/lib/sysxattrs.c +++ b/lib/sysxattrs.c @@ -255,34 +255,40 @@ static ssize_t read_xattr(int attrfd, void *buf, size_t buflen) { STRUCT_STAT sb; ssize_t ret; + int saved_errno; if (fstat(attrfd, &sb) < 0) ret = -1; - else if (sb.st_size > SSIZE_MAX) { + else if (sb.st_size < 0 || sb.st_size > SSIZE_MAX) { errno = ERANGE; ret = -1; } else if (buflen == 0) ret = sb.st_size; - else if (sb.st_size > buflen) { + else if ((size_t)sb.st_size > buflen) { errno = ERANGE; ret = -1; } else { + size_t size = (size_t)sb.st_size; size_t bufpos; - for (bufpos = 0; bufpos < sb.st_size; ) { - ssize_t cnt = read(attrfd, (char*)buf + bufpos, sb.st_size - bufpos); + + ret = (ssize_t)size; + for (bufpos = 0; bufpos < size; ) { + ssize_t cnt = read(attrfd, (char*)buf + bufpos, size - bufpos); if (cnt <= 0) { if (cnt < 0 && errno == EINTR) continue; - bufpos = -1; + if (cnt == 0) + errno = EIO; + ret = -1; break; } bufpos += cnt; } - ret = bufpos; } + saved_errno = errno; close(attrfd); - + errno = saved_errno; return ret; } diff --git a/match.c b/match.c index 1f2ebe580..58519f74c 100644 --- a/match.c +++ b/match.c @@ -510,11 +510,15 @@ void match_sums(int f, struct sum_struct *s, struct map_struct *buf, OFF_T len) * off as long as the checksum doesn't happen to be that, in * which case we turn the last 0 bit into a 1. */ if (buf && buf->status != 0) { + const int sum_len = xfer_sum_len; int i; - for (i = 0; i < xfer_sum_len && sender_file_sum[i] == 0; i++) {} - memset(sender_file_sum, 0, xfer_sum_len); - if (i == xfer_sum_len && i > 0) - sender_file_sum[i-1]++; + + if (sum_len < 0 || (size_t)sum_len > sizeof sender_file_sum) + exit_cleanup(RERR_UNSUPPORTED); + for (i = 0; i < sum_len && sender_file_sum[i] == 0; i++) {} + memset(sender_file_sum, 0, (size_t)sum_len); + if (i == sum_len && i > 0) + sender_file_sum[i-1] = 1; } if (DEBUG_GTE(DELTASUM, 2)) diff --git a/options.c b/options.c index 6bcee00dc..db566bc0e 100644 --- a/options.c +++ b/options.c @@ -359,7 +359,10 @@ static int itemize_changes = 0; static int refused_delete, refused_archive_part, refused_compress; static int refused_partial, refused_progress, refused_delete_before; static int refused_delete_during; -static int refused_inplace, refused_no_iconv; +static int refused_inplace; +#ifdef ICONV_OPTION +static int refused_no_iconv; +#endif static BOOL usermap_via_chown, groupmap_via_chown; static char *outbuf_mode; static char *bwlimit_arg, *max_size_arg, *min_size_arg; @@ -1192,8 +1195,10 @@ static void set_refuse_options(void) refused_progress = op->val; else if (strcmp("inplace", op->longName) == 0) refused_inplace = op->val; +#ifdef ICONV_OPTION else if (strcmp("no-iconv", op->longName) == 0) refused_no_iconv = op->val; +#endif break; } } diff --git a/popt/lookup3.c b/popt/lookup3.c index 04a255684..2cda58bbe 100644 --- a/popt/lookup3.c +++ b/popt/lookup3.c @@ -455,9 +455,7 @@ void jlu32lpair(const void *key, size_t size, uint32_t *pc, uint32_t *pb) u.ptr = key; if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ -#ifdef VALGRIND const uint8_t *k8; -#endif /*-- all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (size > (size_t)12) { @@ -468,36 +466,7 @@ void jlu32lpair(const void *key, size_t size, uint32_t *pc, uint32_t *pb) size -= 12; k += 3; } - /*------------------------- handle the last (probably partial) block */ - /* - * "k[2]&0xffffff" actually reads beyond the end of the string, but - * then masks off the part it's not allowed to read. Because the - * string is aligned, the masked-off tail is in the same word as the - * rest of the string. Every machine with memory protection I've seen - * does it on word boundaries, so is OK with this. But VALGRIND will - * still catch it and complain. The masking trick does make the hash - * noticeably faster for short strings (like English words). - */ -#ifndef VALGRIND - - switch (size) { - case 12: c += k[2]; b+=k[1]; a+=k[0]; break; - case 11: c += k[2]&0xffffff; b+=k[1]; a+=k[0]; break; - case 10: c += k[2]&0xffff; b+=k[1]; a+=k[0]; break; - case 9: c += k[2]&0xff; b+=k[1]; a+=k[0]; break; - case 8: b += k[1]; a+=k[0]; break; - case 7: b += k[1]&0xffffff; a+=k[0]; break; - case 6: b += k[1]&0xffff; a+=k[0]; break; - case 5: b += k[1]&0xff; a+=k[0]; break; - case 4: a += k[0]; break; - case 3: a += k[0]&0xffffff; break; - case 2: a += k[0]&0xffff; break; - case 1: a += k[0]&0xff; break; - case 0: goto exit; - } - -#else /* make valgrind happy */ - + /* Read only bytes belonging to the key in the final block. */ k8 = (const uint8_t *)k; switch (size) { case 12: c += k[2]; b+=k[1]; a+=k[0]; break; @@ -515,8 +484,6 @@ void jlu32lpair(const void *key, size_t size, uint32_t *pc, uint32_t *pb) case 0: goto exit; } -#endif /* !valgrind */ - } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ const uint8_t *k8; diff --git a/popt/popt.c b/popt/popt.c index b86f7e34d..2de7c2d8f 100644 --- a/popt/popt.c +++ b/popt/popt.c @@ -235,6 +235,28 @@ void poptResetContext(poptContext con) return; } +static char *formatOptionName(const char *longName, char shortName, int oneDash) +{ + size_t prefix = longName && !oneDash ? 2 : 1; + size_t len = longName ? strlen(longName) : 1; + char *s; + + if (len >= SIZE_MAX - prefix) + return NULL; + s = malloc(prefix + len + 1); + if (s == NULL) + return NULL; + s[0] = '-'; + if (prefix == 2) + s[1] = '-'; + if (longName) + memcpy(s + prefix, longName, len); + else + s[prefix] = shortName; + s[prefix + len] = '\0'; + return s; +} + /* Only one of longName, shortName should be set, not both. */ static int handleExec(poptContext con, const char * longName, char shortName) @@ -274,19 +296,8 @@ static int handleExec(poptContext con, } i = con->finalArgvCount++; - if (con->finalArgv != NULL) /* XXX can't happen */ - { char *s = malloc((longName ? strlen(longName) : 0) + sizeof("--")); - if (s != NULL) { /* XXX can't happen */ - con->finalArgv[i] = s; - *s++ = '-'; - if (longName) - s = stpcpy( stpcpy(s, "-"), longName); - else - *s++ = shortName; - *s = '\0'; - } else - con->finalArgv[i] = NULL; - } + if (con->finalArgv != NULL) + con->finalArgv[i] = formatOptionName(longName, shortName, 0); return 1; } @@ -408,9 +419,9 @@ static int handleAlias(poptContext con, static const char * findProgramPath(const char * argv0) { - char *path = NULL, *se; - const char *s = NULL; + char *path = NULL, *s = NULL, *se; char *t = NULL; + size_t size; if (argv0 == NULL) return NULL; /* XXX can't happen */ @@ -423,25 +434,27 @@ const char * findProgramPath(const char * argv0) return NULL; /* The return buffer in t is big enough for any path. */ - if ((t = malloc(strlen(path) + strlen(argv0) + sizeof("/"))) != NULL) + size = strlen(path) + strlen(argv0) + sizeof("/"); + if ((t = malloc(size)) != NULL) for (s = path; s && *s; s = se) { + int len; /* Snip PATH element into [s,se). */ if ((se = strchr(s, ':'))) *se++ = '\0'; /* Append argv0 to PATH element. */ - (void) stpcpy(stpcpy(stpcpy(t, s), "/"), argv0); + len = snprintf(t, size, "%s/%s", s, argv0); /* If file is executable, bingo! */ - if (!access(t, X_OK)) + if (len >= 0 && (size_t)len < size && !access(t, X_OK)) break; } /* If no executable was found in PATH, return NULL. */ if (!(s && *s) && t != NULL) t = _free(t); - path = _free(path); + free(path); return t; } @@ -451,7 +464,6 @@ static int execCommand(poptContext con) poptItem item = con->doExec; poptArgv argv = NULL; int argc = 0; - int rc; int ec = POPT_ERROR_ERRNO; if (item == NULL) /*XXX can't happen*/ @@ -466,9 +478,13 @@ static int execCommand(poptContext con) if (argv == NULL) return POPT_ERROR_MALLOC; if (!strchr(item->argv[0], '/') && con->execPath != NULL) { - char *s = malloc(strlen(con->execPath) + strlen(item->argv[0]) + sizeof("/")); - if (s) - (void)stpcpy(stpcpy(stpcpy(s, con->execPath), "/"), item->argv[0]); + size_t size = strlen(con->execPath) + strlen(item->argv[0]) + sizeof("/"); + char *s = malloc(size); + if (s) { + int len = snprintf(s, size, "%s/%s", con->execPath, item->argv[0]); + if (len < 0 || (size_t)len >= size) + s = _free(s); + } argv[argc] = s; } else @@ -497,10 +513,9 @@ static int execCommand(poptContext con) argv[argc] = NULL; #if defined(hpux) || defined(__hpux) - rc = setresgid(getgid(), getgid(),-1); - if (rc) goto exit; - rc = setresuid(getuid(), getuid(),-1); - if (rc) goto exit; + if (setresgid(getgid(), getgid(), -1) != 0 + || setresuid(getuid(), getuid(), -1) != 0) + goto exit; #else /* * XXX " ... on BSD systems setuid() should be preferred over setreuid()" @@ -508,15 +523,11 @@ static int execCommand(poptContext con) * XXX from Norbert Warmuth */ #if defined(HAVE_SETUID) - rc = setgid(getgid()); - if (rc) goto exit; - rc = setuid(getuid()); - if (rc) goto exit; + if (setgid(getgid()) != 0 || setuid(getuid()) != 0) + goto exit; #elif defined (HAVE_SETREUID) - rc = setregid(getgid(), getgid()); - if (rc) goto exit; - rc = setreuid(getuid(), getuid()); - if (rc) goto exit; + if (setregid(getgid(), getgid()) != 0 || setreuid(getuid(), getuid()) != 0) + goto exit; #else /* refuse to exec if we cannot drop suid/sgid privileges */ if (getuid() != geteuid() || getgid() != getegid()) { @@ -536,7 +547,7 @@ if (_popt_debug) } #endif - rc = execvp(argv[0], (char *const *)argv); + execvp(argv[0], (char *const *)argv); /* only reached on execvp() failure */ con->execFail = xstrdup(argv[0]); @@ -672,14 +683,19 @@ expandNextArg(poptContext con, const char * s) } s += sizeof("#:+") - 1; - tn += strlen(a); - { size_t pos = (size_t) (te - t); + { size_t pos = (size_t) (te - t), len = strlen(a); + if (len > SIZE_MAX - tn) { + free(t); + return NULL; + } + tn += len; if ((t_tmp = realloc(t, tn)) == NULL) { /* XXX can't happen */ free(t); return NULL; } t = t_tmp; - te = stpcpy(t + pos, a); + memcpy(t + pos, a, len); + te = t + pos + len; } continue; break; @@ -891,7 +907,7 @@ int poptSaveBits(poptBits * bitsp, if (rc) break; } - tbuf = _free(tbuf); + free(tbuf); return rc; } @@ -929,6 +945,7 @@ static long long poptRandomValue(long long limit) return random() % limit + 1; #else /* XXX avoid adding POPT_ERROR_UNIMPLEMENTED to minimize i18n churn. */ + (void)limit; return POPT_ERROR_BADOPERATION; #endif } @@ -1439,21 +1456,8 @@ int poptGetNextOpt(poptContext con) } if (con->finalArgv != NULL) - { char *s = malloc((opt->longName ? strlen(opt->longName) : 0) + sizeof("--")); - if (s != NULL) { /* XXX can't happen */ - con->finalArgv[con->finalArgvCount++] = s; - *s++ = '-'; - if (opt->longName) { - if (!F_ISSET(opt, ONEDASH)) - *s++ = '-'; - s = stpcpy(s, opt->longName); - } else { - *s++ = opt->shortName; - *s = '\0'; - } - } else - con->finalArgv[con->finalArgvCount++] = NULL; - } + con->finalArgv[con->finalArgvCount++] = + formatOptionName(opt->longName, opt->shortName, F_ISSET(opt, ONEDASH)); if (opt->arg && poptArgType(opt) == POPT_ARG_NONE) ; diff --git a/popt/poptconfig.c b/popt/poptconfig.c index ae1add8ca..e27ff7c0f 100644 --- a/popt/poptconfig.c +++ b/popt/poptconfig.c @@ -139,7 +139,7 @@ int poptReadFile(const char * fn, char ** bp, size_t * nbp, int flags) if ((nb = lseek(fdno, 0, SEEK_END)) == (off_t)-1 || (uintmax_t)nb >= SIZE_MAX || lseek(fdno, 0, SEEK_SET) == (off_t)-1 - || (b = calloc(sizeof(*b), (size_t)nb + 1)) == NULL + || (b = calloc((size_t)nb + 1, sizeof(*b))) == NULL || read(fdno, (char *)b, (size_t)nb) != (ssize_t)nb) { int oerrno = errno; @@ -220,7 +220,8 @@ static int configAppMatch(poptContext con, const char * s) return rc; } -static int poptConfigLine(poptContext con, char * line) +/* Individual malformed or unsupported config entries are ignored. */ +static void poptConfigLine(poptContext con, char * line) { char *b = NULL; size_t nb = 0; @@ -230,8 +231,7 @@ static int poptConfigLine(poptContext con, char * line) const char * opt; struct poptItem_s item_buf; poptItem item = &item_buf; - int i, j; - int rc = POPT_ERROR_BADCONFIG; + int i, j, is_exec; if (con->appName == NULL) goto exit; @@ -251,6 +251,12 @@ static int poptConfigLine(poptContext con, char * line) entryType = se; while (*se != '\0' && !_isspaceptr(se)) se++; if (*se != '\0') *se++ = '\0'; + if (!strcmp(entryType, "alias")) + is_exec = 0; + else if (!strcmp(entryType, "exec")) + is_exec = 1; + else + goto exit; while (*se != '\0' && _isspaceptr(se)) se++; if (*se == '\0') goto exit; @@ -270,7 +276,7 @@ static int poptConfigLine(poptContext con, char * line) const char * fn = opt; /* XXX handle globs and directories in fn? */ - if ((rc = poptReadFile(fn, &b, &nb, POPT_READFILE_TRIMNEWLINES)) != 0) + if (poptReadFile(fn, &b, &nb, POPT_READFILE_TRIMNEWLINES) != 0) goto exit; if (b == NULL || nb == 0) goto exit; @@ -278,11 +284,15 @@ static int poptConfigLine(poptContext con, char * line) /* Append remaining text to the interpolated file option text. */ if (*se != '\0') { size_t nse = strlen(se) + 1; - char *resized = realloc(b, nb + nse); + char *resized; + if (nse > SIZE_MAX - nb) + goto exit; + resized = realloc(b, nb + nse); if (resized == NULL) goto exit; b = resized; - (void) stpcpy( stpcpy(&b[nb-1], " "), se); + b[nb-1] = ' '; + memcpy(b + nb, se, nse); nb += nse; } se = b; @@ -331,15 +341,10 @@ static int poptConfigLine(poptContext con, char * line) item->argc = j; } - if (!strcmp(entryType, "alias")) - rc = poptAddItem(con, item, 0); - else if (!strcmp(entryType, "exec")) - rc = poptAddItem(con, item, 1); + if (poptAddItem(con, item, is_exec) != 0) + free(item->argv); exit: - rc = 0; /* XXX for now, always return success */ - if (b) - free(b); - return rc; + free(b); } int poptReadConfigFile(poptContext con, const char * fn) @@ -370,8 +375,7 @@ int poptReadConfigFile(poptContext con, const char * fn) te = t; while (*te && _isspaceptr(te)) te++; if (*te && *te != '#') - if ((rc = poptConfigLine(con, te)) != 0) - goto exit; + poptConfigLine(con, te); break; case '\\': *te = *se++; @@ -398,7 +402,7 @@ int poptReadConfigFile(poptContext con, const char * fn) int poptReadConfigFiles(poptContext con, const char * paths) { char * buf = (paths ? xstrdup(paths) : NULL); - const char * p; + char * p; char * pe; int rc = 0; /* assume success */ @@ -406,30 +410,28 @@ int poptReadConfigFiles(poptContext con, const char * paths) const char ** av = NULL; int ac = 0; int i; - int xx; /* locate start of next path element */ pe = strchr(p, ':'); if (pe != NULL && *pe == ':') *pe++ = '\0'; else - pe = (char *) (p + strlen(p)); + pe = p + strlen(p); - xx = poptGlob(con, p, &ac, &av); + if (poptGlob(con, p, &ac, &av) != 0 || av == NULL) + continue; /* work-off each resulting file from the path element */ for (i = 0; i < ac; i++) { const char * fn = av[i]; - if (!poptSaneFile(fn)) - continue; - xx = poptReadConfigFile(con, fn); - if (xx && rc == 0) - rc = xx; - free((void *)av[i]); - av[i] = NULL; + if (poptSaneFile(fn)) { + int result = poptReadConfigFile(con, fn); + if (result && rc == 0) + rc = result; + } + free((void *)fn); } free(av); - av = NULL; } if (buf) @@ -441,7 +443,6 @@ int poptReadConfigFiles(poptContext con, const char * paths) int poptReadDefaultConfig(poptContext con, UNUSED(int useEnv)) { const char * home; - struct stat sb; int rc = 0; /* assume success */ if (con->appName == NULL) goto exit; @@ -450,31 +451,32 @@ int poptReadDefaultConfig(poptContext con, UNUSED(int useEnv)) if (rc) goto exit; #if defined(HAVE_GLOB_H) + struct stat sb; + if (!stat(POPT_SYSCONFDIR "/popt.d", &sb) && S_ISDIR(sb.st_mode)) { const char ** av = NULL; int ac = 0; int i; if ((rc = poptGlob(con, POPT_SYSCONFDIR "/popt.d/*", &ac, &av)) == 0) { - for (i = 0; rc == 0 && i < ac; i++) { + for (i = 0; av && i < ac; i++) { const char * fn = av[i]; - if (!poptSaneFile(fn)) - continue; - rc = poptReadConfigFile(con, fn); - free((void *)av[i]); - av[i] = NULL; + if (rc == 0 && poptSaneFile(fn)) + rc = poptReadConfigFile(con, fn); + free((void *)fn); } free(av); - av = NULL; } } if (rc) goto exit; #endif if ((home = getenv("HOME"))) { - char * fn = malloc(strlen(home) + 20); + size_t len = strlen(home); + char * fn = malloc(len + sizeof("/.popt")); if (fn != NULL) { - (void) stpcpy(stpcpy(fn, home), "/.popt"); + memcpy(fn, home, len); + memcpy(fn + len, "/.popt", sizeof("/.popt")); rc = poptReadConfigFile(con, fn); free(fn); } else diff --git a/popt/popthelp.c b/popt/popthelp.c index 4e4268d3d..827ca1eaa 100644 --- a/popt/popthelp.c +++ b/popt/popthelp.c @@ -9,6 +9,7 @@ ftp://ftp.rpm.org/pub/rpm/dist. */ #include "system.h" +#include #define POPT_USE_TIOCGWINSZ #ifdef POPT_USE_TIOCGWINSZ @@ -93,12 +94,12 @@ typedef struct columns_s { * @param fp FILE * @return no. of columns */ -static size_t maxColumnWidth(FILE *fp) +static size_t maxColumnWidth(UNUSED(FILE *fp)) { size_t maxcols = _POPTHELP_MAXLINE; #if defined(TIOCGWINSZ) struct winsize ws; - int fdno = fileno(fp ? fp : stdout); + int fdno = fileno(fp); memset(&ws, 0, sizeof(ws)); if (fdno >= 0 && !ioctl(fdno, (unsigned long)TIOCGWINSZ, &ws)) { @@ -157,6 +158,7 @@ getArgDescrip(const struct poptOption * opt, /* FIX: i18n macros disabled with lclint */ const char * translation_domain) { + (void)translation_domain; if (!poptArgType(opt)) return NULL; if (poptArgType(opt) == POPT_ARG_MAINCALL) @@ -206,73 +208,87 @@ getArgDescrip(const struct poptOption * opt, static char * singleOptionDefaultValue(size_t lineLength, const struct poptOption * opt, - /* FIX: i18n macros disabled with lclint */ const char * translation_domain) { const char * defstr = D_(translation_domain, "default"); - char * le = malloc(4*lineLength + 1); - char * l = le; + char *l, *le; + size_t capacity, room; + int n; - if (le == NULL) return NULL; /* XXX can't happen */ - *le = '\0'; - *le++ = '('; - le = stpcpy(le, defstr); - *le++ = ':'; - *le++ = ' '; - if (opt->arg) { /* XXX programmer error */ - poptArg arg = { .ptr = opt->arg }; - switch (poptArgType(opt)) { - case POPT_ARG_VAL: - case POPT_ARG_INT: - le += sprintf(le, "%d", arg.intp[0]); - break; - case POPT_ARG_SHORT: - le += sprintf(le, "%hd", arg.shortp[0]); - break; - case POPT_ARG_LONG: - le += sprintf(le, "%ld", arg.longp[0]); - break; - case POPT_ARG_LONGLONG: - le += sprintf(le, "%lld", arg.longlongp[0]); - break; - case POPT_ARG_FLOAT: - { double aDouble = (double) arg.floatp[0]; - le += sprintf(le, "%g", aDouble); - } break; - case POPT_ARG_DOUBLE: - le += sprintf(le, "%g", arg.doublep[0]); - break; - case POPT_ARG_MAINCALL: - le += sprintf(le, "%p", opt->arg); - break; - case POPT_ARG_ARGV: - le += sprintf(le, "%p", opt->arg); - break; - case POPT_ARG_STRING: - { const char * s = arg.argv[0]; - if (s == NULL) - le = stpcpy(le, "null"); - else { - size_t limit = 4*lineLength - (le - l) - sizeof("\"\")"); - size_t slen; - *le++ = '"'; - strncpy(le, s, limit); le[limit] = '\0'; le += (slen = strlen(le)); - if (slen == limit && s[limit]) - le[-1] = le[-2] = le[-3] = '.'; - *le++ = '"'; - } - } break; - case POPT_ARG_NONE: - default: - l = _free(l); + (void)translation_domain; + if (lineLength > (INT_MAX - 1) / 4) + return NULL; + capacity = 4 * lineLength + 1; + l = malloc(capacity); + if (l == NULL) return NULL; - break; + n = snprintf(l, capacity, "(%s: ", defstr); + if (n < 0 || (size_t)n >= capacity - 1) + goto fail; + le = l + n; + room = capacity - (size_t)n - 1; /* Reserve room for the closing ')'. */ + n = 0; + + if (opt->arg) { + poptArg arg = { .ptr = opt->arg }; + switch (poptArgType(opt)) { + case POPT_ARG_VAL: + case POPT_ARG_INT: + n = snprintf(le, room, "%d", arg.intp[0]); + break; + case POPT_ARG_SHORT: + n = snprintf(le, room, "%hd", arg.shortp[0]); + break; + case POPT_ARG_LONG: + n = snprintf(le, room, "%ld", arg.longp[0]); + break; + case POPT_ARG_LONGLONG: + n = snprintf(le, room, "%lld", arg.longlongp[0]); + break; + case POPT_ARG_FLOAT: + n = snprintf(le, room, "%g", (double)arg.floatp[0]); + break; + case POPT_ARG_DOUBLE: + n = snprintf(le, room, "%g", arg.doublep[0]); + break; + case POPT_ARG_MAINCALL: + case POPT_ARG_ARGV: + n = snprintf(le, room, "%p", opt->arg); + break; + case POPT_ARG_STRING: { + const char *s = arg.argv[0]; + if (s == NULL) + n = snprintf(le, room, "%s", "null"); + else { + size_t limit, length, shown; + if (room < 4) + goto fail; + limit = room - 4; + length = strlen(s); + shown = length < limit ? length : limit; + le[0] = '"'; + memcpy(le + 1, s, shown); + if (shown < length && shown >= 3) + memcpy(le + 1 + shown - 3, "...", 3); + le[shown + 1] = '"'; + n = (int)shown + 2; + } + break; + } + default: + goto fail; + } } - } + if (n < 0 || (size_t)n >= room) + goto fail; + le += n; *le++ = ')'; *le = '\0'; - return l; + +fail: + free(l); + return NULL; } /** @@ -297,12 +313,14 @@ static void singleOptionHelp(FILE * fp, columns_t columns, char * defs = NULL; char * left; size_t nb = maxLeftCol + 1; + size_t arglen = argDescrip ? strlen(argDescrip) : 0; + int len; int displaypad = 0; /* Make sure there's more than enough room in target buffer. */ if (opt->longName) nb += strlen(opt->longName); if (F_ISSET(opt, TOGGLE)) nb += sizeof("[no]") - 1; - if (argDescrip) nb += strlen(argDescrip); + nb += arglen; left = malloc(nb); if (left == NULL) return; /* XXX can't happen */ @@ -314,14 +332,10 @@ static void singleOptionHelp(FILE * fp, columns_t columns, goto out; if (prtshort && prtlong) { const char *dash = F_ISSET(opt, ONEDASH) ? "-" : "--"; - left[0] = '-'; - left[1] = opt->shortName; - (void) stpcpy(stpcpy(stpcpy(left+2, ", "), dash), opt->longName); + len = snprintf(left, nb, "-%c, %s%s", opt->shortName, dash, opt->longName); } else if (prtshort) { - left[0] = '-'; - left[1] = opt->shortName; - left[2] = '\0'; - } else if (prtlong) { + len = snprintf(left, nb, "-%c", opt->shortName); + } else { /* XXX --long always padded for alignment with/without "-X, ". */ const char *dash = poptArgType(opt) == POPT_ARG_MAINCALL ? "" : (F_ISSET(opt, ONEDASH) ? "-" : "--"); @@ -336,13 +350,19 @@ static void singleOptionHelp(FILE * fp, columns_t columns, } } else toggle = ""; - (void) stpcpy(stpcpy(stpcpy(stpcpy(left, " "), dash), toggle), longName); + len = snprintf(left, nb, " %s%s%s", dash, toggle, longName); } #undef prtlong + if (len < 0 || (size_t)len >= nb) + goto out; if (argDescrip) { - char * le = left + strlen(left); + char * le = left + len; + size_t room = nb - (size_t)len; + size_t extra = F_ISSET(opt, OPTIONAL) ? 3 : 1; + if (room <= extra || arglen >= room - extra) + goto out; if (F_ISSET(opt, OPTIONAL)) *le++ = '['; @@ -350,15 +370,17 @@ static void singleOptionHelp(FILE * fp, columns_t columns, if (F_ISSET(opt, SHOW_DEFAULT)) { defs = singleOptionDefaultValue(lineLength, opt, translation_domain); if (defs) { - char * t = malloc((help ? strlen(help) : 0) + - strlen(defs) + sizeof(" ")); + size_t helplen = help ? strlen(help) : 0; + size_t deflen = strlen(defs); + char *t = helplen <= SIZE_MAX - deflen - 2 + ? malloc(helplen + deflen + 2) : NULL; if (t) { - char * te = t; - if (help) - te = stpcpy(te, help); - *te++ = ' '; - strcpy(te, defs); - defs = _free(defs); + if (helplen) + memcpy(t, help, helplen); + t[helplen] = ' '; + memcpy(t + helplen + 1, defs, deflen); + t[helplen + deflen + 1] = '\0'; + free(defs); defs = t; } } @@ -406,7 +428,8 @@ static void singleOptionHelp(FILE * fp, columns_t columns, case POPT_ARG_DOUBLE: case POPT_ARG_STRING: *le++ = (opt->longName != NULL ? '=' : ' '); - le = stpcpy(le, argDescrip); + memcpy(le, argDescrip, arglen); + le += arglen; break; default: break; @@ -419,7 +442,9 @@ static void singleOptionHelp(FILE * fp, columns_t columns, *le++ = ((poptArgType(opt) == POPT_ARG_MAINCALL) ? ' ' : (poptArgType(opt) == POPT_ARG_ARGV) ? ' ' : opt->longName == NULL ? ' ' : '='); - le = stpcpy(leo = le, argDescrip); + leo = le; + memcpy(le, argDescrip, arglen); + le += arglen; /* Adjust for (possible) wide characters. */ displaypad = (int)((le - leo) - stringDisplayWidth(argDescrip)); @@ -443,7 +468,6 @@ static void singleOptionHelp(FILE * fp, columns_t columns, helpLength = strlen(help); while (helpLength > lineLength) { const char * ch; - char format[16]; ch = help + lineLength - 1; while (ch > help && !_isspaceptr(ch)) @@ -460,8 +484,7 @@ static void singleOptionHelp(FILE * fp, columns_t columns, { char * fmthelp = xstrdup(help); if (fmthelp) { fmthelp[ch - help] = '\0'; - sprintf(format, "%%s\n%%%ds", (int) indentLength); - POPT_fprintf(fp, format, fmthelp, " "); + POPT_fprintf(fp, "%s\n%*s", fmthelp, (int)indentLength, " "); free(fmthelp); } } @@ -473,11 +496,10 @@ static void singleOptionHelp(FILE * fp, columns_t columns, } if (helpLength) fprintf(fp, "%s\n", help); - help = NULL; out: - defs = _free(defs); - left = _free(left); + free(defs); + free(left); } /** @@ -632,7 +654,11 @@ static size_t showHelpIntro(poptContext con, FILE * fp) void poptPrintHelp(poptContext con, FILE * fp, UNUSED(int flags)) { - columns_t columns = calloc((size_t)1, sizeof(*columns)); + columns_t columns; + + if (fp == NULL) + return; + columns = calloc((size_t)1, sizeof(*columns)); (void) showHelpIntro(con, fp); if (con->otherHelp) @@ -848,10 +874,14 @@ static size_t showShortOptions(const struct poptOption * opt, FILE * fp, void poptPrintUsage(poptContext con, FILE * fp, UNUSED(int flags)) { - columns_t columns = calloc((size_t)1, sizeof(*columns)); + columns_t columns; struct poptDone_s done_buf; poptDone done = &done_buf; + if (fp == NULL) + return; + columns = calloc((size_t)1, sizeof(*columns)); + memset(done, 0, sizeof(*done)); done->nopts = 0; done->maxopts = 64; diff --git a/popt/poptint.c b/popt/poptint.c index 53509459d..db85c15a1 100644 --- a/popt/poptint.c +++ b/popt/poptint.c @@ -150,7 +150,7 @@ POPT_fprintf (FILE * stream, const char * format, ...) #if defined(HAVE_VASPRINTF) va_start(ap, format); - if ((rc = vasprintf(&b, format, ap)) < 0) + if (vasprintf(&b, format, ap) < 0) b = NULL; va_end(ap); #else diff --git a/popt/poptint.h b/popt/poptint.h index 001c5c35d..b14c19d0c 100644 --- a/popt/poptint.h +++ b/popt/poptint.h @@ -28,9 +28,7 @@ typedef unsigned int __pbm_bits; #define __PBM_NBITS (8 * sizeof (__pbm_bits)) #define __PBM_IX(d) ((d) / __PBM_NBITS) #define __PBM_MASK(d) ((__pbm_bits) 1 << (((unsigned)(d)) % __PBM_NBITS)) -typedef struct { - __pbm_bits bits[1]; -} pbm_set; +typedef struct poptBits_s pbm_set; #define __PBM_BITS(set) ((set)->bits) #define PBM_ALLOC(d) calloc(__PBM_IX (d) + 1, sizeof(pbm_set)) diff --git a/popt/poptparse.c b/popt/poptparse.c index 5afc6c551..4a70078e6 100644 --- a/popt/poptparse.c +++ b/popt/poptparse.c @@ -13,30 +13,38 @@ int poptDupArgv(int argc, const char **argv, int * argcPtr, const char *** argvPtr) { - size_t nb = (argc + 1) * sizeof(*argv); + size_t nb, argv_bytes; const char ** argv2; char * dst; int i; if (argc <= 0 || argv == NULL) /* XXX can't happen */ return POPT_ERROR_NOARG; + if ((size_t)argc >= SIZE_MAX / sizeof(*argv)) + return POPT_ERROR_OVERFLOW; + nb = argv_bytes = ((size_t)argc + 1) * sizeof(*argv); for (i = 0; i < argc; i++) { + size_t len; + if (argv[i] == NULL) return POPT_ERROR_NOARG; - nb += strlen(argv[i]) + 1; + len = strlen(argv[i]); + if (len >= SIZE_MAX - nb) + return POPT_ERROR_OVERFLOW; + nb += len + 1; } dst = malloc(nb); if (dst == NULL) /* XXX can't happen */ return POPT_ERROR_MALLOC; argv2 = (void *) dst; - dst += (argc + 1) * sizeof(*argv); - *dst = '\0'; + dst += argv_bytes; for (i = 0; i < argc; i++) { + size_t len = strlen(argv[i]) + 1; argv2[i] = dst; - dst = stpcpy(dst, argv[i]); - dst++; /* trailing NUL */ + memcpy(dst, argv[i], len); + dst += len; } argv2[argc] = NULL; @@ -135,105 +143,87 @@ int poptConfigFileToString(FILE *fp, char ** argstrp, { char line[999]; char * argstr; - char * argstr_tmp; - char * p; - char * q; - char * x; - size_t t; - size_t argvlen = 0; - size_t maxlinelen = sizeof(line); - size_t linelen; - size_t maxargvlen = (size_t)480; + size_t used = 0; + size_t maxargvlen = 480; *argstrp = NULL; - - /* | this_is = our_line - * p q x - */ - if (fp == NULL) return POPT_ERROR_NULLARG; argstr = calloc(maxargvlen, sizeof(*argstr)); if (argstr == NULL) return POPT_ERROR_MALLOC; - while (fgets(line, (int)maxlinelen, fp) != NULL) { - p = line; + while (fgets(line, (int)sizeof(line), fp) != NULL) { + char *p = line, *q, *dst; + const char *value = NULL; + size_t linelen, namelen, valuelen, added, needed; - /* loop until first non-space char or EOL */ - while( *p != '\0' && _isspaceptr(p) ) + while (*p != '\0' && _isspaceptr(p)) p++; linelen = strlen(p); - if (linelen >= maxlinelen-1) { + if (linelen >= sizeof(line)-1) { free(argstr); - return POPT_ERROR_OVERFLOW; /* XXX line too long */ + return POPT_ERROR_OVERFLOW; } + if (*p == '\0' || *p == '\n' || *p == '#') + continue; - if (*p == '\0' || *p == '\n') continue; /* line is empty */ - if (*p == '#') continue; /* comment line */ - - q = p; - - while (*q != '\0' && (!_isspaceptr(q)) && *q != '=') - q++; - + for (q = p; *q && !_isspaceptr(q) && *q != '='; q++) {} if (_isspaceptr(q)) { - /* a space after the name, find next non space */ - *q++='\0'; - while( *q != '\0' && _isspaceptr(q) ) q++; + *q++ = '\0'; + while (*q && _isspaceptr(q)) + q++; } - if (*q == '\0') { - /* single command line option (ie, no name=val, just name) */ - q[-1] = '\0'; /* kill off newline from fgets() call */ - argvlen += (t = (size_t)(q - p)) + (sizeof(" --")-1); - if (argvlen >= maxargvlen) { - maxargvlen = (t > maxargvlen) ? t*2 : maxargvlen*2; - argstr_tmp = realloc(argstr, maxargvlen); - if (argstr_tmp == NULL) { - free(argstr); - return POPT_ERROR_MALLOC; - } - argstr = argstr_tmp; - } - strcat(argstr, " --"); - strcat(argstr, p); - continue; + if (*q) { + char *end = p + linelen; + if (*q != '=') + continue; + *q++ = '\0'; + while (*q && _isspaceptr(q)) + q++; + if (!*q) + continue; + while (_isspaceptr(--end)) + *end = '\0'; + value = q; } - if (*q != '=') - continue; /* XXX for now, silently ignore bogus line */ - - /* *q is an equal sign. */ - *q++ = '\0'; - - /* find next non-space letter of value */ - while (*q != '\0' && _isspaceptr(q)) - q++; - if (*q == '\0') - continue; /* XXX silently ignore missing value */ - - /* now, loop and strip all ending whitespace */ - x = p + linelen; - while (_isspaceptr(--x)) - *x = '\0'; /* null out last char if space (including fgets() NL) */ - - /* rest of line accept */ - t = (size_t)(x - p); - argvlen += t + (sizeof("' --='")-1); - if (argvlen >= maxargvlen) { - maxargvlen = (t > maxargvlen) ? t*2 : maxargvlen*2; - argstr_tmp = realloc(argstr, maxargvlen); - if (argstr_tmp == NULL) { + + namelen = strlen(p); + valuelen = value ? strlen(value) : 0; + added = sizeof(" --") - 1 + namelen + (value ? 3 + valuelen : 0); + if (added >= SIZE_MAX - used) { + free(argstr); + return POPT_ERROR_OVERFLOW; + } + needed = used + added + 1; + if (needed > maxargvlen) { + char *resized; + maxargvlen = maxargvlen <= SIZE_MAX / 2 ? maxargvlen * 2 : needed; + if (maxargvlen < needed) + maxargvlen = needed; + resized = realloc(argstr, maxargvlen); + if (resized == NULL) { free(argstr); return POPT_ERROR_MALLOC; } - argstr = argstr_tmp; + argstr = resized; + } + + dst = argstr + used; + memcpy(dst, " --", sizeof(" --") - 1); + dst += sizeof(" --") - 1; + memcpy(dst, p, namelen); + dst += namelen; + if (value) { + *dst++ = '='; + *dst++ = '"'; + memcpy(dst, value, valuelen); + dst += valuelen; + *dst++ = '"'; } - strcat(argstr, " --"); - strcat(argstr, p); - strcat(argstr, "=\""); - strcat(argstr, q); - strcat(argstr, "\""); + *dst = '\0'; + used += added; } *argstrp = argstr; diff --git a/popt/system.h b/popt/system.h index f731d206d..c383a01f9 100644 --- a/popt/system.h +++ b/popt/system.h @@ -15,6 +15,7 @@ #include #endif +#include #include #include #include @@ -46,7 +47,7 @@ static inline char * stpcpy (char *dest, const char * src) { #define xmalloc(_size) (malloc(_size) ? : vmefail()) #define xcalloc(_nmemb, _size) (calloc((_nmemb), (_size)) ? : vmefail()) #define xrealloc(_ptr, _size) (realloc((_ptr), (_size)) ? : vmefail()) -#define xstrdup(_str) (strcpy((malloc(strlen(_str)+1) ? : vmefail()), (_str))) +#define xstrdup(_str) (strdup(_str) ? : vmefail()) #else #define xmalloc(_size) malloc(_size) #define xcalloc(_nmemb, _size) calloc((_nmemb), (_size)) diff --git a/rounding.c b/rounding.c index 1bc353a85..6d25b658a 100644 --- a/rounding.c +++ b/rounding.c @@ -30,9 +30,5 @@ struct test { #define ACTUAL_SIZE SIZEOF(struct test) #define EXPECTED_SIZE (SIZEOF(union file_extras) * ARRAY_LEN + SIZEOF(int64)) - int main(UNUSED(int argc), UNUSED(char *argv[])) -{ - static int test_array[1 - 2 * (ACTUAL_SIZE != EXPECTED_SIZE)]; - test_array[0] = 0; - return 0; -} +/* Reject a candidate layout at compile time without allocating storage. */ +typedef char check_extra_rounding[ACTUAL_SIZE == EXPECTED_SIZE ? 1 : -1]; diff --git a/rsync.c b/rsync.c index bd49fe834..c90ef379d 100644 --- a/rsync.c +++ b/rsync.c @@ -507,7 +507,7 @@ static int same_mtime(struct file_struct *file, STRUCT_STAT *st, int extra_accur } int set_file_attrs(const char *fname, struct file_struct *file, stat_x *sxp, - const char *fnamecmp, int flags) + UNUSED(const char *fnamecmp), int flags) { int updated = 0; int attr_error = 0; diff --git a/rsync.h b/rsync.h index e137f175d..17862374a 100644 --- a/rsync.h +++ b/rsync.h @@ -1281,6 +1281,11 @@ struct name_num_obj { struct name_num_item *list; }; +struct conf_token_state { + char *next; + BOOL commas_only; +}; + #ifdef EXTERNAL_ZLIB #define read_buf read_buf_ #endif diff --git a/sender.c b/sender.c index 5691ffcdf..c55e1c2e8 100644 --- a/sender.c +++ b/sender.c @@ -481,7 +481,7 @@ void successful_send(int ndx) } static void write_ndx_and_attrs(int f_out, int ndx, int iflags, - const char *fname, struct file_struct *file, + UNUSED(const char *fname), UNUSED(struct file_struct *file), uchar fnamecmp_type, char *buf, int len) { write_ndx(f_out, ndx); diff --git a/socket.c b/socket.c index 77b911a7b..0e9014a34 100644 --- a/socket.c +++ b/socket.c @@ -887,7 +887,7 @@ static BOOL parse_socket_integer(const char *text, int *value) /* Set user socket options. */ void set_socket_options(int fd, char *options) { - char *tok; + char *tok, *save = NULL; if (!options || !*options) return; @@ -896,7 +896,7 @@ void set_socket_options(int fd, char *options) if (!options) out_of_memory("set_socket_options"); - for (tok = strtok(options, " \t,"); tok; tok = strtok(NULL, " \t,")) { + for (tok = strtok_r(options, " \t,", &save); tok; tok = strtok_r(NULL, " \t,", &save)) { const struct socket_option *option; int number = 1; char *value = strchr(tok, '='); diff --git a/syscall.c b/syscall.c index 42e0ea7b3..77abb3195 100644 --- a/syscall.c +++ b/syscall.c @@ -172,6 +172,7 @@ int filesfrom_owner_walk_active(void) && (!copy_links || filesfrom_owner_walk_override); } +#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY /* The root an operator/peer-supplied path must stay under, or NULL when nothing * is confined. A daemon has the served module; a server launched by a wrapper * with its own restricted directory (rrsync) gets one from --confine-root. @@ -232,6 +233,7 @@ static const char *fd_pin_tail(const char *p) s += 3; return (*s == '\0' || *s == '/') ? s : NULL; } +#endif /* Ensure link target is prefixed when munge_symlinks is enabled. * Returns the pointer to the target to use (either lnk itself or buf). @@ -255,6 +257,7 @@ static const char *munge_symlink_target(const char *lnk, char *buf, size_t bufle return lnk; } +#if defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY /* An EXACT pin entry, such as "/proc/self/fd/7" or "/dev/fd/7", whose target is * what confinement must judge. rrsync also writes a pinned parent as * ".../fd/7/", but the walk resolves the magic link itself and checks the @@ -386,6 +389,7 @@ static int abspath_step(char *abspath, size_t cap, const char *comp, size_t comp memcpy(abspath + off, comp, comp_len + 1); return 0; } +#endif /* Return the length of a //server/share root, or 0 when path is not a * complete UNC path. Kept platform-independent so the parser is testable on @@ -2154,10 +2158,11 @@ static int chmod_inode(int fd, mode_t mode, enum chmod_policy policy) * dir that becomes a FIFO is still opened. O_NOFOLLOW rejects symlinks, not * type changes. Constraining the open to the observed type would close that; * it is not done here. */ +#ifdef AT_FDCWD static int do_fchmodat_nofollow(int dfd, const char *name, mode_t mode, enum chmod_policy policy) { (void)policy; -#if defined AT_FDCWD && defined AT_SYMLINK_NOFOLLOW +#ifdef AT_SYMLINK_NOFOLLOW mode &= CHMOD_BITS; # ifdef O_NOFOLLOW { @@ -2267,6 +2272,7 @@ static int do_fchmodat_nofollow(int dfd, const char *name, mode_t mode, enum chm return 1; #endif } +#endif /* Symlink-race-safe variant of do_chmod() for receiver-side use. @@ -2688,6 +2694,8 @@ int do_mkstemp(char *template, mode_t perms) #endif return fd; } +#elif defined AT_FDCWD && defined O_NOFOLLOW + return do_mkstemp_atfd(AT_FDCWD, template, perms); #else if (!mktemp(template)) return -1; @@ -3172,6 +3180,8 @@ OFF_T do_fallocate(int fd, OFF_T offset, OFF_T length) * changed to be at pos + len. */ int do_punch_hole(int fd, OFF_T pos, OFF_T len) { + static const char zeros[4096]; + #ifdef HAVE_FALLOCATE # ifdef HAVE_FALLOC_FL_PUNCH_HOLE if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, pos, len) == 0) { @@ -3187,22 +3197,19 @@ int do_punch_hole(int fd, OFF_T pos, OFF_T len) return 0; } # endif -#else - (void)pos; #endif - { - char zeros[4096]; - memset(zeros, 0, sizeof zeros); - while (len > 0) { - int chunk = len > (int)sizeof zeros ? (int)sizeof zeros : len; - int wrote = write(fd, zeros, chunk); - if (wrote <= 0) { - if (wrote < 0 && errno == EINTR) - continue; - return -1; - } - len -= wrote; + (void)pos; + while (len > 0) { + size_t chunk = len > (OFF_T)sizeof zeros ? sizeof zeros : (size_t)len; + ssize_t wrote = write(fd, zeros, chunk); + if (wrote <= 0) { + if (wrote < 0 && errno == EINTR) + continue; + if (wrote == 0) + errno = EIO; + return -1; } + len -= wrote; } return 0; } @@ -3923,9 +3930,7 @@ int secure_relative_dirfd_at_beneath(int anchor_fd, const char *relpath) } #if defined O_NOFOLLOW && defined AT_FDCWD -/* Fill buf with len random bytes. Prefer getentropy() to avoid opening - * /dev/urandom per file. Fall back to rand() if neither source is available - * (e.g. inside a chroot or container without /dev populated). */ +/* Prefer getentropy() to avoid opening /dev/urandom for each file. */ static void rand_bytes(unsigned char *buf, size_t len) { int fd; @@ -3942,15 +3947,20 @@ static void rand_bytes(unsigned char *buf, size_t len) return; } } +#ifdef __OpenBSD__ + arc4random_buf(buf, len); +#else + /* Retain the legacy chroot fallback on systems without an available source. */ for (size_t i = 0; i < len; i++) { buf[i] = (unsigned char)rand(); } +#endif } #endif -/* Create a unique temp file directly in directory `dfd` for the held-dirfd - * traversal: `filename` is the basename ending in "XXXXXX", rewritten in place - * to the chosen name. O_EXCL|O_NOFOLLOW so a planted name can't be followed or +/* Create a unique temp file. The template is a leaf for a held directory or a + * pathname with AT_FDCWD. Its trailing "XXXXXX" is replaced in place. + * O_EXCL|O_NOFOLLOW so a planted name can't be followed or * clobbered. Does NOT close dfd (the caller owns it). Returns the fd, or -1. * This is the create loop shared with secure_mkstemp(). */ int do_mkstemp_atfd(int dfd, char *filename, mode_t perms) @@ -4017,6 +4027,7 @@ int secure_mkstemp(char *template, mode_t perms, int operator_path) { #if !defined(O_NOFOLLOW) || !defined(O_DIRECTORY) || !defined(AT_FDCWD) /* Fall back to regular mkstemp on old systems */ + (void)operator_path; return do_mkstemp(template, perms); #else char *lastslash; diff --git a/t_popt_hash.c b/t_popt_hash.c new file mode 100644 index 000000000..269909a06 --- /dev/null +++ b/t_popt_hash.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +#define _JLU3_jlu32lpair 1 +#define jlu32lpair popt_hash_test +#include "popt/lookup3.c" + +static const struct { + size_t length; + uint32_t first, second; +} cases[] = { + { 0, 0xdeadbeefU, 0xdeadbeefU }, + { 1, 0x1d7d1c42U, 0x8e52e415U }, + { 3, 0xdd43c912U, 0xe2fb34d6U }, + { 5, 0x43fcbca5U, 0x5fee27e3U }, + { 7, 0xf99473baU, 0x34e11d9bU }, + { 9, 0x61d75ea9U, 0x345e1c66U }, + { 11, 0x08e2938fU, 0x5300c7b5U }, + { 12, 0x6ea98463U, 0x4ac33e45U }, + { 13, 0xa6df8451U, 0x63541563U }, + { 64, 0x07683424U, 0xc8f9f989U }, +}; + +int main(int argc, char **argv) +{ + uint8_t pattern[64]; + size_t checked = 0; + + (void)argc; + (void)argv; + for (size_t i = 0; i < sizeof pattern; i++) + pattern[i] = (uint8_t)(i * 73 + 17); + for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) { + for (size_t offset = 0; offset < 4; offset++) { + size_t bytes = cases[i].length + offset; + uint8_t *storage = malloc(bytes ? bytes : 1); + uint32_t first = 0, second = 0; + + if (!storage) + return 2; + memcpy(storage + offset, pattern, cases[i].length); + popt_hash_test(storage + offset, cases[i].length, &first, &second); + free(storage); + if (first != cases[i].first || second != cases[i].second) { + fprintf(stderr, "popt hash mismatch at length %zu, offset %zu\n", + cases[i].length, offset); + return 1; + } + checked++; + } + } + printf("popt hash: %zu lengths and alignments passed\n", checked); + return 0; +} diff --git a/t_secure_relpath.c b/t_secure_relpath.c index 0bbe419eb..9a371d9af 100644 --- a/t_secure_relpath.c +++ b/t_secure_relpath.c @@ -216,8 +216,10 @@ int main(int argc, char **argv) check_unc_root("//server//path", 0); check_unc_root(NULL, 0); - mkdir("subdir", 0755); - symlink("subdir", "alias"); + if (mkdir("subdir", 0755) < 0 || symlink("subdir", "alias") < 0) { + perror("create subdir and alias"); + return 2; + } /* Each of these relpaths must be rejected with EINVAL at the * secure_relative_open() front door. ".." is the actual one-level diff --git a/usage.c b/usage.c index 3c5ca073f..237db4615 100644 --- a/usage.c +++ b/usage.c @@ -251,7 +251,7 @@ static void print_info_flags(enum logcode f) static void output_nno_list(enum logcode f, const char *name, struct name_num_obj *nno) { char namebuf[64], tmpbuf[256]; - char *tok, *next_tok; + char *tok, *next_tok, *save = NULL; static const char * const comma = ","; char *cp; @@ -273,8 +273,8 @@ static void output_nno_list(enum logcode f, const char *name, struct name_num_ob printf(",\n \"%s\": [\n ", namebuf); - for (tok = strtok(tmpbuf, " "); tok; tok = next_tok) { - next_tok = strtok(NULL, " "); + for (tok = strtok_r(tmpbuf, " ", &save); tok; tok = next_tok) { + next_tok = strtok_r(NULL, " ", &save); if (*tok != '(') /* Ignore the aliases in the JSON output */ printf(" \"%s\"%s", tok, comma + (next_tok ? 0 : 1)); } diff --git a/util1.c b/util1.c index 793cef009..b448f4fc9 100644 --- a/util1.c +++ b/util1.c @@ -1154,21 +1154,19 @@ int idn_to_ascii(const char *name, int from_locale, char *buf, size_t buflen) * Split a string into tokens based (usually) on whitespace & commas. If the * string starts with a comma (after skipping any leading whitespace), then * splitting is done only on commas. No empty tokens are ever returned. */ -char *conf_strtok(char *str) +char *conf_strtok(char *str, struct conf_token_state *state) { - static int commas_only = 0; - if (str) { - while (isSpace(str)) str++; - if (*str == ',') { - commas_only = 1; + while (isSpace(str)) str++; - } else - commas_only = 0; + state->commas_only = *str == ','; } - while (commas_only) { - char *end, *tok = strtok(str, ","); + if (!state->commas_only) + return strtok_r(str, " ,\t\r\n", &state->next); + + for (;; str = NULL) { + char *end, *tok = strtok_r(str, ",", &state->next); if (!tok) return NULL; /* Trim just leading and trailing whitespace. */ @@ -1179,10 +1177,7 @@ char *conf_strtok(char *str) *--end = '\0'; if (*tok) return tok; - str = NULL; } - - return strtok(str, " ,\t\r\n"); } /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them. (If @@ -1852,10 +1847,11 @@ char *timestring(time_t t) strlcpy(TimeBuf, "(time out of range)", sizeof buffers[0]); return TimeBuf; } - len = snprintf(TimeBuf, sizeof buffers[0], "%4d/%02d/%02d %02d:%02d:%02d", - (int)tm->tm_year + 1900, (int)tm->tm_mon + 1, (int)tm->tm_mday, - (int)tm->tm_hour, (int)tm->tm_min, (int)tm->tm_sec); - assert(len > 0); /* Silence gcc warning */ + len = snprintf(TimeBuf, sizeof buffers[0], "%4lld/%02d/%02d %02d:%02d:%02d", + (long long)tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, + tm->tm_hour, tm->tm_min, tm->tm_sec); + if (len < 0 || (size_t)len >= sizeof buffers[0]) + strlcpy(TimeBuf, "(time out of range)", sizeof buffers[0]); return TimeBuf; } diff --git a/xattrs.c b/xattrs.c index 2ce275bd4..3b63ad153 100644 --- a/xattrs.c +++ b/xattrs.c @@ -1363,7 +1363,7 @@ int set_stat_xattr(const char *fname, struct file_struct *file, mode_t new_mode, /* Dump the special permissions and enable full owner access. */ mode = (fst.st_mode & _S_IFMT) - | ((override_mode ? tweak_mode(fmode, dest_chmod_modes) : fmode) & ACCESSPERMS) + | ((override_mode ? (mode_t)tweak_mode(fmode, dest_chmod_modes) : fmode) & ACCESSPERMS) | (S_ISDIR(fst.st_mode) ? 0700 : 0600); if (override_mode) { if (fd < 0 || (fmode & _S_IFMT) != (fst.st_mode & _S_IFMT)) {