xref: /aosp_15_r20/external/cronet/net/base/port_util.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_BASE_PORT_UTIL_H_
6 #define NET_BASE_PORT_UTIL_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <string_view>
12 
13 #include "base/containers/span.h"
14 #include "net/base/net_export.h"
15 
16 namespace net {
17 
18 // Checks if |port| is in the valid range (0 to 65535, though 0 is technically
19 // reserved).  Should be used before casting a port to a uint16_t.
20 NET_EXPORT bool IsPortValid(int port);
21 
22 // Returns true if the port is in the range [0, 1023]. These ports are
23 // registered by IANA and typically need root access to listen on.
24 NET_EXPORT bool IsWellKnownPort(int port);
25 
26 // Checks if the port is allowed for the specified scheme.  Ports set as allowed
27 // with SetExplicitlyAllowedPorts() or by using ScopedPortException() will be
28 // considered allowed for any scheme.
29 NET_EXPORT bool IsPortAllowedForScheme(int port, std::string_view url_scheme);
30 
31 // Returns the number of explicitly allowed ports; for testing.
32 NET_EXPORT_PRIVATE size_t GetCountOfExplicitlyAllowedPorts();
33 
34 // Set the list of ports to be allowed that otherwise would not be. This
35 // replaces the list of allowed ports with the list passed to this function. An
36 // empty list will remove all ports. This will reset any ScopedPortExceptions
37 // currently active, so it's best to avoid calling this when any of those are
38 // active.
39 NET_EXPORT void SetExplicitlyAllowedPorts(
40     base::span<const uint16_t> allowed_ports);
41 
42 // Returns true for ports which are permitted to be passed to
43 // SetExplicitlyAllowedPorts(). This is not currently enforced by
44 // SetExplicitlyAllowedPorts() itself, as there are still callers that pass
45 // other ports.
46 NET_EXPORT bool IsAllowablePort(int port);
47 
48 class NET_EXPORT ScopedPortException {
49  public:
50   explicit ScopedPortException(int port);
51   ScopedPortException(const ScopedPortException&) = delete;
52   ScopedPortException& operator=(const ScopedPortException&) = delete;
53   ~ScopedPortException();
54 
55  private:
56   int port_;
57 };
58 
59 // Adds a port to the set permitted by GetAllowablePorts(). Cannot be nested.
60 class NET_EXPORT ScopedAllowablePortForTesting {
61  public:
62   explicit ScopedAllowablePortForTesting(int port);
63   ScopedAllowablePortForTesting(const ScopedAllowablePortForTesting&) = delete;
64   ScopedAllowablePortForTesting& operator=(
65       const ScopedAllowablePortForTesting&) = delete;
66   ~ScopedAllowablePortForTesting();
67 };
68 
69 }  // namespace net
70 
71 #endif  // NET_BASE_PORT_UTIL_H_
72