chenBright commented on code in PR #3767:
URL: https://github.com/apache/brpc/pull/3767#discussion_r4703726405


##########
src/brpc/server.cpp:
##########
@@ -1209,6 +1279,12 @@ int Server::StartInternal(const butil::EndPoint& 
endpoint,
         LOG(ERROR) << "Only IPv4 address supports port range feature";
         return -1;
     }
+    // Acceptors cache the protocol handlers built from ServerOptions, which 
may
+    // change between Start()s of the same Server, so rebuild them.
+    delete _am;
+    _am = nullptr;
+    delete _internal_am;
+    _internal_am = nullptr;

Review Comment:
   `GetStat()` can pass the null check before a second `Start()` deletes `_am`, 
then read the counters from the freed listener. `Join()` only waits for the 
server's own statistics thread. Please protect the entire period during which 
external readers use the listener, or have `GetStat()` read counters owned by 
`Server`.



##########
src/brpc/server.cpp:
##########
@@ -714,14 +792,10 @@ Acceptor* Server::BuildAcceptor() {
             // The protocol does not support server-side.
             continue;
         }
-        // Erase whatever the exemptions below say. http, h2 and
-        // rdma_handshake are always served, but they are still
-        // valid names for the whitelist.
-        bool in_whitelist = (whitelist.erase(protocols[i].name) != 0);
-        if (has_whitelist && !in_whitelist &&
-            !is_http_protocol(protocols[i].name) &&
+        if (has_whitelist && whitelist.count(protocols[i].name) == 0 &&
             !is_rdma_handshake_protocol(protocols[i].name)) {
-            // the protocol is not allowed to serve.
+            // rdma_handshake is always served since it only handles the
+            // transport level handshake and dispatches no request.
             RPC_VLOG << "Skip protocol=" << protocols[i].name;
             continue;

Review Comment:
   `enabled_protocols="h2"` with `alpns="http,h2"` passes startup validation. A 
client that supports both protocols will negotiate the server-preferred 
`http/1.1`, then be disconnected on its first request. Please ensure ALPN 
selects only protocols with installed parsers, or report the configuration 
conflict at startup.



##########
src/brpc/server.cpp:
##########
@@ -1209,6 +1279,12 @@ int Server::StartInternal(const butil::EndPoint& 
endpoint,
         LOG(ERROR) << "Only IPv4 address supports port range feature";
         return -1;
     }
+    // Acceptors cache the protocol handlers built from ServerOptions, which 
may
+    // change between Start()s of the same Server, so rebuild them.
+    delete _am;
+    _am = nullptr;
+    delete _internal_am;
+    _internal_am = nullptr;

Review Comment:
   When `idle_timeout_sec` is enabled, `CloseIdleConnections` may already have 
started before `Socket::Create()` fails. The listener is still `READY`, so both 
`StopAccept()` and `Join()` return immediately during destruction. Please clean 
up the cleanup thread on this failure path; otherwise, after a retry executes 
the `delete` here, the thread will still use the old `this`.



##########
src/brpc/server.cpp:
##########
@@ -1209,6 +1279,12 @@ int Server::StartInternal(const butil::EndPoint& 
endpoint,
         LOG(ERROR) << "Only IPv4 address supports port range feature";
         return -1;
     }
+    // Acceptors cache the protocol handlers built from ServerOptions, which 
may
+    // change between Start()s of the same Server, so rebuild them.
+    delete _am;
+    _am = nullptr;
+    delete _internal_am;
+    _internal_am = nullptr;

Review Comment:
   A short-lived connection can enter recycling before it is added to 
`_socket_map`. When `AddressFailedAsWell()` returns failure, the socket version 
may have just become invalid while `BeforeRecycle()` is still pending. In that 
case, `Join()` cannot see the connection, and a restart may delete the listener 
before the callback accesses it. Please register the socket before I/O, or have 
the socket hold the listener until the callback completes.



##########
src/brpc/server.cpp:
##########
@@ -1209,6 +1279,12 @@ int Server::StartInternal(const butil::EndPoint& 
endpoint,
         LOG(ERROR) << "Only IPv4 address supports port range feature";
         return -1;
     }
+    // Acceptors cache the protocol handlers built from ServerOptions, which 
may
+    // change between Start()s of the same Server, so rebuild them.
+    delete _am;
+    _am = nullptr;
+    delete _internal_am;
+    _internal_am = nullptr;

Review Comment:
   Deleting the old listener here relies on `Join()` having waited for the 
listening socket to be recycled. `_listened_fd == 0` is valid, but it does not 
enter the wait loop in `Acceptor::Join()`. Please check completion against the 
actual sentinel, `-1`, to prevent an event thread that still holds the socket 
from calling back into a freed object.



##########
src/brpc/server.cpp:
##########
@@ -962,6 +1025,13 @@ int Server::StartInternal(const butil::EndPoint& endpoint,
                    << FLAGS_task_group_ntags << ")";
         return -1;
     }
+    // Validate `enabled_protocols' before copy_and_fill_server_options below
+    // adopts the pointers in the user-provided options, so that a rejected
+    // configuration does not transfer their ownership to this server.
+    if (ValidateEnabledProtocols(real_opt) != 0) {
+        return -1;
+    }

Review Comment:
   The public contract for `Start()` includes setting `errno` on failure. This 
configuration rejection path currently only returns `-1`, so callers may read 
an error code left by a previous operation. Please return a consistent `EINVAL` 
for protocol configuration errors.



##########
src/brpc/server.cpp:
##########
@@ -686,24 +686,102 @@ int Server::AddBuiltinServices() {
     return 0;
 }
 
-BUTIL_FORCE_INLINE bool is_http_protocol(const char* name) {
-    if (name[0] != 'h') {
-        return false;
+BUTIL_FORCE_INLINE bool is_rdma_handshake_protocol(const char* name) {
+    return strcmp(name, "rdma_handshake") == 0;
+}
+
+// Restful services are served through http/h2 requests. Empty maps may be
+// left by RemoveService(), so check the number of mappings instead of the
+// existence of the map.
+static bool HasRestfulServices(const Server::ServiceMap& services,
+                               const RestfulMap* global_restful_map) {
+    if (global_restful_map != nullptr && global_restful_map->size() != 0) {
+        return true;
+    }
+    for (Server::ServiceMap::const_iterator it = services.begin();
+         it != services.end(); ++it) {
+        if (it->second.restful_map != nullptr &&
+            it->second.restful_map->size() != 0) {
+            return true;
+        }
     }
-    return strcmp(name, "http") == 0 || strcmp(name, "h2") == 0;
+    return false;
 }
 
-BUTIL_FORCE_INLINE bool is_rdma_handshake_protocol(const char* name) {
-    return strcmp(name, "rdma_handshake") == 0;
+static std::string JoinWithAnd(const std::vector<std::string>& strs) {
+    std::string out;
+    for (size_t i = 0; i < strs.size(); ++i) {
+        if (i != 0) {
+            out.append(i + 1 == strs.size() ? " and " : ", ");
+        }
+        out.append(strs[i]);
+    }
+    return out;
 }
 
-Acceptor* Server::BuildAcceptor() {
+static void ParseEnabledProtocols(const std::string& enabled_protocols,
+                                  std::unordered_set<std::string>* whitelist) {
+    for (butil::StringSplitter sp(enabled_protocols.c_str(), ' '); sp; ++sp) {
+        whitelist->insert(std::string(sp.field(), sp.length()));
+    }
+}
+
+int Server::ValidateEnabledProtocols(const ServerOptions& options) const {
     std::unordered_set<std::string> whitelist;
-    for (butil::StringSplitter sp(_options.enabled_protocols.c_str(), ' ');
-         sp; ++sp) {
-        std::string protocol(sp.field(), sp.length());
-        whitelist.insert(protocol);
+    ParseEnabledProtocols(options.enabled_protocols, &whitelist);
+    if (whitelist.empty()) {
+        return 0;
+    }
+    const bool http_in_whitelist =
+        whitelist.count("http") != 0 || whitelist.count("h2") != 0;
+    std::vector<Protocol> protocols;
+    ListProtocols(&protocols);
+    for (size_t i = 0; i < protocols.size(); ++i) {
+        if (protocols[i].process_request != nullptr) {
+            whitelist.erase(protocols[i].name);
+        }
+    }
+    if (!whitelist.empty()) {
+        std::ostringstream err;
+        err << "ServerOptions.enabled_protocols has unknown protocols=`";
+        for (const auto& protocol : whitelist) {
+            err << protocol << ' ';
+        }
+        err << '\'';
+        LOG(ERROR) << err.str();
+        return -1;
+    }
+    if (http_in_whitelist) {
+        return 0;
+    }
+    std::vector<std::string> features;
+    std::vector<std::string> fixes;
+    if (options.has_builtin_services) {
+        features.push_back("ServerOptions.has_builtin_services is true");
+        fixes.push_back("set ServerOptions.has_builtin_services=false");

Review Comment:
   If this `Server` has previously started successfully with built-in services, 
setting `has_builtin_services=false` as suggested here will cause the next 
attempt to be rejected by the `_builtin_service_count > 0` consistency check. 
Please provide an actionable fix based on the existing registration state.



##########
src/brpc/server.cpp:
##########
@@ -962,6 +1025,13 @@ int Server::StartInternal(const butil::EndPoint& endpoint,
                    << FLAGS_task_group_ntags << ")";
         return -1;
     }
+    // Validate `enabled_protocols' before copy_and_fill_server_options below
+    // adopts the pointers in the user-provided options, so that a rejected
+    // configuration does not transfer their ownership to this server.
+    if (ValidateEnabledProtocols(real_opt) != 0) {
+        return -1;
+    }

Review Comment:
   `bthread_init_fn` runs after this point, when `AddService()` still accepts 
REST mappings. A single callback can cause a `baidu_std`-only server to report 
both successful registration and startup, while the new route remains 
inaccessible. Please retain the early ownership check and ensure that service 
table changes after validation also comply with the HTTP dependency.



##########
src/brpc/server.cpp:
##########
@@ -686,24 +686,102 @@ int Server::AddBuiltinServices() {
     return 0;
 }
 
-BUTIL_FORCE_INLINE bool is_http_protocol(const char* name) {
-    if (name[0] != 'h') {
-        return false;
+BUTIL_FORCE_INLINE bool is_rdma_handshake_protocol(const char* name) {
+    return strcmp(name, "rdma_handshake") == 0;
+}
+
+// Restful services are served through http/h2 requests. Empty maps may be
+// left by RemoveService(), so check the number of mappings instead of the
+// existence of the map.
+static bool HasRestfulServices(const Server::ServiceMap& services,
+                               const RestfulMap* global_restful_map) {
+    if (global_restful_map != nullptr && global_restful_map->size() != 0) {
+        return true;

Review Comment:
   After registering `*.flv => Echo` and calling `ClearServices()`, the global 
mapping's `size()` remains greater than zero. As a result, even though the 
services have been cleared, a `baidu_std`-only `Start()` is still rejected 
here. Please also clear `_global_restful_map` when clearing all services, and 
cover this public API path.



##########
src/brpc/server.h:
##########
@@ -284,10 +284,12 @@ struct ServerOptions {
 
     // Only enable these protocols, separated by spaces.
     // All names inside must be valid, check protocols name in global.cpp
-    // http/h2 and rdma_handshake are served whatever this field says:
-    // the builtin services are only reachable over http/h2, and
-    // rdma_handshake is a transport level handshake dispatching no request.
-    // Naming them here is allowed and changes nothing.
+    // When this field is non-empty, only the listed protocols are served.
+    // rdma_handshake is always served as it is a transport level handshake
+    // dispatching no request; naming it here is allowed and changes nothing.
+    // Builtin and restful services as well as http_master_service are served
+    // through http/h2, so if any of them is enabled, http or h2 must be listed
+    // as well, otherwise Server::Start() fails.

Review Comment:
   It would be helpful to also document ownership after failure here. If 
protocol validation rejects the configuration, the caller needs to free the 
newly supplied `http_master_service`, as the new test does. If failure occurs 
later during port binding, the object is already owned by `Server`. The field 
comment currently says only that the server destructor frees it, so the caller 
cannot choose the correct cleanup based solely on `Start() == -1`.



##########
test/brpc_server_unittest.cpp:
##########
@@ -476,6 +476,9 @@ TEST_F(ServerTest, invalid_protocol_in_enabled_protocols) {
     brpc::ServerOptions opt;
     opt.enabled_protocols = "hehe baidu_std";
     ASSERT_EQ(-1, server.Start(ep, &opt));
+    // Unknown names are rejected before builtin services are added, so this
+    // error is not masked by the http/h2 requirement of builtin services.
+    ASSERT_EQ(0u, server._builtin_service_count);

Review Comment:
   Even if the unknown-name check is skipped entirely, `hehe baidu_std` will 
fail before registering built-in services because it lacks `http`/`h2`. 
Consider using `http hehe` to test the unknown name separately, and checking 
the actual diagnostic for the original input with both errors, so the test 
covers the error priority described in the comment.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to