Debian Codegraph @

src/tools/org/h2/dev/ftp/server/FtpControl.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.BufferedReader;
9 import java.io.IOException;
10 import java.io.InputStreamReader;
11 import java.io.OutputStreamWriter;
12 import java.io.PrintWriter;
13 import java.net.InetAddress;
14 import java.net.ServerSocket;
15 import java.net.Socket;
16 import java.nio.charset.StandardCharsets;
17
18 import org.h2.store.fs.FileUtils;
19 import org.h2.util.StringUtils;
20
21 /**
22 * The implementation of the control channel of the FTP server.
23 */
24 public class FtpControl extends Thread {
25
26 private static final String SERVER_NAME = "Small FTP Server";
27
28 private final FtpServer server;
29 private final Socket control;
30 private FtpData data;
31 private PrintWriter output;
32 private String userName;
33 private boolean connected, readonly;
34 private String currentDir = "/";
35 private String serverIpAddress;
36 private boolean stop;
37 private String renameFrom;
38 private boolean replied;
39 private long restart;
40
41 FtpControl(Socket control, FtpServer server, boolean stop) {
42 this.server = server;
43 this.control = control;
44 this.stop = stop;
45 }
46
47 @Override
48 public void run() {
49 try {
50 output = new PrintWriter(new OutputStreamWriter(
51 control.getOutputStream(), StandardCharsets.UTF_8));
52 if (stop) {
53 reply(421, "Too many users");
54 } else {
55 reply(220, SERVER_NAME);
56 // TODO need option to configure the serverIpAddress?
57 serverIpAddress = control.getLocalAddress().getHostAddress().replace('.', ',');
58 BufferedReader input = new BufferedReader(
59 new InputStreamReader(control.getInputStream()));
60 while (!stop) {
61 String command = null;
62 try {
63 command = input.readLine();
64 } catch (IOException e) {
65 // ignore
66 }
67 if (command == null) {
68 break;
69 }
70 process(command);
71 }
72 if (data != null) {
73 data.close();
74 }
75 }
76 } catch (Throwable t) {
77 server.traceError(t);
78 }
79 server.closeConnection();
80 }
81
82 private void process(String command) throws IOException {
83 int idx = command.indexOf(' ');
84 String param = "";
85 if (idx >= 0) {
86 param = command.substring(idx).trim();
87 command = command.substring(0, idx);
88 }
89 command = StringUtils.toUpperEnglish(command);
90 if (command.length() == 0) {
91 reply(506, "No command");
92 return;
93 }
94 server.trace(">" + command);
95 FtpEventListener listener = server.getEventListener();
96 FtpEvent event = null;
97 if (listener != null) {
98 event = new FtpEvent(this, command, param);
99 listener.beforeCommand(event);
100 }
101 replied = false;
102 if (connected) {
103 processConnected(command, param);
104 }
105 if (!replied) {
106 if ("USER".equals(command)) {
107 userName = param;
108 reply(331, "Need password");
109 } else if ("QUIT".equals(command)) {
110 reply(221, "Bye");
111 stop = true;
112 } else if ("PASS".equals(command)) {
113 if (userName == null) {
114 reply(332, "Need username");
115 } else if (server.checkUserPasswordWrite(userName, param)) {
116 reply(230, "Ok");
117 readonly = false;
118 connected = true;
119 } else if (server.checkUserPasswordReadOnly(userName)) {
120 reply(230, "Ok, readonly");
121 readonly = true;
122 connected = true;
123 } else {
124 reply(431, "Wrong user/password");
125 }
126 } else if ("REIN".equals(command)) {
127 userName = null;
128 connected = false;
129 currentDir = "/";
130 reply(200, "Ok");
131 } else if ("HELP".equals(command)) {
132 reply(214, SERVER_NAME);
133 }
134 }
135 if (!replied) {
136 if (listener != null) {
137 listener.onUnsupportedCommand(event);
138 }
139 reply(506, "Invalid command");
140 }
141 if (listener != null) {
142 listener.afterCommand(event);
143 }
144 }
145
146 private void processConnected(String command, String param) throws IOException {
147 switch (command.charAt(0)) {
148 case 'C':
149 if ("CWD".equals(command)) {
150 String path = getPath(param);
151 String fileName = getFileName(path);
152 if (FileUtils.exists(fileName) && FileUtils.isDirectory(fileName)) {
153 if (!path.endsWith("/")) {
154 path += "/";
155 }
156 currentDir = path;
157 reply(250, "Ok");
158 } else {
159 reply(550, "Failed");
160 }
161 } else if ("CDUP".equals(command)) {
162 if (currentDir.length() > 1) {
163 int idx = currentDir.lastIndexOf('/', currentDir.length() - 2);
164 currentDir = currentDir.substring(0, idx + 1);
165 reply(250, "Ok");
166 } else {
167 reply(550, "Failed");
168 }
169 }
170 break;
171 case 'D':
172 if ("DELE".equals(command)) {
173 String fileName = getFileName(param);
174 if (!readonly && FileUtils.exists(fileName)
175 && !FileUtils.isDirectory(fileName)
176 && FileUtils.tryDelete(fileName)) {
177 if (server.getAllowTask() && fileName.endsWith(FtpServer.TASK_SUFFIX)) {
178 server.stopTask(fileName);
179 }
180 reply(250, "Ok");
181 } else {
182 reply(500, "Delete failed");
183 }
184 }
185 break;
186 case 'L':
187 if ("LIST".equals(command)) {
188 processList(param, true);
189 }
190 break;
191 case 'M':
192 if ("MKD".equals(command)) {
193 processMakeDir(param);
194 } else if ("MODE".equals(command)) {
195 if ("S".equals(StringUtils.toUpperEnglish(param))) {
196 reply(200, "Ok");
197 } else {
198 reply(504, "Invalid");
199 }
200 } else if ("MDTM".equals(command)) {
201 String fileName = getFileName(param);
202 if (FileUtils.exists(fileName) && !FileUtils.isDirectory(fileName)) {
203 reply(213, server.formatLastModified(fileName));
204 } else {
205 reply(550, "Failed");
206 }
207 }
208 break;
209 case 'N':
210 if ("NLST".equals(command)) {
211 processList(param, false);
212 } else if ("NOOP".equals(command)) {
213 reply(200, "Ok");
214 }
215 break;
216 case 'P':
217 if ("PWD".equals(command)) {
218 reply(257, StringUtils.quoteIdentifier(currentDir) + " directory");
219 } else if ("PASV".equals(command)) {
220 ServerSocket dataSocket = FtpServer.createDataSocket();
221 data = new FtpData(server, control.getInetAddress(), dataSocket);
222 data.start();
223 int port = dataSocket.getLocalPort();
224 reply(227, "Passive Mode (" + serverIpAddress + ","
225 + (port >> 8) + "," + (port & 255) + ")");
226 } else if ("PORT".equals(command)) {
227 String[] list = StringUtils.arraySplit(param, ',', true);
228 String host = list[0] + "." + list[1] + "." + list[2] + "." + list[3];
229 int port = (Integer.parseInt(list[4]) << 8) | Integer.parseInt(list[5]);
230 InetAddress address = InetAddress.getByName(host);
231 if (address.equals(control.getInetAddress())) {
232 data = new FtpData(server, address, port);
233 reply(200, "Ok");
234 } else {
235 server.trace("Port REJECTED:" + address + " expected:"
236 + control.getInetAddress());
237 reply(550, "Failed");
238 }
239 }
240 break;
241 case 'R':
242 if ("RNFR".equals(command)) {
243 String fileName = getFileName(param);
244 if (FileUtils.exists(fileName)) {
245 renameFrom = fileName;
246 reply(350, "Ok");
247 } else {
248 reply(450, "Not found");
249 }
250 } else if ("RNTO".equals(command)) {
251 if (renameFrom == null) {
252 reply(503, "RNFR required");
253 } else {
254 String fileOld = renameFrom;
255 String fileNew = getFileName(param);
256 boolean ok = false;
257 if (!readonly) {
258 try {
259 FileUtils.move(fileOld, fileNew);
260 reply(250, "Ok");
261 ok = true;
262 } catch (Exception e) {
263 server.traceError(e);
264 }
265 }
266 if (!ok) {
267 reply(550, "Failed");
268 }
269 }
270 } else if ("RETR".equals(command)) {
271 String fileName = getFileName(param);
272 if (FileUtils.exists(fileName) && !FileUtils.isDirectory(fileName)) {
273 reply(150, "Starting transfer");
274 try {
275 data.send(fileName, restart);
276 reply(226, "Ok");
277 } catch (IOException e) {
278 server.traceError(e);
279 reply(426, "Failed");
280 }
281 restart = 0;
282 } else {
283 // Firefox compatibility
284 // (still not good)
285 processList(param, true);
286 // reply(426, "Not a file");
287 }
288 } else if ("RMD".equals(command)) {
289 processRemoveDir(param);
290 } else if ("REST".equals(command)) {
291 try {
292 restart = Integer.parseInt(param);
293 reply(350, "Ok");
294 } catch (NumberFormatException e) {
295 reply(500, "Invalid");
296 }
297 }
298 break;
299 case 'S':
300 if ("SYST".equals(command)) {
301 reply(215, "UNIX Type: L8");
302 } else if ("SITE".equals(command)) {
303 reply(500, "Not understood");
304 } else if ("SIZE".equals(command)) {
305 param = getFileName(param);
306 if (FileUtils.exists(param) && !FileUtils.isDirectory(param)) {
307 reply(250, Long.toString(FileUtils.size(param)));
308 } else {
309 reply(500, "Failed");
310 }
311 } else if ("STOR".equals(command)) {
312 String fileName = getFileName(param);
313 if (!readonly && !FileUtils.exists(fileName)
314 || !FileUtils.isDirectory(fileName)) {
315 reply(150, "Starting transfer");
316 try {
317 data.receive(fileName);
318 if (server.getAllowTask() && param.endsWith(FtpServer.TASK_SUFFIX)) {
319 server.startTask(fileName);
320 }
321 reply(226, "Ok");
322 } catch (Exception e) {
323 server.traceError(e);
324 reply(426, "Failed");
325 }
326 } else {
327 reply(550, "Failed");
328 }
329 } else if ("STRU".equals(command)) {
330 if ("F".equals(StringUtils.toUpperEnglish(param))) {
331 reply(200, "Ok");
332 } else {
333 reply(504, "Invalid");
334 }
335 }
336 break;
337 case 'T':
338 if ("TYPE".equals(command)) {
339 param = StringUtils.toUpperEnglish(param);
340 if ("A".equals(param) || "A N".equals(param)) {
341 reply(200, "Ok");
342 } else if ("I".equals(param) || "L 8".equals(param)) {
343 reply(200, "Ok");
344 } else {
345 reply(500, "Invalid");
346 }
347 }
348 break;
349 case 'X':
350 if ("XMKD".equals(command)) {
351 processMakeDir(param);
352 } else if ("XRMD".equals(command)) {
353 processRemoveDir(param);
354 }
355 break;
356 }
357 }
358
359 private void processMakeDir(String param) {
360 String fileName = getFileName(param);
361 boolean ok = false;
362 if (!readonly) {
363 try {
364 FileUtils.createDirectories(fileName);
365 reply(257, StringUtils.quoteIdentifier(param) + " directory");
366 ok = true;
367 } catch (Exception e) {
368 server.traceError(e);
369 }
370 }
371 if (!ok) {
372 reply(500, "Failed");
373 }
374 }
375
376 private void processRemoveDir(String param) {
377 String fileName = getFileName(param);
378 if (!readonly && FileUtils.exists(fileName)
379 && FileUtils.isDirectory(fileName)
380 && FileUtils.tryDelete(fileName)) {
381 reply(250, "Ok");
382 } else {
383 reply(500, "Failed");
384 }
385 }
386
387 private String getFileName(String file) {
388 return server.getFileName(file.startsWith("/") ? file : currentDir + file);
389 }
390
391 private String getPath(String path) {
392 return path.startsWith("/") ? path : currentDir + path;
393 }
394
395 private void processList(String param, boolean directories) throws IOException {
396 String directory = getFileName(param);
397 if (!FileUtils.exists(directory)) {
398 reply(450, "Directory does not exist");
399 return;
400 } else if (!FileUtils.isDirectory(directory)) {
401 reply(450, "Not a directory");
402 return;
403 }
404 String list = server.getDirectoryListing(directory, directories);
405 reply(150, "Starting transfer");
406 server.trace(list);
407 // need to use the current locale (UTF-8 would be wrong for the Windows
408 // Explorer)
409 data.send(list.getBytes());
410 reply(226, "Done");
411 }
412
413 private void reply(int code, String message) {
414 server.trace(code + " " + message);
415 output.print(code + " " + message + "\r\n");
416 output.flush();
417 replied = true;
418 }
419
420 }