Serves a context's contents from a file based resource. The file is located by stripping the given context prefix from the request's path, and appending the result to the given base directory. Missing, forbidden and otherwise invalid files return the appropriate error response. Directories a
(File base, String context,
Request req, Response resp)
| 2904 | * @throws IOException if an error occurs |
| 2905 | */ |
| 2906 | public static int serveFile(File base, String context, |
| 2907 | Request req, Response resp) throws IOException { |
| 2908 | String relativePath = req.getPath().substring(context.length()); |
| 2909 | File file = new File(base, relativePath).getCanonicalFile(); |
| 2910 | if (!file.exists() || file.isHidden() || file.getName().startsWith(".")) { |
| 2911 | return 404; |
| 2912 | } else if (!file.canRead() || !file.getPath().startsWith(base.getPath())) { // validate |
| 2913 | return 403; |
| 2914 | } else if (file.isDirectory()) { |
| 2915 | if (relativePath.endsWith("/")) { |
| 2916 | if (!req.getVirtualHost().isAllowGeneratedIndex()) |
| 2917 | return 403; |
| 2918 | resp.send(200, createIndex(file, req.getPath())); |
| 2919 | } else { // redirect to the normalized directory URL ending with '/' |
| 2920 | resp.redirect(req.getBaseURL() + req.getPath() + "/", true); |
| 2921 | } |
| 2922 | } else if (relativePath.endsWith("/")) { |
| 2923 | return 404; // non-directory ending with slash (File constructor removed it) |
| 2924 | } else { |
| 2925 | serveFileContent(file, req, resp); |
| 2926 | } |
| 2927 | return 0; |
| 2928 | } |
| 2929 | |
| 2930 | /** |
| 2931 | * Serves the contents of a file, with its corresponding content type, |
no test coverage detected