/
SimpleWebServer.java
325 lines (302 loc) · 11.3 KB
/
SimpleWebServer.java
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
* Unless otherwise specified through the '@author' tag or comments at
* the top of the file or on a specific portion of the code the following license applies:
*
* Copyright (c) 2014, DoubleDoorDevelopment
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* The header specified or the above copyright notice, this list of conditions
* and the following disclaimer below must be displayed at the top of the source code
* of any web page received while using any part of the service this software provides.
*
* The header to be displayed:
* This page was generated by DoubleDoorDevelopment's D3Backend or a derivative thereof.
*
* Neither the name of the project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.doubledoordev.backend.webserver;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
public abstract class SimpleWebServer extends NanoHTTPD
{
/**
* Common mime type for dynamic content: binary
*/
public static final String MIME_DEFAULT_BINARY = "application/octet-stream";
/**
* Default Index file names.
*/
public static final List<String> INDEX_FILE_NAMES = new ArrayList<String>()
{{
add("index.html");
}};
/**
* Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
*/
private static final Map<String, String> MIME_TYPES = new HashMap<String, String>()
{{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
}};
private final String rootDir;
public SimpleWebServer(String host, int port, String wwwroot)
{
super(host, port);
if (!wwwroot.endsWith("/")) wwwroot += "/";
this.rootDir = wwwroot;
this.init();
}
/**
* Used to initialize and customize the server.
*/
public void init()
{
}
/**
* URL-encodes everything between "/"-characters. Encodes spaces as '%20' instead of '+'.
*/
private String encodeUri(String uri)
{
String newUri = "";
StringTokenizer st = new StringTokenizer(uri, "/ ", true);
while (st.hasMoreTokens())
{
String tok = st.nextToken();
if (tok.equals("/"))
newUri += "/";
else if (tok.equals(" "))
newUri += "%20";
else
{
try
{
newUri += URLEncoder.encode(tok, "UTF-8");
}
catch (UnsupportedEncodingException ignored)
{
}
}
}
return newUri;
}
protected Response respond(String uri)
{
// Remove URL arguments
uri = uri.trim().replace(File.separatorChar, '/');
if (uri.indexOf('?') >= 0)
{
uri = uri.substring(0, uri.indexOf('?'));
}
// Prohibit getting out of current directory
if (uri.startsWith("src/main") || uri.endsWith("src/main") || uri.contains("../"))
{
return getForbiddenResponse("Won't serve ../ for security reasons.");
}
if (!canServeUri(uri))
{
return getNotFoundResponse();
}
Response response = serveResourceFile(uri);
return response != null ? response : getNotFoundResponse();
}
protected Response getNotFoundResponse()
{
return createResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Error 404, file not found.");
}
protected Response getForbiddenResponse(String s)
{
return createResponse(Response.Status.FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: " + s);
}
private boolean canServeUri(String uri)
{
return this.getClass().getResource(rootDir + uri) != null;
}
/**
* Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and HTTP parameters.
*/
Response serveResourceFile(String uri)
{
Response res;
try
{
InputStream stream = getClass().getResourceAsStream(rootDir + uri);
int fileLen = stream.available();
res = createResponse(Response.Status.OK, getMimeTypeForFile(uri), stream);
res.addHeader("Content-Length", "" + fileLen);
}
catch (IOException ioe)
{
res = getForbiddenResponse("Reading file failed.");
}
return res;
}
// Get MIME type from file name extension, if possible
public String getMimeTypeForFile(String uri)
{
int dot = uri.lastIndexOf('.');
String mime = null;
if (dot >= 0)
{
mime = MIME_TYPES.get(uri.substring(dot + 1).toLowerCase());
}
return mime == null ? MIME_DEFAULT_BINARY : mime;
}
// Announce that the file server accepts partial content requests
Response createResponse(Response.Status status, String mimeType, InputStream message)
{
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
// Announce that the file server accepts partial content requests
Response createResponse(Response.Status status, String mimeType, String message)
{
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
private String findIndexFileInDirectory(File directory)
{
for (String fileName : INDEX_FILE_NAMES)
{
File indexFile = new File(directory, fileName);
if (indexFile.exists())
{
return fileName;
}
}
return null;
}
protected String listDirectory(String uri, File f)
{
String heading = "Directory " + uri;
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n" +
"span.dirname { font-weight: bold; }\n" +
"span.filesize { font-size: 75%; }\n" +
"// -->\n" +
"</style>" +
"</head><body><h1>" + heading + "</h1>");
String up = null;
if (uri.length() > 1)
{
String u = uri.substring(0, uri.length() - 1);
int slash = u.lastIndexOf('/');
if (slash >= 0 && slash < u.length())
{
up = uri.substring(0, slash + 1);
}
}
List<String> files = Arrays.asList(f.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return new File(dir, name).isFile();
}
}));
Collections.sort(files);
List<String> directories = Arrays.asList(f.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String name)
{
return new File(dir, name).isDirectory();
}
}));
Collections.sort(directories);
if (up != null || directories.size() + files.size() > 0)
{
msg.append("<ul>");
if (up != null || directories.size() > 0)
{
msg.append("<section class=\"directories\">");
if (up != null)
{
msg.append("<li><a rel=\"directory\" href=\"").append(up).append("\"><span class=\"dirname\">..</span></a></b></li>");
}
for (String directory : directories)
{
String dir = directory + "/";
msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></b></li>");
}
msg.append("</section>");
}
if (files.size() > 0)
{
msg.append("<section class=\"files\">");
for (String file : files)
{
msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>");
File curFile = new File(f, file);
long len = curFile.length();
msg.append(" <span class=\"filesize\">(");
if (len < 1024)
{
msg.append(len).append(" bytes");
}
else if (len < 1024 * 1024)
{
msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
}
else
{
msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10 % 100).append(" MB");
}
msg.append(")</span></li>");
}
msg.append("</section>");
}
msg.append("</ul>");
}
msg.append("</body></html>");
return msg.toString();
}
}