import java.io.*; import java.net.*; public class HTTPServer { public static void main(String[] args) throws Exception { final int httpd = Integer.parseInt(args[0]); // our port ServerSocket ssock = new ServerSocket(httpd); while (true) { Socket sock = ssock.accept(); System.out.println("** Client has made socket connection."); OneConnection_C client = new OneConnection_C(sock); new Thread(client).start(); } } } class OneConnection { Socket sock; BufferedReader in = null; DataOutputStream out = null; OneConnection(Socket sock) throws Exception { this.sock = sock; in = new BufferedReader (new InputStreamReader (sock.getInputStream())); out = new DataOutputStream(sock.getOutputStream()); } String getRequest() throws Exception { String s = null; while ((s = in.readLine()) != null) { System.out.println("got: " + s); } return s; } } class OneConnection_A extends OneConnection { OneConnection_A (Socket sock) throws Exception { super(sock); } String getRequest() throws Exception { String s = null; while ((s = in.readLine()) != null) { System.out.println("got: " + s); if (s.indexOf("GET") > -1) { out.writeBytes("HTTP-1.0 200 OK\r\n"); s = s.substring(4); int i = s.indexOf(" "); System.out.println("file: " + s.substring(0, i)); return s.substring(0, i); } } return null; } } class OneConnection_B extends OneConnection_A { OneConnection_B(Socket sock) throws Exception { super(sock); } void sendFile(String fname) throws Exception { String where = "htdocs" + fname; if (where.indexOf("..") > -1) throw new SecurityException("No access to parent dirs"); System.out.println("Looking for " + where); File f = new File(where); DataInputStream din = new DataInputStream(new FileInputStream(f)); int len = (int) f.length(); byte[] buf = new byte[len]; din.readFully(buf); out.writeBytes("Content-Length: " + len + "\r\n"); out.writeBytes("Content-type: text/html\r\n\r\n"); out.write(buf); out.flush(); out.close(); } } class OneConnection_C extends OneConnection_B implements Runnable { OneConnection_C(Socket sock) throws Exception { super(sock); } public void run() { try { String filename = getRequest(); sendFile(filename); } catch (Exception e) { System.out.println("Exception: " + e); } } }