You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Webserver.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999-2005 Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later.
  9. *
  10. * Software distributed under the License is distributed on an "AS IS" basis,
  11. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12. * for the specific language governing rights and limitations under the
  13. * License.
  14. */
  15. package javassist.tools.web;
  16. import java.net.*;
  17. import java.io.*;
  18. import java.util.Date;
  19. import javassist.*;
  20. /**
  21. * A web server for running sample programs.
  22. *
  23. * <p>This enables a Java program to instrument class files loaded by
  24. * web browsers for applets. Since the (standard) security manager
  25. * does not allow an applet to create and use a class loader,
  26. * instrumenting class files must be done by this web server.
  27. *
  28. * <p><b>Note:</b> although this class is included in the Javassist API,
  29. * it is provided as a sample implementation of the web server using
  30. * Javassist. Especially, there might be security flaws in this server.
  31. * Please use this with YOUR OWN RISK.
  32. */
  33. public class Webserver {
  34. private ServerSocket socket;
  35. private ClassPool classPool;
  36. protected Translator translator;
  37. private final static byte[] endofline = { 0x0d, 0x0a };
  38. private byte[] filebuffer = new byte[4096];
  39. private final static int typeHtml = 1;
  40. private final static int typeClass = 2;
  41. private final static int typeGif = 3;
  42. private final static int typeJpeg = 4;
  43. private final static int typeText = 5;
  44. /**
  45. * If this field is not null, the class files taken from
  46. * <code>ClassPool</code> are written out under the directory
  47. * specified by this field. The directory name must not end
  48. * with a directory separator.
  49. */
  50. public String debugDir = null;
  51. /**
  52. * The top directory of html (and .gif, .class, ...) files.
  53. * It must end with the directory separator such as "/".
  54. * (For portability, "/" should be used as the directory separator.
  55. * Javassist automatically translates "/" into a platform-dependent
  56. * character.)
  57. * If this field is null, the top directory is the current one where
  58. * the JVM is running.
  59. *
  60. * <p>If the given URL indicates a class file and the class file
  61. * is not found under the directory specified by this variable,
  62. * then <code>Class.getResourceAsStream()</code> is called
  63. * for searching the Java class paths.
  64. */
  65. public String htmlfileBase = null;
  66. /**
  67. * Starts a web server.
  68. * The port number is specified by the first argument.
  69. */
  70. public static void main(String[] args) throws IOException {
  71. if (args.length == 1) {
  72. Webserver web = new Webserver(args[0]);
  73. web.run();
  74. }
  75. else
  76. System.err.println(
  77. "Usage: java javassist.tools.web.Webserver <port number>");
  78. }
  79. /**
  80. * Constructs a web server.
  81. *
  82. * @param port port number
  83. */
  84. public Webserver(String port) throws IOException {
  85. this(Integer.parseInt(port));
  86. }
  87. /**
  88. * Constructs a web server.
  89. *
  90. * @param port port number
  91. */
  92. public Webserver(int port) throws IOException {
  93. socket = new ServerSocket(port);
  94. classPool = null;
  95. translator = null;
  96. }
  97. /**
  98. * Requests the web server to use the specified
  99. * <code>ClassPool</code> object for obtaining a class file.
  100. */
  101. public void setClassPool(ClassPool loader) {
  102. classPool = loader;
  103. }
  104. /**
  105. * Adds a translator, which is called whenever a client requests
  106. * a class file.
  107. *
  108. * @param cp the <code>ClassPool</code> object for obtaining
  109. * a class file.
  110. * @param t a translator.
  111. */
  112. public void addTranslator(ClassPool cp, Translator t)
  113. throws NotFoundException, CannotCompileException
  114. {
  115. classPool = cp;
  116. translator = t;
  117. t.start(classPool);
  118. }
  119. /**
  120. * Closes the socket.
  121. */
  122. public void end() throws IOException {
  123. socket.close();
  124. }
  125. /**
  126. * Prints a log message.
  127. */
  128. public void logging(String msg) {
  129. System.out.println(msg);
  130. }
  131. /**
  132. * Prints a log message.
  133. */
  134. public void logging(String msg1, String msg2) {
  135. System.out.print(msg1);
  136. System.out.print(" ");
  137. System.out.println(msg2);
  138. }
  139. /**
  140. * Prints a log message.
  141. */
  142. public void logging(String msg1, String msg2, String msg3) {
  143. System.out.print(msg1);
  144. System.out.print(" ");
  145. System.out.print(msg2);
  146. System.out.print(" ");
  147. System.out.println(msg3);
  148. }
  149. /**
  150. * Prints a log message with indentation.
  151. */
  152. public void logging2(String msg) {
  153. System.out.print(" ");
  154. System.out.println(msg);
  155. }
  156. /**
  157. * Begins the HTTP service.
  158. */
  159. public void run() {
  160. System.err.println("ready to service...");
  161. for (;;)
  162. try {
  163. ServiceThread th = new ServiceThread(this, socket.accept());
  164. th.start();
  165. }
  166. catch (IOException e) {
  167. logging(e.toString());
  168. }
  169. }
  170. final void process(Socket clnt) throws IOException {
  171. InputStream in = new BufferedInputStream(clnt.getInputStream());
  172. String cmd = readLine(in);
  173. logging(clnt.getInetAddress().getHostName(),
  174. new Date().toString(), cmd);
  175. while (skipLine(in) > 0){
  176. }
  177. OutputStream out = new BufferedOutputStream(clnt.getOutputStream());
  178. try {
  179. doReply(in, out, cmd);
  180. }
  181. catch (BadHttpRequest e) {
  182. replyError(out, e);
  183. }
  184. out.flush();
  185. in.close();
  186. out.close();
  187. clnt.close();
  188. }
  189. private String readLine(InputStream in) throws IOException {
  190. StringBuffer buf = new StringBuffer();
  191. int c;
  192. while ((c = in.read()) >= 0 && c != 0x0d)
  193. buf.append((char)c);
  194. in.read(); /* skip 0x0a (LF) */
  195. return buf.toString();
  196. }
  197. private int skipLine(InputStream in) throws IOException {
  198. int c;
  199. int len = 0;
  200. while ((c = in.read()) >= 0 && c != 0x0d)
  201. ++len;
  202. in.read(); /* skip 0x0a (LF) */
  203. return len;
  204. }
  205. /**
  206. * Proceses a HTTP request from a client.
  207. *
  208. * @param out the output stream to a client
  209. * @param cmd the command received from a client
  210. */
  211. public void doReply(InputStream in, OutputStream out, String cmd)
  212. throws IOException, BadHttpRequest
  213. {
  214. int len;
  215. int fileType;
  216. String filename, urlName;
  217. if (cmd.startsWith("GET /"))
  218. filename = urlName = cmd.substring(5, cmd.indexOf(' ', 5));
  219. else
  220. throw new BadHttpRequest();
  221. if (filename.endsWith(".class"))
  222. fileType = typeClass;
  223. else if (filename.endsWith(".html") || filename.endsWith(".htm"))
  224. fileType = typeHtml;
  225. else if (filename.endsWith(".gif"))
  226. fileType = typeGif;
  227. else if (filename.endsWith(".jpg"))
  228. fileType = typeJpeg;
  229. else
  230. fileType = typeText; // or textUnknown
  231. len = filename.length();
  232. if (fileType == typeClass
  233. && letUsersSendClassfile(out, filename, len))
  234. return;
  235. checkFilename(filename, len);
  236. if (htmlfileBase != null)
  237. filename = htmlfileBase + filename;
  238. if (File.separatorChar != '/')
  239. filename = filename.replace('/', File.separatorChar);
  240. File file = new File(filename);
  241. if (file.canRead()) {
  242. sendHeader(out, file.length(), fileType);
  243. FileInputStream fin = new FileInputStream(file);
  244. for (;;) {
  245. len = fin.read(filebuffer);
  246. if (len <= 0)
  247. break;
  248. else
  249. out.write(filebuffer, 0, len);
  250. }
  251. fin.close();
  252. return;
  253. }
  254. // If the file is not found under the html-file directory,
  255. // then Class.getResourceAsStream() is tried.
  256. if (fileType == typeClass) {
  257. InputStream fin
  258. = getClass().getResourceAsStream("/" + urlName);
  259. if (fin != null) {
  260. ByteArrayOutputStream barray = new ByteArrayOutputStream();
  261. for (;;) {
  262. len = fin.read(filebuffer);
  263. if (len <= 0)
  264. break;
  265. else
  266. barray.write(filebuffer, 0, len);
  267. }
  268. byte[] classfile = barray.toByteArray();
  269. sendHeader(out, classfile.length, typeClass);
  270. out.write(classfile);
  271. fin.close();
  272. return;
  273. }
  274. }
  275. throw new BadHttpRequest();
  276. }
  277. private void checkFilename(String filename, int len)
  278. throws BadHttpRequest
  279. {
  280. for (int i = 0; i < len; ++i) {
  281. char c = filename.charAt(i);
  282. if (!Character.isJavaIdentifierPart(c) && c != '.' && c != '/')
  283. throw new BadHttpRequest();
  284. }
  285. if (filename.indexOf("..") >= 0)
  286. throw new BadHttpRequest();
  287. }
  288. private boolean letUsersSendClassfile(OutputStream out,
  289. String filename, int length)
  290. throws IOException, BadHttpRequest
  291. {
  292. if (classPool == null)
  293. return false;
  294. byte[] classfile;
  295. String classname
  296. = filename.substring(0, length - 6).replace('/', '.');
  297. try {
  298. if (translator != null)
  299. translator.onLoad(classPool, classname);
  300. CtClass c = classPool.get(classname);
  301. classfile = c.toBytecode();
  302. if (debugDir != null)
  303. c.writeFile(debugDir);
  304. }
  305. catch (Exception e) {
  306. throw new BadHttpRequest(e);
  307. }
  308. sendHeader(out, classfile.length, typeClass);
  309. out.write(classfile);
  310. return true;
  311. }
  312. private void sendHeader(OutputStream out, long dataLength, int filetype)
  313. throws IOException
  314. {
  315. out.write("HTTP/1.0 200 OK".getBytes());
  316. out.write(endofline);
  317. out.write("Content-Length: ".getBytes());
  318. out.write(Long.toString(dataLength).getBytes());
  319. out.write(endofline);
  320. if (filetype == typeClass)
  321. out.write("Content-Type: application/octet-stream".getBytes());
  322. else if (filetype == typeHtml)
  323. out.write("Content-Type: text/html".getBytes());
  324. else if (filetype == typeGif)
  325. out.write("Content-Type: image/gif".getBytes());
  326. else if (filetype == typeJpeg)
  327. out.write("Content-Type: image/jpg".getBytes());
  328. else if (filetype == typeText)
  329. out.write("Content-Type: text/plain".getBytes());
  330. out.write(endofline);
  331. out.write(endofline);
  332. }
  333. private void replyError(OutputStream out, BadHttpRequest e)
  334. throws IOException
  335. {
  336. logging2("bad request: " + e.toString());
  337. out.write("HTTP/1.0 400 Bad Request".getBytes());
  338. out.write(endofline);
  339. out.write(endofline);
  340. out.write("<H1>Bad Request</H1>".getBytes());
  341. }
  342. }
  343. class ServiceThread extends Thread {
  344. Webserver web;
  345. Socket sock;
  346. public ServiceThread(Webserver w, Socket s) {
  347. web = w;
  348. sock = s;
  349. }
  350. public void run() {
  351. try {
  352. web.process(sock);
  353. }
  354. catch (IOException e) {
  355. }
  356. }
  357. }