· 10 years ago · Sep 18, 2016, 08:44 PM
1<%@page import="java.util.*,
2 java.net.*,
3 java.text.*,
4 java.util.zip.*,
5 java.io.*"
6%>
7<%!
8 private static final boolean NATIVE_COMMANDS = true;
9
10 private static final boolean READ_ONLY = false;
11 private static final boolean ALLOW_UPLOAD = true;
12
13 private static final boolean RESTRICT_BROWSING = false;
14 private static final boolean RESTRICT_WHITELIST = false;
15 private static final String RESTRICT_PATH = "/etc;/var";
16
17 private static final int UPLOAD_MONITOR_REFRESH = 2;
18 private static final int EDITFIELD_COLS = 85;
19 private static final int EDITFIELD_ROWS = 30;
20 private static final boolean USE_POPUP = true;
21 private static final boolean USE_DIR_PREVIEW = false;
22 private static final int DIR_PREVIEW_NUMBER = 10;
23 private static final String CSS_NAME = "Browser.css";
24 private static final int COMPRESSION_LEVEL = 1;
25 private static final String[] FORBIDDEN_DRIVES = {"a:\\"};
26 private static final String[] COMMAND_INTERPRETER = {"/bin/bash","-c"}; // Unix
27
28 private static final long MAX_PROCESS_RUNNING_TIME = 30 * 1000; //30 seconds
29
30 private static final String SAVE_AS_ZIP = "Download selected files as (z)ip";
31 private static final String RENAME_FILE = "(R)ename File";
32 private static final String DELETE_FILES = "(Del)ete selected files";
33 private static final String CREATE_DIR = "Create (D)ir";
34 private static final String CREATE_FILE = "(C)reate File";
35 private static final String MOVE_FILES = "(M)ove Files";
36 private static final String COPY_FILES = "Cop(y) Files";
37 private static final String LAUNCH_COMMAND = "(L)aunch external program";
38 private static final String UPLOAD_FILES = "Upload";
39
40 private static String tempdir = ".";
41 private static String VERSION_NR = "1.2";
42 private static DateFormat dateFormat = DateFormat.getDateTimeInstance();
43
44 public class UplInfo {
45
46 public long totalSize;
47 public long currSize;
48 public long starttime;
49 public boolean aborted;
50
51 public UplInfo() {
52 totalSize = 0l;
53 currSize = 0l;
54 starttime = System.currentTimeMillis();
55 aborted = false;
56 }
57
58 public UplInfo(int size) {
59 totalSize = size;
60 currSize = 0;
61 starttime = System.currentTimeMillis();
62 aborted = false;
63 }
64
65 public String getUprate() {
66 long time = System.currentTimeMillis() - starttime;
67 if (time != 0) {
68 long uprate = currSize * 1000 / time;
69 return convertFileSize(uprate) + "/s";
70 }
71 else return "n/a";
72 }
73
74 public int getPercent() {
75 if (totalSize == 0) return 0;
76 else return (int) (currSize * 100 / totalSize);
77 }
78
79 public String getTimeElapsed() {
80 long time = (System.currentTimeMillis() - starttime) / 1000l;
81 if (time - 60l >= 0){
82 if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
83 else return time / 60 + ":0" + (time % 60) + "m";
84 }
85 else return time<10 ? "0" + time + "s": time + "s";
86 }
87
88 public String getTimeEstimated() {
89 if (currSize == 0) return "n/a";
90 long time = System.currentTimeMillis() - starttime;
91 time = totalSize * time / currSize;
92 time /= 1000l;
93 if (time - 60l >= 0){
94 if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
95 else return time / 60 + ":0" + (time % 60) + "m";
96 }
97 else return time<10 ? "0" + time + "s": time + "s";
98 }
99
100 }
101
102 public class FileInfo {
103
104 public String name = null, clientFileName = null, fileContentType = null;
105 private byte[] fileContents = null;
106 public File file = null;
107 public StringBuffer sb = new StringBuffer(100);
108
109 public void setFileContents(byte[] aByteArray) {
110 fileContents = new byte[aByteArray.length];
111 System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length);
112 }
113 }
114
115 public static class UploadMonitor {
116
117 static Hashtable uploadTable = new Hashtable();
118
119 static void set(String fName, UplInfo info) {
120 uploadTable.put(fName, info);
121 }
122
123 static void remove(String fName) {
124 uploadTable.remove(fName);
125 }
126
127 static UplInfo getInfo(String fName) {
128 UplInfo info = (UplInfo) uploadTable.get(fName);
129 return info;
130 }
131 }
132
133 public class HttpMultiPartParser {
134
135 private final int ONE_MB = 1024 * 1;
136
137 public Hashtable processData(ServletInputStream is, String boundary, String saveInDir,
138 int clength) throws IllegalArgumentException, IOException {
139 if (is == null) throw new IllegalArgumentException("InputStream");
140 if (boundary == null || boundary.trim().length() < 1) throw new IllegalArgumentException(
141 "\"" + boundary + "\" is an illegal boundary indicator");
142 boundary = "--" + boundary;
143 StringTokenizer stLine = null, stFields = null;
144 FileInfo fileInfo = null;
145 Hashtable dataTable = new Hashtable(5);
146 String line = null, field = null, paramName = null;
147 boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
148 boolean isFile = false;
149 if (saveFiles) { // Create the required directory (including parent dirs)
150 File f = new File(saveInDir);
151 f.mkdirs();
152 }
153 line = getLine(is);
154 if (line == null || !line.startsWith(boundary)) throw new IOException(
155 "Boundary not found; boundary = " + boundary + ", line = " + line);
156 while (line != null) {
157 if (line == null || !line.startsWith(boundary)) return dataTable;
158 line = getLine(is);
159 if (line == null) return dataTable;
160 stLine = new StringTokenizer(line, ";\r\n");
161 if (stLine.countTokens() < 2) throw new IllegalArgumentException(
162 "Bad data in second line");
163 line = stLine.nextToken().toLowerCase();
164 if (line.indexOf("form-data") < 0) throw new IllegalArgumentException(
165 "Bad data in second line");
166 stFields = new StringTokenizer(stLine.nextToken(), "=\"");
167 if (stFields.countTokens() < 2) throw new IllegalArgumentException(
168 "Bad data in second line");
169 fileInfo = new FileInfo();
170 stFields.nextToken();
171 paramName = stFields.nextToken();
172 isFile = false;
173 if (stLine.hasMoreTokens()) {
174 field = stLine.nextToken();
175 stFields = new StringTokenizer(field, "=\"");
176 if (stFields.countTokens() > 1) {
177 if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
178 fileInfo.name = paramName;
179 String value = stFields.nextToken();
180 if (value != null && value.trim().length() > 0) {
181 fileInfo.clientFileName = value;
182 isFile = true;
183 }
184 else {
185 line = getLine(is); // Skip "Content-Type:" line
186 line = getLine(is); // Skip blank line
187 line = getLine(is); // Skip blank line
188 line = getLine(is); // Position to boundary line
189 continue;
190 }
191 }
192 }
193 else if (field.toLowerCase().indexOf("filename") >= 0) {
194 line = getLine(is); // Skip "Content-Type:" line
195 line = getLine(is); // Skip blank line
196 line = getLine(is); // Skip blank line
197 line = getLine(is); // Position to boundary line
198 continue;
199 }
200 }
201 boolean skipBlankLine = true;
202 if (isFile) {
203 line = getLine(is);
204 if (line == null) return dataTable;
205 if (line.trim().length() < 1) skipBlankLine = false;
206 else {
207 stLine = new StringTokenizer(line, ": ");
208 if (stLine.countTokens() < 2) throw new IllegalArgumentException(
209 "Bad data in third line");
210 stLine.nextToken(); // Content-Type
211 fileInfo.fileContentType = stLine.nextToken();
212 }
213 }
214 if (skipBlankLine) {
215 line = getLine(is);
216 if (line == null) return dataTable;
217 }
218 if (!isFile) {
219 line = getLine(is);
220 if (line == null) return dataTable;
221 dataTable.put(paramName, line);
222 // If parameter is dir, change saveInDir to dir
223 if (paramName.equals("dir")) saveInDir = line;
224 line = getLine(is);
225 continue;
226 }
227 try {
228 UplInfo uplInfo = new UplInfo(clength);
229 UploadMonitor.set(fileInfo.clientFileName, uplInfo);
230 OutputStream os = null;
231 String path = null;
232 if (saveFiles) os = new FileOutputStream(path = getFileName(saveInDir,
233 fileInfo.clientFileName));
234 else os = new ByteArrayOutputStream(ONE_MB);
235 boolean readingContent = true;
236 byte previousLine[] = new byte[2 * ONE_MB];
237 byte temp[] = null;
238 byte currentLine[] = new byte[2 * ONE_MB];
239 int read, read3;
240 if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
241 line = null;
242 break;
243 }
244 while (readingContent) {
245 if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
246 line = null;
247 uplInfo.aborted = true;
248 break;
249 }
250 if (compareBoundary(boundary, currentLine)) {
251 os.write(previousLine, 0, read - 2);
252 line = new String(currentLine, 0, read3);
253 break;
254 }
255 else {
256 os.write(previousLine, 0, read);
257 uplInfo.currSize += read;
258 temp = currentLine;
259 currentLine = previousLine;
260 previousLine = temp;
261 read = read3;
262 }//end else
263 }//end while
264 os.flush();
265 os.close();
266 if (!saveFiles) {
267 ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
268 fileInfo.setFileContents(baos.toByteArray());
269 }
270 else fileInfo.file = new File(path);
271 dataTable.put(paramName, fileInfo);
272 uplInfo.currSize = uplInfo.totalSize;
273 }//end try
274 catch (IOException e) {
275 throw e;
276 }
277 }
278 return dataTable;
279 }
280
281 private boolean compareBoundary(String boundary, byte ba[]) {
282 if (boundary == null || ba == null) return false;
283 for (int i = 0; i < boundary.length(); i++)
284 if ((byte) boundary.charAt(i) != ba[i]) return false;
285 return true;
286 }
287
288 private synchronized String getLine(ServletInputStream sis) throws IOException {
289 byte b[] = new byte[1024];
290 int read = sis.readLine(b, 0, b.length), index;
291 String line = null;
292 if (read != -1) {
293 line = new String(b, 0, read);
294 if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1);
295 }
296 return line;
297 }
298
299 public String getFileName(String dir, String fileName) throws IllegalArgumentException {
300 String path = null;
301 if (dir == null || fileName == null) throw new IllegalArgumentException(
302 "dir or fileName is null");
303 int index = fileName.lastIndexOf('/');
304 String name = null;
305 if (index >= 0) name = fileName.substring(index + 1);
306 else name = fileName;
307 index = name.lastIndexOf('\\');
308 if (index >= 0) fileName = name.substring(index + 1);
309 path = dir + File.separator + fileName;
310 if (File.separatorChar == '/') return path.replace('\\', File.separatorChar);
311 else return path.replace('/', File.separatorChar);
312 }
313 } //End of class HttpMultiPartParser
314
315 class FileComp implements Comparator {
316
317 int mode;
318 int sign;
319
320 FileComp() {
321 this.mode = 1;
322 this.sign = 1;
323 }
324
325 /**
326 * @param mode sort by 1=Filename, 2=Size, 3=Date, 4=Type
327 * The default sorting method is by Name
328 * Negative mode means descending sort
329 */
330 FileComp(int mode) {
331 if (mode < 0) {
332 this.mode = -mode;
333 sign = -1;
334 }
335 else {
336 this.mode = mode;
337 this.sign = 1;
338 }
339 }
340
341 public int compare(Object o1, Object o2) {
342 File f1 = (File) o1;
343 File f2 = (File) o2;
344 if (f1.isDirectory()) {
345 if (f2.isDirectory()) {
346 switch (mode) {
347 //Filename or Type
348 case 1:
349 case 4:
350 return sign
351 * f1.getAbsolutePath().toUpperCase().compareTo(
352 f2.getAbsolutePath().toUpperCase());
353 //Filesize
354 case 2:
355 return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
356 //Date
357 case 3:
358 return sign
359 * (new Long(f1.lastModified())
360 .compareTo(new Long(f2.lastModified())));
361 default:
362 return 1;
363 }
364 }
365 else return -1;
366 }
367 else if (f2.isDirectory()) return 1;
368 else {
369 switch (mode) {
370 case 1:
371 return sign
372 * f1.getAbsolutePath().toUpperCase().compareTo(
373 f2.getAbsolutePath().toUpperCase());
374 case 2:
375 return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
376 case 3:
377 return sign
378 * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
379 case 4: { // Sort by extension
380 int tempIndexf1 = f1.getAbsolutePath().lastIndexOf('.');
381 int tempIndexf2 = f2.getAbsolutePath().lastIndexOf('.');
382 if ((tempIndexf1 == -1) && (tempIndexf2 == -1)) { // Neither have an extension
383 return sign
384 * f1.getAbsolutePath().toUpperCase().compareTo(
385 f2.getAbsolutePath().toUpperCase());
386 }
387 // f1 has no extension
388 else if (tempIndexf1 == -1) return -sign;
389 // f2 has no extension
390 else if (tempIndexf2 == -1) return sign;
391 // Both have an extension
392 else {
393 String tempEndf1 = f1.getAbsolutePath().toUpperCase()
394 .substring(tempIndexf1);
395 String tempEndf2 = f2.getAbsolutePath().toUpperCase()
396 .substring(tempIndexf2);
397 return sign * tempEndf1.compareTo(tempEndf2);
398 }
399 }
400 default:
401 return 1;
402 }
403 }
404 }
405 }
406
407 class Writer2Stream extends OutputStream {
408
409 Writer out;
410
411 Writer2Stream(Writer w) {
412 super();
413 out = w;
414 }
415
416 public void write(int i) throws IOException {
417 out.write(i);
418 }
419
420 public void write(byte[] b) throws IOException {
421 for (int i = 0; i < b.length; i++) {
422 int n = b[i];
423 //Convert byte to ubyte
424 n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
425 out.write(n);
426 }
427 }
428
429 public void write(byte[] b, int off, int len) throws IOException {
430 for (int i = off; i < off + len; i++) {
431 int n = b[i];
432 n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
433 out.write(n);
434 }
435 }
436 } //End of class Writer2Stream
437
438 static Vector expandFileList(String[] files, boolean inclDirs) {
439 Vector v = new Vector();
440 if (files == null) return v;
441 for (int i = 0; i < files.length; i++)
442 v.add(new File(URLDecoder.decode(files[i])));
443 for (int i = 0; i < v.size(); i++) {
444 File f = (File) v.get(i);
445 if (f.isDirectory()) {
446 File[] fs = f.listFiles();
447 for (int n = 0; n < fs.length; n++)
448 v.add(fs[n]);
449 if (!inclDirs) {
450 v.remove(i);
451 i--;
452 }
453 }
454 }
455 return v;
456 }
457
458 static String getDir(String dir, String name) {
459 if (!dir.endsWith(File.separator)) dir = dir + File.separator;
460 File mv = new File(name);
461 String new_dir = null;
462 if (!mv.isAbsolute()) {
463 new_dir = dir + name;
464 }
465 else new_dir = name;
466 return new_dir;
467 }
468
469 static String convertFileSize(long size) {
470 int divisor = 1;
471 String unit = "bytes";
472 if (size >= 1024 * 1024) {
473 divisor = 1024 * 1024;
474 unit = "MB";
475 }
476 else if (size >= 1024) {
477 divisor = 1024;
478 unit = "KB";
479 }
480 if (divisor == 1) return size / divisor + " " + unit;
481 String aftercomma = "" + 100 * (size % divisor) / divisor;
482 if (aftercomma.length() == 1) aftercomma = "0" + aftercomma;
483 return size / divisor + "." + aftercomma + " " + unit;
484 }
485
486 static void copyStreams(InputStream in, OutputStream out, byte[] buffer) throws IOException {
487 copyStreamsWithoutClose(in, out, buffer);
488 in.close();
489 out.close();
490 }
491
492 static void copyStreamsWithoutClose(InputStream in, OutputStream out, byte[] buffer)
493 throws IOException {
494 int b;
495 while ((b = in.read(buffer)) != -1)
496 out.write(buffer, 0, b);
497 }
498
499 static String getMimeType(String fName) {
500 fName = fName.toLowerCase();
501 if (fName.endsWith(".jpg") || fName.endsWith(".jpeg") || fName.endsWith(".jpe")) return "image/jpeg";
502 else if (fName.endsWith(".gif")) return "image/gif";
503 else if (fName.endsWith(".pdf")) return "application/pdf";
504 else if (fName.endsWith(".htm") || fName.endsWith(".html") || fName.endsWith(".shtml")) return "text/html";
505 else if (fName.endsWith(".avi")) return "video/x-msvideo";
506 else if (fName.endsWith(".mov") || fName.endsWith(".qt")) return "video/quicktime";
507 else if (fName.endsWith(".mpg") || fName.endsWith(".mpeg") || fName.endsWith(".mpe")) return "video/mpeg";
508 else if (fName.endsWith(".zip")) return "application/zip";
509 else if (fName.endsWith(".tiff") || fName.endsWith(".tif")) return "image/tiff";
510 else if (fName.endsWith(".rtf")) return "application/rtf";
511 else if (fName.endsWith(".mid") || fName.endsWith(".midi")) return "audio/x-midi";
512 else if (fName.endsWith(".xl") || fName.endsWith(".xls") || fName.endsWith(".xlv")
513 || fName.endsWith(".xla") || fName.endsWith(".xlb") || fName.endsWith(".xlt")
514 || fName.endsWith(".xlm") || fName.endsWith(".xlk")) return "application/excel";
515 else if (fName.endsWith(".doc") || fName.endsWith(".dot")) return "application/msword";
516 else if (fName.endsWith(".png")) return "image/png";
517 else if (fName.endsWith(".xml")) return "text/xml";
518 else if (fName.endsWith(".svg")) return "image/svg+xml";
519 else if (fName.endsWith(".mp3")) return "audio/mp3";
520 else if (fName.endsWith(".ogg")) return "audio/ogg";
521 else return "text/plain";
522 }
523
524 static String conv2Html(int i) {
525 if (i == '&') return "&";
526 else if (i == '<') return "<";
527 else if (i == '>') return ">";
528 else if (i == '"') return """;
529 else return "" + (char) i;
530 }
531
532 static String conv2Html(String st) {
533 StringBuffer buf = new StringBuffer();
534 for (int i = 0; i < st.length(); i++) {
535 buf.append(conv2Html(st.charAt(i)));
536 }
537 return buf.toString();
538 }
539
540 static String startProcess(String command, String dir) throws IOException {
541 StringBuffer ret = new StringBuffer();
542 String[] comm = new String[3];
543 comm[0] = COMMAND_INTERPRETER[0];
544 comm[1] = COMMAND_INTERPRETER[1];
545 comm[2] = command;
546 long start = System.currentTimeMillis();
547 try {
548 //Start process
549 Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
550 //Get input and error streams
551 BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
552 BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
553 boolean end = false;
554 while (!end) {
555 int c = 0;
556 while ((ls_err.available() > 0) && (++c <= 1000)) {
557 ret.append(conv2Html(ls_err.read()));
558 }
559 c = 0;
560 while ((ls_in.available() > 0) && (++c <= 1000)) {
561 ret.append(conv2Html(ls_in.read()));
562 }
563 try {
564 ls_proc.exitValue();
565 //if the process has not finished, an exception is thrown
566 //else
567 while (ls_err.available() > 0)
568 ret.append(conv2Html(ls_err.read()));
569 while (ls_in.available() > 0)
570 ret.append(conv2Html(ls_in.read()));
571 end = true;
572 }
573 catch (IllegalThreadStateException ex) {
574 //Process is running
575 }
576 //The process is not allowed to run longer than given time.
577 if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
578 ls_proc.destroy();
579 end = true;
580 ret.append("!!!! Process has timed out, destroyed !!!!!");
581 }
582 try {
583 Thread.sleep(50);
584 }
585 catch (InterruptedException ie) {}
586 }
587 }
588 catch (IOException e) {
589 ret.append("Error: " + e);
590 }
591 return ret.toString();
592 }
593
594 static String dir2linkdir(String dir, String browserLink, int sortMode) {
595 File f = new File(dir);
596 StringBuffer buf = new StringBuffer();
597 while (f.getParentFile() != null) {
598 if (f.canRead()) {
599 String encPath = URLEncoder.encode(f.getAbsolutePath());
600 buf.insert(0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir="
601 + encPath + "\">" + conv2Html(f.getName()) + File.separator + "</a>");
602 }
603 else buf.insert(0, conv2Html(f.getName()) + File.separator);
604 f = f.getParentFile();
605 }
606 if (f.canRead()) {
607 String encPath = URLEncoder.encode(f.getAbsolutePath());
608 buf.insert(0, "<a href=\"" + browserLink + "?sort=" + sortMode + "&dir=" + encPath
609 + "\">" + conv2Html(f.getAbsolutePath()) + "</a>");
610 }
611 else buf.insert(0, f.getAbsolutePath());
612 return buf.toString();
613 }
614
615 static boolean isPacked(String name, boolean gz) {
616 return (name.toLowerCase().endsWith(".zip") || name.toLowerCase().endsWith(".jar")
617 || (gz && name.toLowerCase().endsWith(".gz")) || name.toLowerCase()
618 .endsWith(".war"));
619 }
620
621 static boolean isAllowed(File path, boolean write) throws IOException{
622 if (READ_ONLY && write) return false;
623 if (RESTRICT_BROWSING) {
624 StringTokenizer stk = new StringTokenizer(RESTRICT_PATH, ";");
625 while (stk.hasMoreTokens()){
626 if (path!=null && path.getCanonicalPath().startsWith(stk.nextToken()))
627 return RESTRICT_WHITELIST;
628 }
629 return !RESTRICT_WHITELIST;
630 }
631 else return true;
632 }
633
634
635 %>
636<%
637 request.setAttribute("dir", request.getParameter("dir"));
638 final String browser_name = request.getRequestURI();
639 final String FOL_IMG = "";
640 boolean nohtml = false;
641 boolean dir_view = true;
642 if (request.getParameter("Javascript") != null) {
643 dir_view = false;
644 nohtml = true;
645 response.setHeader("Cache-Control", "public");
646 Date now = new Date();
647 SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);
648 response.setHeader("Expires", sdf.format(new Date(now.getTime() + 1000 * 60 * 60 * 24*2)));
649 response.setHeader("Content-Type", "text/javascript");
650 %>
651 var check = false;
652 function dis(){check = true;}
653
654 var DOM = 0, MS = 0, OP = 0, b = 0;
655 function CheckBrowser(){
656 if (b == 0){
657 if (window.opera) OP = 1;
658 // Moz or Netscape
659 if(document.getElementById) DOM = 1;
660 // Micro$oft
661 if(document.all && !OP) MS = 1;
662 b = 1;
663 }
664 }
665 function selrow (element, i){
666 var erst;
667 CheckBrowser();
668 if ((OP==1)||(MS==1)) erst = element.firstChild.firstChild;
669 else if (DOM==1) erst = element.firstChild.nextSibling.firstChild;
670 if (i==0){
671 if (erst.checked == true) element.className='mousechecked';
672 else element.className='mousein';
673 }
674 else if (i==1){
675 if (erst.checked == true) element.className='checked';
676 else element.className='mouseout';
677 }
678 else if ((i==2)&&(!check)){
679 if (erst.checked==true) element.className='mousein';
680 else element.className='mousechecked';
681 erst.click();
682 }
683 else check=false;
684 }
685 function filter (begriff){
686 var suche = begriff.value.toLowerCase();
687 var table = document.getElementById("filetable");
688 var ele;
689 for (var r = 1; r < table.rows.length; r++){
690 ele = table.rows[r].cells[1].innerHTML.replace(/<[^>]+>/g,"");
691 if (ele.toLowerCase().indexOf(suche)>=0 )
692 table.rows[r].style.display = '';
693 else table.rows[r].style.display = 'none';
694 }
695 }
696 function AllFiles(){
697 for(var x=0;x < document.FileList.elements.length;x++){
698 var y = document.FileList.elements[x];
699 var ytr = y.parentNode.parentNode;
700 var check = document.FileList.selall.checked;
701 if(y.name == 'selfile' && ytr.style.display != 'none'){
702 if (y.disabled != true){
703 y.checked = check;
704 if (y.checked == true) ytr.className = 'checked';
705 else ytr.className = 'mouseout';
706 }
707 }
708 }
709 }
710
711 function shortKeyHandler(_event){
712 if (!_event) _event = window.event;
713 if (_event.which) {
714 keycode = _event.which;
715 } else if (_event.keyCode) {
716 keycode = _event.keyCode;
717 }
718 var t = document.getElementById("text_Dir");
719 //z
720 if (keycode == 122){
721 document.getElementById("but_Zip").click();
722 }
723 //r, F2
724 else if (keycode == 113 || keycode == 114){
725 var path = prompt("Please enter new filename", "");
726 if (path == null) return;
727 t.value = path;
728 document.getElementById("but_Ren").click();
729 }
730 //c
731 else if (keycode == 99){
732 var path = prompt("Please enter filename", "");
733 if (path == null) return;
734 t.value = path;
735 document.getElementById("but_NFi").click();
736 }
737 //d
738 else if (keycode == 100){
739 var path = prompt("Please enter directory name", "");
740 if (path == null) return;
741 t.value = path;
742 document.getElementById("but_NDi").click();
743 }
744 //m
745 else if (keycode == 109){
746 var path = prompt("Please enter move destination", "");
747 if (path == null) return;
748 t.value = path;
749 document.getElementById("but_Mov").click();
750 }
751 //y
752 else if (keycode == 121){
753 var path = prompt("Please enter copy destination", "");
754 if (path == null) return;
755 t.value = path;
756 document.getElementById("but_Cop").click();
757 }
758 //l
759 else if (keycode == 108){
760 document.getElementById("but_Lau").click();
761 }
762 //Del
763 else if (keycode == 46){
764 document.getElementById("but_Del").click();
765 }
766 }
767
768 function popUp(URL){
769 fname = document.getElementsByName("myFile")[0].value;
770 if (fname != "")
771 window.open(URL+"?first&uplMonitor="+encodeURIComponent(fname),"","width=400,height=150,resizable=yes,depend=yes")
772 }
773
774 document.onkeypress = shortKeyHandler;
775<% }
776 else if (request.getParameter("file") != null) {
777 File f = new File(request.getParameter("file"));
778 if (!isAllowed(f, false)) {
779 request.setAttribute("dir", f.getParent());
780 request.setAttribute("error", "You are not allowed to access "+f.getAbsolutePath());
781 }
782 else if (f.exists() && f.canRead()) {
783 if (isPacked(f.getName(), false)) {
784 }
785 else{
786 String mimeType = getMimeType(f.getName());
787 response.setContentType(mimeType);
788 if (mimeType.equals("text/plain")) response.setHeader(
789 "Content-Disposition", "inline;filename=\"temp.txt\"");
790 else response.setHeader("Content-Disposition", "inline;filename=\""
791 + f.getName() + "\"");
792 BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(f));
793 byte buffer[] = new byte[8 * 1024];
794 out.clearBuffer();
795 OutputStream out_s = new Writer2Stream(out);
796 copyStreamsWithoutClose(fileInput, out_s, buffer);
797 fileInput.close();
798 out_s.flush();
799 nohtml = true;
800 dir_view = false;
801 }
802 }
803 else {
804 request.setAttribute("dir", f.getParent());
805 request.setAttribute("error", "File " + f.getAbsolutePath()
806 + " does not exist or is not readable on the server");
807 }
808 }
809 else if ((request.getParameter("Submit") != null)
810 && (request.getParameter("Submit").equals(SAVE_AS_ZIP))) {
811 Vector v = expandFileList(request.getParameterValues("selfile"), false);
812 String notAllowedFile = null;
813 for (int i = 0;i < v.size(); i++){
814 File f = (File) v.get(i);
815 if (!isAllowed(f, false)){
816 notAllowedFile = f.getAbsolutePath();
817 break;
818 }
819 }
820 if (notAllowedFile != null){
821 request.setAttribute("error", "You are not allowed to access " + notAllowedFile);
822 }
823 else if (v.size() == 0) {
824 request.setAttribute("error", "No files selected");
825 }
826 else {
827 File dir_file = new File("" + request.getAttribute("dir"));
828 int dir_l = dir_file.getAbsolutePath().length();
829 response.setContentType("application/zip");
830 response.setHeader("Content-Disposition", "attachment;filename=\"rename_me.zip\"");
831 out.clearBuffer();
832 ZipOutputStream zipout = new ZipOutputStream(new Writer2Stream(out));
833 zipout.setComment("Created by jsp File Browser v. " + VERSION_NR);
834 zipout.setLevel(COMPRESSION_LEVEL);
835 for (int i = 0; i < v.size(); i++) {
836 File f = (File) v.get(i);
837 if (f.canRead()) {
838 zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
839 BufferedInputStream fr = new BufferedInputStream(new FileInputStream(f));
840 byte buffer[] = new byte[0xffff];
841 copyStreamsWithoutClose(fr, zipout, buffer);
842 /* int b;
843 while ((b=fr.read())!=-1) zipout.write(b);*/
844 fr.close();
845 zipout.closeEntry();
846 }
847 }
848 zipout.finish();
849 out.flush();
850 nohtml = true;
851 dir_view = false;
852 }
853 }
854 else if (request.getParameter("downfile") != null) {
855 String filePath = request.getParameter("downfile");
856 File f = new File(filePath);
857 if (!isAllowed(f, false)){
858 request.setAttribute("dir", f.getParent());
859 request.setAttribute("error", "You are not allowed to access " + f.getAbsoluteFile());
860 }
861 else if (f.exists() && f.canRead()) {
862 response.setContentType("application/octet-stream");
863 response.setHeader("Content-Disposition", "attachment;filename=\"" + f.getName()
864 + "\"");
865 response.setContentLength((int) f.length());
866 BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(f));
867 byte buffer[] = new byte[8 * 1024];
868 out.clearBuffer();
869 OutputStream out_s = new Writer2Stream(out);
870 copyStreamsWithoutClose(fileInput, out_s, buffer);
871 fileInput.close();
872 out_s.flush();
873 nohtml = true;
874 dir_view = false;
875 }
876 else {
877 request.setAttribute("dir", f.getParent());
878 request.setAttribute("error", "File " + f.getAbsolutePath()
879 + " does not exist or is not readable on the server");
880 }
881 }
882 if (nohtml) return;
883 if (request.getAttribute("dir") == null) {
884 String path = null;
885 if (application.getRealPath(request.getRequestURI()) != null) {
886 File f = new File(application.getRealPath(request.getRequestURI())).getParentFile();
887 //This is a hack needed for tomcat
888 while (f != null && !f.exists())
889 f = f.getParentFile();
890 if (f != null)
891 path = f.getAbsolutePath();
892 }
893 if (path == null) { // handle the case where we are not in a directory (ex: war file)
894 path = new File(".").getAbsolutePath();
895 }
896 //Check path
897 if (!isAllowed(new File(path), false)){
898 //TODO Blacklist
899 if (RESTRICT_PATH.indexOf(";")<0) path = RESTRICT_PATH;
900 else path = RESTRICT_PATH.substring(0, RESTRICT_PATH.indexOf(";"));
901 }
902 request.setAttribute("dir", path);
903 }%>
904<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
905"http://www.w3.org/TR/html4/loose.dtd">
906<html>
907<head>
908<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
909<meta name="robots" content="noindex">
910<meta http-equiv="expires" content="0">
911<meta http-equiv="pragma" content="no-cache">
912<%
913 String cssPath = null;
914 if (application.getRealPath(request.getRequestURI()) != null) cssPath = new File(
915 application.getRealPath(request.getRequestURI())).getParent()
916 + File.separator + CSS_NAME;
917 if (cssPath == null) cssPath = application.getResource(CSS_NAME).toString();
918 if (new File(cssPath).exists()) {
919%>
920<link rel="stylesheet" type="text/css" href="<%=CSS_NAME%>">
921 <%}
922 else if (request.getParameter("uplMonitor") == null) {%>
923 <style type="text/css">
924 input.button {background-color: #c0c0c0; color: #666666;
925 border: 1px solid #999999; margin: 5px 1px 5px 1px;}
926 input.textfield {margin: 5px 1px 5px 1px;}
927 input.button:Hover { color: #444444 }
928 table.filelist {background-color:#666666; width:100%; border:0px none #ffffff}
929 .formular {margin: 1px; background-color:#ffffff; padding: 1em; border:1px solid #000000;}
930 .formular2 {margin: 1px;}
931 th { background-color:#c0c0c0 }
932 tr.mouseout { background-color:#ffffff; }
933 tr.mousein { background-color:#eeeeee; }
934 tr.checked { background-color:#cccccc }
935 tr.mousechecked { background-color:#c0c0c0 }
936 td { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
937 td.message { background-color: #FFFF00; color: #000000; text-align:center; font-weight:bold}
938 td.error { background-color: #FF0000; color: #000000; text-align:center; font-weight:bold}
939 A { text-decoration: none; }
940 A:Hover { color : Red; text-decoration : underline; }
941 BODY { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
942 </style>
943 <%}
944
945 if (!isAllowed(new File((String)request.getAttribute("dir")), false)){
946 request.setAttribute("error", "You are not allowed to access " + request.getAttribute("dir"));
947 }
948 else if (request.getParameter("uplMonitor") != null) {%>
949 <style type="text/css">
950 BODY { font-family:Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; color: #666666;}
951 </style><%
952 String fname = request.getParameter("uplMonitor");
953 boolean first = false;
954 if (request.getParameter("first") != null) first = true;
955 UplInfo info = new UplInfo();
956 if (!first) {
957 info = UploadMonitor.getInfo(fname);
958 if (info == null) {
959 int posi = fname.lastIndexOf("/");
960 if (posi != -1) info = UploadMonitor.getInfo(fname.substring(posi + 1));
961 }
962 }
963 dir_view = false;
964 request.setAttribute("dir", null);
965 if (info.aborted) {
966 UploadMonitor.remove(fname);
967 %>
968</head>
969<body>
970<b>Upload of <%=fname%></b><br><br>
971Upload aborted.</body>
972</html><%
973 }
974 else if (info.totalSize != info.currSize || info.currSize == 0) {
975 %>
976<META HTTP-EQUIV="Refresh" CONTENT="<%=UPLOAD_MONITOR_REFRESH%>;URL=<%=browser_name %>?uplMonitor=<%=URLEncoder.encode(fname)%>">
977</head>
978<body>
979<b>Upload of <%=fname%></b><br><br>
980<center>
981<table height="20px" width="90%" bgcolor="#eeeeee" style="border:1px solid #cccccc"><tr>
982<td bgcolor="blue" width="<%=info.getPercent()%>%"></td><td width="<%=100-info.getPercent()%>%"></td>
983</tr></table></center>
984<%=convertFileSize(info.currSize)%> from <%=convertFileSize(info.totalSize)%>
985(<%=info.getPercent()%> %) uploaded (Speed: <%=info.getUprate()%>).<br>
986Time: <%=info.getTimeElapsed()%> from <%=info.getTimeEstimated()%>
987</body>
988</html><%
989 }
990 else {
991 UploadMonitor.remove(fname);
992 %>
993</head>
994<body onload="javascript:window.close()">
995<b>Upload of <%=fname%></b><br><br>
996Upload finished.
997</body>
998</html><%
999 }
1000 }
1001 //Comandwindow
1002 else if (request.getParameter("command") != null) {
1003 if (!NATIVE_COMMANDS){
1004 request.setAttribute("error", "Execution of native commands is not allowed!");
1005 }
1006 else if (!"Cancel".equalsIgnoreCase(request.getParameter("Submit"))) {
1007%>
1008<title>Launch commands in <%=request.getAttribute("dir")%></title>
1009</head>
1010<body><center>
1011<h2><%=LAUNCH_COMMAND %></h2><br />
1012<%
1013 out.println("<form action=\"" + browser_name + "\" method=\"Post\">\n"
1014 + "<textarea name=\"text\" wrap=\"off\" cols=\"" + EDITFIELD_COLS
1015 + "\" rows=\"" + EDITFIELD_ROWS + "\" readonly>");
1016 String ret = "";
1017 if (!request.getParameter("command").equalsIgnoreCase(""))
1018 ret = startProcess(
1019 request.getParameter("command"), (String) request.getAttribute("dir"));
1020 out.println(ret);
1021%></textarea>
1022 <input type="hidden" name="dir" value="<%= request.getAttribute("dir")%>">
1023 <br /><br />
1024 <table class="formular">
1025 <tr><td title="Enter your command">
1026 Command: <input size="<%=EDITFIELD_COLS-5%>" type="text" name="command" value="">
1027 </td></tr>
1028 <tr><td><input class="button" type="Submit" name="Submit" value="Launch">
1029 <input type="hidden" name="sort" value="<%=request.getParameter("sort")%>">
1030 <input type="Submit" class="button" name="Submit" value="Cancel"></td></tr>
1031 </table>
1032 </form>
1033 <br />
1034 <hr>
1035 <center>
1036 <small>jsp File Browser version <%= VERSION_NR%> by <a href="http://www.vonloesch.de">www.vonloesch.de</a></small>
1037 </center>
1038 </center>
1039</body>
1040</html>
1041<%
1042 dir_view = false;
1043 request.setAttribute("dir", null);
1044 }
1045 }
1046
1047 //Click on a filename, special viewer (zip+jar file)
1048 else if (request.getParameter("file") != null) {
1049 File f = new File(request.getParameter("file"));
1050 if (!isAllowed(f, false)){
1051 request.setAttribute("error", "You are not allowed to access " + f.getAbsolutePath());
1052 }
1053 else if (isPacked(f.getName(), false)) {
1054 //ZipFile
1055 try {
1056 ZipFile zf = new ZipFile(f);
1057 Enumeration entries = zf.entries();
1058%>
1059<title><%= f.getAbsolutePath()%></title>
1060</head>
1061<body>
1062 <h2>Content of <%=conv2Html(f.getName())%></h2><br />
1063 <table class="filelist" cellspacing="1px" cellpadding="0px">
1064 <th>Name</th><th>Uncompressed size</th><th>Compressed size</th><th>Compr. ratio</th><th>Date</th>
1065<%
1066 long size = 0;
1067 int fileCount = 0;
1068 while (entries.hasMoreElements()) {
1069 ZipEntry entry = (ZipEntry) entries.nextElement();
1070 if (!entry.isDirectory()) {
1071 fileCount++;
1072 size += entry.getSize();
1073 long ratio = 0;
1074 if (entry.getSize() != 0) ratio = (entry.getCompressedSize() * 100)
1075 / entry.getSize();
1076 out.println("<tr class=\"mouseout\"><td>" + conv2Html(entry.getName())
1077 + "</td><td>" + convertFileSize(entry.getSize()) + "</td><td>"
1078 + convertFileSize(entry.getCompressedSize()) + "</td><td>"
1079 + ratio + "%" + "</td><td>"
1080 + dateFormat.format(new Date(entry.getTime())) + "</td></tr>");
1081
1082 }
1083 }
1084 zf.close();
1085 //No directory view
1086 dir_view = false;
1087 request.setAttribute("dir", null);
1088%>
1089 </table>
1090 <p align=center>
1091 <b><%=convertFileSize(size)%> in <%=fileCount%> files in <%=f.getName()%>. Compression ratio: <%=(f.length() * 100) / size%>%
1092 </b></p>
1093</body></html>
1094<%
1095 }
1096 catch (ZipException ex) {
1097 request.setAttribute("error", "Cannot read " + f.getName()
1098 + ", no valid zip file");
1099 }
1100 catch (IOException ex) {
1101 request.setAttribute("error", "Reading of " + f.getName() + " aborted. Error: "
1102 + ex);
1103 }
1104 }
1105 }
1106 // Upload
1107 else if ((request.getContentType() != null)
1108 && (request.getContentType().toLowerCase().startsWith("multipart"))) {
1109 if (!ALLOW_UPLOAD){
1110 request.setAttribute("error", "Upload is forbidden!");
1111 }
1112 response.setContentType("text/html");
1113 HttpMultiPartParser parser = new HttpMultiPartParser();
1114 boolean error = false;
1115 try {
1116 int bstart = request.getContentType().lastIndexOf("oundary=");
1117 String bound = request.getContentType().substring(bstart + 8);
1118 int clength = request.getContentLength();
1119 Hashtable ht = parser
1120 .processData(request.getInputStream(), bound, tempdir, clength);
1121 if (!isAllowed(new File((String)ht.get("dir")), false)){
1122 //This is a hack, cos we are writing to this directory
1123 request.setAttribute("error", "You are not allowed to access " + ht.get("dir"));
1124 error = true;
1125 }
1126 else if (ht.get("myFile") != null) {
1127 FileInfo fi = (FileInfo) ht.get("myFile");
1128 File f = fi.file;
1129 UplInfo info = UploadMonitor.getInfo(fi.clientFileName);
1130 if (info != null && info.aborted) {
1131 f.delete();
1132 request.setAttribute("error", "Upload aborted");
1133 }
1134 else {
1135 // Move file from temp to the right dir
1136 String path = (String) ht.get("dir");
1137 if (!path.endsWith(File.separator)) path = path + File.separator;
1138 if (!f.renameTo(new File(path + f.getName()))) {
1139 request.setAttribute("error", "Cannot upload file.");
1140 error = true;
1141 f.delete();
1142 }
1143 }
1144 }
1145 else {
1146 request.setAttribute("error", "No file selected for upload");
1147 error = true;
1148 }
1149 request.setAttribute("dir", (String) ht.get("dir"));
1150 }
1151 catch (Exception e) {
1152 request.setAttribute("error", "Error " + e + ". Upload aborted");
1153 error = true;
1154 }
1155 if (!error) request.setAttribute("message", "File upload correctly finished.");
1156 }
1157 // The form to edit a text file
1158 else if (request.getParameter("editfile") != null) {
1159 File ef = new File(request.getParameter("editfile"));
1160 if (!isAllowed(ef, true)){
1161 request.setAttribute("error", "You are not allowed to access " + ef.getAbsolutePath());
1162 }
1163 else{
1164%>
1165<title>Edit <%=conv2Html(request.getParameter("editfile"))%></title>
1166</head>
1167<body>
1168<center>
1169<h2>Edit <%=conv2Html(request.getParameter("editfile"))%></h2><br />
1170<%
1171 BufferedReader reader = new BufferedReader(new FileReader(ef));
1172 String disable = "";
1173 if (!ef.canWrite()) disable = " readonly";
1174 out.println("<form action=\"" + browser_name + "\" method=\"Post\">\n"
1175 + "<textarea name=\"text\" wrap=\"off\" cols=\"" + EDITFIELD_COLS
1176 + "\" rows=\"" + EDITFIELD_ROWS + "\"" + disable + ">");
1177 String c;
1178 // Write out the file and check if it is a win or unix file
1179 int i;
1180 boolean dos = false;
1181 boolean cr = false;
1182 while ((i = reader.read()) >= 0) {
1183 out.print(conv2Html(i));
1184 if (i == '\r') cr = true;
1185 else if (cr && (i == '\n')) dos = true;
1186 else cr = false;
1187 }
1188 reader.close();
1189 //No File directory is shown
1190 request.setAttribute("dir", null);
1191 dir_view = false;
1192
1193%></textarea><br /><br />
1194<table class="formular">
1195 <input type="hidden" name="nfile" value="<%= request.getParameter("editfile")%>">
1196 <input type="hidden" name="sort" value="<%=request.getParameter("sort")%>">
1197 <tr><td colspan="2"><input type="radio" name="lineformat" value="dos" <%= dos?"checked":""%>>Ms-Dos/Windows
1198 <input type="radio" name="lineformat" value="unix" <%= dos?"":"checked"%>>Unix
1199 <input type="checkbox" name="Backup" checked>Write backup</td></tr>
1200 <tr><td title="Enter the new filename"><input type="text" name="new_name" value="<%=ef.getName()%>">
1201 <input type="Submit" name="Submit" value="Save"></td>
1202 </form>
1203 <form action="<%=browser_name%>" method="Post">
1204 <td align="left">
1205 <input type="Submit" name="Submit" value="Cancel">
1206 <input type="hidden" name="nfile" value="<%= request.getParameter("editfile")%>">
1207 <input type="hidden" name="sort" value="<%=request.getParameter("sort")%>">
1208 </td>
1209 </form>
1210 </tr>
1211 </table>
1212 </center>
1213 <br />
1214 <hr>
1215 <center>
1216 <small>jsp File Browser version <%= VERSION_NR%> by <a href="http://www.vonloesch.de">www.vonloesch.de</a></small>
1217 </center>
1218</body>
1219</html>
1220<%
1221 }
1222 }
1223 // Save or cancel the edited file
1224 else if (request.getParameter("nfile") != null) {
1225 File f = new File(request.getParameter("nfile"));
1226 if (request.getParameter("Submit").equals("Save")) {
1227 File new_f = new File(getDir(f.getParent(), request.getParameter("new_name")));
1228 if (!isAllowed(new_f, true)){
1229 request.setAttribute("error", "You are not allowed to access " + new_f.getAbsolutePath());
1230 }
1231 if (new_f.exists() && new_f.canWrite() && request.getParameter("Backup") != null) {
1232 File bak = new File(new_f.getAbsolutePath() + ".bak");
1233 bak.delete();
1234 new_f.renameTo(bak);
1235 }
1236 if (new_f.exists() && !new_f.canWrite()) request.setAttribute("error",
1237 "Cannot write to " + new_f.getName() + ", file is write protected.");
1238 else {
1239 BufferedWriter outs = new BufferedWriter(new FileWriter(new_f));
1240 StringReader text = new StringReader(request.getParameter("text"));
1241 int i;
1242 boolean cr = false;
1243 String lineend = "\n";
1244 if (request.getParameter("lineformat").equals("dos")) lineend = "\r\n";
1245 while ((i = text.read()) >= 0) {
1246 if (i == '\r') cr = true;
1247 else if (i == '\n') {
1248 outs.write(lineend);
1249 cr = false;
1250 }
1251 else if (cr) {
1252 outs.write(lineend);
1253 cr = false;
1254 }
1255 else {
1256 outs.write(i);
1257 cr = false;
1258 }
1259 }
1260 outs.flush();
1261 outs.close();
1262 }
1263 }
1264 request.setAttribute("dir", f.getParent());
1265 }
1266 //Unpack file to the current directory without overwriting
1267 else if (request.getParameter("unpackfile") != null) {
1268 File f = new File(request.getParameter("unpackfile"));
1269 String root = f.getParent();
1270 request.setAttribute("dir", root);
1271 if (!isAllowed(new File(root), true)){
1272 request.setAttribute("error", "You are not allowed to access " + root);
1273 }
1274 //Check if file exists
1275 else if (!f.exists()) {
1276 request.setAttribute("error", "Cannot unpack " + f.getName()
1277 + ", file does not exist");
1278 }
1279 //Check if directory is readonly
1280 else if (!f.getParentFile().canWrite()) {
1281 request.setAttribute("error", "Cannot unpack " + f.getName()
1282 + ", directory is write protected.");
1283 }
1284 //GZip
1285 else if (f.getName().toLowerCase().endsWith(".gz")) {
1286 //New name is old Name without .gz
1287 String newName = f.getAbsolutePath().substring(0, f.getAbsolutePath().length() - 3);
1288 try {
1289 byte buffer[] = new byte[0xffff];
1290 copyStreams(new GZIPInputStream(new FileInputStream(f)), new FileOutputStream(
1291 newName), buffer);
1292 }
1293 catch (IOException ex) {
1294 request.setAttribute("error", "Unpacking of " + f.getName()
1295 + " aborted. Error: " + ex);
1296 }
1297 }
1298 //Else try Zip
1299 else {
1300 try {
1301 ZipFile zf = new ZipFile(f);
1302 Enumeration entries = zf.entries();
1303 //First check whether a file already exist
1304 boolean error = false;
1305 while (entries.hasMoreElements()) {
1306 ZipEntry entry = (ZipEntry) entries.nextElement();
1307 if (!entry.isDirectory()
1308 && new File(root + File.separator + entry.getName()).exists()) {
1309 request.setAttribute("error", "Cannot unpack " + f.getName()
1310 + ", File " + entry.getName() + " already exists.");
1311 error = true;
1312 break;
1313 }
1314 }
1315 if (!error) {
1316 //Unpack File
1317 entries = zf.entries();
1318 byte buffer[] = new byte[0xffff];
1319 while (entries.hasMoreElements()) {
1320 ZipEntry entry = (ZipEntry) entries.nextElement();
1321 File n = new File(root + File.separator + entry.getName());
1322 if (entry.isDirectory()) n.mkdirs();
1323 else {
1324 n.getParentFile().mkdirs();
1325 n.createNewFile();
1326 copyStreams(zf.getInputStream(entry), new FileOutputStream(n),
1327 buffer);
1328 }
1329 }
1330 zf.close();
1331 request.setAttribute("message", "Unpack of " + f.getName()
1332 + " was successful.");
1333 }
1334 }
1335 catch (ZipException ex) {
1336 request.setAttribute("error", "Cannot unpack " + f.getName()
1337 + ", no valid zip file");
1338 }
1339 catch (IOException ex) {
1340 request.setAttribute("error", "Unpacking of " + f.getName()
1341 + " aborted. Error: " + ex);
1342 }
1343 }
1344 }
1345 // Delete Files
1346 else if ((request.getParameter("Submit") != null)
1347 && (request.getParameter("Submit").equals(DELETE_FILES))) {
1348 Vector v = expandFileList(request.getParameterValues("selfile"), true);
1349 boolean error = false;
1350 //delete backwards
1351 for (int i = v.size() - 1; i >= 0; i--) {
1352 File f = (File) v.get(i);
1353 if (!isAllowed(f, true)){
1354 request.setAttribute("error", "You are not allowed to access " + f.getAbsolutePath());
1355 error = true;
1356 break;
1357 }
1358 if (!f.canWrite() || !f.delete()) {
1359 request.setAttribute("error", "Cannot delete " + f.getAbsolutePath()
1360 + ". Deletion aborted");
1361 error = true;
1362 break;
1363 }
1364 }
1365 if ((!error) && (v.size() > 1)) request.setAttribute("message", "All files deleted");
1366 else if ((!error) && (v.size() > 0)) request.setAttribute("message", "File deleted");
1367 else if (!error) request.setAttribute("error", "No files selected");
1368 }
1369 // Create Directory
1370 else if ((request.getParameter("Submit") != null)
1371 && (request.getParameter("Submit").equals(CREATE_DIR))) {
1372 String dir = "" + request.getAttribute("dir");
1373 String dir_name = request.getParameter("cr_dir");
1374 String new_dir = getDir(dir, dir_name);
1375 if (!isAllowed(new File(new_dir), true)){
1376 request.setAttribute("error", "You are not allowed to access " + new_dir);
1377 }
1378 else if (new File(new_dir).mkdirs()) {
1379 request.setAttribute("message", "Directory created");
1380 }
1381 else request.setAttribute("error", "Creation of directory " + new_dir + " failed");
1382 }
1383 // Create a new empty file
1384 else if ((request.getParameter("Submit") != null)
1385 && (request.getParameter("Submit").equals(CREATE_FILE))) {
1386 String dir = "" + request.getAttribute("dir");
1387 String file_name = request.getParameter("cr_dir");
1388 String new_file = getDir(dir, file_name);
1389 if (!isAllowed(new File(new_file), true)){
1390 request.setAttribute("error", "You are not allowed to access " + new_file);
1391 }
1392 // Test, if file_name is empty
1393 else if (!"".equals(file_name.trim()) && !file_name.endsWith(File.separator)) {
1394 if (new File(new_file).createNewFile()) request.setAttribute("message",
1395 "File created");
1396 else request.setAttribute("error", "Creation of file " + new_file + " failed");
1397 }
1398 else request.setAttribute("error", "Error: " + file_name + " is not a valid filename");
1399 }
1400 // Rename a file
1401 else if ((request.getParameter("Submit") != null)
1402 && (request.getParameter("Submit").equals(RENAME_FILE))) {
1403 Vector v = expandFileList(request.getParameterValues("selfile"), true);
1404 String dir = "" + request.getAttribute("dir");
1405 String new_file_name = request.getParameter("cr_dir");
1406 String new_file = getDir(dir, new_file_name);
1407 if (!isAllowed(new File(new_file), true)){
1408 request.setAttribute("error", "You are not allowed to access " + new_file);
1409 }
1410 // The error conditions:
1411 // 1) Zero Files selected
1412 else if (v.size() <= 0) request.setAttribute("error",
1413 "Select exactly one file or folder. Rename failed");
1414 // 2a) Multiple files selected and the first isn't a dir
1415 // Here we assume that expandFileList builds v from top-bottom, starting with the dirs
1416 else if ((v.size() > 1) && !(((File) v.get(0)).isDirectory())) request.setAttribute(
1417 "error", "Select exactly one file or folder. Rename failed");
1418 // 2b) If there are multiple files from the same directory, rename fails
1419 else if ((v.size() > 1) && ((File) v.get(0)).isDirectory()
1420 && !(((File) v.get(0)).getPath().equals(((File) v.get(1)).getParent()))) {
1421 request.setAttribute("error", "Select exactly one file or folder. Rename failed");
1422 }
1423 else {
1424 File f = (File) v.get(0);
1425 if (!isAllowed(f, true)){
1426 request.setAttribute("error", "You are not allowed to access " + f.getAbsolutePath());
1427 }
1428 // Test, if file_name is empty
1429 else if ((new_file.trim() != "") && !new_file.endsWith(File.separator)) {
1430 if (!f.canWrite() || !f.renameTo(new File(new_file.trim()))) {
1431 request.setAttribute("error", "Creation of file " + new_file + " failed");
1432 }
1433 else request.setAttribute("message", "Renamed file "
1434 + ((File) v.get(0)).getName() + " to " + new_file);
1435 }
1436 else request.setAttribute("error", "Error: \"" + new_file_name
1437 + "\" is not a valid filename");
1438 }
1439 }
1440 // Move selected file(s)
1441 else if ((request.getParameter("Submit") != null)
1442 && (request.getParameter("Submit").equals(MOVE_FILES))) {
1443 Vector v = expandFileList(request.getParameterValues("selfile"), true);
1444 String dir = "" + request.getAttribute("dir");
1445 String dir_name = request.getParameter("cr_dir");
1446 String new_dir = getDir(dir, dir_name);
1447 if (!isAllowed(new File(new_dir), false)){
1448 request.setAttribute("error", "You are not allowed to access " + new_dir);
1449 }
1450 else{
1451 boolean error = false;
1452 // This ensures that new_dir is a directory
1453 if (!new_dir.endsWith(File.separator)) new_dir += File.separator;
1454 for (int i = v.size() - 1; i >= 0; i--) {
1455 File f = (File) v.get(i);
1456 if (!isAllowed(f, true)){
1457 request.setAttribute("error", "You are not allowed to access " + f.getAbsolutePath());
1458 error = true;
1459 break;
1460 }
1461 else if (!f.canWrite() || !f.renameTo(new File(new_dir
1462 + f.getAbsolutePath().substring(dir.length())))) {
1463 request.setAttribute("error", "Cannot move " + f.getAbsolutePath()
1464 + ". Move aborted");
1465 error = true;
1466 break;
1467 }
1468 }
1469 if ((!error) && (v.size() > 1)) request.setAttribute("message", "All files moved");
1470 else if ((!error) && (v.size() > 0)) request.setAttribute("message", "File moved");
1471 else if (!error) request.setAttribute("error", "No files selected");
1472 }
1473 }
1474 // Copy Files
1475 else if ((request.getParameter("Submit") != null)
1476 && (request.getParameter("Submit").equals(COPY_FILES))) {
1477 Vector v = expandFileList(request.getParameterValues("selfile"), true);
1478 String dir = (String) request.getAttribute("dir");
1479 if (!dir.endsWith(File.separator)) dir += File.separator;
1480 String dir_name = request.getParameter("cr_dir");
1481 String new_dir = getDir(dir, dir_name);
1482 if (!isAllowed(new File(new_dir), true)){
1483 request.setAttribute("error", "You are not allowed to access " + new_dir);
1484 }
1485 else{
1486 boolean error = false;
1487 if (!new_dir.endsWith(File.separator)) new_dir += File.separator;
1488 try {
1489 byte buffer[] = new byte[0xffff];
1490 for (int i = 0; i < v.size(); i++) {
1491 File f_old = (File) v.get(i);
1492 File f_new = new File(new_dir + f_old.getAbsolutePath().substring(dir.length()));
1493 if (!isAllowed(f_old, false)|| !isAllowed(f_new, true)){
1494 request.setAttribute("error", "You are not allowed to access " + f_new.getAbsolutePath());
1495 error = true;
1496 }
1497 else if (f_old.isDirectory()) f_new.mkdirs();
1498 // Overwriting is forbidden
1499 else if (!f_new.exists()) {
1500 copyStreams(new FileInputStream(f_old), new FileOutputStream(f_new), buffer);
1501 }
1502 else {
1503 // File exists
1504 request.setAttribute("error", "Cannot copy " + f_old.getAbsolutePath()
1505 + ", file already exists. Copying aborted");
1506 error = true;
1507 break;
1508 }
1509 }
1510 }
1511 catch (IOException e) {
1512 request.setAttribute("error", "Error " + e + ". Copying aborted");
1513 error = true;
1514 }
1515 if ((!error) && (v.size() > 1)) request.setAttribute("message", "All files copied");
1516 else if ((!error) && (v.size() > 0)) request.setAttribute("message", "File copied");
1517 else if (!error) request.setAttribute("error", "No files selected");
1518 }
1519 }
1520 // Directory viewer
1521 if (dir_view && request.getAttribute("dir") != null) {
1522 File f = new File("" + request.getAttribute("dir"));
1523 //Check, whether the dir exists
1524 if (!f.exists() || !isAllowed(f, false)) {
1525 if (!f.exists()){
1526 request.setAttribute("error", "Directory " + f.getAbsolutePath() + " does not exist.");
1527 }
1528 else{
1529 request.setAttribute("error", "You are not allowed to access " + f.getAbsolutePath());
1530 }
1531 //if attribute olddir exists, it will change to olddir
1532 if (request.getAttribute("olddir") != null && isAllowed(new File((String) request.getAttribute("olddir")), false)) {
1533 f = new File("" + request.getAttribute("olddir"));
1534 }
1535 //try to go to the parent dir
1536 else {
1537 if (f.getParent() != null && isAllowed(f, false)) f = new File(f.getParent());
1538 }
1539 //If this dir also do also not exist, go back to browser.jsp root path
1540 if (!f.exists()) {
1541 String path = null;
1542 if (application.getRealPath(request.getRequestURI()) != null) path = new File(
1543 application.getRealPath(request.getRequestURI())).getParent();
1544
1545 if (path == null) // handle the case were we are not in a directory (ex: war file)
1546 path = new File(".").getAbsolutePath();
1547 f = new File(path);
1548 }
1549 if (isAllowed(f, false)) request.setAttribute("dir", f.getAbsolutePath());
1550 else request.setAttribute("dir", null);
1551 }
1552%>
1553<script type="text/javascript" src="<%=browser_name %>?Javascript">
1554</script>
1555<title><%=request.getAttribute("dir")%></title>
1556</head>
1557<body>
1558<%
1559 //Output message
1560 if (request.getAttribute("message") != null) {
1561 out.println("<table border=\"0\" width=\"100%\"><tr><td class=\"message\">");
1562 out.println(request.getAttribute("message"));
1563 out.println("</td></tr></table>");
1564 }
1565 //Output error
1566 if (request.getAttribute("error") != null) {
1567 out.println("<table border=\"0\" width=\"100%\"><tr><td class=\"error\">");
1568 out.println(request.getAttribute("error"));
1569 out.println("</td></tr></table>");
1570 }
1571 if (request.getAttribute("dir") != null){
1572%>
1573
1574 <form class="formular" action="<%= browser_name %>" method="Post" name="FileList">
1575 Filename filter: <input name="filt" onKeypress="event.cancelBubble=true;" onkeyup="filter(this)" type="text">
1576 <br /><br />
1577 <table id="filetable" class="filelist" cellspacing="1px" cellpadding="0px">
1578<%
1579 // Output the table, starting with the headers.
1580 String dir = URLEncoder.encode("" + request.getAttribute("dir"));
1581 String cmd = browser_name + "?dir=" + dir;
1582 int sortMode = 1;
1583 if (request.getParameter("sort") != null) sortMode = Integer.parseInt(request
1584 .getParameter("sort"));
1585 int[] sort = new int[] {1, 2, 3, 4};
1586 for (int i = 0; i < sort.length; i++)
1587 if (sort[i] == sortMode) sort[i] = -sort[i];
1588 out.print("<tr><th> </th><th title=\"Sort files by name\" align=left><a href=\""
1589 + cmd + "&sort=" + sort[0] + "\">Name</a></th>"
1590 + "<th title=\"Sort files by size\" align=\"right\"><a href=\"" + cmd
1591 + "&sort=" + sort[1] + "\">Size</a></th>"
1592 + "<th title=\"Sort files by type\" align=\"center\"><a href=\"" + cmd
1593 + "&sort=" + sort[3] + "\">Type</a></th>"
1594 + "<th title=\"Sort files by date\" align=\"left\"><a href=\"" + cmd
1595 + "&sort=" + sort[2] + "\">Date</a></th>"
1596 + "<th> </th>");
1597 if (!READ_ONLY) out.print ("<th> </th>");
1598 out.println("</tr>");
1599 char trenner = File.separatorChar;
1600 // Output the Root-Dirs, without FORBIDDEN_DRIVES
1601 File[] entry = File.listRoots();
1602 for (int i = 0; i < entry.length; i++) {
1603 boolean forbidden = false;
1604 for (int i2 = 0; i2 < FORBIDDEN_DRIVES.length; i2++) {
1605 if (entry[i].getAbsolutePath().toLowerCase().equals(FORBIDDEN_DRIVES[i2])) forbidden = true;
1606 }
1607 if (!forbidden) {
1608 out.println("<tr class=\"mouseout\" onmouseover=\"this.className='mousein'\""
1609 + "onmouseout=\"this.className='mouseout'\">");
1610 out.println("<td> </td><td align=left >");
1611 String name = URLEncoder.encode(entry[i].getAbsolutePath());
1612 String buf = entry[i].getAbsolutePath();
1613 out.println(" <a href=\"" + browser_name + "?sort=" + sortMode
1614 + "&dir=" + name + "\">[" + buf + "]</a>");
1615 out.print("</td><td> </td><td> </td><td> </td><td> </td><td></td></tr>");
1616 }
1617 }
1618 // Output the parent directory link ".."
1619 if (f.getParent() != null) {
1620 out.println("<tr class=\"mouseout\" onmouseover=\"this.className='mousein'\""
1621 + "onmouseout=\"this.className='mouseout'\">");
1622 out.println("<td></td><td align=left>");
1623 out.println(" <a href=\"" + browser_name + "?sort=" + sortMode + "&dir="
1624 + URLEncoder.encode(f.getParent()) + "\">" + FOL_IMG + "[..]</a>");
1625 out.print("</td><td> </td><td> </td><td> </td><td> </td><td></td></tr>");
1626 }
1627 // Output all files and dirs and calculate the number of files and total size
1628 entry = f.listFiles();
1629 if (entry == null) entry = new File[] {};
1630 long totalSize = 0; // The total size of the files in the current directory
1631 long fileCount = 0; // The count of files in the current working directory
1632 if (entry != null && entry.length > 0) {
1633 Arrays.sort(entry, new FileComp(sortMode));
1634 for (int i = 0; i < entry.length; i++) {
1635 String name = URLEncoder.encode(entry[i].getAbsolutePath());
1636 String type = "File"; // This String will tell the extension of the file
1637 if (entry[i].isDirectory()) type = "DIR"; // It's a DIR
1638 else {
1639 String tempName = entry[i].getName().replace(' ', '_');
1640 if (tempName.lastIndexOf('.') != -1) type = tempName.substring(
1641 tempName.lastIndexOf('.')).toLowerCase();
1642 }
1643 String ahref = "<a onmousedown=\"dis()\" href=\"" + browser_name + "?sort="
1644 + sortMode + "&";
1645 String dlink = " "; // The "Download" link
1646 String elink = " "; // The "Edit" link
1647 String buf = conv2Html(entry[i].getName());
1648 if (!entry[i].canWrite()) buf = "<i>" + buf + "</i>";
1649 String link = buf; // The standard view link, uses Mime-type
1650 if (entry[i].isDirectory()) {
1651 if (entry[i].canRead() && USE_DIR_PREVIEW) {
1652 //Show the first DIR_PREVIEW_NUMBER directory entries in a tooltip
1653 File[] fs = entry[i].listFiles();
1654 if (fs == null) fs = new File[] {};
1655 Arrays.sort(fs, new FileComp());
1656 StringBuffer filenames = new StringBuffer();
1657 for (int i2 = 0; (i2 < fs.length) && (i2 < 10); i2++) {
1658 String fname = conv2Html(fs[i2].getName());
1659 if (fs[i2].isDirectory()) filenames.append("[" + fname + "];");
1660 else filenames.append(fname + ";");
1661 }
1662 if (fs.length > DIR_PREVIEW_NUMBER) filenames.append("...");
1663 else if (filenames.length() > 0) filenames
1664 .setLength(filenames.length() - 1);
1665 link = ahref + "dir=" + name + "\" title=\"" + filenames + "\">"
1666 + FOL_IMG + "[" + buf + "]</a>";
1667 }
1668 else if (entry[i].canRead()) {
1669 link = ahref + "dir=" + name + "\">" + FOL_IMG + "[" + buf + "]</a>";
1670 }
1671 else link = FOL_IMG + "[" + buf + "]";
1672 }
1673 else if (entry[i].isFile()) { //Entry is file
1674 totalSize = totalSize + entry[i].length();
1675 fileCount = fileCount + 1;
1676 if (entry[i].canRead()) {
1677 dlink = ahref + "downfile=" + name + "\">Download</a>";
1678 if (USE_POPUP) link = ahref + "file=" + name + "\" target=\"_blank\">"
1679 + buf + "</a>";
1680 else link = ahref + "file=" + name + "\">" + buf + "</a>";
1681 if (entry[i].canWrite()) { // The file can be edited
1682 if (isPacked(name, true)) elink = ahref + "unpackfile=" + name
1683 + "\">Unpack</a>";
1684 else elink = ahref + "editfile=" + name + "\">Edit</a>";
1685 }
1686 else {
1687 if (isPacked(name, true)) elink = ahref + "unpackfile=" + name
1688 + "\">Unpack</a>";
1689 else elink = ahref + "editfile=" + name + "\">View</a>";
1690 }
1691 }
1692 else {
1693 link = buf;
1694 }
1695 }
1696 String date = dateFormat.format(new Date(entry[i].lastModified()));
1697 out.println("<tr class=\"mouseout\" onmouseup=\"selrow(this, 2)\" "
1698 + "onmouseover=\"selrow(this, 0);\" onmouseout=\"selrow(this, 1)\">");
1699 if (entry[i].canRead()) {
1700 out.println("<td align=center><input type=\"checkbox\" name=\"selfile\" value=\""
1701 + name + "\" onmousedown=\"dis()\"></td>");
1702 }
1703 else {
1704 out.println("<td align=center><input type=\"checkbox\" name=\"selfile\" disabled></td>");
1705 }
1706 out.print("<td align=left> " + link + "</td>");
1707 if (entry[i].isDirectory()) out.print("<td> </td>");
1708 else {
1709 out.print("<td align=right title=\"" + entry[i].length() + " bytes\">"
1710 + convertFileSize(entry[i].length()) + "</td>");
1711 }
1712 out.println("<td align=\"center\">" + type + "</td><td align=left> " + // The file type (extension)
1713 date + "</td><td>" + // The date the file was created
1714 dlink + "</td>"); // The download link
1715 if (!READ_ONLY)
1716 out.print ("<td>" + elink + "</td>"); // The edit link (or view, depending)
1717 out.println("</tr>");
1718 }
1719 }%>
1720 </table>
1721 <input type="checkbox" name="selall" onClick="AllFiles(this.form)">Select all
1722 <p align=center>
1723 <b title="<%=totalSize%> bytes">
1724 <%=convertFileSize(totalSize)%></b><b> in <%=fileCount%> files in <%= dir2linkdir((String) request.getAttribute("dir"), browser_name, sortMode)%>
1725 </b>
1726 </p>
1727 <input type="hidden" name="dir" value="<%=request.getAttribute("dir")%>">
1728 <input type="hidden" name="sort" value="<%=sortMode%>">
1729 <input title="Download selected files and directories as one zip file" class="button" id="but_Zip" type="Submit" name="Submit" value="<%=SAVE_AS_ZIP%>">
1730 <% if (!READ_ONLY) {%>
1731 <input title="Delete all selected files and directories incl. subdirs" class="button" id="but_Del" type="Submit" name="Submit" value="<%=DELETE_FILES%>"
1732 onclick="return confirm('Do you really want to delete the entries?')">
1733 <% } %>
1734 <% if (!READ_ONLY) {%>
1735 <br />
1736 <input title="Enter new dir or filename or the relative or absolute path" class="textfield" type="text" onKeypress="event.cancelBubble=true;" id="text_Dir" name="cr_dir">
1737 <input title="Create a new directory with the given name" class="button" id="but_NDi" type="Submit" name="Submit" value="<%=CREATE_DIR%>">
1738 <input title="Create a new empty file with the given name" class="button" id="but_NFi" type="Submit" name="Submit" value="<%=CREATE_FILE%>">
1739 <input title="Move selected files and directories to the entered path" id="but_Mov" class="button" type="Submit" name="Submit" value="<%=MOVE_FILES%>">
1740 <input title="Copy selected files and directories to the entered path" id="but_Cop" class="button" type="Submit" name="Submit" value="<%=COPY_FILES%>">
1741 <input title="Rename selected file or directory to the entered name" id="but_Ren" class="button" type="Submit" name="Submit" value="<%=RENAME_FILE%>">
1742 <% } %>
1743 </form>
1744 <br />
1745 <div class="formular">
1746 <% if (ALLOW_UPLOAD) { %>
1747 <form class="formular2" action="<%= browser_name%>" enctype="multipart/form-data" method="POST">
1748 <input type="hidden" name="dir" value="<%=request.getAttribute("dir")%>">
1749 <input type="hidden" name="sort" value="<%=sortMode%>">
1750 <input type="file" class="textfield" onKeypress="event.cancelBubble=true;" name="myFile">
1751 <input title="Upload selected file to the current working directory" type="Submit" class="button" name="Submit" value="<%=UPLOAD_FILES%>"
1752 onClick="javascript:popUp('<%= browser_name%>')">
1753 </form>
1754 <%} %>
1755 <% if (NATIVE_COMMANDS) {%>
1756 <form class="formular2" action="<%= browser_name%>" method="POST">
1757 <input type="hidden" name="dir" value="<%=request.getAttribute("dir")%>">
1758 <input type="hidden" name="sort" value="<%=sortMode%>">
1759 <input type="hidden" name="command" value="">
1760 <input title="Launch command in current directory" type="Submit" class="button" id="but_Lau" name="Submit" value="<%=LAUNCH_COMMAND%>">
1761 </form><%
1762 }%>
1763 </div>
1764 <%}%>
1765 <hr>
1766 <center>
1767 <small>jsp File Browser version <%= VERSION_NR%> by <a href="http://www.vonloesch.de">www.vonloesch.de</a></small>
1768 </center>
1769</body>
1770</html><%
1771 }
1772%>