commit 8e9008b7f992f0fea2c2a7366e7615f49a735e0a
parent 72e45b1281e0ec88f7e5564dd3ff83c8b51574a4
Author: David Engel <dengel@ucalgary.ca>
Date: Fri, 28 Apr 2017 22:50:02 -0600
server: sockets timeout after 5 seconds to prevent thread exhaustion from attackers
Diffstat:
2 files changed, 16 insertions(+), 11 deletions(-)
diff --git a/server/shlist/Server.java b/server/shlist/Server.java
@@ -3,6 +3,7 @@ package shlist;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
+import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -21,7 +22,7 @@ public class Server {
try {
sSock = new ServerSocket(PORT);
} catch (IOException e) {
- e.printStackTrace();
+ System.out.println("IO Error1: " + e);
}
// Add the runtime hook, for ctrl+c
@@ -31,11 +32,12 @@ public class Server {
while (true) {
try {
sock = sSock.accept();
+ sock.setSoTimeout(5000);
+ exec.execute(new Worker(sock));
} catch (IOException e) {
- //System.out.println("IO Error: " + e);
+ System.out.println("IO Error: " + e);
break;
}
- exec.execute(new Worker(sock));
}
}
}
diff --git a/server/shlist/Worker.java b/server/shlist/Worker.java
@@ -20,7 +20,6 @@ public class Worker implements Runnable {
inp = sock.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
} catch (IOException e) {
- e.printStackTrace();
return;
}
System.out.println("Started new thread");
@@ -29,15 +28,19 @@ public class Worker implements Runnable {
line = brinp.readLine();
if (line != null) {
System.out.println(line);
- } else {
- sock.close();
- brinp.close();
- System.out.println("Closing Socket");
}
+ sock.close();
+ brinp.close();
+ System.out.println("Closing Socket");
} catch (IOException e) {
- e.printStackTrace();
- return;
- }
+ try {
+ sock.close();
+ brinp.close();
+ System.out.println("Closing Socket");
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ }
+ }
System.out.println("Exiting Thread");
}
}