1619
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 5:
An unnamed web site allowed a user to purchase tickets for an event. A menu option allowed the
user to purchase up to 10 tickets, but the back end did not restrict the actual number of tickets that
could be purchased.
Example 6:
Here the problem is that every time a connection is made, more memory is allocated. So if one just
opened up more and more connections, eventually the machine would run out of memory.
Example Language: C (Bad)
bar connection() {
foo = malloc(1024);
return foo;
}
endConnection(bar foo) {
free(foo);
}
int main() {
while(1) {
foo=connection();
}
endConnection(foo)
}
CWE Version 4.14
CWE-770: Allocation of Resources Without Limits or Throttling
CWE-770: Allocation of Resources Without Limits or Throttling