/* ** Objektorienteeritud programmeerimine - pisikene WWW-server. ** ** NB! Tegemist on õppeotstarbelise näitega, mis ei ole ** mõeldud reaalses elus kasutamiseks. ** ** NB! Seda serverit reaalses elus PALUN ärge kasutage. ** ** @author Gunnar Kudrjavets [gk@aprote.ee] ** @version 0.1, 04.04.1999 ** @since JDK 1.0 */ import java.io.*; import java.net.*; import java.util.*; public class TinyHttpd { public static void main(String argv[]) throws IOException { if (argv.length == 1) { System.setSecurityManager(new TinyHttpdSecurityManager()); ServerSocket listener = new ServerSocket(Integer.parseInt(argv[0])); while (true) new TinyHttpdConnection(listener.accept()); } else { System.out.println("I need only one thing - port number!"); } } } class TinyHttpdConnection extends Thread { Socket s; TinyHttpdConnection(Socket sServer) { s = sServer; setPriority(NORM_PRIORITY - 1); start(); } public void run() { try { OutputStream out = s.getOutputStream(); String strRequest = new DataInputStream(s.getInputStream()).readLine(); System.out.println("Request: " + strRequest); StringTokenizer st = new StringTokenizer(strRequest); if ((st.countTokens() >= 2) && st.nextToken().equals("GET")) { if ((strRequest = st.nextToken()).startsWith("/")) strRequest = strRequest.substring(1); if (strRequest.endsWith("/") || strRequest.equals("")) strRequest = strRequest + "index.html"; try { FileInputStream fis = new FileInputStream(strRequest); byte[] data = new byte[fis.available()]; fis.read(data); out.write(data); } catch (FileNotFoundException e) { new PrintStream(out).println("404 Not Found"); } catch (SecurityException e) { new PrintStream(out).println("403 Forbidden\n" + e); } s.close(); } else { new PrintStream(out).println("400 Bad Request"); s.close(); } } catch (IOException e) { System.out.println("I/O error: " + e); } } } class TinyHttpdSecurityManager extends SecurityManager { public void checkAccess(Thread g) {}; public void checkAccess(ThreadGroup tg) {}; public void checkListen(int port) {}; public void checkLink(String lib) {}; public void checkPropertyAccess(String key) {}; public void checkAccept(String host, int port) {}; public void checkWrite(FileDescriptor fd) {}; public void checkRead(FileDescriptor fd) {}; public void checkRead(String s) { if (new File(s).isAbsolute() || (s.indexOf("..") != -1)) throw new SecurityException("Access to file " + s + " denied.\nGo away!"); } }