Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.74 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. import java.text.DateFormat;
  5. import java.text.SimpleDateFormat;
  6. import java.util.*;
  7.  
  8.  
  9. /**
  10. * Clasa ce implementeaza parsarea header-elor HTTP.
  11. * Se interpreteaza cererea utilizatorului.
  12. *Se livreaza pagina ceruta, in cazul in care aceasta exista.
  13. * @author Apostol Ioana
  14. */
  15.  
  16. public class HTTP_parser{
  17. /**
  18. * Declararea si instantierea membrilor clasei Parser
  19. * Realizarea administrarii conexiunii clientului
  20. */
  21. static final File WEB_ROOT = new File(".");
  22. static final String DEFAULT_FILE = "index.html";
  23. static final String MOVED_PERMANENTLY = "301.html";
  24. static final String BAD_REQUEST = "400.html";
  25. static final String UNAUTHORIZED= "401.html";
  26. static final String FILE_NOT_FOUND = "404.html";
  27. static final String INTERNAL_SERVER_ERR = "500.html";
  28. static final String NOT_IMPLEMENTED = "501.html";
  29. static final String HTTPversion_NOTsupported = "505.html";
  30. static final boolean verbose = true;
  31. static String fileRequested=null;
  32. static Logger a = Logger.getInstance();
  33. static String mod = ReadFile.getLoglevel();
  34. private static int PortClient;
  35. public static void Parser(Socket connect) {
  36.  
  37. PortClient=JavaHTTPServer.getPortClient();
  38. BufferedReader in = null;
  39. PrintWriter out = null;
  40. BufferedOutputStream dataOut = null;
  41. // String fileRequested = null;
  42.  
  43. try {
  44. // Se citesc caracterele de la client prin intermediul stream-ului de input din socket
  45. in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
  46. // Se obtine stream-ul de output de caractere catre client (pentru headere)
  47. out = new PrintWriter(connect.getOutputStream());
  48. // Se obtine stream-ul binar de output catre client (pentru datele cerute)
  49. dataOut = new BufferedOutputStream(connect.getOutputStream());
  50.  
  51. // Se citeste prima linie din cererea clientului
  52. String input = in.readLine();
  53. // se interpreteaza cererea cu un string tokenizer
  54. StringTokenizer parse = new StringTokenizer(input);
  55. String method = parse.nextToken().toUpperCase(); //Se obtine metoda HTTP a clientului
  56. // Se obtine pagina ceruta
  57. fileRequested = parse.nextToken().toLowerCase();
  58.  
  59. if (!method.equals("GET") && !method.equals("POST")) {
  60. NotImplemented(out, dataOut, fileRequested);
  61. } else {
  62. if (fileRequested.endsWith("/")) {
  63. fileRequested += DEFAULT_FILE;
  64. }
  65.  
  66. File file = new File(WEB_ROOT, fileRequested);
  67. int fileLength = (int) file.length();
  68. //Se returneaza tipul MIME(Multipurpose Internet Mail Extensions)
  69. String content = GetMimeType.getType(fileRequested);
  70. String[] phpCode;
  71. if (method.equals("GET")) {
  72. /*if(content.equals("text/html")){
  73. if(SenderPHP.PHP_identifier(fileRequested))
  74. phpCode = SenderPHP.SendFileRequested(fileRequested);
  75. } */
  76. byte[] fileData = readFileData(file, fileLength);
  77. // Se trimit header-ele HTTP
  78. out.println("HTTP/1.1 200 OK");
  79. out.println("Server: Java HTTP Server: 1.0");
  80. out.println("Date: " + new Date());
  81. out.println("Content-type: " + content);
  82. out.println("Content-length: " + fileLength);
  83. out.println();
  84. out.flush();
  85. Logger.notice= " ";
  86. Logger.notice += PortClient;
  87. Logger.notice += " GET ";
  88. Logger.notice += fileRequested ;
  89. Logger.notice += " 200 Ok ";
  90. Logger.notice += new Date();
  91. Logger.notice += "\n";
  92. if(Objects.equals(mod,"verbose"))
  93. a.WriteFile();
  94.  
  95. dataOut.write(fileData, 0, fileLength);
  96. dataOut.flush();
  97. }
  98. if(method.equals("POST")){
  99. File fileToRead = new File(WEB_ROOT, fileRequested);
  100.  
  101. int fileLen = (int) file.length();
  102. if(fileToRead.isDirectory()){
  103.  
  104. try {
  105. BadRequest(out,dataOut,fileRequested);
  106. } catch (IOException ioe1) {
  107. System.err.println("Bad Request : ");
  108. }
  109. }
  110.  
  111. String contentType = GetMimeType.getType(fileRequested);
  112. if(contentType == null || !contentType.equals("application/x-www-form-urlencoded")){
  113. try {
  114. InternalServerError(out, dataOut, fileRequested);
  115. } catch (IOException ioe1) {
  116. Logger.error = "Server error";
  117. if(Objects.equals(mod,"error"))
  118. a.WriteFile1();
  119. }
  120. }
  121.  
  122. String extension = fileRequested.substring(fileRequested.lastIndexOf('.') + 1);
  123. if(!extension.equalsIgnoreCase("cgi")){
  124. try {
  125. Unauthorized(out, dataOut, fileRequested);
  126. } catch (IOException ioe1) {
  127. System.err.println("Unauthorized : ");
  128. Logger.error = "Unauthorized ";
  129. if(Objects.equals(mod,"error"))
  130. a.WriteFile1(); }
  131. }
  132.  
  133. ProcessBuilder pb = new ProcessBuilder(fileToRead.getAbsoluteFile().toString());
  134.  
  135. Map<String, String> env = pb.environment();
  136. env.put("SCRIPT_NAME", fileRequested);
  137. ((Map) env).put("CONTENT_LENGTH", "" + fileLen);
  138. env.put("SERVER_NAME", connect.getInetAddress().toString());
  139. env.put("SERVER_PORT", "" + connect.getPort());
  140.  
  141. String responsePayload = readInputStream(connect.getInputStream());
  142. String status;
  143. if(responsePayload.equals("")){
  144. status = "HTTP/1.0 204 No Content";
  145. }
  146. else status = "HTTP/1.0 200 OK";
  147.  
  148. //set headers again
  149. String headerLines = addHeaders(fileToRead, responsePayload.length(),contentType);
  150. }
  151. }
  152.  
  153. } catch (FileNotFoundException fnfe) {
  154. try {
  155. fileNotFound(out, dataOut, fileRequested);
  156. } catch (IOException ioe) {
  157. System.err.println("Error with file not found exception : " + ioe.getMessage());
  158. }
  159.  
  160. } catch (IOException e) {
  161. e.printStackTrace();
  162. } finally {
  163. try {
  164. in.close();
  165. out.close();
  166. dataOut.close();
  167. connect.close(); // Se inchide conexiunea
  168. } catch (Exception e) {
  169. System.err.println("Error closing stream : " + e.getMessage());
  170. }
  171.  
  172. }
  173. }
  174.  
  175. /**
  176. * Se citeste si se returneaza marimea paginii cerute, in cazul in care aceasta exista.
  177. * In caz contrar, se arunca o exceptie si se inchide fisierul.
  178. */
  179.  
  180. static byte[] readFileData(File file, int fileLength) throws IOException {
  181. FileInputStream fileIn = null;
  182. byte[] fileData = new byte[fileLength];
  183.  
  184. try {
  185. fileIn = new FileInputStream(file);
  186. fileIn.read(fileData);
  187. } finally {
  188. if (fileIn != null)
  189. fileIn.close();
  190. }
  191.  
  192. return fileData;
  193. }
  194.  
  195.  
  196. /**
  197. * Se trateaza cazul in care utilizatorul cere o pagina care nu exista.
  198. * Pentru aceasta situatie, codul de return este "404 File Not Found".
  199. */
  200.  
  201. private static void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  202. Logger a = Logger.getInstance();
  203. File file = new File(WEB_ROOT, FILE_NOT_FOUND);
  204. int fileLength = (int) file.length();
  205. String content = "text/html";
  206. byte[] fileData = readFileData(file, fileLength);
  207.  
  208. out.println("HTTP/1.1 404 File Not Found");
  209. out.println("Server: Java HTTP Server: 1.0");
  210. out.println("Date: " + new Date());
  211. out.println("Content-type: " + content);
  212. out.println("Content-length: " + fileLength);
  213. out.println();
  214. out.flush();
  215. dataOut.write(fileData, 0, fileLength);
  216. dataOut.flush();
  217. Logger.notice = " ";
  218. Logger.notice += PortClient;
  219. Logger.notice += " GET ";
  220. Logger.notice += "404 ";
  221. Logger.notice += fileRequested ;
  222. Logger.notice += " File Not Found ";
  223. Logger.notice += new Date();
  224. Logger.notice += "\n";
  225. if(Objects.equals(mod,"error"))
  226. a.WriteFile();
  227. }
  228.  
  229. /**
  230. * Codul de raspuns al statusului de redirect indica faptul ca resursa ceruta a fost mutata definitiv catre alt URL.
  231. * Browser-ul redirecteaza utilizatorul la aceasta pagina si cauta sa updateze link-urile catre resura ceruta.
  232. */
  233. private static void movedPermanently(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  234. File file = new File(WEB_ROOT, MOVED_PERMANENTLY);
  235. int fileLength = (int) file.length();
  236. String content = "text/html";
  237. byte[] fileData = readFileData(file, fileLength);
  238.  
  239. out.println("HTTP/1.1 301 Moved Permanently");
  240. out.println("Server: Java HTTP Server: 1.0");
  241. out.println("Date: " + new Date());
  242. out.println("Content-type: " + content);
  243. out.println("Content-length: " + fileLength);
  244. out.println();
  245. out.flush();
  246. Logger.notice = " ";
  247. Logger.notice += PortClient;
  248. Logger.notice += " GET ";
  249. Logger.notice += "301 ";
  250. Logger.notice += fileRequested ;
  251. Logger.notice += " Moved Permanently ";
  252. Logger.notice += new Date();
  253. Logger.notice += "\n";
  254. if(Objects.equals(mod,"error"))
  255. a.WriteFile();
  256.  
  257. dataOut.write(fileData, 0, fileLength);
  258. dataOut.flush();
  259. }
  260.  
  261. /**
  262. * Cererea nu poate fi aplicata, deoarece lipsesc credentialele valide pentru autentificare, necesare resursei cerute.
  263. */
  264. private static void Unauthorized(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  265. File file = new File(WEB_ROOT, UNAUTHORIZED);
  266. int fileLength = (int) file.length();
  267. String content = "text/html";
  268. byte[] fileData = readFileData(file, fileLength);
  269.  
  270. out.println("HTTP/1.1 401 Unauthorized");
  271. out.println("Server: Java HTTP Server: 1.0");
  272. out.println("Date: " + new Date());
  273. out.println("Content-type: " + content);
  274. out.println("Content-length: " + fileLength);
  275. out.println();
  276. out.flush();
  277. Logger.notice = " ";
  278. Logger.notice += PortClient;
  279. Logger.notice += " GET ";
  280. Logger.notice += "401 ";
  281. Logger.notice += fileRequested ;
  282. Logger.notice += " Unauthorized ";
  283. Logger.notice += new Date();
  284. Logger.notice += "\n";
  285. if(Objects.equals(mod,"error"))
  286. a.WriteFile();
  287.  
  288. dataOut.write(fileData, 0, fileLength);
  289. dataOut.flush();
  290. }
  291.  
  292. /**
  293. * Se indica faptul ca serverul nu a putut procesa cererea trimisa de catre client din cauza sintaxei invalide
  294. */
  295. private static void BadRequest(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  296. File file = new File(WEB_ROOT, BAD_REQUEST);
  297. int fileLength = (int) file.length();
  298. String content = "text/html";
  299. byte[] fileData = readFileData(file, fileLength);
  300.  
  301. out.println("HTTP/1.1 400 Bad Request");
  302. out.println("Server: Java HTTP Server: 1.0");
  303. out.println("Date: " + new Date());
  304. out.println("Content-type: " + content);
  305. out.println("Content-length: " + fileLength);
  306. out.println();
  307. out.flush();
  308. Logger.notice = " ";
  309. Logger.notice += PortClient;
  310. Logger.notice += " GET ";
  311. Logger.notice += "400 ";
  312. Logger.notice += fileRequested ;
  313. Logger.notice += " Bad Request ";
  314. Logger.notice += new Date();
  315. Logger.notice += "\n";
  316. if(Objects.equals(mod,"error"))
  317. a.WriteFile();
  318.  
  319.  
  320.  
  321. dataOut.write(fileData, 0, fileLength);
  322. dataOut.flush();
  323. }
  324. /**
  325. * Apare in momentul in care ceva nu functioneaza pe serverul site-ului, dar serverul nu poate specifica exact ce anume.
  326. */
  327. private static void InternalServerError(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  328. File file = new File(WEB_ROOT, INTERNAL_SERVER_ERR);
  329. int fileLength = (int) file.length();
  330. String content = "text/html";
  331. byte[] fileData = readFileData(file, fileLength);
  332.  
  333. out.println("HTTP/1.1 500 Internal Server Error");
  334. out.println("Server: Java HTTP Server: 1.0");
  335. out.println("Date: " + new Date());
  336. out.println("Content-type: " + content);
  337. out.println("Content-length: " + fileLength);
  338. out.println();
  339. out.flush();
  340. Logger.notice = " ";
  341. Logger.notice += PortClient;
  342. Logger.notice += " GET ";
  343. Logger.notice += "500 ";
  344. Logger.notice += fileRequested ;
  345. Logger.notice += " Internal Server Error ";
  346. Logger.notice += new Date();
  347. Logger.notice += "\n";
  348. if(Objects.equals(mod,"error"))
  349. a.WriteFile();
  350.  
  351.  
  352. dataOut.write(fileData, 0, fileLength);
  353. dataOut.flush();
  354. }
  355.  
  356. /**
  357. * Este tratat cazul in care serverul nu poate realiza functionalitatea ceruta pentru a indeplini cererea facuta de catre utilizator
  358. */
  359. private static void NotImplemented(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  360. File file = new File(WEB_ROOT, NOT_IMPLEMENTED);
  361. int fileLength = (int) file.length();
  362. String content = "text/html";
  363. byte[] fileData = readFileData(file, fileLength);
  364.  
  365. out.println("HTTP/1.1 501 Not Implemented");
  366. out.println("Server: Java HTTP Server: 1.0");
  367. out.println("Date: " + new Date());
  368. out.println("Content-type: " + content);
  369. out.println("Content-length: " + fileLength);
  370. out.println();
  371. out.flush();
  372. Logger.notice = " ";
  373. Logger.notice += PortClient;
  374. Logger.notice = " GET ";
  375. Logger.notice += "501 ";
  376. Logger.notice += fileRequested ;
  377. Logger.notice += " Not Implemented ";
  378. Logger.notice += new Date();
  379. Logger.notice += "\n";
  380. if(Objects.equals(mod,"error"))
  381. a.WriteFile();
  382.  
  383.  
  384. dataOut.write(fileData, 0, fileLength);
  385. dataOut.flush();
  386. }
  387.  
  388. /**
  389. * Se indica faptul ca serverul nu lucreaza cu versiunea de HTTP folosita in request
  390. */
  391.  
  392. private static void NotSupported(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
  393. File file = new File(WEB_ROOT, HTTPversion_NOTsupported);
  394. int fileLength = (int) file.length();
  395. String contentMimeType = "text/html";
  396. //read content to return to client
  397. byte[] fileData = readFileData(file, fileLength);
  398.  
  399.  
  400. out.println("HTTP/1.1 505 Not Supported");
  401. out.println("Server: Java HTTP Server: 1.0");
  402. out.println("Date: " + new Date());
  403. out.println("Content-type: " + contentMimeType);
  404. out.println("Content-length: " + fileLength);
  405. out.println();
  406. out.flush();
  407.  
  408. Logger.notice = " ";
  409. Logger.notice += PortClient;
  410. Logger.notice = " 505 ";
  411. Logger.notice += "400 ";
  412. Logger.notice += fileRequested ;
  413. Logger.notice += " Not Supported ";
  414. Logger.notice += new Date();
  415. Logger.notice += "\n";
  416. if(Objects.equals(mod,"error"))
  417. a.WriteFile();
  418.  
  419.  
  420. dataOut.write(fileData, 0, fileLength);
  421. dataOut.flush();
  422. }
  423.  
  424. public String getFrom(String request) throws IOException{
  425. String [] lines = request.split("\r\n");
  426. for(String i: lines){
  427. String field = i.split(" ")[0];
  428. if(field.equals("From:")){
  429. return i.substring(6);
  430. }
  431. }
  432. return null;
  433. }
  434.  
  435. public static String readInputStream(InputStream is) throws IOException{
  436. String retval = "";
  437. BufferedReader buff = new BufferedReader(new InputStreamReader(is));
  438. while(buff.ready()){
  439. retval += (char)buff.read();
  440. }
  441. return retval;
  442. }
  443. public static String addHeaders(File fileToRead, int CL, String type){
  444.  
  445. String typeLine = "Content-Type: ";
  446.  
  447. typeLine += type + '\r' + '\n';
  448.  
  449. String lengthLine = "Content-Length: "+ CL + '\r' + '\n';
  450.  
  451. long time = fileToRead.lastModified();
  452. String modifiedLine = "Last-Modified: " + getFormattedTime(time) + '\r' + '\n';
  453.  
  454. String encodingLine = "Content-Encoding: identity" + '\r' + '\n';
  455.  
  456. String allowLine = "Allow: GET, POST" + '\r' + '\n';
  457.  
  458. String expireLine = "Expires: " + getFormattedTime(System.currentTimeMillis() + 525600) + '\r' + '\n';
  459.  
  460. return typeLine + lengthLine + modifiedLine + encodingLine + allowLine + expireLine;
  461.  
  462.  
  463. }
  464.  
  465. public static String getFormattedTime(long millis){
  466.  
  467. DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
  468. Calendar calendar = Calendar.getInstance();
  469. calendar.setTimeInMillis(millis);
  470.  
  471. String s = formatter.format(calendar.getTime());
  472.  
  473. return s;
  474.  
  475. }
  476. public static String getFileRequested(){
  477. return fileRequested;
  478. }
  479. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement