-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAwesomeHTTP.java
More file actions
217 lines (184 loc) · 5.59 KB
/
AwesomeHTTP.java
File metadata and controls
217 lines (184 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class AwesomeHTTP extends Thread {
public static void main(String[] args) {
int port = 0;
if(args.length != 1){
System.out.println("Usage: java AwesomeHTTP portnumber");
System.exit(1);
}
try {
port = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
}
if(port <=0 || port >= 65536) {
System.out.println("That is not a valid portnumber");
System.exit(2);
}
try {
ServerSocket s = new ServerSocket(port);
while (true) {
Socket c = s.accept();
AwesomeHTTP t = new AwesomeHTTP(c);
t.start();
}
} catch (IOException e) {
System.out.println("Network error:\n");
e.printStackTrace();
}
}
private Socket socket;
public AwesomeHTTP(Socket s) {
super(s.getInetAddress().toString());
this.socket = s;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
StringBuilder requestString = new StringBuilder();
String line = in.readLine();
while (line != null && !line.isEmpty()) {
requestString.append(line);
requestString.append('\n');
line = in.readLine();
}
if (line != null) {
try {
HttpRequest request = new HttpRequest(requestString.toString());
handleRequest(request).writeOn(out);
out.flush();
} catch (HttpRequest.InvalidHttpRequest e) {
new HttpResponse(400).writeOn(out);
}
}
out.close();
in.close();
socket.close();
} catch (IOException e) {
System.out.println("Netzwerkfehler ist aufgetreten:");
e.printStackTrace();
}
}
private HttpResponse handleRequest(HttpRequest request) {
if (!request.getMethod().equals("GET")) {
HttpResponse response = new HttpResponse(405);
response.addHeader("Allow", "GET");
return response;
}
if (!request.getPath().startsWith("/")) {
return new HttpResponse(404);
}
File f = new File(securePath(request.getPath()));
if (!f.exists() || !f.canRead()) {
return new HttpResponse(404);
}
if (request.getHeader("If-Modified-Since") != null) {
Date d = HttpUtils.parseDate(request.getHeader("If-Modified-Since"));
if(d != null && d.compareTo(new Date(f.lastModified())) >= 0)
return new HttpResponse(304);
}
HttpResponse response = new HttpResponse(200);
if (f.isDirectory()) {
File indexFile = new File(f, "/index.html");
if(indexFile.exists() && indexFile.canRead() && !indexFile.isDirectory()) {
f = indexFile;
}
}
if(f.isDirectory()) {
response.setData(renderDirectory(f, request.getPath()));
response.addHeader("Content-Type", "text/html; charset=utf-8");
} else {
byte[] b = new byte[(int) f.length()];
try {
FileInputStream fis = new FileInputStream(f);
fis.read(b);
} catch (IOException e) {
e.printStackTrace();
return new HttpResponse(500);
}
response.setData(b);
String mimeType = URLConnection.guessContentTypeFromName(f.getName());
if (mimeType != null) {
if (mimeType.startsWith("text/")) {
mimeType += "; charset=utf-8";
}
response.addHeader("Content-Type", mimeType);
}
}
response.addHeader("Last-Modified", HttpUtils.formatDate(
new Date(f.lastModified())));
return response;
}
private String securePath(String path) {
if (File.pathSeparatorChar != '/')
path = path.replace(File.pathSeparatorChar, '_');
List<String> parts = Arrays.asList(path.split("/"));
for (int i = 0; i < parts.size();) {
if (parts.get(i).equals(".")) {
parts.remove(i);
} else if (parts.get(i).equals("..")) {
parts.remove(i);
if (i > 0)
parts.remove(--i);
} else {
i++;
}
}
path = "." + HttpUtils.join(parts, "/");
if (File.separatorChar != '/')
path = path.replace('/', File.separatorChar);
return path;
}
private byte[] renderDirectory(File dir, String pathname) {
if(!pathname.endsWith("/"))
pathname += "/";
StringBuilder buffer = new StringBuilder();
buffer.append("<!DOCTYPE html>\n");
buffer.append("<html lang=\"en\" xml:lang=\"en\"><head><title>Index of ");
buffer.append(HttpUtils.escapeHtml(pathname));
buffer.append("</title></head>\n");
buffer.append("<body>\n");
buffer.append("<h1>Index of ");
buffer.append(HttpUtils.escapeHtml(pathname));
buffer.append("</h1>\n");
buffer.append("<table>\n");
buffer.append("<tr><th> </th><th>Name</th><th>Last Modified</th><th>Size</th></tr>\n");
File[] files = dir.listFiles();
for(File f: files) {
buffer.append("<tr><td>");
if(f.isDirectory())
buffer.append("[DIR]");
buffer.append("</td><td><a href=\"");
buffer.append(HttpUtils.escapeHtml(pathname));
buffer.append(HttpUtils.escapeHtml(f.getName()));
buffer.append("\">");
buffer.append(HttpUtils.escapeHtml(f.getName()));
buffer.append("</a></td><td>");
buffer.append(HttpUtils.formatDate(new Date(f.lastModified())));
buffer.append("</td><td>");
buffer.append(f.length());
buffer.append("</td></tr>\n");
}
buffer.append("</table>\n");
buffer.append("Awesome HTTP-Server");
buffer.append("</body></html>");
try {
return buffer.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}