969
In the following example, a server object creates a server socket and accepts client connections to
the socket. For every client connection to the socket a separate thread object is generated using
the ClientSocketThread class that handles request made by the client through the socket.
Example Language: Java (Bad)
public void acceptConnections() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
Socket client = serverSocket.accept();
Thread t = new Thread(new ClientSocketThread(client));
t.setName(client.getInetAddress().getHostName() + ":" + counter++);
t.start();
}
serverSocket.close();
} catch (IOException ex) {...}
}
In this example there is no limit to the number of client connections and client threads that
are created. Allowing an unlimited number of client connections and threads could potentially
overwhelm the system and system resources.
The server should limit the number of client connections and the client threads that are created.
This can be easily done by creating a thread pool object that limits the number of threads that are
generated.
Example Language: Java (Good)
public static final int SERVER_PORT = 4444;
public static final int MAX_CONNECTIONS = 10;
...
public void acceptConnections() {
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
hasConnections = checkForMoreConnections();
Socket client = serverSocket.accept();
Thread t = new Thread(new ClientSocketThread(client));
t.setName(client.getInetAddress().getHostName() + ":" + counter++);
ExecutorService pool = Executors.newFixedThreadPool(MAX_CONNECTIONS);
pool.execute(t);
}
serverSocket.close();
} catch (IOException ex) {...}
}
Example 6:
In the following example, the serve function receives an http request and an http response writer. It
reads the entire request body.
Example Language: Go (Bad)
func serve(w http.ResponseWriter, r *http.Request) {
var body []byte
if r.Body != nil {
if data, err := io.ReadAll(r.Body); err == nil {
body = data
}
}
CWE Version 4.14
CWE-400: Uncontrolled Resource Consumption
CWE-400: Uncontrolled Resource Consumption