Compare commits

..

5 Commits

Author SHA1 Message Date
5faa970b79 Feat: 다중 사용자 인증 시스템 구현
- EncryptedSharedPreferences를 사용한 암호화된 사용자 저장
- SHA-256 해싱으로 비밀번호 보안 강화 (username을 salt로 사용)
- 사용자 CRUD 기능 (추가/수정/삭제/조회)
- 사용자 관리 UI 추가 (UserManagementActivity)
- FTP 인증 로직을 placeholder에서 실제 검증으로 변경
- 기본 admin/admin 사용자 자동 생성
- 마지막 사용자 삭제 방지 기능

보안 기능:
- 이중 보안: 비밀번호 해싱 + EncryptedSharedPreferences
- 평문 저장 없음
- 유효성 검사 (username: 3-20자 영숫자+_, password: 최소 4자)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-02 05:52:05 +09:00
0c3b7054bd Fix: Windows에서 한글 파일명 분리 현상 해결
FTP RFC 2640 표준에 따라 파일명을 NFC 형식으로 전송하도록 변경.
- 기존 NFD 변환 코드 제거 (convertFileListToNFD, denormalizeFilename 호출)
- Windows 클라이언트: NFC로 받아 한글이 정상 표시
- Mac 클라이언트: NFC를 자동으로 NFD 변환하여 처리
- 파일 검색 시 NFD/NFC 양방향 호환성은 findFileWithNormalization()으로 유지

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-02 05:02:06 +09:00
3357fe76d4 Feat: 데이터 포트 범위 지정 기능 추가
방화벽 환경에서 특정 포트 범위만 개방하여 사용할 수 있도록 데이터 포트 범위 설정 기능 추가.
- FTPConfig에 minDataPort, maxDataPort 설정 추가 (기본값: 50000-50100)
- FTPDataConnection에서 지정된 범위 내 사용 가능한 포트 자동 할당
- MainActivity UI에 데이터 포트 범위 설정 필드 추가
- 포트 범위 유효성 검증 (최소 10개 포트, 1024-65535 범위)
- 범위 미지정 시 기존처럼 랜덤 포트 사용

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-02 04:33:53 +09:00
12f27e9f13 Fix: 앱 재시작 시 UI 상태와 서비스 상태 동기화 문제 해결
onResume()에서 실제 FTPService 실행 상태를 확인하여 UI를 동기화함으로써 화면 전환 또는 앱 재시작 시에도 올바른 버튼 상태가 표시되도록 수정.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-02 02:10:39 +09:00
e6e4ef7df5 Fix: macOS 한글 파일명 유니코드 정규화 문제 해결
macOS NFD와 Android NFC 유니코드 정규화 차이로 인한 한글 파일명 처리 오류 수정.
파일 검색 시 NFD/NFC 모두 지원하도록 개선하여 macOS에서 업로드/다운로드/삭제 작업이 정상 동작함.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-02 00:58:17 +09:00
17 changed files with 1375 additions and 190 deletions

Binary file not shown.

View File

@@ -32,6 +32,7 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.security:security-crypto:1.1.0-alpha06'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

View File

@@ -31,6 +31,15 @@
</intent-filter>
</activity>
<activity
android:name=".UserManagementActivity"
android:label="Manage Users"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
<service
android:name=".FTPService"
android:enabled="true"

View File

@@ -9,8 +9,12 @@ public class FTPConfig {
private static final String KEY_PORT = "ftp_port";
private static final String KEY_ROOT_DIR_URI = "root_directory_uri";
private static final String KEY_ROOT_DIR_PATH = "root_directory_path";
private static final String KEY_MIN_DATA_PORT = "min_data_port";
private static final String KEY_MAX_DATA_PORT = "max_data_port";
private static final int DEFAULT_PORT = 2121;
private static final int DEFAULT_MIN_DATA_PORT = 50000;
private static final int DEFAULT_MAX_DATA_PORT = 50100;
private final SharedPreferences preferences;
@@ -60,4 +64,27 @@ public class FTPConfig {
.putString(KEY_ROOT_DIR_PATH, rootDirPath)
.apply();
}
public int getMinDataPort() {
return preferences.getInt(KEY_MIN_DATA_PORT, DEFAULT_MIN_DATA_PORT);
}
public void setMinDataPort(int port) {
preferences.edit().putInt(KEY_MIN_DATA_PORT, port).apply();
}
public int getMaxDataPort() {
return preferences.getInt(KEY_MAX_DATA_PORT, DEFAULT_MAX_DATA_PORT);
}
public void setMaxDataPort(int port) {
preferences.edit().putInt(KEY_MAX_DATA_PORT, port).apply();
}
public void setDataPortRange(int minPort, int maxPort) {
preferences.edit()
.putInt(KEY_MIN_DATA_PORT, minPort)
.putInt(KEY_MAX_DATA_PORT, maxPort)
.apply();
}
}

View File

@@ -20,14 +20,41 @@ public class FTPDataConnection {
private int passivePort;
public boolean openPassiveMode(InetAddress bindAddress) {
return openPassiveMode(bindAddress, 0, 0);
}
public boolean openPassiveMode(InetAddress bindAddress, int minPort, int maxPort) {
try {
if (minPort <= 0 || maxPort <= 0 || minPort > maxPort) {
// Use port 0 to get a random available port
passiveSocket = new ServerSocket(0, 1, bindAddress);
passiveSocket.setSoTimeout(DATA_CONNECTION_TIMEOUT);
passivePort = passiveSocket.getLocalPort();
Log.i(TAG, "Passive mode enabled on port: " + passivePort);
Log.i(TAG, "Passive mode enabled on random port: " + passivePort);
return true;
}
// Try to find an available port in the specified range
IOException lastException = null;
for (int port = minPort; port <= maxPort; port++) {
try {
passiveSocket = new ServerSocket(port, 1, bindAddress);
passiveSocket.setSoTimeout(DATA_CONNECTION_TIMEOUT);
passivePort = passiveSocket.getLocalPort();
Log.i(TAG, "Passive mode enabled on port: " + passivePort + " (range: " + minPort + "-" + maxPort + ")");
return true;
} catch (IOException e) {
lastException = e;
// Port is in use, try next port
}
}
// No available port found in range
Log.e(TAG, "No available port in range " + minPort + "-" + maxPort);
if (lastException != null) {
Log.e(TAG, "Last error: " + lastException.getMessage());
}
return false;
} catch (IOException e) {
Log.e(TAG, "Error opening passive mode: " + e.getMessage());
return false;

View File

@@ -1,9 +1,14 @@
package be.gyu.android.server.ftp;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import androidx.documentfile.provider.DocumentFile;
import java.io.File;
import java.text.Normalizer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -13,34 +18,41 @@ import java.util.Locale;
public class FTPFileSystem {
private static final String TAG = "FTPFileSystem";
private final File rootDirectory;
private File currentDirectory;
private final Context context;
private final DocumentFile rootDirectory;
private DocumentFile currentDirectory;
private final boolean useDocumentFile;
public FTPFileSystem() {
this(null);
public FTPFileSystem(Context context) {
this(context, null);
}
public FTPFileSystem(String rootDirectoryPath) {
if (rootDirectoryPath != null && !rootDirectoryPath.isEmpty()) {
// Use user-specified directory
File userDir = new File(rootDirectoryPath);
if (userDir.exists() && userDir.isDirectory()) {
public FTPFileSystem(Context context, Uri rootDirectoryUri) {
this.context = context;
if (rootDirectoryUri != null) {
// Use user-specified directory via DocumentFile
DocumentFile userDir = DocumentFile.fromTreeUri(context, rootDirectoryUri);
if (userDir != null && userDir.exists() && userDir.isDirectory()) {
this.rootDirectory = userDir;
Log.i(TAG, "Using user-specified root: " + rootDirectory.getAbsolutePath());
this.useDocumentFile = true;
Log.i(TAG, "Using user-specified root (DocumentFile): " + rootDirectoryUri);
} else {
Log.w(TAG, "User-specified directory does not exist: " + rootDirectoryPath);
Log.w(TAG, "User-specified directory does not exist: " + rootDirectoryUri);
this.rootDirectory = getDefaultRootDirectory();
this.useDocumentFile = false;
}
} else {
// Use default directory
this.rootDirectory = getDefaultRootDirectory();
this.useDocumentFile = false;
}
this.currentDirectory = rootDirectory;
Log.d(TAG, "File system initialized. Root: " + rootDirectory.getAbsolutePath());
Log.d(TAG, "File system initialized. Root: " + getDisplayPath(rootDirectory));
}
private File getDefaultRootDirectory() {
private DocumentFile getDefaultRootDirectory() {
File externalStorage = Environment.getExternalStorageDirectory();
File ftpServerDir = new File(externalStorage, "FTPServer");
@@ -48,14 +60,22 @@ public class FTPFileSystem {
if (!ftpServerDir.exists()) {
if (ftpServerDir.mkdirs()) {
Log.i(TAG, "Root directory created: " + ftpServerDir.getAbsolutePath());
return ftpServerDir;
} else {
Log.w(TAG, "Failed to create root directory, using external storage root");
return externalStorage;
ftpServerDir = externalStorage;
}
} else {
return ftpServerDir;
}
return DocumentFile.fromFile(ftpServerDir);
}
private String getDisplayPath(DocumentFile file) {
if (file == null) return "null";
Uri uri = file.getUri();
if (uri != null) {
return uri.toString();
}
return file.getName();
}
public String getCurrentPath() {
@@ -64,71 +84,55 @@ public class FTPFileSystem {
}
public boolean changeDirectory(String path) {
File newDir;
DocumentFile newDir;
if (path.startsWith("/")) {
// Absolute path
newDir = new File(rootDirectory, path.substring(1));
newDir = findDocumentFile(rootDirectory, path.substring(1));
} else {
// Relative path
newDir = new File(currentDirectory, path);
newDir = findDocumentFile(currentDirectory, path);
}
try {
String canonicalPath = newDir.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (newDir != null && newDir.exists() && newDir.isDirectory()) {
// Security check: prevent escaping root directory
if (!canonicalPath.startsWith(rootPath)) {
Log.w(TAG, "Attempted to escape root directory: " + canonicalPath);
return false;
}
if (newDir.exists() && newDir.isDirectory()) {
if (isSubDirectory(newDir, rootDirectory)) {
currentDirectory = newDir;
Log.d(TAG, "Changed directory to: " + currentDirectory.getAbsolutePath());
Log.d(TAG, "Changed directory to: " + getDisplayPath(currentDirectory));
return true;
} else {
Log.w(TAG, "Directory does not exist: " + newDir.getAbsolutePath());
Log.w(TAG, "Attempted to escape root directory");
return false;
}
} catch (Exception e) {
Log.e(TAG, "Error changing directory: " + e.getMessage());
} else {
Log.w(TAG, "Directory does not exist: " + path);
return false;
}
}
public boolean changeToParentDirectory() {
File parent = currentDirectory.getParentFile();
DocumentFile parent = currentDirectory.getParentFile();
if (parent == null) {
return false;
}
try {
String parentPath = parent.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
// Cannot go above root directory
if (!parentPath.startsWith(rootPath)) {
if (!isSubDirectory(parent, rootDirectory) && !isSameFile(parent, rootDirectory)) {
return false;
}
currentDirectory = parent;
Log.d(TAG, "Changed to parent directory: " + currentDirectory.getAbsolutePath());
Log.d(TAG, "Changed to parent directory: " + getDisplayPath(currentDirectory));
return true;
} catch (Exception e) {
Log.e(TAG, "Error changing to parent directory: " + e.getMessage());
return false;
}
}
public List<File> listFiles() {
File[] files = currentDirectory.listFiles();
List<File> fileList = new ArrayList<>();
public List<DocumentFile> listFiles() {
DocumentFile[] files = currentDirectory.listFiles();
List<DocumentFile> fileList = new ArrayList<>();
if (files != null) {
for (File file : files) {
for (DocumentFile file : files) {
fileList.add(file);
}
}
@@ -137,19 +141,19 @@ public class FTPFileSystem {
}
public String formatFileList(boolean detailed) {
List<File> files = listFiles();
List<DocumentFile> files = listFiles();
StringBuilder sb = new StringBuilder();
if (detailed) {
// LIST format: Unix-style detailed listing
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm", Locale.US);
for (File file : files) {
for (DocumentFile file : files) {
sb.append(formatDetailedFile(file, dateFormat)).append("\r\n");
}
} else {
// NLST format: names only
for (File file : files) {
for (DocumentFile file : files) {
sb.append(file.getName()).append("\r\n");
}
}
@@ -157,7 +161,7 @@ public class FTPFileSystem {
return sb.toString();
}
private String formatDetailedFile(File file, SimpleDateFormat dateFormat) {
private String formatDetailedFile(DocumentFile file, SimpleDateFormat dateFormat) {
// Format: drwxrwxrwx 1 owner group size date name
String permissions = file.isDirectory() ? "drwxr-xr-x" : "-rw-r--r--";
String owner = "ftp";
@@ -171,123 +175,198 @@ public class FTPFileSystem {
}
public boolean makeDirectory(String dirName) {
File newDir = new File(currentDirectory, dirName);
DocumentFile newDir = currentDirectory.createDirectory(dirName);
try {
String canonicalPath = newDir.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (!canonicalPath.startsWith(rootPath)) {
return false;
}
if (newDir.mkdir()) {
Log.i(TAG, "Directory created: " + newDir.getAbsolutePath());
if (newDir != null) {
Log.i(TAG, "Directory created: " + dirName);
return true;
} else {
Log.w(TAG, "Failed to create directory: " + newDir.getAbsolutePath());
return false;
}
} catch (Exception e) {
Log.e(TAG, "Error creating directory: " + e.getMessage());
Log.w(TAG, "Failed to create directory: " + dirName);
return false;
}
}
public boolean removeDirectory(String dirName) {
File dir = new File(currentDirectory, dirName);
DocumentFile dir = findFileWithNormalization(currentDirectory, dirName);
try {
String canonicalPath = dir.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (!canonicalPath.startsWith(rootPath)) {
return false;
}
if (dir.exists() && dir.isDirectory() && dir.delete()) {
Log.i(TAG, "Directory removed: " + dir.getAbsolutePath());
if (dir != null && dir.exists() && dir.isDirectory() && dir.delete()) {
Log.i(TAG, "Directory removed: " + dirName);
return true;
} else {
Log.w(TAG, "Failed to remove directory: " + dir.getAbsolutePath());
return false;
}
} catch (Exception e) {
Log.e(TAG, "Error removing directory: " + e.getMessage());
Log.w(TAG, "Failed to remove directory: " + dirName);
return false;
}
}
public boolean deleteFile(String fileName) {
File file = new File(currentDirectory, fileName);
DocumentFile file = findFileWithNormalization(currentDirectory, fileName);
try {
String canonicalPath = file.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (!canonicalPath.startsWith(rootPath)) {
return false;
}
if (file.exists() && file.isFile() && file.delete()) {
Log.i(TAG, "File deleted: " + file.getAbsolutePath());
if (file != null && file.exists() && file.isFile() && file.delete()) {
Log.i(TAG, "File deleted: " + fileName);
return true;
} else {
Log.w(TAG, "Failed to delete file: " + file.getAbsolutePath());
return false;
}
} catch (Exception e) {
Log.e(TAG, "Error deleting file: " + e.getMessage());
Log.w(TAG, "Failed to delete file: " + fileName);
return false;
}
}
public File getFile(String fileName) {
File file = new File(currentDirectory, fileName);
try {
String canonicalPath = file.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (!canonicalPath.startsWith(rootPath)) {
return null;
}
return file.exists() ? file : null;
} catch (Exception e) {
Log.e(TAG, "Error getting file: " + e.getMessage());
return null;
}
public DocumentFile getFile(String fileName) {
return findFileWithNormalization(currentDirectory, fileName);
}
public long getFileSize(String fileName) {
File file = getFile(fileName);
DocumentFile file = getFile(fileName);
return (file != null && file.isFile()) ? file.length() : -1;
}
private String getRelativePath(File file) {
try {
String filePath = file.getCanonicalPath();
String rootPath = rootDirectory.getCanonicalPath();
if (filePath.equals(rootPath)) {
return "";
} else if (filePath.startsWith(rootPath + File.separator)) {
return filePath.substring(rootPath.length() + 1).replace(File.separator, "/");
} else {
private String getRelativePath(DocumentFile file) {
if (file == null) {
return "";
}
} catch (Exception e) {
Log.e(TAG, "Error getting relative path: " + e.getMessage());
if (isSameFile(file, rootDirectory)) {
return "";
}
List<String> pathParts = new ArrayList<>();
DocumentFile current = file;
while (current != null && !isSameFile(current, rootDirectory)) {
pathParts.add(0, current.getName());
current = current.getParentFile();
}
if (current == null) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pathParts.size(); i++) {
sb.append(pathParts.get(i));
if (i < pathParts.size() - 1) {
sb.append("/");
}
}
public File getRootDirectory() {
return sb.toString();
}
private boolean isSameFile(DocumentFile file1, DocumentFile file2) {
if (file1 == null || file2 == null) {
return false;
}
return file1.getUri().equals(file2.getUri());
}
private boolean isSubDirectory(DocumentFile child, DocumentFile parent) {
if (child == null || parent == null) {
return false;
}
if (isSameFile(child, parent)) {
return true;
}
DocumentFile current = child;
while (current != null) {
if (isSameFile(current, parent)) {
return true;
}
current = current.getParentFile();
}
return false;
}
private DocumentFile findDocumentFile(DocumentFile parent, String path) {
if (path == null || path.isEmpty()) {
return parent;
}
String[] parts = path.split("/");
DocumentFile current = parent;
for (String part : parts) {
if (part.isEmpty() || part.equals(".")) {
continue;
}
if (part.equals("..")) {
DocumentFile parentFile = current.getParentFile();
if (parentFile != null && isSubDirectory(parentFile, rootDirectory)) {
current = parentFile;
}
continue;
}
DocumentFile next = findFileWithNormalization(current, part);
if (next == null) {
return null;
}
current = next;
}
return current;
}
public DocumentFile getRootDirectory() {
return rootDirectory;
}
public File getCurrentDirectory() {
public DocumentFile getCurrentDirectory() {
return currentDirectory;
}
public Context getContext() {
return context;
}
/**
* Find a file with Unicode normalization handling for macOS compatibility.
* This method tries multiple approaches to find the file:
* 1. Direct match with given name
* 2. Try NFD normalization (macOS format)
* 3. Manual search with NFC normalization comparison
*/
private DocumentFile findFileWithNormalization(DocumentFile parent, String fileName) {
if (parent == null || fileName == null || fileName.isEmpty()) {
return null;
}
// Try to find file with exact name first
DocumentFile file = parent.findFile(fileName);
if (file != null && file.exists()) {
return file;
}
// If not found, try with NFD normalization (for macOS compatibility)
String nfdFileName = Normalizer.normalize(fileName, Normalizer.Form.NFD);
if (!nfdFileName.equals(fileName)) {
file = parent.findFile(nfdFileName);
if (file != null && file.exists()) {
return file;
}
}
// If still not found, manually search through all files
// This handles cases where filesystem has mixed normalization
DocumentFile[] files = parent.listFiles();
if (files != null) {
String normalizedFileName = Normalizer.normalize(fileName, Normalizer.Form.NFC);
for (DocumentFile f : files) {
String name = f.getName();
if (name != null) {
// Compare both NFC normalized forms
String normalizedName = Normalizer.normalize(name, Normalizer.Form.NFC);
if (normalizedName.equals(normalizedFileName)) {
Log.d(TAG, "Found file with normalized match: '" + name + "' == '" + fileName + "'");
return f;
}
}
}
}
Log.d(TAG, "File not found with any normalization: " + fileName);
return null;
}
}

View File

@@ -1,5 +1,7 @@
package be.gyu.android.server.ftp;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
@@ -19,20 +21,32 @@ public class FTPServer {
private Thread acceptThread;
private boolean isRunning = false;
private int port;
private String rootDirectory;
private Context context;
private Uri rootDirectoryUri;
private int minDataPort = 0;
private int maxDataPort = 0;
private FTPUserManager userManager;
public FTPServer() {
this(DEFAULT_PORT, null);
public FTPServer(Context context) {
this(context, DEFAULT_PORT, null, 0, 0);
}
public FTPServer(int port) {
this(port, null);
public FTPServer(Context context, int port) {
this(context, port, null, 0, 0);
}
public FTPServer(int port, String rootDirectory) {
public FTPServer(Context context, int port, Uri rootDirectoryUri) {
this(context, port, rootDirectoryUri, 0, 0);
}
public FTPServer(Context context, int port, Uri rootDirectoryUri, int minDataPort, int maxDataPort) {
this.context = context;
this.port = port;
this.rootDirectory = rootDirectory;
this.rootDirectoryUri = rootDirectoryUri;
this.minDataPort = minDataPort;
this.maxDataPort = maxDataPort;
this.executorService = Executors.newFixedThreadPool(MAX_CONNECTIONS);
this.userManager = FTPUserManager.getInstance(context);
}
public void start() {
@@ -52,7 +66,7 @@ public class FTPServer {
Socket clientSocket = serverSocket.accept();
Log.i(TAG, "New client connection from: " + clientSocket.getInetAddress());
FTPSession session = new FTPSession(clientSocket, rootDirectory);
FTPSession session = new FTPSession(clientSocket, context, rootDirectoryUri, minDataPort, maxDataPort, userManager);
executorService.execute(session);
} catch (IOException e) {

View File

@@ -36,8 +36,14 @@ public class FTPService extends Service {
if (ACTION_START.equals(action)) {
int port = intent.getIntExtra("port", 2121);
String rootDir = intent.getStringExtra("rootDir");
startFTPServer(port, rootDir);
String rootDirUriString = intent.getStringExtra("rootDirUri");
int minDataPort = intent.getIntExtra("minDataPort", 0);
int maxDataPort = intent.getIntExtra("maxDataPort", 0);
android.net.Uri rootDirUri = null;
if (rootDirUriString != null && !rootDirUriString.isEmpty()) {
rootDirUri = android.net.Uri.parse(rootDirUriString);
}
startFTPServer(port, rootDirUri, minDataPort, maxDataPort);
} else if (ACTION_STOP.equals(action)) {
stopFTPServer();
}
@@ -46,19 +52,24 @@ public class FTPService extends Service {
return START_STICKY;
}
private void startFTPServer(int port, String rootDir) {
private void startFTPServer(int port, android.net.Uri rootDirUri, int minDataPort, int maxDataPort) {
if (ftpServer != null && ftpServer.isRunning()) {
Log.w(TAG, "FTP Server is already running");
return;
}
ftpServer = new FTPServer(port, rootDir);
ftpServer = new FTPServer(this, port, rootDirUri, minDataPort, maxDataPort);
ftpServer.start();
Notification notification = createNotification("FTP Server is running on port " + ftpServer.getPort());
String notificationText = "FTP Server is running on port " + ftpServer.getPort();
if (minDataPort > 0 && maxDataPort > 0) {
notificationText += " (Data ports: " + minDataPort + "-" + maxDataPort + ")";
}
Notification notification = createNotification(notificationText);
startForeground(NOTIFICATION_ID, notification);
Log.i(TAG, "FTP Server started on port " + port + " with root: " + rootDir);
Log.i(TAG, "FTP Server started on port " + port + " with root URI: " + rootDirUri +
", data port range: " + minDataPort + "-" + maxDataPort);
}
private void stopFTPServer() {

View File

@@ -1,13 +1,21 @@
package be.gyu.android.server.ftp;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import androidx.documentfile.provider.DocumentFile;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.text.Normalizer;
public class FTPSession implements Runnable {
private static final String TAG = "FTPSession";
@@ -22,22 +30,38 @@ public class FTPSession implements Runnable {
private FTPFileSystem fileSystem;
private FTPDataConnection dataConnection;
private String transferType = "A"; // A = ASCII, I = Binary
private boolean useUtf8 = true; // UTF-8 enabled by default for better compatibility
private int minDataPort = 0;
private int maxDataPort = 0;
private FTPUserManager userManager;
public FTPSession(Socket socket) {
this(socket, null);
public FTPSession(Socket socket, Context context) {
this(socket, context, null, 0, 0, null);
}
public FTPSession(Socket socket, String rootDirectory) {
public FTPSession(Socket socket, Context context, Uri rootDirectoryUri) {
this(socket, context, rootDirectoryUri, 0, 0, null);
}
public FTPSession(Socket socket, Context context, Uri rootDirectoryUri, int minDataPort, int maxDataPort) {
this(socket, context, rootDirectoryUri, minDataPort, maxDataPort, null);
}
public FTPSession(Socket socket, Context context, Uri rootDirectoryUri, int minDataPort, int maxDataPort, FTPUserManager userManager) {
this.controlSocket = socket;
this.fileSystem = new FTPFileSystem(rootDirectory);
this.fileSystem = new FTPFileSystem(context, rootDirectoryUri);
this.dataConnection = null;
this.minDataPort = minDataPort;
this.maxDataPort = maxDataPort;
this.userManager = userManager;
}
@Override
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(controlSocket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(controlSocket.getOutputStream()));
// Use UTF-8 encoding for better international character support
reader = new BufferedReader(new InputStreamReader(controlSocket.getInputStream(), StandardCharsets.UTF_8));
writer = new BufferedWriter(new OutputStreamWriter(controlSocket.getOutputStream(), StandardCharsets.UTF_8));
Log.d(TAG, "Client connected: " + controlSocket.getInetAddress());
sendResponse(FTPResponse.SERVICE_READY, "FTP Server ready");
@@ -120,6 +144,12 @@ public class FTPSession implements Runnable {
case "NOOP":
handleNoop();
break;
case "FEAT":
handleFeat();
break;
case "OPTS":
handleOpts(argument);
break;
default:
sendResponse(FTPResponse.COMMAND_NOT_IMPLEMENTED_502, "Command not implemented");
break;
@@ -137,10 +167,16 @@ public class FTPSession implements Runnable {
return;
}
// Simple authentication - accept any password for now
// In production, implement proper authentication
// Authenticate using FTPUserManager
if (userManager != null && userManager.authenticate(username, password)) {
isAuthenticated = true;
sendResponse(FTPResponse.USER_LOGGED_IN, "User logged in");
Log.i(TAG, "User authenticated: " + username);
} else {
isAuthenticated = false;
sendResponse(FTPResponse.NOT_LOGGED_IN, "Authentication failed");
Log.w(TAG, "Authentication failed for user: " + username);
}
}
private void handleQuit() throws IOException {
@@ -172,8 +208,12 @@ public class FTPSession implements Runnable {
return;
}
// Normalize path for internal use (NFD -> NFC)
path = normalizeFilename(path);
if (fileSystem.changeDirectory(path)) {
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "Directory changed to " + fileSystem.getCurrentPath());
String currentPath = fileSystem.getCurrentPath();
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "Directory changed to " + currentPath);
} else {
sendResponse(FTPResponse.FILE_UNAVAILABLE, "Failed to change directory");
}
@@ -186,7 +226,8 @@ public class FTPSession implements Runnable {
}
if (fileSystem.changeToParentDirectory()) {
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "Directory changed to " + fileSystem.getCurrentPath());
String currentPath = fileSystem.getCurrentPath();
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "Directory changed to " + currentPath);
} else {
sendResponse(FTPResponse.FILE_UNAVAILABLE, "Already at root directory");
}
@@ -265,6 +306,9 @@ public class FTPSession implements Runnable {
return;
}
// Normalize filename for MacOS compatibility (NFD -> NFC for storage)
dirName = normalizeFilename(dirName);
if (fileSystem.makeDirectory(dirName)) {
String newPath = fileSystem.getCurrentPath() + "/" + dirName;
sendResponse(FTPResponse.PATHNAME_CREATED, "\"" + newPath + "\" directory created");
@@ -284,6 +328,9 @@ public class FTPSession implements Runnable {
return;
}
// Normalize filename for MacOS compatibility
dirName = normalizeFilename(dirName);
if (fileSystem.removeDirectory(dirName)) {
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "Directory removed");
} else {
@@ -302,6 +349,9 @@ public class FTPSession implements Runnable {
return;
}
// Normalize filename for MacOS compatibility
fileName = normalizeFilename(fileName);
if (fileSystem.deleteFile(fileName)) {
sendResponse(FTPResponse.REQUESTED_FILE_ACTION_OK, "File deleted");
} else {
@@ -320,6 +370,9 @@ public class FTPSession implements Runnable {
return;
}
// Normalize filename for MacOS compatibility
fileName = normalizeFilename(fileName);
long size = fileSystem.getFileSize(fileName);
if (size >= 0) {
sendResponse(FTPResponse.FILE_STATUS, String.valueOf(size));
@@ -360,7 +413,7 @@ public class FTPSession implements Runnable {
// Get server address from control socket
String serverAddress = controlSocket.getLocalAddress().getHostAddress();
if (dataConnection.openPassiveMode(controlSocket.getLocalAddress())) {
if (dataConnection.openPassiveMode(controlSocket.getLocalAddress(), minDataPort, maxDataPort)) {
int port = dataConnection.getPassivePort();
// Format: h1,h2,h3,h4,p1,p2
@@ -395,7 +448,10 @@ public class FTPSession implements Runnable {
return;
}
java.io.File file = fileSystem.getFile(fileName);
// Normalize filename for MacOS compatibility
fileName = normalizeFilename(fileName);
DocumentFile file = fileSystem.getFile(fileName);
if (file == null || !file.exists() || !file.isFile()) {
sendResponse(FTPResponse.FILE_UNAVAILABLE, "File not found");
dataConnection.close();
@@ -407,14 +463,14 @@ public class FTPSession implements Runnable {
if (dataConnection.acceptConnection()) {
try {
java.io.FileInputStream fis = new java.io.FileInputStream(file);
if (dataConnection.transferStream(fis)) {
InputStream fis = fileSystem.getContext().getContentResolver().openInputStream(file.getUri());
if (fis != null && dataConnection.transferStream(fis)) {
fis.close();
dataConnection.close();
sendResponse(FTPResponse.CLOSING_DATA_CONNECTION, "Transfer complete");
Log.i(TAG, "File sent: " + fileName + " (" + file.length() + " bytes)");
} else {
fis.close();
if (fis != null) fis.close();
dataConnection.close();
sendResponse(FTPResponse.CONNECTION_CLOSED, "Transfer failed");
}
@@ -447,20 +503,37 @@ public class FTPSession implements Runnable {
return;
}
java.io.File file = new java.io.File(fileSystem.getCurrentDirectory(), fileName);
// Normalize filename for MacOS compatibility
fileName = normalizeFilename(fileName);
// Create or get the file in the current directory
DocumentFile currentDir = fileSystem.getCurrentDirectory();
DocumentFile file = currentDir.findFile(fileName);
// If file doesn't exist, create it
if (file == null) {
file = currentDir.createFile("application/octet-stream", fileName);
}
if (file == null) {
sendResponse(FTPResponse.FILE_UNAVAILABLE, "Cannot create file");
dataConnection.close();
dataConnection = null;
return;
}
sendResponse(FTPResponse.FILE_STATUS_OK, "Opening data connection for " + fileName);
if (dataConnection.acceptConnection()) {
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
if (dataConnection.receiveStream(fos)) {
OutputStream fos = fileSystem.getContext().getContentResolver().openOutputStream(file.getUri(), "wt");
if (fos != null && dataConnection.receiveStream(fos)) {
fos.close();
dataConnection.close();
sendResponse(FTPResponse.CLOSING_DATA_CONNECTION, "Transfer complete");
Log.i(TAG, "File received: " + fileName + " (" + file.length() + " bytes)");
} else {
fos.close();
if (fos != null) fos.close();
dataConnection.close();
sendResponse(FTPResponse.CONNECTION_CLOSED, "Transfer failed");
}
@@ -481,6 +554,90 @@ public class FTPSession implements Runnable {
sendResponse(FTPResponse.COMMAND_OK, "OK");
}
private void handleFeat() throws IOException {
// Send list of supported features
writer.write("211-Features:\r\n");
writer.write(" UTF8\r\n");
writer.write(" SIZE\r\n");
writer.write(" PASV\r\n");
writer.write("211 End\r\n");
writer.flush();
Log.d(TAG, "FEAT command handled");
}
private void handleOpts(String options) throws IOException {
if (options.isEmpty()) {
sendResponse(FTPResponse.SYNTAX_ERROR_PARAMETERS, "No options specified");
return;
}
String[] parts = options.split("\\s+", 2);
String option = parts[0].toUpperCase();
String value = parts.length > 1 ? parts[1].toUpperCase() : "";
if (option.equals("UTF8")) {
if (value.equals("ON") || value.isEmpty()) {
useUtf8 = true;
sendResponse(FTPResponse.COMMAND_OK, "UTF8 enabled");
Log.d(TAG, "UTF-8 encoding enabled");
} else if (value.equals("OFF")) {
useUtf8 = false;
sendResponse(FTPResponse.COMMAND_OK, "UTF8 disabled");
Log.d(TAG, "UTF-8 encoding disabled");
} else {
sendResponse(FTPResponse.SYNTAX_ERROR_PARAMETERS, "Invalid UTF8 option");
}
} else {
sendResponse(FTPResponse.COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER, "Option not supported");
}
}
/**
* Normalize filename from MacOS NFD (Decomposed) to NFC (Composed) format.
* MacOS uses NFD normalization for filenames, which can cause issues on Android/Windows.
* This method converts filenames to NFC format for compatibility.
* Used when RECEIVING filenames from client (STOR, RETR, DELE, etc.)
*/
private String normalizeFilename(String filename) {
if (filename == null || filename.isEmpty()) {
return filename;
}
// Normalize to NFC (Canonical Decomposition, followed by Canonical Composition)
String normalized = Normalizer.normalize(filename, Normalizer.Form.NFC);
Log.d(TAG, "Filename normalized NFD->NFC: '" + filename + "' -> '" + normalized + "'");
return normalized;
}
/**
* Normalize filename to NFD (Decomposed) format for MacOS compatibility.
* MacOS expects filenames in NFD format for proper display.
* This method converts filenames from NFC to NFD format.
* Used when SENDING filenames to client (LIST, NLST, PWD, etc.)
*/
private String denormalizeFilename(String filename) {
if (filename == null || filename.isEmpty()) {
return filename;
}
// Normalize to NFD (Canonical Decomposition) for MacOS
String normalized = Normalizer.normalize(filename, Normalizer.Form.NFD);
Log.d(TAG, "Filename normalized NFC->NFD: '" + filename + "' -> '" + normalized + "'");
return normalized;
}
/**
* Convert entire file list to NFD format for MacOS compatibility.
* This method normalizes all filenames in the file list string to NFD format.
*/
private String convertFileListToNFD(String fileList) {
if (fileList == null || fileList.isEmpty()) {
return fileList;
}
// Normalize entire string to NFD for MacOS
String normalized = Normalizer.normalize(fileList, Normalizer.Form.NFD);
Log.d(TAG, "File list converted to NFD for MacOS");
return normalized;
}
private void sendResponse(int code, String message) throws IOException {
String response = FTPResponse.format(code, message);
writer.write(response);

View File

@@ -0,0 +1,53 @@
package be.gyu.android.server.ftp;
import org.json.JSONException;
import org.json.JSONObject;
public class FTPUser {
private String username;
private String passwordHash;
private long createdTimestamp;
public FTPUser(String username, String passwordHash) {
this.username = username;
this.passwordHash = passwordHash;
this.createdTimestamp = System.currentTimeMillis();
}
public FTPUser(String username, String passwordHash, long createdTimestamp) {
this.username = username;
this.passwordHash = passwordHash;
this.createdTimestamp = createdTimestamp;
}
public String getUsername() {
return username;
}
public String getPasswordHash() {
return passwordHash;
}
public long getCreatedTimestamp() {
return createdTimestamp;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("username", username);
json.put("passwordHash", passwordHash);
json.put("createdTimestamp", createdTimestamp);
return json;
}
public static FTPUser fromJson(JSONObject json) throws JSONException {
String username = json.getString("username");
String passwordHash = json.getString("passwordHash");
long createdTimestamp = json.optLong("createdTimestamp", System.currentTimeMillis());
return new FTPUser(username, passwordHash, createdTimestamp);
}
}

View File

@@ -0,0 +1,211 @@
package be.gyu.android.server.ftp;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.security.crypto.EncryptedSharedPreferences;
import androidx.security.crypto.MasterKey;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
public class FTPUserManager {
private static final String TAG = "FTPUserManager";
private static final String PREF_NAME = "ftp_users_encrypted";
private static final String KEY_USERS = "ftp_users";
private static FTPUserManager instance;
private SharedPreferences encryptedPrefs;
private FTPUserManager(Context context) {
try {
MasterKey masterKey = new MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
encryptedPrefs = EncryptedSharedPreferences.create(
context,
PREF_NAME,
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
} catch (Exception e) {
Log.e(TAG, "Failed to create encrypted preferences: " + e.getMessage());
}
}
public static synchronized FTPUserManager getInstance(Context context) {
if (instance == null) {
instance = new FTPUserManager(context.getApplicationContext());
}
return instance;
}
public synchronized boolean addUser(String username, String password) {
if (!isValidUsername(username) || !isValidPassword(password)) {
return false;
}
if (userExists(username)) {
Log.w(TAG, "User already exists: " + username);
return false;
}
List<FTPUser> users = loadUsers();
String passwordHash = hashPassword(password, username);
users.add(new FTPUser(username, passwordHash));
saveUsers(users);
Log.i(TAG, "User added: " + username);
return true;
}
public synchronized boolean updateUser(String username, String newPassword) {
if (!isValidPassword(newPassword)) {
return false;
}
List<FTPUser> users = loadUsers();
for (FTPUser user : users) {
if (user.getUsername().equals(username)) {
String newPasswordHash = hashPassword(newPassword, username);
user.setPasswordHash(newPasswordHash);
saveUsers(users);
Log.i(TAG, "User updated: " + username);
return true;
}
}
Log.w(TAG, "User not found for update: " + username);
return false;
}
public synchronized boolean deleteUser(String username) {
List<FTPUser> users = loadUsers();
// Prevent deleting the last user
if (users.size() <= 1) {
Log.w(TAG, "Cannot delete last user");
return false;
}
boolean removed = users.removeIf(user -> user.getUsername().equals(username));
if (removed) {
saveUsers(users);
Log.i(TAG, "User deleted: " + username);
}
return removed;
}
public synchronized List<FTPUser> getAllUsers() {
return new ArrayList<>(loadUsers());
}
public synchronized FTPUser getUser(String username) {
List<FTPUser> users = loadUsers();
for (FTPUser user : users) {
if (user.getUsername().equals(username)) {
return user;
}
}
return null;
}
public synchronized boolean authenticate(String username, String password) {
FTPUser user = getUser(username);
if (user == null) {
Log.w(TAG, "Authentication failed - user not found: " + username);
return false;
}
String passwordHash = hashPassword(password, username);
boolean authenticated = passwordHash.equals(user.getPasswordHash());
if (authenticated) {
Log.i(TAG, "User authenticated: " + username);
} else {
Log.w(TAG, "Authentication failed - wrong password: " + username);
}
return authenticated;
}
public boolean userExists(String username) {
return getUser(username) != null;
}
public boolean isValidUsername(String username) {
if (username == null || username.trim().isEmpty()) {
return false;
}
username = username.trim();
return username.length() >= 3 &&
username.length() <= 20 &&
username.matches("^[a-zA-Z0-9_]+$");
}
public boolean isValidPassword(String password) {
return password != null && password.length() >= 4;
}
private String hashPassword(String password, String salt) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
String saltedPassword = salt + password;
byte[] hash = digest.digest(saltedPassword.getBytes(StandardCharsets.UTF_8));
// Convert to hex string
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "SHA-256 not available: " + e.getMessage());
return "";
}
}
private List<FTPUser> loadUsers() {
List<FTPUser> users = new ArrayList<>();
String usersJson = encryptedPrefs.getString(KEY_USERS, "[]");
try {
JSONArray jsonArray = new JSONArray(usersJson);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject userJson = jsonArray.getJSONObject(i);
users.add(FTPUser.fromJson(userJson));
}
} catch (JSONException e) {
Log.e(TAG, "Error loading users: " + e.getMessage());
}
return users;
}
private void saveUsers(List<FTPUser> users) {
try {
JSONArray jsonArray = new JSONArray();
for (FTPUser user : users) {
jsonArray.put(user.toJson());
}
encryptedPrefs.edit()
.putString(KEY_USERS, jsonArray.toString())
.apply();
} catch (JSONException e) {
Log.e(TAG, "Error saving users: " + e.getMessage());
}
}
}

View File

@@ -8,6 +8,8 @@ import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;
import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
@@ -33,6 +35,9 @@ public class MainActivity extends AppCompatActivity {
private TextView rootDirPathTextView;
private Button selectDirButton;
private Button saveSettingsButton;
private EditText minDataPortEditText;
private EditText maxDataPortEditText;
private Button manageUsersButton;
private FTPConfig config;
private ActivityResultLauncher<Uri> directoryPickerLauncher;
@@ -50,6 +55,7 @@ public class MainActivity extends AppCompatActivity {
loadSettings();
setupListeners();
requestPermissions();
initializeDefaultUser();
}
private void setupDirectoryPicker() {
@@ -89,11 +95,16 @@ public class MainActivity extends AppCompatActivity {
rootDirPathTextView = findViewById(R.id.rootDirPathTextView);
selectDirButton = findViewById(R.id.selectDirButton);
saveSettingsButton = findViewById(R.id.saveSettingsButton);
minDataPortEditText = findViewById(R.id.minDataPortEditText);
maxDataPortEditText = findViewById(R.id.maxDataPortEditText);
manageUsersButton = findViewById(R.id.manageUsersButton);
}
private void loadSettings() {
int port = config.getPort();
String rootPath = config.getRootDirectoryPath();
int minDataPort = config.getMinDataPort();
int maxDataPort = config.getMaxDataPort();
portEditText.setText(String.valueOf(port));
portTextView.setText("Port: " + port);
@@ -103,6 +114,9 @@ public class MainActivity extends AppCompatActivity {
} else {
rootDirPathTextView.setText("Not selected");
}
minDataPortEditText.setText(String.valueOf(minDataPort));
maxDataPortEditText.setText(String.valueOf(maxDataPort));
}
private void setupListeners() {
@@ -110,6 +124,7 @@ public class MainActivity extends AppCompatActivity {
stopButton.setOnClickListener(v -> stopFTPServer());
selectDirButton.setOnClickListener(v -> selectDirectory());
saveSettingsButton.setOnClickListener(v -> saveSettings());
manageUsersButton.setOnClickListener(v -> openUserManagement());
}
private void selectDirectory() {
@@ -140,7 +155,45 @@ public class MainActivity extends AppCompatActivity {
return;
}
// Validate data port range
String minPortStr = minDataPortEditText.getText().toString().trim();
String maxPortStr = maxDataPortEditText.getText().toString().trim();
int minDataPort = 0;
int maxDataPort = 0;
if (!minPortStr.isEmpty() || !maxPortStr.isEmpty()) {
if (minPortStr.isEmpty() || maxPortStr.isEmpty()) {
Toast.makeText(this, "Please enter both min and max data ports or leave both empty", Toast.LENGTH_SHORT).show();
return;
}
try {
minDataPort = Integer.parseInt(minPortStr);
maxDataPort = Integer.parseInt(maxPortStr);
if (minDataPort < 1024 || minDataPort > 65535 || maxDataPort < 1024 || maxDataPort > 65535) {
Toast.makeText(this, "Data ports must be between 1024 and 65535", Toast.LENGTH_SHORT).show();
return;
}
if (minDataPort >= maxDataPort) {
Toast.makeText(this, "Min data port must be less than max data port", Toast.LENGTH_SHORT).show();
return;
}
if (maxDataPort - minDataPort < 10) {
Toast.makeText(this, "Data port range should be at least 10 ports", Toast.LENGTH_SHORT).show();
return;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Invalid data port number", Toast.LENGTH_SHORT).show();
return;
}
}
config.setPort(port);
config.setDataPortRange(minDataPort, maxDataPort);
portTextView.setText("Port: " + port);
Toast.makeText(this, "Settings saved", Toast.LENGTH_SHORT).show();
@@ -184,7 +237,8 @@ public class MainActivity extends AppCompatActivity {
}
}
if (!config.hasRootDirectory()) {
String rootDirUri = config.getRootDirectoryUri();
if (rootDirUri == null || rootDirUri.isEmpty()) {
Toast.makeText(this, "Please select a root directory first", Toast.LENGTH_LONG).show();
return;
}
@@ -192,7 +246,9 @@ public class MainActivity extends AppCompatActivity {
Intent serviceIntent = new Intent(this, FTPService.class);
serviceIntent.setAction(FTPService.ACTION_START);
serviceIntent.putExtra("port", config.getPort());
serviceIntent.putExtra("rootDir", config.getRootDirectoryPath());
serviceIntent.putExtra("rootDirUri", rootDirUri);
serviceIntent.putExtra("minDataPort", config.getMinDataPort());
serviceIntent.putExtra("maxDataPort", config.getMaxDataPort());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(serviceIntent);
@@ -238,4 +294,40 @@ public class MainActivity extends AppCompatActivity {
}
}
}
/**
* Check if FTPService is currently running in the background
*/
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
if (manager != null) {
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (FTPService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
}
return false;
}
@Override
protected void onResume() {
super.onResume();
// Sync UI with actual service state when activity resumes
isServerRunning = isServiceRunning();
updateUI();
}
private void openUserManagement() {
Intent intent = new Intent(this, UserManagementActivity.class);
startActivity(intent);
}
private void initializeDefaultUser() {
FTPUserManager userManager = FTPUserManager.getInstance(this);
if (userManager.getAllUsers().isEmpty()) {
userManager.addUser("admin", "admin");
Toast.makeText(this, "Default user created: admin/admin\nPlease change the password in User Management", Toast.LENGTH_LONG).show();
}
}
}

View File

@@ -0,0 +1,252 @@
package be.gyu.android.server.ftp;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class UserManagementActivity extends AppCompatActivity {
private FTPUserManager userManager;
private ListView userListView;
private UserListAdapter userAdapter;
private List<FTPUser> userList;
private TextView emptyView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_management);
userManager = FTPUserManager.getInstance(this);
initViews();
setupListeners();
refreshUserList();
}
private void initViews() {
userListView = findViewById(R.id.userListView);
emptyView = findViewById(R.id.emptyView);
Button addUserButton = findViewById(R.id.addUserButton);
userList = new ArrayList<>();
userAdapter = new UserListAdapter();
userListView.setAdapter(userAdapter);
userListView.setEmptyView(emptyView);
}
private void setupListeners() {
findViewById(R.id.addUserButton).setOnClickListener(v -> showAddUserDialog());
}
private void showAddUserDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_user, null);
builder.setView(dialogView);
TextView dialogTitle = dialogView.findViewById(R.id.dialogTitle);
EditText usernameEditText = dialogView.findViewById(R.id.usernameEditText);
EditText passwordEditText = dialogView.findViewById(R.id.passwordEditText);
EditText confirmPasswordEditText = dialogView.findViewById(R.id.confirmPasswordEditText);
TextView errorTextView = dialogView.findViewById(R.id.errorTextView);
Button saveButton = dialogView.findViewById(R.id.saveButton);
Button cancelButton = dialogView.findViewById(R.id.cancelButton);
dialogTitle.setText("Add User");
AlertDialog dialog = builder.create();
saveButton.setOnClickListener(v -> {
String username = usernameEditText.getText().toString().trim();
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
// Validate username
if (username.isEmpty()) {
errorTextView.setText("Username is required");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (!userManager.isValidUsername(username)) {
errorTextView.setText("Username must be 3-20 characters, alphanumeric + underscore");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (userManager.userExists(username)) {
errorTextView.setText("Username already exists");
errorTextView.setVisibility(View.VISIBLE);
return;
}
// Validate password
if (password.isEmpty()) {
errorTextView.setText("Password is required");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (!userManager.isValidPassword(password)) {
errorTextView.setText("Password must be at least 4 characters");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (!password.equals(confirmPassword)) {
errorTextView.setText("Passwords do not match");
errorTextView.setVisibility(View.VISIBLE);
return;
}
// Add user
if (userManager.addUser(username, password)) {
Toast.makeText(this, "User added successfully", Toast.LENGTH_SHORT).show();
refreshUserList();
dialog.dismiss();
} else {
errorTextView.setText("Failed to add user");
errorTextView.setVisibility(View.VISIBLE);
}
});
cancelButton.setOnClickListener(v -> dialog.dismiss());
dialog.show();
}
private void showEditUserDialog(FTPUser user) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_user, null);
builder.setView(dialogView);
TextView dialogTitle = dialogView.findViewById(R.id.dialogTitle);
EditText usernameEditText = dialogView.findViewById(R.id.usernameEditText);
EditText passwordEditText = dialogView.findViewById(R.id.passwordEditText);
EditText confirmPasswordEditText = dialogView.findViewById(R.id.confirmPasswordEditText);
TextView errorTextView = dialogView.findViewById(R.id.errorTextView);
Button saveButton = dialogView.findViewById(R.id.saveButton);
Button cancelButton = dialogView.findViewById(R.id.cancelButton);
dialogTitle.setText("Edit User");
usernameEditText.setText(user.getUsername());
usernameEditText.setEnabled(false);
AlertDialog dialog = builder.create();
saveButton.setOnClickListener(v -> {
String password = passwordEditText.getText().toString();
String confirmPassword = confirmPasswordEditText.getText().toString();
// Validate password
if (password.isEmpty()) {
errorTextView.setText("Password is required");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (!userManager.isValidPassword(password)) {
errorTextView.setText("Password must be at least 4 characters");
errorTextView.setVisibility(View.VISIBLE);
return;
}
if (!password.equals(confirmPassword)) {
errorTextView.setText("Passwords do not match");
errorTextView.setVisibility(View.VISIBLE);
return;
}
// Update user
if (userManager.updateUser(user.getUsername(), password)) {
Toast.makeText(this, "User updated successfully", Toast.LENGTH_SHORT).show();
refreshUserList();
dialog.dismiss();
} else {
errorTextView.setText("Failed to update user");
errorTextView.setVisibility(View.VISIBLE);
}
});
cancelButton.setOnClickListener(v -> dialog.dismiss());
dialog.show();
}
private void showDeleteConfirmation(FTPUser user) {
// Check if this is the last user
if (userList.size() <= 1) {
Toast.makeText(this, "Cannot delete the last user", Toast.LENGTH_LONG).show();
return;
}
new AlertDialog.Builder(this)
.setTitle("Delete User")
.setMessage("Are you sure you want to delete user '" + user.getUsername() + "'?")
.setPositiveButton("Delete", (dialog, which) -> {
if (userManager.deleteUser(user.getUsername())) {
Toast.makeText(this, "User deleted successfully", Toast.LENGTH_SHORT).show();
refreshUserList();
} else {
Toast.makeText(this, "Failed to delete user", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", null)
.show();
}
private void refreshUserList() {
userList.clear();
userList.addAll(userManager.getAllUsers());
userAdapter.notifyDataSetChanged();
}
private class UserListAdapter extends BaseAdapter {
@Override
public int getCount() {
return userList.size();
}
@Override
public Object getItem(int position) {
return userList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(UserManagementActivity.this)
.inflate(R.layout.item_user, parent, false);
}
FTPUser user = userList.get(position);
TextView usernameView = convertView.findViewById(R.id.usernameTextView);
Button editButton = convertView.findViewById(R.id.editButton);
Button deleteButton = convertView.findViewById(R.id.deleteButton);
usernameView.setText(user.getUsername());
editButton.setOnClickListener(v -> showEditUserDialog(user));
deleteButton.setOnClickListener(v -> showDeleteConfirmation(user));
return convertView;
}
}
}

View File

@@ -68,13 +68,24 @@
app:layout_constraintTop_toBottomOf="@id/startButton"
android:layout_marginTop="16dp" />
<Button
android:id="@+id/manageUsersButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Manage Users"
android:minWidth="150dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/stopButton"
android:layout_marginTop="16dp" />
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#CCCCCC"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@id/stopButton"
app:layout_constraintTop_toBottomOf="@id/manageUsersButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
@@ -144,6 +155,62 @@
app:layout_constraintTop_toBottomOf="@id/rootDirPathTextView"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/dataPortRangeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data Port Range:"
android:textSize="16sp"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/selectDirButton"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/minDataPortLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Min:"
android:textSize="14sp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@id/dataPortRangeLabel"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/minDataPortEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="50000"
android:layout_marginStart="16dp"
app:layout_constraintBaseline_toBaselineOf="@id/minDataPortLabel"
app:layout_constraintStart_toEndOf="@id/minDataPortLabel"
app:layout_constraintEnd_toStartOf="@id/maxDataPortLabel"
app:layout_constraintWidth_default="percent"
app:layout_constraintHorizontal_weight="1" />
<TextView
android:id="@+id/maxDataPortLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Max:"
android:textSize="14sp"
android:layout_marginStart="16dp"
app:layout_constraintBaseline_toBaselineOf="@id/minDataPortLabel"
app:layout_constraintStart_toEndOf="@id/minDataPortEditText" />
<EditText
android:id="@+id/maxDataPortEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="50100"
android:layout_marginStart="16dp"
app:layout_constraintBaseline_toBaselineOf="@id/minDataPortLabel"
app:layout_constraintStart_toEndOf="@id/maxDataPortLabel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintWidth_default="percent"
app:layout_constraintHorizontal_weight="1" />
<Button
android:id="@+id/saveSettingsButton"
android:layout_width="wrap_content"
@@ -151,7 +218,7 @@
android:text="Save Settings"
android:minWidth="150dp"
android:layout_marginTop="24dp"
app:layout_constraintTop_toBottomOf="@id/selectDirButton"
app:layout_constraintTop_toBottomOf="@id/minDataPortLabel"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".UserManagementActivity">
<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Management"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp" />
<ListView
android:id="@+id/userListView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="24dp"
android:layout_marginBottom="16dp"
app:layout_constraintTop_toBottomOf="@id/titleTextView"
app:layout_constraintBottom_toTopOf="@id/addUserButton"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/emptyView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No users. Add your first user."
android:textSize="16sp"
android:textColor="#999999"
android:visibility="gone"
app:layout_constraintTop_toTopOf="@id/userListView"
app:layout_constraintBottom_toBottomOf="@id/userListView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/addUserButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add User"
android:minWidth="150dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginBottom="16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<TextView
android:id="@+id/dialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add User"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username:"
android:textSize="14sp"
android:layout_marginBottom="4dp" />
<EditText
android:id="@+id/usernameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="3-20 characters, alphanumeric + underscore"
android:inputType="text"
android:layout_marginBottom="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textSize="14sp"
android:layout_marginBottom="4dp" />
<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Minimum 4 characters"
android:inputType="textPassword"
android:layout_marginBottom="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirm Password:"
android:textSize="14sp"
android:layout_marginBottom="4dp" />
<EditText
android:id="@+id/confirmPasswordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Re-enter password"
android:inputType="textPassword"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/errorTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Error message"
android:textColor="#FF0000"
android:textSize="14sp"
android:visibility="gone"
android:layout_marginBottom="16dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="end">
<Button
android:id="@+id/cancelButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
style="?android:attr/borderlessButtonStyle"
android:layout_marginEnd="8dp" />
<Button
android:id="@+id/saveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
</LinearLayout>
</LinearLayout>

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:gravity="center_vertical">
<TextView
android:id="@+id/usernameTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="16sp"
android:textStyle="bold"
android:text="Username" />
<Button
android:id="@+id/editButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:layout_marginStart="8dp"
style="?android:attr/borderlessButtonStyle" />
<Button
android:id="@+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:layout_marginStart="8dp"
style="?android:attr/borderlessButtonStyle" />
</LinearLayout>