FTP 测试通过
This commit is contained in:
@@ -946,7 +946,6 @@ static int net_recv_locked(net_sock_t *p_sock, void *buf, int len, int flags) {
|
||||
ch395f_read_recv_buf(sockfd, (uint8_t *)buf, (uint16_t)read_len);
|
||||
p_sock->recv_bytes += (uint32_t)read_len;
|
||||
p_sock->readable = 0; /* 已消费数据(注:部分读受 Trap 13 限制,下一次 RECV_OK 会重新置位) */
|
||||
HAL_Delay(1); /* 等待 CH395F 刷新 recv_len 寄存器 */
|
||||
return read_len;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,74 +1,74 @@
|
||||
*** Using Compiler 'V5.06 update 7 (build 960)', folder: 'C:\Keil_v5\ARM\ARMCC\Bin'
|
||||
Rebuild target 'STM32F407-Demo'
|
||||
assembling startup_stm32f407xx.s...
|
||||
compiling crc.c...
|
||||
compiling ringbuf.c...
|
||||
compiling crc.c...
|
||||
compiling stm32f4xx_hal_flash_ramfunc.c...
|
||||
compiling stm32f4xx_hal_gpio.c...
|
||||
compiling stm32f4xx_hal_msp.c...
|
||||
compiling i2c.c...
|
||||
compiling stm32f4xx_hal_dma_ex.c...
|
||||
compiling stm32f4xx_hal_dma.c...
|
||||
compiling stm32f4xx_hal_msp.c...
|
||||
compiling stm32f4xx_hal_timebase_tim.c...
|
||||
compiling dma.c...
|
||||
compiling stm32f4xx_hal_dma_ex.c...
|
||||
compiling spi.c...
|
||||
compiling stm32f4xx_hal_flash_ex.c...
|
||||
compiling stm32f4xx_hal_dma.c...
|
||||
compiling stm32f4xx_it.c...
|
||||
compiling usart.c...
|
||||
compiling stm32f4xx_hal_flash.c...
|
||||
compiling sys_clock.c...
|
||||
compiling app_main.c...
|
||||
compiling spi.c...
|
||||
compiling gpio.c...
|
||||
compiling dma.c...
|
||||
compiling rs485_task.c...
|
||||
compiling stm32f4xx_hal_rcc_ex.c...
|
||||
compiling adc_task.c...
|
||||
compiling stm32f4xx_hal_flash_ex.c...
|
||||
compiling freertos.c...
|
||||
compiling stm32f4xx_hal_tim_ex.c...
|
||||
compiling app_main.c...
|
||||
compiling gpio.c...
|
||||
compiling usart.c...
|
||||
compiling stm32f4xx_hal_rcc.c...
|
||||
compiling rs485_task.c...
|
||||
compiling adc_task.c...
|
||||
compiling freertos.c...
|
||||
compiling main.c...
|
||||
compiling net_task.c...
|
||||
compiling stm32f4xx_hal_tim_ex.c...
|
||||
compiling stm32f4xx_hal_tim.c...
|
||||
compiling lftpd_string.c...
|
||||
compiling stm32f4xx_hal_tim.c...
|
||||
compiling croutine.c...
|
||||
compiling event_groups.c...
|
||||
compiling list.c...
|
||||
compiling queue.c...
|
||||
compiling stream_buffer.c...
|
||||
compiling stm32f4xx_hal_pwr.c...
|
||||
compiling timers.c...
|
||||
compiling tasks.c...
|
||||
compiling heap_4.c...
|
||||
compiling port.c...
|
||||
compiling journal.c...
|
||||
compiling stm32f4xx_hal_pwr.c...
|
||||
compiling map.c...
|
||||
compiling stm32f4xx_hal_pwr_ex.c...
|
||||
compiling ff.c...
|
||||
compiling stm32f4xx_hal_i2c_ex.c...
|
||||
compiling stm32f4xx_hal.c...
|
||||
compiling stm32f4xx_hal_cortex.c...
|
||||
compiling stm32f4xx_hal_pwr_ex.c...
|
||||
compiling stm32f4xx_hal_exti.c...
|
||||
compiling sd2506.c...
|
||||
compiling cmsis_os2.c...
|
||||
compiling stm32f4xx_hal_spi.c...
|
||||
compiling stm32f4xx_hal_i2c_ex.c...
|
||||
compiling stm32f4xx_hal_cortex.c...
|
||||
compiling stm32f4xx_hal.c...
|
||||
compiling system_stm32f4xx.c...
|
||||
compiling sd2506.c...
|
||||
compiling rs485.c...
|
||||
compiling gd5f2gq5ue.c...
|
||||
compiling nand_ftl.c...
|
||||
compiling stm32f4xx_hal_spi.c...
|
||||
compiling ch395f.c...
|
||||
compiling cmsis_os2.c...
|
||||
compiling lftpd_io.c...
|
||||
compiling tpafe5160.c...
|
||||
compiling lftpd_inet.c...
|
||||
compiling nand_ftl.c...
|
||||
compiling gd5f2gq5ue.c...
|
||||
compiling net_select.c...
|
||||
compiling stm32f4xx_hal_i2c.c...
|
||||
compiling ch395f.c...
|
||||
compiling lftpd.c...
|
||||
compiling stm32f4xx_hal_uart.c...
|
||||
compiling lftpd_inet.c...
|
||||
compiling lftpd.c...
|
||||
compiling net_socket.c...
|
||||
compiling stm32f4xx_hal_i2c.c...
|
||||
compiling ch395f_test_task.c...
|
||||
compiling net_test_task.c...
|
||||
compiling storage_test_task.c...
|
||||
compiling gd5f_test_task.c...
|
||||
compiling storage_test_task.c...
|
||||
linking...
|
||||
Program Size: Code=56352 RO-data=3756 RW-data=228 ZI-data=54044
|
||||
Program Size: Code=58880 RO-data=2436 RW-data=408 ZI-data=51872
|
||||
FromELF: creating hex file...
|
||||
".\STM32F407-Demo\STM32F407-Demo.axf" - 0 Error(s), 0 Warning(s).
|
||||
Build Time Elapsed: 00:00:16
|
||||
Build Time Elapsed: 00:00:17
|
||||
|
||||
@@ -168,9 +168,33 @@ void MX_FREERTOS_Init(void) {
|
||||
void StartDefaultTask(void *argument)
|
||||
{
|
||||
/* USER CODE BEGIN StartDefaultTask */
|
||||
/* 测试任务已全部收归 ch395fTestTask 统一调度,本任务不再承担任何测试 */
|
||||
(void)argument;
|
||||
|
||||
/* 系统启动期挂载 NAND 上的 FatFS 卷,供 FTP 及其它模块访问。
|
||||
* f_mount(forced=1) 会触发 disk_initialize() → nand_ftl_init()
|
||||
* (dhara_map_resume)。此前默认构建从未挂载,导致 FTP 的
|
||||
* LIST/STOR/RETR 全部返回 550(f_opendir 失败)。
|
||||
* 若卷为空(FR_NO_FILESYSTEM,如恢复/坏块重建后清空),则首次自动
|
||||
* 格式化建卷(MKFS_PARM 与存储测试一致:FM_FAT32 / 无分区表)。 */
|
||||
static FATFS default_fatfs;
|
||||
FRESULT fr = f_mount(&default_fatfs, "", 1);
|
||||
if (fr == FR_NO_FILESYSTEM) {
|
||||
DBG_INFO("[FS] no FAT volume, formatting NAND...");
|
||||
static uint8_t fs_work[FF_MAX_SS];
|
||||
MKFS_PARM opts = { FM_FAT32, 0, 0, 0, 0 };
|
||||
fr = f_mkfs("", &opts, fs_work, sizeof(fs_work));
|
||||
if (fr == FR_OK) {
|
||||
fr = f_mount(&default_fatfs, "", 1);
|
||||
} else {
|
||||
DBG_ERROR("[FS] f_mkfs failed (fr=%d)", (int)fr);
|
||||
}
|
||||
}
|
||||
if (fr == FR_OK) {
|
||||
DBG_INFO("[FS] FATFS mounted");
|
||||
} else {
|
||||
DBG_ERROR("[FS] f_mount failed (fr=%d)", (int)fr);
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
osDelay(1000);
|
||||
}
|
||||
|
||||
168
docs/FTP_Test_Guide.md
Normal file
168
docs/FTP_Test_Guide.md
Normal file
@@ -0,0 +1,168 @@
|
||||
# FTP 功能测试指导
|
||||
|
||||
> 适用对象:STM32F4-Base 上基于 `lftpd` 的 FTP Server 功能验证。
|
||||
> 配套源码:`Drivers/BSP/NET/lftpd/`、`App/task/net_task.c`、`Src/freertos.c`(StartFtpTask)。
|
||||
> 关联文档:`CH395F_Test_Guide.md`(网络测试总说明·阶段 8)、`NET_Socket_FTP_Support_Plan.md`(PASV 改造方案)、`CH395F_Trap_Records.md`。
|
||||
|
||||
---
|
||||
|
||||
## 1. 概述
|
||||
|
||||
- FTP Server(`lftpd`)在**默认固件构建中即常驻运行**:`Src/freertos.c` 的 `StartFtpTask`(默认 `__weak` 实现)直接调用 `lftpd_start("/", 21, &ftp)`,与测试套件选择无关。
|
||||
- 监听端口 **21**,根目录 `/`(即 NAND 上的 FatFS 卷),**匿名登录**(`USER anonymous` / `PASS` 任意)。
|
||||
- 仅支持 **1 个并发客户端**(控制通道 Socket0 + PASV 数据通道动态 Socket2,backlog=1)。
|
||||
- 测试分两类:
|
||||
- **PC 端手测(推荐,覆盖真实 FTP 行为)**:用 `test/` 下 Python 脚本或 GUI 客户端。
|
||||
- **固件自动化(TEST_SUITE_CH395F 阶段 8)**:TC-NET-801/802/803 文件传输。
|
||||
|
||||
---
|
||||
|
||||
## 2. 测试环境
|
||||
|
||||
### 2.1 硬件与网络
|
||||
|
||||
- CH395F 网口经以太网连接到 PC 或同一台交换机。
|
||||
- PC 网卡与固件 IP **同网段**。固件默认静态 IP **192.168.1.100**(掩码 255.255.255.0);PC 可设 192.168.1.x(如 192.168.1.77)。
|
||||
- 启动时 `netTask` 完成 `net_init()` + PHY 稳定(约 >2s),`ftpTask` 另有 `osDelay(7000)` 等待后才 `listen`;若 `open_socket` 失败会 `vTaskDelay(3000)` 重试(最多 3 次)。**客户端应在上电约 7s 后、串口出现 `[FTP] waiting for connection...` 再连接。**
|
||||
|
||||
### 2.2 软件
|
||||
|
||||
- Python 3.x(脚本位于 `test/`)。
|
||||
- 可选 GUI 客户端:FileZilla / MobaXterm / lftp。
|
||||
|
||||
---
|
||||
|
||||
## 3. 编译与运行(固件侧)
|
||||
|
||||
- **默认构建即可提供 FTP Server**,无需切换测试套件。
|
||||
- 任何改动后必须执行 `@build`(即 `MDK-ARM/build.bat`),确认 **0 Error(s) 0 Warning(s)** 再烧录(遵循 AGENTS.md 铁律)。
|
||||
- 若需跑**自动化 FTP 文件传输用例**:在 `test/test_config.h` 选择 `TEST_SUITE_CH395F`,并在 `test/ch395f_test.h` 打开 `ENABLE_PHASE8_TESTS`(文件传输阶段),重新编译烧录。
|
||||
- 烧录后打开串口(115200bps)观察:
|
||||
- `net_init` 完成、PHY link up;
|
||||
- `[FTP] waiting for connection...`(约 3 次重试足够 PHY 稳定);
|
||||
- 客户端连接后进入 FTP 会话(控制通道 220 欢迎)。
|
||||
|
||||
---
|
||||
|
||||
## 4. PC 端脚本手测(主要手段)
|
||||
|
||||
所有脚本支持 `--host`(默认 `192.168.1.100`)、`--port`(默认 21),在 `test/` 目录运行。
|
||||
|
||||
### 4.1 冒烟测试:`ftp_test.py`
|
||||
|
||||
- 用途:验证连接、登录、`PWD`、`PASV`、`LIST` 基本链路。
|
||||
- 命令:`python ./test/ftp_test.py --host 192.168.1.100`
|
||||
- 预期:
|
||||
- 连接成功并读到 `220` 欢迎;
|
||||
- `USER anonymous` / `PASS` 返回 `230`;
|
||||
- `PASV` 返回 `227` 并解析出数据端口(或回退 `EPSV`);
|
||||
- `LIST` 返回目录列表;
|
||||
- `QUIT` 正常关闭。
|
||||
- 判据:全程无 `[NO RESPONSE]` / `CONNECT FAILED`,且 LIST 返回 `226` 即 PASS。**空卷下 LIST 数据通道为 0 字节属正常**(新格式化卷无文件),不必要求有目录列表输出。
|
||||
|
||||
### 4.2 上传 / 下载 / 比对:`ftp_up_dl_test.py`
|
||||
|
||||
- 用途:验证 `STOR`/`RETR`/`DELE` 与数据一致性(`TYPE I` 二进制 + `PASV`)。
|
||||
- 命令:`python ./test/ftp_up_dl_test.py --host 192.168.1.100`
|
||||
- 流程:登录 → `TYPE I` → `STOR up_test.dat` → `LIST` 校验存在 → `RETR up_test.dat` → 逐字节比对 → `DELE` 清理 → `QUIT`。
|
||||
- 预期:`*** MATCH! Upload/Download success. ***`,且 LIST 中出现 `up_test.dat`。
|
||||
- 判据:上传/下载字节数相等且内容逐字节一致。
|
||||
|
||||
### 4.3 速度与大数据量:`ftp_speed_test.py`
|
||||
|
||||
- 用途:测量上传/下载吞吐,作回归基线,同时验证大文件不丢字节。
|
||||
- 命令:`python ./test/ftp_speed_test.py --host 192.168.1.100 --size 512`(默认 512KB,`--size` 可调)。
|
||||
- 预期:上传/下载均返回 `226`,回读 `MATCH!`,打印 KB/s。
|
||||
- 注意:脚本使用 8.3 文件名 `SPEEDTST.DAT`(**FTP 仅支持 8.3 短文件名**,见 §8.3);以回读比对(MATCH)为最终判据,中间打印的 Sent 字段仅供参考。
|
||||
- 判据:size 一致 + MATCH + 速度稳定(受 SPI2 分频 8 限制,通常约 300~450 KB/s,参见 `CH395F_Test_Guide.md` 阶段 5 吞吐基线)。
|
||||
|
||||
### 4.4 抓包辅助:`ftp_capture.py`
|
||||
|
||||
- 用途:连接/传输过程中抓包,分析 PASV 端口、命令/数据通道交互,用于疑难排查。
|
||||
- 用法参见脚本内 `--help` / 注释。
|
||||
|
||||
---
|
||||
|
||||
## 5. GUI 客户端手测(可选)
|
||||
|
||||
- **FileZilla**:主机 `192.168.1.100`,端口 21,用户 `anonymous`,密码任意;可拖拽上传/下载、浏览目录。
|
||||
- 要点:使用二进制模式传输;文件名遵守 8.3;**一次只连一个客户端**。
|
||||
|
||||
---
|
||||
|
||||
## 6. 自动化测试(TEST_SUITE_CH395F 阶段 8)
|
||||
|
||||
- 入口:`ENABLE_PHASE8_TESTS` → 文件传输阶段(100KB 文件)。
|
||||
- 用例:
|
||||
- `TC-NET-801`:100KB 文件上发(MCU→PC);
|
||||
- `TC-NET-802`:100KB 文件下发(PC→MCU);
|
||||
- `TC-NET-803`:round-trip(可选)。
|
||||
- 详见 `docs/CH395F_Test_Guide.md` 阶段 8。
|
||||
|
||||
---
|
||||
|
||||
## 7. 测试清单(Checklist)
|
||||
|
||||
- [ ] 默认构建烧录,串口见 `[FTP] waiting for connection`。
|
||||
- [ ] `ftp_test.py` 冒烟 PASS(连接 / 登录 / PASV / LIST)。
|
||||
- [ ] `ftp_up_dl_test.py` 上传下载比对 `MATCH`。
|
||||
- [ ] `ftp_speed_test.py` 大文件 `MATCH` + 记录速度基线。
|
||||
- [ ] (可选)GUI 客户端手动上传/下载成功。
|
||||
- [ ] (可选)阶段 8 自动化 `TC-NET-801/802/803` PASS。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见失败与排查(基于已知陷阱)
|
||||
|
||||
### 8.1 连接被拒 / 长时间无欢迎
|
||||
|
||||
- 确认 PC 与固件同网段、IP 正确;上电后等待约 7s(PHY 稳定 + `ftpTask` 延迟)再连。
|
||||
- 若反复 `open_socket` 失败:见 **TRAP-09**(PHY 未稳定;固件已做 3 次重试 + 7s 延迟,仍失败检查网线/交换机)。
|
||||
|
||||
### 8.2 PASV 失败 / 数据通道连不上
|
||||
|
||||
- 确认 PC 防火墙未阻断高端口(PASV 动态端口)。
|
||||
- **数据通道必须先 `connect` 再发命令**(如 `LIST`/`STOR`),顺序反了会失败(脚本已遵循)。
|
||||
- **TRAP-11**:`net_accept_locked` 在 `ESTABLISHED` 状态导致 PASV 失败——需校验 `ESTABLISHED`。
|
||||
|
||||
### 8.3 STOR 报 FR_INVALID_NAME (err=6)
|
||||
|
||||
- **8.3 文件名限制**:`upload_test.dat`(11+3)超过 8.3 → `FR_INVALID_NAME`。改用短名如 `UPLOAD.DAT` / `SPEEDTST.DAT`。这是 FatFS LFN/8.3 约束,非驱动 bug。
|
||||
|
||||
### 8.4 大文件传输中途 RST / 速度抖动
|
||||
|
||||
- **TRAP-13** / 设计约束:CH395F `WRITE_SEND_BUF` 芯片侧吞吐限制,单帧 >1KB 才稳定;TCP 背压会"堵一会儿",属正常流控,不丢数据。
|
||||
- 接收侧 `recv_len` 首包可能较大、次包可能为 0,**必须循环读直到连接关闭**(脚本已处理)。
|
||||
- 若持续 RST:检查 **SPI 分频 = 8**(PCB 设计限制)、`net_poll()` 周期(10ms)是否正常、中断是否统一在 `net_poll()` 中经 `GET_GLOB_INT_STATUS` 处理。
|
||||
|
||||
### 8.5 路径问题
|
||||
|
||||
- **TRAP-12**:FatFS 根路径 `/` 前缀由 `to_fatfs_path()` 统一处理;客户端用绝对路径(如 `/UPLOAD.DAT`)即可。
|
||||
|
||||
### 8.6 单客户端限制
|
||||
|
||||
- FTP 仅接受 1 个并发客户端;上一个会话未 `QUIT` 前,新连接会被拒。每次测完务必 `QUIT` / 断开。
|
||||
|
||||
### 8.7 LIST/STOR/RETR 全部 550:卷未挂载 / 无 FAT 文件系统
|
||||
|
||||
- 根因:FTP 服务的是 NAND 上的 FatFS 卷。固件在 `StartDefaultTask` 启动期执行 `f_mount(&fs, "", 1)`(会触发 `disk_initialize` → `nand_ftl_init`),使卷可用。
|
||||
- **首启自动建卷**:若 `f_mount` 返回 `FR_NO_FILESYSTEM`(如坏块重建/恢复测试后卷被清空),固件会自动 `f_mkfs`(FM_FAT32、无分区表,参数与存储测试一致)再挂载。该过程上电会多花数秒(格式化),串口可见 `[FS] no FAT volume, formatting NAND...` → `[FS] FATFS mounted`。
|
||||
- 若串口见 `[FS] f_mount failed (fr=...)` 且非首次(已建卷仍失败):检查 `f_mkfs` 是否报错(`[FS] f_mkfs failed`),或 NAND 是否存在物理/ECC 错误;必要时用 `TEST_SUITE_STORAGE` 跑一次确认磁盘健康。
|
||||
|
||||
---
|
||||
|
||||
## 9. 诊断手段(沿用前期测试经验)
|
||||
|
||||
- **串口日志 + `DBG_*`**:在 `lftpd.c` / `net_socket` 关键路径加 `DBG_ERROR/INFO` 打印(注意编码安全铁律——只用 Edit 改中文源文件,禁止用 `Get/Set-Content` 整文件重写)。
|
||||
- **抓包**:`ftp_capture.py` 或 Wireshark 过滤 `tcp.port==21`。
|
||||
- **编译验证**:`@build` 必须 0/0 再烧录(AGENTS.md 铁律)。
|
||||
- **套件切换**:`test/test_config.h` 改 `TEST_SUITE_CH395F` / `TEST_SUITE_GD5F` / `TEST_SUITE_STORAGE`(三选一,互斥)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 参考文档
|
||||
|
||||
- `docs/CH395F_Test_Guide.md` —— 网络测试总说明(含阶段 8 文件传输、FTP 陷阱清单)
|
||||
- `docs/NET_Socket_FTP_Support_Plan.md` —— FTP / PASV Socket 改造方案
|
||||
- `docs/CH395F_Trap_Records.md` —— CH395F 已知陷阱
|
||||
- `docs/BSD_Socket_API_使用指南.md` —— BSD Socket API 用法
|
||||
BIN
test/__pycache__/ftp_speed_test.cpython-311.pyc
Normal file
BIN
test/__pycache__/ftp_speed_test.cpython-311.pyc
Normal file
Binary file not shown.
BIN
test/__pycache__/ftp_test.cpython-311.pyc
Normal file
BIN
test/__pycache__/ftp_test.cpython-311.pyc
Normal file
Binary file not shown.
BIN
test/__pycache__/ftp_up_dl_test.cpython-311.pyc
Normal file
BIN
test/__pycache__/ftp_up_dl_test.cpython-311.pyc
Normal file
Binary file not shown.
@@ -52,84 +52,122 @@ def test_speed(host, port, size_kb):
|
||||
print(f"\n=== FTP Speed Test: {host}:{port}, {size_kb}KB file ===")
|
||||
print(f" Test data: {total_bytes:,} bytes generated\n")
|
||||
|
||||
# ---- Upload ----
|
||||
print("[UPLOAD] Connecting...")
|
||||
checks = []
|
||||
|
||||
def check(label, ok, detail=""):
|
||||
checks.append((label, ok, detail))
|
||||
mark = "PASS" if ok else "FAIL"
|
||||
print(f" [{mark}] {label}{(' - ' + detail) if detail else ''}")
|
||||
|
||||
def finish(sock):
|
||||
passed = all(ok for _, ok, _ in checks)
|
||||
print("\n" + "=" * 40)
|
||||
print("FTP Speed Test Summary:")
|
||||
for label, ok, _ in checks:
|
||||
print(f" [{'PASS' if ok else 'FAIL'}] {label}")
|
||||
print("=" * 40)
|
||||
if passed:
|
||||
print(">>> TEST PASSED <<<")
|
||||
else:
|
||||
print(">>> TEST FAILED <<<")
|
||||
print("=== Test Complete ===")
|
||||
if sock:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
return passed
|
||||
|
||||
# ---- Connect + Login ----
|
||||
print("[Connect] Connecting...")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(60.0)
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
except Exception as e:
|
||||
print(f" CONNECT FAILED: {e}")
|
||||
check("Connect", False, str(e))
|
||||
return finish(sock)
|
||||
recv_line(sock) # 220
|
||||
send_cmd(sock, "USER anonymous")
|
||||
send_cmd(sock, "PASS test@test.com")
|
||||
if not send_cmd(sock, "USER anonymous"):
|
||||
check("Login USER", False)
|
||||
return finish(sock)
|
||||
if not send_cmd(sock, "PASS test@test.com"):
|
||||
check("Login PASS", False)
|
||||
return finish(sock)
|
||||
check("Login (USER/PASS)", True)
|
||||
send_cmd(sock, "TYPE I")
|
||||
|
||||
# PASV
|
||||
# ---- Upload ----
|
||||
print("[UPLOAD] Connecting...")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
print(" PASV failed"); sock.close(); return
|
||||
check("PASV", False, "no response")
|
||||
return finish(sock)
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
if pasv_port is None:
|
||||
print(f" PASV parse failed: {resp.decode()}"); sock.close(); return
|
||||
check("PASV parse", False, resp.decode())
|
||||
return finish(sock)
|
||||
check("PASV parse", True, f"{pasv_ip}:{pasv_port}")
|
||||
|
||||
# Connect data channel
|
||||
data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
data.settimeout(60.0)
|
||||
data.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # 关 Nagle,防 FIN 跑在数据前面
|
||||
try:
|
||||
data.connect((pasv_ip, pasv_port))
|
||||
except Exception as e:
|
||||
print(f" Data connect failed: {e}"); sock.close(); return
|
||||
print(f" Data connect failed: {e}")
|
||||
check("PASV data connect", False, str(e))
|
||||
return finish(sock)
|
||||
check("PASV data connect", True)
|
||||
|
||||
# STOR - measure from STOR send to 226 response
|
||||
t0 = time.time()
|
||||
send_cmd(sock, f"STOR {test_name}")
|
||||
|
||||
# Send all data at once (sendall handles partial sends)
|
||||
data.sendall(test_data)
|
||||
data.shutdown(socket.SHUT_WR)
|
||||
data.close()
|
||||
|
||||
# Wait for response from server (data received + written to disk)
|
||||
resp = recv_line(sock, timeout=120.0)
|
||||
t1 = time.time()
|
||||
|
||||
upload_time = t1 - t0
|
||||
upload_speed = total_bytes / upload_time / 1024 if upload_time > 0 else 0
|
||||
|
||||
# Read STOR response
|
||||
resp = recv_line(sock)
|
||||
stor_code = resp[:3].decode() if resp else "???"
|
||||
|
||||
print(f" Sent: {sent:,} / {total_bytes:,} bytes")
|
||||
print(f" Sent: {total_bytes:,} / {total_bytes:,} bytes")
|
||||
print(f" Time: {upload_time:.1f}s")
|
||||
print(f" Speed: {upload_speed:.1f} KB/s")
|
||||
print(f" Response: {resp.decode().rstrip() if resp else 'NONE'}")
|
||||
|
||||
if stor_code != "226":
|
||||
print(f" UPLOAD FAILED (code={stor_code}), skipping download")
|
||||
upload_ok = (stor_code == "226")
|
||||
check("STOR 226", upload_ok, f"{stor_code} up={upload_speed:.1f}KB/s")
|
||||
|
||||
if not upload_ok:
|
||||
send_cmd(sock, "QUIT")
|
||||
sock.close()
|
||||
return
|
||||
return finish(sock)
|
||||
|
||||
# ---- Download ----
|
||||
time.sleep(3.0)
|
||||
|
||||
print("[DOWNLOAD] Connecting...")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
print(" PASV failed"); sock.close(); return
|
||||
check("RETR PASV", False, "no response")
|
||||
return finish(sock)
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
if pasv_port is None:
|
||||
print(f" PASV parse failed"); sock.close(); return
|
||||
|
||||
check("RETR PASV parse", False, resp.decode())
|
||||
return finish(sock)
|
||||
data = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
data.settimeout(60.0)
|
||||
try:
|
||||
data.connect((pasv_ip, pasv_port))
|
||||
except Exception as e:
|
||||
print(f" Data connect failed: {e}"); sock.close(); return
|
||||
print(f" Data connect failed: {e}")
|
||||
check("RETR data connect", False, str(e))
|
||||
return finish(sock)
|
||||
check("RETR data connect", True)
|
||||
|
||||
t0 = time.time()
|
||||
send_cmd(sock, f"RETR {test_name}")
|
||||
|
||||
dl_data = b""
|
||||
while True:
|
||||
try:
|
||||
@@ -140,25 +178,24 @@ def test_speed(host, port, size_kb):
|
||||
except socket.timeout:
|
||||
break
|
||||
data.close()
|
||||
|
||||
resp = recv_line(sock, timeout=120.0)
|
||||
t1 = time.time()
|
||||
|
||||
download_time = t1 - t0
|
||||
download_speed = len(dl_data) / download_time / 1024 if download_time > 0 else 0
|
||||
|
||||
resp = recv_line(sock)
|
||||
retr_code = resp[:3].decode() if resp else "???"
|
||||
|
||||
print(f"\n[DOWNLOAD]")
|
||||
print(f" Received: {len(dl_data):,} / {total_bytes:,} bytes")
|
||||
print(f" Time: {download_time:.1f}s")
|
||||
print(f" Speed: {download_speed:.1f} KB/s")
|
||||
print(f" Response: {resp.decode().rstrip() if resp else 'NONE'}")
|
||||
|
||||
retr_ok = bool(resp) and resp.startswith(b"226")
|
||||
check("RETR 226", retr_ok,
|
||||
f"{resp[:3].decode() if resp else '???'} dl={download_speed:.1f}KB/s")
|
||||
|
||||
# Compare
|
||||
print(f"\n[VERIFY]")
|
||||
if len(dl_data) == total_bytes and dl_data == test_data:
|
||||
match = (len(dl_data) == total_bytes and dl_data == test_data)
|
||||
if match:
|
||||
print(f" *** MATCH! {total_bytes:,} bytes identical. ***")
|
||||
else:
|
||||
print(f" MISMATCH: sent={total_bytes}, got={len(dl_data)}")
|
||||
@@ -169,16 +206,15 @@ def test_speed(host, port, size_kb):
|
||||
if dl_data[i] != test_data[i]:
|
||||
print(f" First diff at byte {i}")
|
||||
break
|
||||
check("Upload/Download MATCH", match,
|
||||
f"up={total_bytes:,} dl={len(dl_data):,} up={upload_speed:.1f}KB/s dl={download_speed:.1f}KB/s")
|
||||
|
||||
# Cleanup
|
||||
send_cmd(sock, f"DELE {test_name}")
|
||||
send_cmd(sock, "QUIT")
|
||||
sock.close()
|
||||
|
||||
print(f"\n=== Summary ===")
|
||||
print(f" File size: {total_bytes:,} bytes ({size_kb} KB)")
|
||||
print(f" Upload: {upload_speed:.1f} KB/s ({upload_time:.1f}s)")
|
||||
print(f" Download: {download_speed:.1f} KB/s ({download_time:.1f}s)")
|
||||
return finish(sock)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="FTP Speed Test")
|
||||
@@ -187,7 +223,8 @@ def main():
|
||||
parser.add_argument("--size", type=int, default=FILE_SIZE_KB,
|
||||
help=f"File size in KB (default {FILE_SIZE_KB})")
|
||||
args = parser.parse_args()
|
||||
test_speed(args.host, args.port, args.size)
|
||||
success = test_speed(args.host, args.port, args.size)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -55,6 +55,12 @@ def parse_pasv(response):
|
||||
|
||||
def test_ftp(host, port):
|
||||
print(f"=== FTP Test: {host}:{port} ===\n")
|
||||
checks = [] # (label, ok, detail)
|
||||
|
||||
def check(label, ok, detail=""):
|
||||
checks.append((label, ok, detail))
|
||||
mark = "PASS" if ok else "FAIL"
|
||||
print(f" [{mark}] {label}{(' - ' + detail) if detail else ''}")
|
||||
|
||||
# 1. Connect
|
||||
print("[1] Connecting to control channel...")
|
||||
@@ -63,8 +69,10 @@ def test_ftp(host, port):
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
print(f" Connected to {host}:{port}")
|
||||
check("Connect", True)
|
||||
except Exception as e:
|
||||
print(f" CONNECT FAILED: {e}")
|
||||
check("Connect", False, str(e))
|
||||
return False
|
||||
|
||||
# 2. Read welcome
|
||||
@@ -72,8 +80,11 @@ def test_ftp(host, port):
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" {resp.decode(errors='replace').rstrip()}")
|
||||
check("Welcome 220", resp.startswith(b"220"),
|
||||
resp.decode(errors='replace').rstrip())
|
||||
else:
|
||||
print(" NO WELCOME BANNER")
|
||||
check("Welcome 220", False, "no banner")
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
@@ -82,27 +93,35 @@ def test_ftp(host, port):
|
||||
resp = send_cmd(sock, "USER anonymous")
|
||||
if not resp:
|
||||
sock.close()
|
||||
check("Login USER", False, "no response")
|
||||
return False
|
||||
|
||||
resp = send_cmd(sock, "PASS test@test.com")
|
||||
if not resp:
|
||||
sock.close()
|
||||
check("Login PASS", False, "no response")
|
||||
return False
|
||||
login_ok = b"230" in resp
|
||||
check("Login (USER/PASS 230)", login_ok,
|
||||
resp.decode(errors='replace').rstrip())
|
||||
|
||||
# 4. PWD
|
||||
print("\n[4] PWD...")
|
||||
resp = send_cmd(sock, "PWD")
|
||||
pwd_ok = bool(resp) and resp.startswith(b"257")
|
||||
check("PWD 257", pwd_ok,
|
||||
resp.decode(errors='replace').rstrip() if resp else "no response")
|
||||
|
||||
# 5. PASV mode
|
||||
print("\n[5] PASV...")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
pasv_ip, pasv_port = (None, None)
|
||||
if resp:
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
if pasv_port is None and resp and b"227" in resp:
|
||||
# 227 响应但解析端口失败
|
||||
pasv_port = None
|
||||
if pasv_port is None:
|
||||
print(" FAILED to parse PASV response")
|
||||
# Try EPSV
|
||||
print("\n[5b] Trying EPSV...")
|
||||
resp = send_cmd(sock, "EPSV")
|
||||
@@ -113,21 +132,21 @@ def test_ftp(host, port):
|
||||
pasv_port = int(m.group(1))
|
||||
pasv_ip = host
|
||||
print(f" EPSV: {pasv_ip}:{pasv_port}")
|
||||
|
||||
if pasv_port is None:
|
||||
print(" PASV/EPSV FAILED, trying PORT mode...")
|
||||
# Skip data connection tests
|
||||
else:
|
||||
print(f" Data channel: {pasv_ip}:{pasv_port}")
|
||||
pasv_ok = pasv_port is not None
|
||||
check("PASV/EPSV data port", pasv_ok,
|
||||
f"{pasv_ip}:{pasv_port}" if pasv_ok else "no port")
|
||||
|
||||
# 6. LIST (correct PASV flow: connect data first, then send LIST)
|
||||
if pasv_ok:
|
||||
print(f" Data channel: {pasv_ip}:{pasv_port}")
|
||||
print("\n[6] LIST...")
|
||||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
data_sock.settimeout(5.0)
|
||||
try:
|
||||
data_sock.connect((pasv_ip, pasv_port))
|
||||
print(f" Data connected to {pasv_ip}:{pasv_port}")
|
||||
send_cmd(sock, "LIST")
|
||||
resp = send_cmd(sock, "LIST")
|
||||
list_open = bool(resp) and resp.startswith(b"150")
|
||||
data = b""
|
||||
while True:
|
||||
try:
|
||||
@@ -140,22 +159,41 @@ def test_ftp(host, port):
|
||||
print(f" LIST result ({len(data)} bytes):")
|
||||
print(data.decode(errors='replace'))
|
||||
data_sock.close()
|
||||
resp = recv_line(sock)
|
||||
list_close = bool(resp) and resp.startswith(b"226")
|
||||
print(f" LIST response: "
|
||||
f"{resp.decode(errors='replace').rstrip() if resp else 'none'}")
|
||||
list_ok = list_open and list_close
|
||||
check("LIST 150->226", list_ok,
|
||||
f"open={list_open} close={list_close} bytes={len(data)}")
|
||||
except Exception as e:
|
||||
print(f" LIST FAILED: {e}")
|
||||
data_sock.close()
|
||||
|
||||
# Read LIST response
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" LIST response: {resp.decode(errors='replace').rstrip()}")
|
||||
check("LIST 150->226", False, str(e))
|
||||
else:
|
||||
print(" Skipping LIST (no data port)")
|
||||
|
||||
# 7. QUIT
|
||||
print("\n[7] QUIT...")
|
||||
send_cmd(sock, "QUIT")
|
||||
|
||||
resp = send_cmd(sock, "QUIT")
|
||||
quit_ok = bool(resp) and resp.startswith(b"221")
|
||||
check("QUIT 221", quit_ok,
|
||||
resp.decode(errors='replace').rstrip() if resp else "no response")
|
||||
sock.close()
|
||||
print("\n=== Test Complete ===")
|
||||
return True
|
||||
|
||||
# Summary
|
||||
passed = all(ok for _, ok, _ in checks)
|
||||
print("\n" + "=" * 40)
|
||||
print("FTP Test Summary:")
|
||||
for label, ok, _ in checks:
|
||||
print(f" [{'PASS' if ok else 'FAIL'}] {label}")
|
||||
print("=" * 40)
|
||||
if passed:
|
||||
print(">>> TEST PASSED <<<")
|
||||
else:
|
||||
print(">>> TEST FAILED <<<")
|
||||
print("=== Test Complete ===")
|
||||
return passed
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="FTP Server Test")
|
||||
|
||||
@@ -128,33 +128,67 @@ def ftp_transfer_data(host, pasv_ip, pasv_port, cmd, data_to_send=None, read_dat
|
||||
|
||||
def test_upload_download(host, port):
|
||||
print(f"=== FTP Upload/Download Test: {host}:{port} ===\n")
|
||||
checks = []
|
||||
|
||||
def check(label, ok, detail=""):
|
||||
checks.append((label, ok, detail))
|
||||
mark = "PASS" if ok else "FAIL"
|
||||
print(f" [{mark}] {label}{(' - ' + detail) if detail else ''}")
|
||||
|
||||
def finish(sock):
|
||||
passed = all(ok for _, ok, _ in checks)
|
||||
print("\n" + "=" * 40)
|
||||
print("FTP Upload/Download Summary:")
|
||||
for label, ok, _ in checks:
|
||||
print(f" [{'PASS' if ok else 'FAIL'}] {label}")
|
||||
print("=" * 40)
|
||||
if passed:
|
||||
print(">>> TEST PASSED <<<")
|
||||
else:
|
||||
print(">>> TEST FAILED <<<")
|
||||
print("=== Test Complete ===")
|
||||
if sock:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
return passed
|
||||
|
||||
# 1. Connect + Login
|
||||
print("[1] Connect + Login")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(TIMEOUT)
|
||||
try:
|
||||
sock.connect((host, port))
|
||||
except Exception as e:
|
||||
print(f" CONNECT FAILED: {e}")
|
||||
check("Connect", False, str(e))
|
||||
return finish(sock)
|
||||
recv_line(sock) # 220
|
||||
|
||||
if not send_cmd(sock, "USER anonymous", 230):
|
||||
sock.close(); return
|
||||
check("Login USER 230", False)
|
||||
return finish(sock)
|
||||
if not send_cmd(sock, "PASS test@test.com", 230):
|
||||
sock.close(); return
|
||||
check("Login PASS 230", False)
|
||||
return finish(sock)
|
||||
check("Login (USER/PASS 230)", True)
|
||||
|
||||
# 2. TYPE I (binary mode)
|
||||
print("\n[2] Set binary mode")
|
||||
send_cmd(sock, "TYPE I")
|
||||
resp = send_cmd(sock, "TYPE I")
|
||||
type_ok = bool(resp) and resp.startswith(b"200")
|
||||
check("TYPE I 200", type_ok)
|
||||
|
||||
# 3. PASV + STOR (upload)
|
||||
print("\n[3] Upload: STOR up_test.dat")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
sock.close(); return
|
||||
|
||||
check("PASV", False, "no response")
|
||||
return finish(sock)
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
print(f" PASV: {pasv_ip}:{pasv_port}")
|
||||
|
||||
# Connect data channel
|
||||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
data_sock.settimeout(10.0)
|
||||
try:
|
||||
@@ -162,12 +196,11 @@ def test_upload_download(host, port):
|
||||
print(f" Data connected.")
|
||||
except Exception as e:
|
||||
print(f" Data connect FAILED: {e}")
|
||||
sock.close(); return
|
||||
check("PASV data connect", False, str(e))
|
||||
return finish(sock)
|
||||
check("PASV data connect", True, f"{pasv_ip}:{pasv_port}")
|
||||
|
||||
# Send STOR
|
||||
send_cmd(sock, "STOR up_test.dat")
|
||||
|
||||
# Send file data
|
||||
total = 0
|
||||
while total < len(TEST_DATA):
|
||||
try:
|
||||
@@ -179,20 +212,20 @@ def test_upload_download(host, port):
|
||||
print(f" Send error: {e}")
|
||||
break
|
||||
print(f" Uploaded {total}/{len(TEST_DATA)} bytes.")
|
||||
|
||||
data_sock.shutdown(socket.SHUT_WR)
|
||||
data_sock.close()
|
||||
|
||||
# Read STOR response
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" Response: {resp.decode().rstrip()}")
|
||||
stor_ok = bool(resp) and resp.startswith(b"226") and total == len(TEST_DATA)
|
||||
check("STOR 226 + bytes", stor_ok,
|
||||
f"uploaded={total}/{len(TEST_DATA)} resp={resp.decode().rstrip() if resp else 'none'}")
|
||||
|
||||
# 4. PASV + LIST (verify)
|
||||
print("\n[4] Verify: LIST")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
sock.close(); return
|
||||
check("LIST PASV", False, "no response")
|
||||
return finish(sock)
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
|
||||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
@@ -213,15 +246,17 @@ def test_upload_download(host, port):
|
||||
data_sock.close()
|
||||
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" Response: {resp.decode().rstrip()}")
|
||||
list_ok = bool(data) and b"UP_TEST.DAT" in data.upper()
|
||||
check("LIST shows UP_TEST.DAT", list_ok,
|
||||
resp.decode().rstrip() if resp else "no resp")
|
||||
|
||||
# 5. PASV + RETR (download)
|
||||
time.sleep(1.0)
|
||||
print("\n[5] Download: RETR up_test.dat")
|
||||
resp = send_cmd(sock, "PASV")
|
||||
if not resp:
|
||||
sock.close(); return
|
||||
check("RETR PASV", False, "no response")
|
||||
return finish(sock)
|
||||
pasv_ip, pasv_port = parse_pasv(resp)
|
||||
|
||||
data_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
@@ -230,10 +265,11 @@ def test_upload_download(host, port):
|
||||
data_sock.connect((pasv_ip, pasv_port))
|
||||
except Exception as e:
|
||||
print(f" Data connect FAILED: {e}")
|
||||
sock.close(); return
|
||||
check("RETR data connect", False, str(e))
|
||||
return finish(sock)
|
||||
check("RETR data connect", True, f"{pasv_ip}:{pasv_port}")
|
||||
|
||||
send_cmd(sock, "RETR up_test.dat")
|
||||
|
||||
dl_data = b""
|
||||
while True:
|
||||
try:
|
||||
@@ -244,39 +280,46 @@ def test_upload_download(host, port):
|
||||
except socket.timeout:
|
||||
break
|
||||
data_sock.close()
|
||||
|
||||
resp = recv_line(sock)
|
||||
if resp:
|
||||
print(f" Response: {resp.decode().rstrip()}")
|
||||
retr_ok = bool(resp) and resp.startswith(b"226")
|
||||
check("RETR 226", retr_ok, resp.decode().rstrip() if resp else "no resp")
|
||||
|
||||
# Compare
|
||||
print(f"\n[6] Compare")
|
||||
print(f" Uploaded: {len(TEST_DATA)} bytes")
|
||||
print(f" Downloaded: {len(dl_data)} bytes")
|
||||
if dl_data == TEST_DATA:
|
||||
match = (dl_data == TEST_DATA)
|
||||
if match:
|
||||
print(f" *** MATCH! Upload/Download success. ***")
|
||||
else:
|
||||
print(f" *** MISMATCH! ***")
|
||||
if dl_data:
|
||||
print(f" First 80 bytes uploaded: {TEST_DATA[:80]!r}")
|
||||
print(f" First 80 bytes downloaded: {dl_data[:80]!r}")
|
||||
check("Upload/Download MATCH", match, f"up={len(TEST_DATA)} dl={len(dl_data)}")
|
||||
|
||||
# 7. DELE (delete test file)
|
||||
print("\n[7] Cleanup: DELE up_test.dat")
|
||||
send_cmd(sock, "DELE up_test.dat")
|
||||
resp = send_cmd(sock, "DELE up_test.dat")
|
||||
dele_ok = bool(resp) and resp.startswith(b"250")
|
||||
check("DELE 250", dele_ok, resp.decode().rstrip() if resp else "no resp")
|
||||
|
||||
# 8. QUIT
|
||||
print("\n[8] QUIT")
|
||||
send_cmd(sock, "QUIT")
|
||||
sock.close()
|
||||
print("\n=== Test Complete ===")
|
||||
resp = send_cmd(sock, "QUIT")
|
||||
quit_ok = bool(resp) and resp.startswith(b"221")
|
||||
check("QUIT 221", quit_ok, resp.decode().rstrip() if resp else "no resp")
|
||||
|
||||
return finish(sock)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="FTP Upload/Download Test")
|
||||
parser.add_argument("--host", default=HOST)
|
||||
parser.add_argument("--port", type=int, default=PORT)
|
||||
args = parser.parse_args()
|
||||
test_upload_download(args.host, args.port)
|
||||
success = test_upload_download(args.host, args.port)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user