Debian Codegraph @

src/tools/org/h2/dev/ftp/server/FtpServer.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.ftp.server;
7
8 import java.io.File;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.net.ServerSocket;
13 import java.net.Socket;
14 import java.sql.SQLException;
15 import java.text.SimpleDateFormat;
16 import java.util.Date;
17 import java.util.HashMap;
18 import java.util.Locale;
19 import java.util.Properties;
20 import org.h2.server.Service;
21 import org.h2.store.fs.FileUtils;
22 import org.h2.tools.Server;
23 import org.h2.util.IOUtils;
24 import org.h2.util.NetUtils;
25 import org.h2.util.SortedProperties;
26 import org.h2.util.Tool;
27
28 /**
29 * Small FTP Server. Intended for ad-hoc networks in a secure environment.
30 * Remote connections are possible.
31 * See also https://cr.yp.to/ftp.html http://www.ftpguide.com/
32 */
33 public class FtpServer extends Tool implements Service {
34
35 /**
36 * The default port to use for the FTP server.
37 * This value is also in the documentation and in the Server javadoc.
38 */
39 public static final int DEFAULT_PORT = 8021;
40
41 /**
42 * The default root directory name used by the FTP server.
43 * This value is also in the documentation and in the Server javadoc.
44 */
45 public static final String DEFAULT_ROOT = "ftp";
46
47 /**
48 * The default user name that is allowed to read data.
49 * This value is also in the documentation and in the Server javadoc.
50 */
51 public static final String DEFAULT_READ = "guest";
52
53 /**
54 * The default user name that is allowed to read and write data.
55 * This value is also in the documentation and in the Server javadoc.
56 */
57 public static final String DEFAULT_WRITE = "sa";
58
59 /**
60 * The default password of the user that is allowed to read and write data.
61 * This value is also in the documentation and in the Server javadoc.
62 */
63 public static final String DEFAULT_WRITE_PASSWORD = "sa";
64
65 static final String TASK_SUFFIX = ".task";
66
67 private static final int MAX_CONNECTION_COUNT = 100;
68
69 private ServerSocket serverSocket;
70 private int port = DEFAULT_PORT;
71 private int openConnectionCount;
72
73 private final SimpleDateFormat dateFormatNew = new SimpleDateFormat(
74 "MMM dd HH:mm", Locale.ENGLISH);
75 private final SimpleDateFormat dateFormatOld = new SimpleDateFormat(
76 "MMM dd yyyy", Locale.ENGLISH);
77 private final SimpleDateFormat dateFormat = new SimpleDateFormat(
78 "yyyyMMddHHmmss");
79
80 private String root = DEFAULT_ROOT;
81 private String writeUserName = DEFAULT_WRITE,
82 writePassword = DEFAULT_WRITE_PASSWORD;
83 private String readUserName = DEFAULT_READ;
84 private final HashMap<String, Process> tasks = new HashMap<>();
85
86 private boolean trace;
87 private boolean allowTask;
88
89 private FtpEventListener eventListener;
90
91
92 /**
93 * When running without options, -tcp, -web, -browser,
94 * and -pg are started.
95 * Options are case sensitive.
96 * <table>
97 * <caption>Supported options</caption>
98 * <tr><td>[-help] or [-?]</td>
99 * <td>Print the list of options</td></tr>
100 * <tr><td>[-web]</td>
101 * <td>Start the web server with the H2 Console</td></tr>
102 * <tr><td>[-webAllowOthers]</td>
103 * <td>Allow other computers to connect</td></tr>
104 * <tr><td>[-webPort &lt;port&gt;]</td>
105 * <td>The port (default: 8082)</td></tr>
106 * <tr><td>[-webSSL]</td>
107 * <td>Use encrypted (HTTPS) connections</td></tr>
108 * <tr><td>[-browser]</td>
109 * <td>Start a browser and open a page to login to the web server</td></tr>
110 * <tr><td>[-tcp]</td>
111 * <td>Start the TCP server</td></tr>
112 * <tr><td>[-tcpAllowOthers]</td>
113 * <td>Allow other computers to connect</td></tr>
114 * <tr><td>[-tcpPort &lt;port&gt;]</td>
115 * <td>The port (default: 9092)</td></tr>
116 * <tr><td>[-tcpSSL]</td>
117 * <td>Use encrypted (SSL) connections</td></tr>
118 * <tr><td>[-tcpPassword &lt;pwd&gt;]</td>
119 * <td>The password for shutting down a TCP server</td></tr>
120 * <tr><td>[-tcpShutdown "&lt;url&gt;"]</td>
121 * <td>Stop the TCP server; example: tcp://localhost:9094</td></tr>
122 * <tr><td>[-tcpShutdownForce]</td>
123 * <td>Do not wait until all connections are closed</td></tr>
124 * <tr><td>[-pg]</td>
125 * <td>Start the PG server</td></tr>
126 * <tr><td>[-pgAllowOthers]</td>
127 * <td>Allow other computers to connect</td></tr>
128 * <tr><td>[-pgPort &lt;port&gt;]</td>
129 * <td>The port (default: 5435)</td></tr>
130 * <tr><td>[-ftp]</td>
131 * <td>Start the FTP server</td></tr>
132 * <tr><td>[-ftpPort &lt;port&gt;]</td>
133 * <td>The port (default: 8021)</td></tr>
134 * <tr><td>[-ftpDir &lt;dir&gt;]</td>
135 * <td>The base directory (default: ftp)</td></tr>
136 * <tr><td>[-ftpRead &lt;user&gt;]</td>
137 * <td>The user name for reading (default: guest)</td></tr>
138 * <tr><td>[-ftpWrite &lt;user&gt;]</td>
139 * <td>The user name for writing (default: sa)</td></tr>
140 * <tr><td>[-ftpWritePassword &lt;p&gt;]</td>
141 * <td>The write password (default: sa)</td></tr>
142 * <tr><td>[-baseDir &lt;dir&gt;]</td>
143 * <td>The base directory for H2 databases; for all servers</td></tr>
144 * <tr><td>[-ifExists]</td>
145 * <td>Only existing databases may be opened; for all servers</td></tr>
146 * <tr><td>[-trace]</td>
147 * <td>Print additional trace information; for all servers</td></tr>
148 * </table>
149 *
150 * @param args the command line arguments
151 */
152 public static void main(String... args) throws SQLException {
153 new FtpServer().runTool(args);
154 }
155
156 @Override
157 public void runTool(String... args) throws SQLException {
158 for (int i = 0; args != null && i < args.length; i++) {
159 String arg = args[i];
160 if (arg == null) {
161 continue;
162 } else if ("-?".equals(arg) || "-help".equals(arg)) {
163 showUsage();
164 return;
165 } else if (arg.startsWith("-ftp")) {
166 if ("-ftpPort".equals(arg)) {
167 i++;
168 } else if ("-ftpDir".equals(arg)) {
169 i++;
170 } else if ("-ftpRead".equals(arg)) {
171 i++;
172 } else if ("-ftpWrite".equals(arg)) {
173 i++;
174 } else if ("-ftpWritePassword".equals(arg)) {
175 i++;
176 } else if ("-ftpTask".equals(arg)) {
177 // no parameters
178 } else {
179 showUsageAndThrowUnsupportedOption(arg);
180 }
181 } else if ("-trace".equals(arg)) {
182 // no parameters
183 } else {
184 showUsageAndThrowUnsupportedOption(arg);
185 }
186 }
187 Server server = new Server(this, args);
188 server.start();
189 out.println(server.getStatus());
190 }
191
192 @Override
193 public void listen() {
194 try {
195 while (serverSocket != null) {
196 Socket s = serverSocket.accept();
197 boolean stop;
198 synchronized (this) {
199 openConnectionCount++;
200 stop = openConnectionCount > MAX_CONNECTION_COUNT;
201 }
202 FtpControl c = new FtpControl(s, this, stop);
203 c.start();
204 }
205 } catch (Exception e) {
206 traceError(e);
207 }
208 }
209
210 /**
211 * Close a connection. The open connection count will be decremented.
212 */
213 void closeConnection() {
214 synchronized (this) {
215 openConnectionCount--;
216 }
217 }
218
219 /**
220 * Create a socket to listen for incoming data connections.
221 *
222 * @return the server socket
223 */
224 static ServerSocket createDataSocket() {
225 return NetUtils.createServerSocket(0, false);
226 }
227
228 private void appendFile(StringBuilder buff, String fileName) {
229 buff.append(FileUtils.isDirectory(fileName) ? 'd' : '-');
230 buff.append('r');
231 buff.append(FileUtils.canWrite(fileName) ? 'w' : '-');
232 buff.append("------- 1 owner group ");
233 String size = Long.toString(FileUtils.size(fileName));
234 for (int i = size.length(); i < 15; i++) {
235 buff.append(' ');
236 }
237 buff.append(size);
238 buff.append(' ');
239 Date now = new Date(), mod = new Date(FileUtils.lastModified(fileName));
240 String date;
241 if (mod.after(now)
242 || Math.abs((now.getTime() - mod.getTime()) /
243 1000 / 60 / 60 / 24) > 180) {
244 synchronized (dateFormatOld) {
245 date = dateFormatOld.format(mod);
246 }
247 } else {
248 synchronized (dateFormatNew) {
249 date = dateFormatNew.format(mod);
250 }
251 }
252 buff.append(date);
253 buff.append(' ');
254 buff.append(FileUtils.getName(fileName));
255 buff.append("\r\n");
256 }
257
258 /**
259 * Get the last modified date of a date and format it as required by the FTP
260 * protocol.
261 *
262 * @param fileName the file name
263 * @return the last modified date of this file
264 */
265 String formatLastModified(String fileName) {
266 synchronized (dateFormat) {
267 return dateFormat.format(new Date(FileUtils.lastModified(fileName)));
268 }
269 }
270
271 /**
272 * Get the full file name of this relative path.
273 *
274 * @param path the relative path
275 * @return the file name
276 */
277 String getFileName(String path) {
278 return root + getPath(path);
279 }
280
281 private String getPath(String path) {
282 if (path.indexOf("..") > 0) {
283 path = "/";
284 }
285 while (path.startsWith("/") && root.endsWith("/")) {
286 path = path.substring(1);
287 }
288 while (path.endsWith("/")) {
289 path = path.substring(0, path.length() - 1);
290 }
291 trace("path: " + path);
292 return path;
293 }
294
295 /**
296 * Get the directory listing for this directory.
297 *
298 * @param directory the directory to list
299 * @param listDirectories if sub-directories should be listed
300 * @return the list
301 */
302 String getDirectoryListing(String directory, boolean listDirectories) {
303 StringBuilder buff = new StringBuilder();
304 for (String fileName : FileUtils.newDirectoryStream(directory)) {
305 if (!FileUtils.isDirectory(fileName)
306 || (FileUtils.isDirectory(fileName) && listDirectories)) {
307 appendFile(buff, fileName);
308 }
309 }
310 return buff.toString();
311 }
312
313 /**
314 * Check if this user name is allowed to write.
315 *
316 * @param userName the user name
317 * @param password the password
318 * @return true if this user may write
319 */
320 boolean checkUserPasswordWrite(String userName, String password) {
321 return userName.equals(this.writeUserName)
322 && password.equals(this.writePassword);
323 }
324
325 /**
326 * Check if this user name is allowed to read.
327 *
328 * @param userName the user name
329 * @return true if this user may read
330 */
331 boolean checkUserPasswordReadOnly(String userName) {
332 return userName.equals(this.readUserName);
333 }
334
335 @Override
336 public void init(String... args) {
337 for (int i = 0; args != null && i < args.length; i++) {
338 String a = args[i];
339 if ("-ftpPort".equals(a)) {
340 port = Integer.decode(args[++i]);
341 } else if ("-ftpDir".equals(a)) {
342 root = FileUtils.toRealPath(args[++i]);
343 } else if ("-ftpRead".equals(a)) {
344 readUserName = args[++i];
345 } else if ("-ftpWrite".equals(a)) {
346 writeUserName = args[++i];
347 } else if ("-ftpWritePassword".equals(a)) {
348 writePassword = args[++i];
349 } else if ("-trace".equals(a)) {
350 trace = true;
351 } else if ("-ftpTask".equals(a)) {
352 allowTask = true;
353 }
354 }
355 }
356
357 @Override
358 public String getURL() {
359 return "ftp://" + NetUtils.getLocalAddress() + ":" + port;
360 }
361
362 @Override
363 public int getPort() {
364 return port;
365 }
366
367 @Override
368 public void start() {
369 root = FileUtils.toRealPath(root);
370 FileUtils.createDirectories(root);
371 serverSocket = NetUtils.createServerSocket(port, false);
372 port = serverSocket.getLocalPort();
373 }
374
375 @Override
376 public void stop() {
377 if (serverSocket == null) {
378 return;
379 }
380 try {
381 serverSocket.close();
382 } catch (IOException e) {
383 traceError(e);
384 }
385 serverSocket = null;
386 }
387
388 @Override
389 public boolean isRunning(boolean traceError) {
390 if (serverSocket == null) {
391 return false;
392 }
393 try {
394 Socket s = NetUtils.createLoopbackSocket(port, false);
395 s.close();
396 return true;
397 } catch (IOException e) {
398 if (traceError) {
399 traceError(e);
400 }
401 return false;
402 }
403 }
404
405 @Override
406 public boolean getAllowOthers() {
407 return true;
408 }
409
410 @Override
411 public String getType() {
412 return "FTP";
413 }
414
415 @Override
416 public String getName() {
417 return "H2 FTP Server";
418 }
419
420 /**
421 * Write trace information if trace is enabled.
422 *
423 * @param s the message to write
424 */
425 void trace(String s) {
426 if (trace) {
427 System.out.println(s);
428 }
429 }
430
431 /**
432 * Write the stack trace if trace is enabled.
433 *
434 * @param e the exception
435 */
436 void traceError(Throwable e) {
437 if (trace) {
438 e.printStackTrace();
439 }
440 }
441
442 boolean getAllowTask() {
443 return allowTask;
444 }
445
446 /**
447 * Start a task.
448 *
449 * @param path the name of the task file
450 */
451 void startTask(String path) throws IOException {
452 stopTask(path);
453 if (path.endsWith(".zip.task")) {
454 trace("expand: " + path);
455 Process p = Runtime.getRuntime().exec("jar -xf " + path, null, new File(root));
456 new StreamRedirect(path, p.getInputStream(), null).start();
457 return;
458 }
459 Properties prop = SortedProperties.loadProperties(path);
460 String command = prop.getProperty("command");
461 String outFile = path.substring(0, path.length() - TASK_SUFFIX.length());
462 String errorFile = root + "/"
463 + prop.getProperty("error", outFile + ".err.txt");
464 String outputFile = root + "/"
465 + prop.getProperty("output", outFile + ".out.txt");
466 trace("start process: " + path + " / " + command);
467 Process p = Runtime.getRuntime().exec(command, null, new File(root));
468 new StreamRedirect(path, p.getErrorStream(), errorFile).start();
469 new StreamRedirect(path, p.getInputStream(), outputFile).start();
470 tasks.put(path, p);
471 }
472
473 /**
474 * This class re-directs an input stream to a file.
475 */
476 private static class StreamRedirect extends Thread {
477 private final InputStream in;
478 private OutputStream out;
479 private String outFile;
480 private final String processFile;
481
482 StreamRedirect(String processFile, InputStream in, String outFile) {
483 this.processFile = processFile;
484 this.in = in;
485 this.outFile = outFile;
486 }
487
488 private void openOutput() {
489 if (outFile != null) {
490 try {
491 this.out = FileUtils.newOutputStream(outFile, false);
492 } catch (Exception e) {
493 // ignore
494 }
495 outFile = null;
496 }
497 }
498
499 @Override
500 public void run() {
501 while (true) {
502 try {
503 int x = in.read();
504 if (x < 0) {
505 break;
506 }
507 openOutput();
508 if (out != null) {
509 out.write(x);
510 }
511 } catch (IOException e) {
512 // ignore
513 }
514 }
515 IOUtils.closeSilently(out);
516 IOUtils.closeSilently(in);
517 new File(processFile).delete();
518 }
519 }
520
521 /**
522 * Stop a running task.
523 *
524 * @param processName the task name
525 */
526 void stopTask(String processName) {
527 trace("kill process: " + processName);
528 Process p = tasks.remove(processName);
529 if (p == null) {
530 return;
531 }
532 p.destroy();
533 }
534
535 /**
536 * Set the event listener. Only one listener can be registered.
537 *
538 * @param eventListener the new listener, or null to de-register
539 */
540 public void setEventListener(FtpEventListener eventListener) {
541 this.eventListener = eventListener;
542 }
543
544 /**
545 * Get the registered event listener.
546 *
547 * @return the event listener, or null if non is registered
548 */
549 FtpEventListener getEventListener() {
550 return eventListener;
551 }
552
553 /**
554 * Create a new FTP server, but does not start it yet. Example:
555 *
556 * <pre>
557 * Server server = FtpServer.createFtpServer(null).start();
558 * </pre>
559 *
560 * @param args the argument list
561 * @return the server
562 */
563 public static Server createFtpServer(String... args) throws SQLException {
564 return new Server(new FtpServer(), args);
565 }
566
567 @Override
568 public boolean isDaemon() {
569 return false;
570 }
571
572 }