Skip to content

Reject out-of-range and wrapping port values (-p, --statsd-port, --graphite-port, --uri, --read-server) - #699

Merged
fcostaoliveira merged 5 commits into
masterfrom
fix-697-port-range
Oct 16, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
fix-697-port-range

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Decision: -p/--port, --statsd-port, --graphite-port, the --read-server HOST:PORT port and the --uri port now accept only digits, as a number in [1,65535]. Values above 65535, negative values, empty strings and trailing junk are rejected with the existing error messages. 0 is still rejected (it already was for all of them).

Small compatibility change: a value with a leading sign or whitespace (+6379, " 6379", "\t6379") used to be accepted and is now rejected. The value must start with a digit because strtoul() skips any leading whitespace (including \n and \v) and accepts a sign, so a check for a leading - alone could be bypassed: "\n-18446744073709551615" wrapped to port 1. Leading zeros (06379) are still accepted. --prometheus-port is unchanged here (0 means an ephemeral port); it has a related leading-whitespace hole tracked in #705.

Problem

Values above 65535 that did not wrap to exactly 0 were silently accepted modulo 65536. -p 65537 connected to port 1, and -p 88536 ran a normal benchmark against a Redis on port 23000. Negative values were accepted too: -p -65535 meant port 1. --statsd-port and --graphite-port had the same problem. --uri and --read-server range-checked correctly but still accepted a negative value that wraps into range: --uri=redis://host:-18446744073709551615 connected to port 1. (#697 said these two were not affected; review found they were.)

Root cause

config_parse_args() cast strtoul()'s result to unsigned short before the range check:

cfg->port = (unsigned short) strtoul(optarg, &endptr, 10);
if (!cfg->port || cfg->port > 65535 || ...)   // -Wtype-limits: always false

So only multiples of 65536 were rejected, because they wrap to 0. strtoul() negates a leading -, so negative input wrapped as well. --statsd-port and --graphite-port used the same cast and only checked == 0.

Fix

I added one small parse_port() helper, next to parse_backoff_factor(), and all five port inputs use it. It follows the --prometheus-port pattern:

  • it requires the value to start with a digit (this rejects empty input, signs and leading whitespace)
  • it rejects input with no digits, trailing junk and ERANGE (it resets errno first, so overflow from an earlier option cannot leak in)
  • it range-checks the unsigned long to [1,65535] before narrowing

The -Wtype-limits warning at the old -p line goes away: building with -O0 -Wtype-limits gives one warning in memtier_benchmark.cpp on master and none with this patch.

Tests

New file tests/test_cli_validation_ports.py. It uses --version, which exits right after parsing, so it needs no server. It covers:

  • rejected for each of --port, --statsd-port and --graphite-port: 65536 65537 88536 131072 70000 99999999999999999999999 -1 -65535 -0 " -1" 0 "" " " abc 1x "6379 " 0x50, the wrapping negatives -18446744073709551615 and -18446744073709545916 (also with \n/\v in front), and +6379 " 6379" "\t6379"
  • rejected for --read-server and --uri ports: out of range, 0, a wrapping negative and a leading +; valid --read-server specs (including [::1]:6379) are accepted
  • rejected with the short form: -p 65537|88536|-65535
  • accepted: 1 6379 65535
  • accepted: a valid port for all three options after an earlier option overflowed strtoul (the stale errno case)

The file is added to the asan/tsan/ubsan "Single Endpoint: TCP TLS (cli)" and "OSS TCP TLS v1.3 (cli)" selections, next to the other test_cli_validation_* files.

Local results, --env existing-env:

binary result
origin/master 1d13ff5 4 of 6 tests fail (out-of-range/negative values accepted)
this branch 6 of 6 pass; make check 7/7

Direct matrix (--<opt>=<v> --version, rc). The three options give the same result:

           65536 65537 88536 -1 -65535 "" abc 1x 0 1 6379 65535 9999..(23 digits)
master       2     0     0    0    0    2  2   2  2 0  0    0     0
this PR      2     2     2    2    2    2  2   2  2 0  0    0     2

+6379, " 6379" and "\n-18446744073709551615": rc 0 on master, rc 2 with this PR.

A real run with -p <valid port> still completes normally.

Fixes #697

Affected versions

1.0.0 through 2.5.2 (latest) and master.

🤖 Generated with Claude Code


Note

Medium Risk
Changes argument parsing for all main connection/metrics ports; behavior shifts for previously accepted malformed values, but valid ports should behave the same.

Overview
Tightens CLI port parsing so -p/--port, --statsd-port, --graphite-port, --uri host ports, and --read-server HOST:PORT only accept a plain decimal in 1–65535, checked on the unsigned long before casting to unsigned short.

A shared parse_port() helper replaces per-option strtoul + early cast logic that let values like 65537 or wrapping negatives connect to the wrong port (#697). Inputs must start with a digit (rejecting signs, leading whitespace, and junk); 0 stays invalid. --prometheus-port is unchanged.

Adds tests/test_cli_validation_ports.py (mostly via --version) and wires it into the asan/tsan/ubsan “TCP TLS (cli)” matrix jobs.

Reviewed by Cursor Bugbot for commit 9436446. Bugbot is set up for automated code reviews on this repo. Configure here.

fcostaoliveira and others added 2 commits October 16, 2026 11:35
config_parse_args() narrowed strtoul()'s result to unsigned short before
range-checking it, so the "> 65535" test could never be true
(gcc -Wtype-limits: "comparison is always false"). Any value above 65535
that did not wrap to exactly 0 was silently accepted modulo 65536:
-p 65537 connected to port 1 and -p 88536 to port 23000. strtoul() also
negates a leading '-', so -p -65535 meant port 1. --statsd-port and
--graphite-port had the same cast and only rejected 0.

Parse all three through one parse_port() helper that rejects empty input,
a leading '-', trailing junk and ERANGE, and range-checks the unsigned
long to [1,65535] before narrowing, as --prometheus-port already does.
Valid inputs and the existing error messages are unchanged.

Add tests/test_cli_validation_ports.py (uses --version, no server
needed) and run it in the asan/tsan/ubsan TLS (cli) jobs.

Fixes #697

Co-Authored-By: Claude Opus 5.5 <[email protected]>
strtoul() skips any leading whitespace and accepts a sign, and
optarg_is_negative() only skips spaces and tabs, so "\n-18446744073709551615"
still wrapped to port 1. parse_port() now requires the value to start
with a digit, which also rejects "+6379" and " 6379" (plain decimal
only, as documented). Tests cover the wrapping negatives, with and
without leading whitespace, and the stale-errno case for --graphite-port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Follow-up from review, now rebased on master:

  • parse_port() now requires the value to start with a digit. optarg_is_negative() skips only spaces and tabs, but strtoul() skips any whitespace and accepts a sign, so "\n-18446744073709551615" still wrapped to port 1. A reviewer reproduced that against a live server.
  • This also makes "plain decimal" literal: +6379 and 6379 are now rejected. master accepted them.
  • The tests now include the wrapping negatives (-18446744073709551615, -18446744073709545916, and the same with \n/\v in front), which catch removal of the negative-sign guard. The stale-errno case now also covers --graphite-port.
  • make check 7/7 and test_cli_validation_ports.py 4/4 pass locally.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this. I went through it and the fix itself looks right to me. All five port inputs now go through a single parse_port(), and the range check happens on the unsigned long before the value is narrowed, which addresses the root cause rather than the symptom. The tests also do what I'd want: they're parse-only via --version, they fail on master as shown in the PR table, and they include the stale-errno case.

One question on compatibility, since that's the part this project has historically been careful about. In PR#212 the less-breaking fix was chosen specifically because the stricter one would make previously-working command lines error out. Here, " 6379" and "\t6379" were accepted before and will now fail. I agree that requiring a leading digit is the simplest way to close the "\n-18446744073709551615" hole. Did you consider a middle ground, though? Skip leading spaces and tabs (roughly what optarg_is_negative() already does), and then require a digit. That still rejects the sign and \n/\v cases but keeps the space-padded form working. I may be overthinking it: I doubt many people pass a padded port, and +6379 being rejected seems fine either way. Since the break is user-facing CLI behavior, though, I'd want the choice to be deliberate rather than a side effect of the simplest fix.

Nitpicking: test_uri_port_rejects_out_of_range_and_malformed checks returncode != 0, while the other tests pin it to 2. If the URI error path has a stable exit code, pinning it would make the test a bit tighter.

The core change looks solid to me. I'd just like the leading-whitespace question answered before this merges.

fcostaoliveira and others added 2 commits October 16, 2026 11:41
Both parsers checked the strtoul() result for [1,65535] but accepted a
leading '-', which strtoul() negates modulo 2^64, so
--uri=redis://host:-18446744073709551615 and
--read-server=host:-18446744073709551615 connected to port 1. They now
share parse_port() with -p, --statsd-port and --graphite-port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The leading-digit check already guarantees strtoul() consumes at least
one character, so endptr == s cannot be true. Also note in the stale
errno test why --max-reconnect-attempts is used to leave ERANGE set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the automated review of a2a6b5b:

  • Leading whitespace and + (a): rejecting them is intentional, and the PR description now says so under "Small compatibility change". A check that skips whitespace and a + would need to match strtoul()'s whitespace set exactly to stay safe, and nobody passes a padded or signed port on purpose. Leading zeros are still accepted.
  • Stale description (b): rewritten for the current head. The Fix, Tests and matrix sections now describe the leading-digit check and the new values.
  • Redundant endptr == s (c): removed in cced292.
  • Also new since a2a6b5b: --uri and --read-server HOST:PORT now use parse_port() too (6cb2c08). Both accepted a negative value that wraps into range: --uri=redis://host:-18446744073709551615 connected to port 1. The tests cover both, and test_cli_validation_ports.py passes 6/6 here and fails 4/6 on master.

The comment still described the leading '-' check and listed only three
options. parse_port() now sits above its first caller, so the forward
declaration is gone. Also clarify why the --uri test needs no server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira fcostaoliveira changed the title Reject out-of-range -p/--port, --statsd-port and --graphite-port values Reject out-of-range and wrapping port values (-p, --statsd-port, --graphite-port, --uri, --read-server) Oct 16, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the automated review of cced292, fixed in the new head:

  • Tolerant version: yes, it was considered, and the strict rule was chosen on purpose. Skipping isspace() and then requiring a digit would also close the \n-… hole. But it keeps a second whitespace rule next to strtoul()'s, plus one for the optional +, all for inputs nobody types on purpose. A quoted port with a leading space is almost certainly a scripting mistake, and rejecting it gives a clear error instead of a silently accepted value. Leading zeros still work. Unlike the strtod/strtoull case in Fix issue #211. Allow key_stddev and key_median options to be set values #212, no documented or tested usage relied on these forms. If maintainers prefer the tolerant form, it's a two-line change in parse_port().
  • Stale comment and title: the comment now describes the leading-digit rule and lists all five callers. The PR title now covers --uri and --read-server.
  • Forward declaration: parse_port() now sits above parse_uri(), and the forward declaration is gone.
  • --uri test comment: reworded to say parsing fails before any connection attempt.
  • Stale-errno test: that tradeoff is acceptable. The docstring says to switch to another unchecked option once --max-reconnect-attempts is fixed (--max-reconnect-attempts and --retry-backoff-ms silently accept negative, overflowing and empty values (wrap to unlimited / UINT_MAX / 0) #695).

Local: make check 7/7, test_cli_validation_ports.py 6/6.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Re the automated review posted at 11:12:57, which crossed with my reply at 11:12:02:

  • Leading whitespace: the choice is deliberate. Skipping spaces and tabs and then requiring a digit was considered. It would keep " 6379" working, but strtoul() also skips \n, \v, \f and \r. So the guard has to treat spaces and tabs differently from the other whitespace strtoul() skips, and that mismatch is what let "\n-18446744073709551615" through in the first place. Requiring a digit first leaves one rule and nothing left to keep in sync. A padded port is almost certainly a quoting mistake, and it now gets a clear error. The compatibility change is listed at the top of the PR description, and it is a two-line change to relax if maintainers prefer.
  • --uri exit code: a URI error goes through parse_uri() and returns 1 from main(), unlike the getopt validators, which exit 2. The test asserts != 0 together with the exact invalid port number diagnostic, so it cannot pass by accident. Pinning it to 1 is possible, but would tie the test to that difference between the two paths.

@fcostaoliveira
fcostaoliveira merged commit f308ed6 into master Oct 16, 2026
171 of 172 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
13 numeric options used strtoul()/strtoull() and a narrowing cast with
no range or format check (#705, #695). Negative values wrapped to huge
ones ("-1", or "\n-18446744073709551000" which slipped past the old
leading-'-' check), values above the option's type were silently
truncated (-c 4294967296 became 0), overflow was ignored, and an empty
value meant 0, e.g. --max-reconnect-attempts= meaning "unlimited".

All of them now go through one parser, parse_unsigned(), and
parse_port() is built on it:
- leading whitespace and a single '+' are accepted, as strtoul() always
  accepted them, so existing command lines keep working (the reasoning
  of #212);
- any '-', an empty value, trailing junk, overflow and values above the
  option's maximum are rejected with exit 2;
- the "unset" sentinels are excluded (-n <= ULLONG_MAX-1,
  --connection-stage-timeout <= UINT_MAX-1).

Messages for -n/-c/-t/--test-time: "must be a positive integer" for
malformed input, "must be greater than zero" for 0, "must be <= MAX"
when too large. Port options (-p, --uri, --read-server, the prometheus
port) follow the same rule, which restores what releases before the
unreleased #699 accepted.

Release note: an empty --max-reconnect-attempts= is now an error; pass
0 for unlimited.

Tests cover every bypass vector per option, the accepted relaxed forms,
the sentinels, the messages and stale-errno handling; they fail on
master. The remaining unchecked options are tracked in #725.

Fixes #705
Fixes #695

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

-p/--port, --statsd-port and --graphite-port accept values above 65535 (and negative values), wrapped modulo 65536

1 participant