Fix SplitHostPort for empty strings.

Add unittests to catch such errors in the future.
pull/19488/head
Soheil Hassas Yeganeh 6 years ago
parent dbf88dd66f
commit c9ec1a64ed
  1. 8
      src/core/lib/gprpp/host_port.cc
  2. 36
      test/core/gprpp/host_port_test.cc

@ -87,11 +87,15 @@ bool SplitHostPort(StringView name, StringView* host, StringView* port) {
bool SplitHostPort(StringView name, UniquePtr<char>* host,
UniquePtr<char>* port) {
GPR_DEBUG_ASSERT(host != nullptr && *host == nullptr);
GPR_DEBUG_ASSERT(port != nullptr && *port == nullptr);
StringView host_view;
StringView port_view;
const bool ret = SplitHostPort(name, &host_view, &port_view);
host->reset(host_view.empty() ? nullptr : host_view.dup().release());
port->reset(port_view.empty() ? nullptr : port_view.dup().release());
if (ret) {
*host = host_view.dup();
*port = port_view.dup();
}
return ret;
}
} // namespace grpc_core

@ -48,11 +48,47 @@ static void test_join_host_port_garbage(void) {
join_host_port_expect("::]", 107, "[::]]:107");
}
static void split_host_port_expect(const char* name, const char* host,
const char* port, bool ret) {
grpc_core::UniquePtr<char> actual_host;
grpc_core::UniquePtr<char> actual_port;
const bool actual_ret =
grpc_core::SplitHostPort(name, &actual_host, &actual_port);
GPR_ASSERT(actual_ret == ret);
if (host == nullptr) {
GPR_ASSERT(actual_host == nullptr);
} else {
GPR_ASSERT(strcmp(host, actual_host.get()) == 0);
}
if (port == nullptr) {
GPR_ASSERT(actual_port == nullptr);
} else {
GPR_ASSERT(strcmp(port, actual_port.get()) == 0);
}
}
static void test_split_host_port() {
split_host_port_expect("", "", "", true);
split_host_port_expect("[a:b]", "a:b", "", true);
split_host_port_expect("1.2.3.4", "1.2.3.4", "", true);
split_host_port_expect("a:b:c::", "a:b:c::", "", true);
split_host_port_expect("[a:b]:30", "a:b", "30", true);
split_host_port_expect("1.2.3.4:30", "1.2.3.4", "30", true);
split_host_port_expect(":30", "", "30", true);
}
static void test_split_host_port_invalid() {
split_host_port_expect("[a:b", nullptr, nullptr, false);
split_host_port_expect("[a:b]30", nullptr, nullptr, false);
}
int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv);
test_join_host_port();
test_join_host_port_garbage();
test_split_host_port();
test_split_host_port_invalid();
return 0;
}

Loading…
Cancel
Save