commit 2a343ec2cd2a322bd01d571a4c049fbc12b44303 Author: alex Date: Sun Sep 14 04:15:37 2025 +0800 初始提交:文件传输系统基础框架 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5a2f94d --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2025 Alex_jzr + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..97d55bb --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# TCP-file + +基于TPC协议和RSA非对称加密的点对点文件传输软件 \ No newline at end of file diff --git a/key/private_key.pem b/key/private_key.pem new file mode 100644 index 0000000..dbb898f --- /dev/null +++ b/key/private_key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyXvR6bvmkuk/J +sjiTiIrmT4vzpDGjIRJ8+GofLbw6BIZ8cjAwwiHRY3D+dSYJlPmT5JXj3rp1aQpX +gGCl4PYxCMXdPRDWeCkyQ4izaZBMybL4ztnRetazuKyKRWOds2PIskOm1yO6Pq7Y +wHVtptubAHsK8dO6a3YjDCZrxO7iNJJ2/48WR3ajpjmn21e2om8iVKZmFEnUUkkg +98qVIF7rLjT40WaxHOAwKvUFdJrbennRVFHS6iTIAHtTxOZhber4VvNgqvDIwxQZ +XjeOLT4HgJZ2vB9bKUNZA5M/HS+Z7Fm53KOMU6Iyed7o//TPEInHMmgQH9hMXvsk +TyIFsyMhAgMBAAECggEAKwFb3n0NMZs+C3oty9xa6OZ67rZCxXr+0yStqXDEdhSL +PEvntInJz4szPhaOojbJ6c9uGC+mMxKtTKWGJ9hSY0YjNpE3kw4LmLPRrLgh83GZ +9gUhXTFJvLEk4H2UY/xRbZ0VVI+AbLIaQ+Y7KcHWJsv53oypqMOqCw8t4EPt+Jmf +P6ZkgJbT2Ml6Q/3tTeqv9HfOb981K7NEEBZKS+ddtZGQXFPYO9cxxcsxtP8HcfPy +aVghu9TC47REmifjyglIcNLeZbnzZS7dtmKjnGYOyOpz19G/yHFQO4eZDEFjipar +WUsC2oe/6xTSbk43rEybn6kkuN7I4YFHaFeeTft8MQKBgQDWBHIK1QCwFs22wbyO +yrod1GZWk5Xmyw3SwZBcHMefPhuf2o7muNx0P273kN1U3vTGtS7uNcFqyIKXanHd +widzda/cEBYMzm4/de4JfGVuM9saCM0xn2aPRo6ZXiEVOcS3yFpYgsb+OQ0YdR5X +ENX5NfaSJgQKFjPCnD0WyqgFbQKBgQDVXGlBU60QmOkd9Lb19tf47DUQuPtpxwt4 +Jiyx4aVOn33F1n/94HHXrjpJ9LNTxjE4FlInEckkZudGr2Vf6sXqloK/XQTK2N77 +iL+l/g1tPbKY04X7UsoYt+jS3jUN+1h7LH4oy3SXGMuT/8VUJcB4rpQUOap/B7du +GY9BPJooBQKBgDNAEUdCxs1kSJLxRgQzy+oEyRUGdqk0CvVjYPyN78fUiaz4G6xo +rHIyFpK2YCpI0fkbvkdRHCZEKfG0jdv6+JOPpTNfrsgWTxRnWz9uSKPhSyCq5uhx +MZAx50gW4HlCwjb4hZoYhyqt4tLuiPt0jqkFISzSabk4o+CApahlk2LpAoGBALk6 +wSY1vsnp9nhLO4vOATHZ3zflYF80roBgo+zKOPlI/agD0JpXgH3+hBwwlH7mUVSg +DDJe/oDb1W1IWHotGCXRBTGdT8vK+8rjrX4uUPnF1odXG7pU5Z8QCtEGmIjK7MYC +moRQHagPnq2eH3IuVCpxZZ0pcxtVV6n+BqBcPHkBAoGBAKBlbfX7DScF41wBsjMm +fRO+M/qvXuQdlA9r8mA54yOCw6yhCFcUvDBA36jZPNX/PDtPSeIj9eye/IbBPOJY +xKmiCD/qD9lvUZrYG6hYR1swcOzNKz05Hx40tdhCM/xTNxbOOSERGBk7w0OO/ptQ +Nyd1AK7no8fhr69yPGq553KV +-----END PRIVATE KEY----- diff --git a/key/public_key.pem b/key/public_key.pem new file mode 100644 index 0000000..839ec80 --- /dev/null +++ b/key/public_key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsl70em75pLpPybI4k4iK +5k+L86QxoyESfPhqHy28OgSGfHIwMMIh0WNw/nUmCZT5k+SV4966dWkKV4BgpeD2 +MQjF3T0Q1ngpMkOIs2mQTMmy+M7Z0XrWs7isikVjnbNjyLJDptcjuj6u2MB1babb +mwB7CvHTumt2Iwwma8Tu4jSSdv+PFkd2o6Y5p9tXtqJvIlSmZhRJ1FJJIPfKlSBe +6y40+NFmsRzgMCr1BXSa23p50VRR0uokyAB7U8TmYW3q+FbzYKrwyMMUGV43ji0+ +B4CWdrwfWylDWQOTPx0vmexZudyjjFOiMnne6P/0zxCJxzJoEB/YTF77JE8iBbMj +IQIDAQAB +-----END PUBLIC KEY----- diff --git a/key/rsamake.py b/key/rsamake.py new file mode 100644 index 0000000..ae60c3c --- /dev/null +++ b/key/rsamake.py @@ -0,0 +1,38 @@ +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.backends import default_backend + +# 生成私钥 +private_key = rsa.generate_private_key( + public_exponent=65537, + key_size=2048, + backend=default_backend() +) + +# 获取公钥 +public_key = private_key.public_key() + +# 序列化私钥 +private_pem = private_key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption() +) + +# 序列化公钥 +public_pem = public_key.public_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PublicFormat.SubjectPublicKeyInfo +) + +# 保存私钥到文件 +with open('private_key.pem', 'wb') as f: + f.write(private_pem) + +# 保存公钥到文件 +with open('public_key.pem', 'wb') as f: + f.write(public_pem) + +print("RSA密钥对生成成功!") +print("私钥已保存到: private_key.pem") +print("公钥已保存到: public_key.pem") diff --git a/main.py b/main.py new file mode 100755 index 0000000..0942086 --- /dev/null +++ b/main.py @@ -0,0 +1,585 @@ +#!/usr/bin/env python3 +import sys +import os +import json +import base64 +from typing import Dict, List, Tuple, Any, Optional + +# 添加src目录到Python路径 +sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) + +from file import File +from network import TCPIPv6Transporter +from rsa import RSACrypto + +class FileTransferSystem: + def __init__(self): + self.transporter = TCPIPv6Transporter() + self.received_files = {} + self.current_status = "ready" + self.temp_files = {} + + + def process_command(self, command: str, args: Dict[str, Any]) -> Dict[str, Any]: + """处理来自shell的命令""" + try: + self.current_status = "processing" + + if command == "send_file": + return self._send_file_complete(args) + elif command == "start_receiver": + return self._start_receiver(args) + elif command == "stop_receiver": + return self._stop_receiver(args) + elif command == "get_status": + return self._get_status(args) + elif command == "list_received_files": + return self._list_received_files(args) + elif command == "get_received_file": + return self._get_received_file(args) + elif command == "cleanup": + return self._cleanup(args) + else: + return { + "success": False, + "message": f"未知命令: {command}", + "data": None + } + + except Exception as e: + return { + "success": False, + "message": f"处理命令时出错: {e}", + "data": None + } + finally: + self.current_status = "ready" + + def _send_file_complete(self, args: Dict) -> Dict: + """完整的文件发送流程""" + file_path = args.get("file_path") + target_ip = args.get("target_ip") + target_port = args.get("target_port") + public_key_path = args.get("public_key_path") + chunk_size = args.get("chunk_size", 2048) + + # 验证参数 + if not all([file_path, target_ip, target_port]): + return { + "success": False, + "message": "缺少必要参数: file_path, target_ip, target_port", + "data": None + } + + if not os.path.exists(file_path): + return { + "success": False, + "message": f"文件不存在: {file_path}", + "data": None + } + + try: + # 1. 读取文件 + file_handler = File(file_path, chunk_size) + file_data = file_handler.read_file() + + # 2. 如果需要加密 + if public_key_path and os.path.exists(public_key_path): + # 分割文件为适合RSA加密的小块 + max_block_size = RSACrypto.get_max_block_size() + blocks = [] + for i in range(0, len(file_data), max_block_size): + block = file_data[i:i + max_block_size] + blocks.append(block) + + # 加密所有块 + encrypted_blocks = RSACrypto.encrypt_blocks(blocks, public_key_path) + # 合并加密后的块 + file_data = b''.join(encrypted_blocks) + encryption_status = "encrypted" + else: + encryption_status = "not_encrypted" + + # 3. 发送文件 + success, message = self.transporter.send_file(file_data, target_ip, target_port) + + if success: + return { + "success": True, + "message": f"文件发送成功 ({encryption_status})", + "data": { + "file_size": len(file_data), + "encryption": encryption_status, + "target": f"[{target_ip}]:{target_port}" + } + } + else: + return { + "success": False, + "message": f"发送失败: {message}", + "data": None + } + + except Exception as e: + return { + "success": False, + "message": f"发送流程出错: {e}", + "data": None + } + + + def _handle_received_data(self, data: bytes, client_addr: Tuple): + """处理接收到的数据回调""" + try: + file_id = f"{client_addr[0]}_{int(time.time())}" + + # 存储接收到的文件数据 + self.received_files[file_id] = { + 'data': data, + 'from': client_addr, + 'time': time.time(), + 'size': len(data) + } + + print(f"接收到文件 {file_id}, 大小: {len(data)} bytes") + + except Exception as e: + print(f"处理接收数据出错: {e}") + + def _start_receiver(self, args: Dict) -> Dict: + """启动接收器""" + listen_port = args.get("listen_port") + private_key_path = args.get("private_key_path") + + if not listen_port: + return { + "success": False, + "message": "缺少参数: listen_port", + "data": None + } + + # 存储私钥路径用于后续解密 + if private_key_path and os.path.exists(private_key_path): + self.temp_files['private_key_path'] = private_key_path + + try: + success, message = self.transporter.start_server(listen_port, self._handle_received_data) + + return { + "success": success, + "message": message, + "data": { + "port": listen_port, + "encryption_ready": private_key_path is not None + } + } + except Exception as e: + return { + "success": False, + "message": f"启动接收器失败: {e}", + "data": None + } + + + def _split_file(self, args: Dict) -> Dict: + """分割文件为块""" + file_path = args.get("file_path") + chunk_size = args.get("chunk_size", 2048) + + if not file_path or not os.path.exists(file_path): + return { + "success": False, + "message": f"文件不存在: {file_path}", + "data": None + } + + try: + file_handler = File(file_path, chunk_size) + chunks = file_handler.split_to_chunks() + + return { + "success": True, + "message": f"文件分割成功,共 {len(chunks)} 个块", + "data": { + "chunks_count": len(chunks), + "chunk_size": chunk_size, + "file_size": os.path.getsize(file_path) + } + } + except Exception as e: + return { + "success": False, + "message": f"分割文件失败: {e}", + "data": None + } + + def _encrypt_blocks(self, args: Dict) -> Dict: + """加密数据块""" + blocks = args.get("blocks") + public_key_path = args.get("public_key_path") + + if not blocks or not public_key_path: + return { + "success": False, + "message": "缺少参数: blocks 或 public_key_path", + "data": None + } + + if not os.path.exists(public_key_path): + return { + "success": False, + "message": f"公钥文件不存在: {public_key_path}", + "data": None + } + + try: + encrypted_blocks = RSACrypto.encrypt_blocks(blocks, public_key_path) + + return { + "success": True, + "message": f"加密成功,共 {len(encrypted_blocks)} 个加密块", + "data": { + "encrypted_blocks": encrypted_blocks, + "blocks_count": len(encrypted_blocks) + } + } + except Exception as e: + return { + "success": False, + "message": f"加密失败: {e}", + "data": None + } + + def _decrypt_blocks(self, args: Dict) -> Dict: + """解密数据块""" + encrypted_blocks = args.get("encrypted_blocks") + private_key_path = args.get("private_key_path") + + if not encrypted_blocks or not private_key_path: + return { + "success": False, + "message": "缺少参数: encrypted_blocks 或 private_key_path", + "data": None + } + + if not os.path.exists(private_key_path): + return { + "success": False, + "message": f"私钥文件不存在: {private_key_path}", + "data": None + } + + try: + decrypted_blocks = RSACrypto.decrypt_blocks(encrypted_blocks, private_key_path) + + return { + "success": True, + "message": f"解密成功,共 {len(decrypted_blocks)} 个解密块", + "data": { + "decrypted_blocks": decrypted_blocks, + "blocks_count": len(decrypted_blocks) + } + } + except Exception as e: + return { + "success": False, + "message": f"解密失败: {e}", + "data": None + } + + def _send_file(self, args: Dict) -> Dict: + """发送文件""" + file_data = args.get("file_data") + target_ip = args.get("target_ip") + target_port = args.get("target_port") + + if not file_data or not target_ip or not target_port: + return { + "success": False, + "message": "缺少参数: file_data, target_ip 或 target_port", + "data": None + } + + try: + success, message = self.transporter.send_file(file_data, target_ip, target_port) + + return { + "success": success, + "message": message, + "data": None + } + except Exception as e: + return { + "success": False, + "message": f"发送文件失败: {e}", + "data": None + } + + def _handle_received_data(self, data: bytes, client_addr: Tuple): + """处理接收到的数据回调""" + file_id = f"{client_addr[0]}_{int(time.time())}" + self.received_files[file_id] = { + 'data': data, + 'from': client_addr, + 'time': time.time(), + 'size': len(data) + } + print(f"接收到文件 {file_id}, 大小: {len(data)} bytes") + + def _start_receiver(self, args: Dict) -> Dict: + """启动接收器""" + listen_port = args.get("listen_port") + + if not listen_port: + return { + "success": False, + "message": "缺少参数: listen_port", + "data": None + } + + try: + success, message = self.transporter.start_server(listen_port, self._handle_received_data) + + return { + "success": success, + "message": message, + "data": { + "port": listen_port + } + } + except Exception as e: + return { + "success": False, + "message": f"启动接收器失败: {e}", + "data": None + } + + def _stop_receiver(self, args: Dict) -> Dict: + """停止接收器""" + port = args.get("port") + + if not port: + return { + "success": False, + "message": "缺少参数: port", + "data": None + } + + try: + success, message = self.transporter.stop_server(port) + + return { + "success": success, + "message": message, + "data": { + "port": port + } + } + except Exception as e: + return { + "success": False, + "message": f"停止接收器失败: {e}", + "data": None + } + + def _get_status(self, args: Dict) -> Dict: + """获取系统状态""" + listening_ports = self.transporter.get_listening_ports() + + return { + "success": True, + "message": "系统状态获取成功", + "data": { + "status": self.current_status, + "listening_ports": listening_ports, + "received_files_count": len(self.received_files), + "received_files_size": sum(f['size'] for f in self.received_files.values()) + } + } + + def _list_received_files(self, args: Dict) -> Dict: + """列出接收到的文件""" + files_info = [] + for file_id, file_data in self.received_files.items(): + files_info.append({ + "id": file_id, + "size": file_data['size'], + "from": file_data['from'], + "time": file_data['time'] + }) + + return { + "success": True, + "message": f"共 {len(files_info)} 个接收到的文件", + "data": { + "files": files_info + } + } + + def _get_received_file(self, args: Dict) -> Dict: + """获取接收到的文件数据""" + file_id = args.get("file_id") + + if not file_id or file_id not in self.received_files: + return { + "success": False, + "message": f"文件不存在: {file_id}", + "data": None + } + + file_data = self.received_files[file_id] + + return { + "success": True, + "message": "文件数据获取成功", + "data": { + "file_data": file_data['data'], + "file_info": { + "id": file_id, + "size": file_data['size'], + "from": file_data['from'], + "time": file_data['time'] + } + } + } + + def _get_received_file(self, args: Dict) -> Dict: + """获取接收到的文件数据""" + file_id = args.get("file_id") + save_path = args.get("save_path") + private_key_path = args.get("private_key_path") or self.temp_files.get('private_key_path') + + if not file_id or file_id not in self.received_files: + return { + "success": False, + "message": f"文件不存在: {file_id}", + "data": None + } + + try: + file_data = self.received_files[file_id]['data'] + + # 尝试解密(如果有私钥) + if private_key_path and os.path.exists(private_key_path): + try: + # RSA加密的数据有固定长度特征 + if len(file_data) % 256 == 0: # 2048位RSA加密块大小 + # 分割为加密块 + encrypted_blocks = [] + for i in range(0, len(file_data), 256): + block = file_data[i:i + 256] + encrypted_blocks.append(block) + + # 解密所有块 + decrypted_blocks = RSACrypto.decrypt_blocks(encrypted_blocks, private_key_path) + file_data = b''.join(decrypted_blocks) + encryption_status = "decrypted" + else: + encryption_status = "not_encrypted" + except Exception as e: + encryption_status = f"decryption_failed: {e}" + else: + encryption_status = "not_decrypted" + + # 保存文件(如果指定了路径) + if save_path: + try: + file_handler = File(save_path) + file_handler.save_file(file_data) + save_status = f"saved_to_{save_path}" + except Exception as e: + save_status = f"save_failed: {e}" + else: + save_status = "not_saved" + + file_info = { + "id": file_id, + "size": len(file_data), + "from": self.received_files[file_id]['from'], + "time": self.received_files[file_id]['time'], + "encryption_status": encryption_status, + "save_status": save_status + } + + return { + "success": True, + "message": "文件数据获取成功", + "data": { + "file_data": base64.b64encode(file_data).decode('utf-8') if not save_path else None, + "file_info": file_info + } + } + + except Exception as e: + return { + "success": False, + "message": f"获取文件失败: {e}", + "data": None + } + + def _cleanup(self, args: Dict) -> Dict: + """清理资源""" + try: + # 停止所有服务器 + success, message = self.transporter.stop_all_servers() + + # 清空接收文件缓存 + self.received_files.clear() + + return { + "success": success, + "message": f"清理完成: {message}", + "data": None + } + except Exception as e: + return { + "success": False, + "message": f"清理失败: {e}", + "data": None + } + +def main(): + """主程序入口""" + system = FileTransferSystem() + + # 从标准输入读取命令 + for line in sys.stdin: + try: + # 解析JSON命令 + command_data = json.loads(line.strip()) + command = command_data.get("command") + args = command_data.get("args", {}) + + if not command: + result = { + "success": False, + "message": "缺少命令名称", + "data": None + } + else: + # 处理命令 + result = system.process_command(command, args) + + # 输出结果 + print(json.dumps(result)) + sys.stdout.flush() + + except json.JSONDecodeError: + result = { + "success": False, + "message": "无效的JSON格式", + "data": None + } + print(json.dumps(result)) + sys.stdout.flush() + except Exception as e: + result = { + "success": False, + "message": f"处理命令时发生错误: {e}", + "data": None + } + print(json.dumps(result)) + sys.stdout.flush() + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8a703dd --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +# requirements.txt +cryptography>=41.0.0 +pycryptodome>=3.19.0 +argcomplete>=3.0.0 +rich>=13.0.0 +prompt-toolkit>=3.0.0 diff --git a/shell.py b/shell.py new file mode 100644 index 0000000..e8efd66 --- /dev/null +++ b/shell.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +import json +import subprocess +import sys +import os +import time +import base64 +from typing import Dict, Any, List +import argparse +import readline + +class FileTransferShell: + def __init__(self): + self.process = None + self.start_main_process() + + def start_main_process(self): + """启动主程序进程""" + try: + self.process = subprocess.Popen( + [sys.executable, "main.py"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + bufsize=1 + ) + print("✓ 文件传输系统已启动") + except Exception as e: + print(f"✗ 启动失败: {e}") + sys.exit(1) + + def send_command(self, command: str, args: Dict[str, Any] = None) -> Dict[str, Any]: + """发送命令到主程序""" + if args is None: + args = {} + + try: + command_data = { + "command": command, + "args": args + } + + self.process.stdin.write(json.dumps(command_data) + '\n') + self.process.stdin.flush() + + response_line = self.process.stdout.readline().strip() + if not response_line: + return {"success": False, "message": "无响应", "data": None} + + return json.loads(response_line) + + except Exception as e: + return {"success": False, "message": f"通信错误: {e}", "data": None} + + def print_result(self, result: Dict[str, Any]): + """美化打印结果""" + if result["success"]: + print(f"✓ {result['message']}") + if result["data"]: + print("数据详情:") + print(json.dumps(result["data"], indent=2, ensure_ascii=False)) + else: + print(f"✗ {result['message']}") + print() + + def send_file_interactive(self): + """交互式文件发送""" + print("\n=== 文件发送模式 ===") + + # 获取文件路径 + file_path = input("请输入要发送的文件路径: ").strip() + if not os.path.exists(file_path): + print("文件不存在!") + return + + # 获取目标地址 + target_ip = input("请输入目标IPv6地址: ").strip() + target_port = int(input("请输入目标端口: ").strip()) + + # 询问是否加密 + use_encryption = input("是否使用加密?(y/n): ").strip().lower() == 'y' + public_key_path = None + if use_encryption: + public_key_path = input("请输入公钥文件路径: ").strip() + if not os.path.exists(public_key_path): + print("公钥文件不存在!") + return + + # 发送文件 + args = { + "file_path": file_path, + "target_ip": target_ip, + "target_port": target_port + } + + if public_key_path: + args["public_key_path"] = public_key_path + + result = self.send_command("send_file", args) + self.print_result(result) + + def receive_file_interactive(self): + """交互式文件接收""" + print("\n=== 文件接收模式 ===") + + # 获取监听端口 + listen_port = int(input("请输入监听端口: ").strip()) + + # 询问是否有私钥 + use_decryption = input("是否准备解密文件?(y/n): ").strip().lower() == 'y' + private_key_path = None + if use_decryption: + private_key_path = input("请输入私钥文件路径: ").strip() + if not os.path.exists(private_key_path): + print("私钥文件不存在!") + return + + # 启动接收器 + args = {"listen_port": listen_port} + if private_key_path: + args["private_key_path"] = private_key_path + + result = self.send_command("start_receiver", args) + self.print_result(result) + + if result["success"]: + print(f"接收器已在端口 {listen_port} 启动,等待文件传输...") + print("输入 'stop' 停止接收器") + + def stop_receiver_interactive(self): + """停止接收器""" + port = int(input("请输入要停止的端口: ").strip()) + result = self.send_command("stop_receiver", {"port": port}) + self.print_result(result) + + def list_received_files(self): + """列出接收到的文件""" + result = self.send_command("list_received_files", {}) + self.print_result(result) + + def save_received_file(self): + """保存接收到的文件""" + file_id = input("请输入文件ID: ").strip() + save_path = input("请输入保存路径: ").strip() + + # 检查是否有私钥 + private_key_path = None + use_decryption = input("是否使用私钥解密?(y/n): ").strip().lower() == 'y' + if use_decryption: + private_key_path = input("请输入私钥文件路径: ").strip() + if not os.path.exists(private_key_path): + print("私钥文件不存在!") + return + + args = {"file_id": file_id, "save_path": save_path} + if private_key_path: + args["private_key_path"] = private_key_path + + result = self.send_command("get_received_file", args) + self.print_result(result) + + def interactive_shell(self): + """交互式Shell""" + print("=" * 60) + print(" 文件传输系统 - 简化模式") + print("=" * 60) + print("可用命令:") + print(" send - 发送文件") + print(" receive - 启动接收器") + print(" stop - 停止接收器") + print(" list - 列出接收的文件") + print(" save - 保存接收的文件") + print(" status - 查看系统状态") + print(" cleanup - 清理资源") + print(" exit - 退出程序") + print("=" * 60) + + while True: + try: + command = input("ftp> ").strip().lower() + + if command == "exit": + print("再见!") + break + elif command == "send": + self.send_file_interactive() + elif command == "receive": + self.receive_file_interactive() + elif command == "stop": + self.stop_receiver_interactive() + elif command == "list": + self.list_received_files() + elif command == "save": + self.save_received_file() + elif command == "status": + result = self.send_command("get_status", {}) + self.print_result(result) + elif command == "cleanup": + result = self.send_command("cleanup", {}) + self.print_result(result) + elif command == "": + continue + else: + print("未知命令,可用命令: send, receive, stop, list, save, status, cleanup, exit") + + except KeyboardInterrupt: + print("\n输入 'exit' 退出程序") + except Exception as e: + print(f"错误: {e}") + +def main(): + """Shell主入口""" + shell = FileTransferShell() + shell.interactive_shell() + +if __name__ == "__main__": + main() diff --git a/src/__pycache__/file.cpython-313.pyc b/src/__pycache__/file.cpython-313.pyc new file mode 100644 index 0000000..3215c9d Binary files /dev/null and b/src/__pycache__/file.cpython-313.pyc differ diff --git a/src/__pycache__/network.cpython-313.pyc b/src/__pycache__/network.cpython-313.pyc new file mode 100644 index 0000000..8bfc795 Binary files /dev/null and b/src/__pycache__/network.cpython-313.pyc differ diff --git a/src/__pycache__/rsa.cpython-313.pyc b/src/__pycache__/rsa.cpython-313.pyc new file mode 100644 index 0000000..0a11fc9 Binary files /dev/null and b/src/__pycache__/rsa.cpython-313.pyc differ diff --git a/src/file.py b/src/file.py new file mode 100644 index 0000000..a44f834 --- /dev/null +++ b/src/file.py @@ -0,0 +1,62 @@ + +import os +import hashlib + +class File: + def __init__(self, file_path, chunk_size=2048): + self.file_path = file_path + self.chunk_size = chunk_size + + def split_to_chunks(self): + """将文件分割为指定大小的块""" + chunks = [] + with open(self.file_path, 'rb') as f: + while True: + chunk = f.read(self.chunk_size) + if not chunk: + break + chunks.append(chunk) + return chunks + + def read_file(self): + """读取整个文件为二进制数据""" + with open(self.file_path, 'rb') as f: + return f.read() + + def save_file(self, data, output_path=None): + """保存数据到文件""" + if output_path is None: + output_path = self.file_path + + os.makedirs(os.path.dirname(output_path), exist_ok=True) + with open(output_path, 'wb') as f: + f.write(data) + return output_path + + def get_file_info(self): + """获取文件信息""" + if not os.path.exists(self.file_path): + return None + + file_size = os.path.getsize(self.file_path) + file_hash = self.calculate_hash() + + return { + 'path': self.file_path, + 'size': file_size, + 'hash': file_hash, + 'chunks_count': (file_size + self.chunk_size - 1) // self.chunk_size + } + + def calculate_hash(self): + """计算文件SHA256哈希值""" + sha256_hash = hashlib.sha256() + with open(self.file_path, "rb") as f: + for byte_block in iter(lambda: f.read(4096), b""): + sha256_hash.update(byte_block) + return sha256_hash.hexdigest() + + @staticmethod + def combine_chunks(chunks): + """合并数据块为完整文件""" + return b''.join(chunks) diff --git a/src/network.py b/src/network.py new file mode 100644 index 0000000..08991c0 --- /dev/null +++ b/src/network.py @@ -0,0 +1,253 @@ + +import socket +import threading +import struct +import time +from typing import Callable, Optional, Tuple + +class TCPIPv6Transporter: + def __init__(self): + self.servers = {} # 存储服务器socket {port: socket} + self.is_listening = False + self.receive_callback = None + + def send_file(self, file_data: bytes, target_ip: str, target_port: int) -> Tuple[bool, str]: + """ + 发送文件到指定IPv6地址和端口 + + Args: + file_data: 要发送的文件数据 + target_ip: 目标IPv6地址 + target_port: 目标端口 + + Returns: + Tuple[bool, str]: (是否成功, 错误信息) + """ + try: + # 创建IPv6 TCP socket + with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock: + # 设置超时时间 + sock.settimeout(30) + + print(f"连接到 [{target_ip}]:{target_port}...") + + # 连接到目标 + sock.connect((target_ip, target_port, 0, 0)) + print("连接成功") + + # 发送数据长度(8字节,大端序) + data_length = len(file_data) + sock.send(struct.pack('!Q', data_length)) + + # 发送实际数据 + total_sent = 0 + chunk_size = 4096 + + while total_sent < data_length: + # 计算本次发送的数据量 + remaining = data_length - total_sent + send_size = min(chunk_size, remaining) + + # 发送数据块 + sent = sock.send(file_data[total_sent:total_sent + send_size]) + if sent == 0: + raise ConnectionError("连接中断") + + total_sent += sent + + # 显示进度 + progress = (total_sent / data_length) * 100 + if total_sent % (chunk_size * 10) == 0 or total_sent == data_length: + print(f"发送进度: {progress:.1f}% ({total_sent}/{data_length} bytes)") + + print("文件发送完成") + return True, "发送成功" + + except socket.timeout: + error_msg = "连接超时" + print(error_msg) + return False, error_msg + except ConnectionRefusedError: + error_msg = "连接被拒绝,目标可能未启动服务" + print(error_msg) + return False, error_msg + except Exception as e: + error_msg = f"发送失败: {e}" + print(error_msg) + return False, error_msg + + def start_server(self, listen_port: int, callback: Callable) -> Tuple[bool, str]: + """ + 启动TCP服务器监听指定端口 + + Args: + listen_port: 监听端口 + callback: 接收到数据时的回调函数 + + Returns: + Tuple[bool, str]: (是否成功, 错误信息) + """ + if listen_port in self.servers: + return False, f"端口 {listen_port} 已经在监听中" + + try: + # 创建IPv6 TCP socket + server_socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) + server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + # 绑定到所有IPv6地址 + server_socket.bind(('::', listen_port)) + server_socket.listen(5) + + self.servers[listen_port] = server_socket + self.receive_callback = callback + self.is_listening = True + + print(f"服务器开始监听端口 {listen_port}") + + # 启动监听线程 + thread = threading.Thread(target=self._accept_connections, args=(listen_port,)) + thread.daemon = True + thread.start() + + return True, f"服务器启动成功,监听端口 {listen_port}" + + except PermissionError: + error_msg = f"权限不足,无法监听端口 {listen_port}" + print(error_msg) + return False, error_msg + except Exception as e: + error_msg = f"启动服务器失败: {e}" + print(error_msg) + return False, error_msg + + def _accept_connections(self, port: int): + """接受连接请求""" + server_socket = self.servers.get(port) + if not server_socket: + return + + try: + while self.is_listening: + print(f"等待连接在端口 {port}...") + client_socket, client_addr = server_socket.accept() + + print(f"接收到来自 [{client_addr[0]}]:{client_addr[1]} 的连接") + + # 处理客户端连接 + client_thread = threading.Thread( + target=self._handle_client, + args=(client_socket, client_addr) + ) + client_thread.daemon = True + client_thread.start() + + except Exception as e: + if self.is_listening: + print(f"接受连接错误: {e}") + + def _handle_client(self, client_socket: socket.socket, client_addr: Tuple): + """处理客户端连接""" + try: + # 设置超时时间 + client_socket.settimeout(30) + + # 接收数据长度(8字节,大端序) + length_data = client_socket.recv(8) + if not length_data or len(length_data) != 8: + raise ValueError("无效的数据长度信息") + + data_length = struct.unpack('!Q', length_data)[0] + print(f"准备接收 {data_length} bytes 数据") + + # 接收实际数据 + received_data = b'' + total_received = 0 + chunk_size = 4096 + + while total_received < data_length: + # 计算本次接收的数据量 + remaining = data_length - total_received + recv_size = min(chunk_size, remaining) + + # 接收数据块 + chunk = client_socket.recv(recv_size) + if not chunk: + raise ConnectionError("连接中断") + + received_data += chunk + total_received += len(chunk) + + # 显示进度 + progress = (total_received / data_length) * 100 + if total_received % (chunk_size * 10) == 0 or total_received == data_length: + print(f"接收进度: {progress:.1f}% ({total_received}/{data_length} bytes)") + + print("文件接收完成") + + # 调用回调函数处理接收到的数据 + if self.receive_callback: + self.receive_callback(received_data, client_addr) + else: + print("警告: 未设置接收回调函数") + + except socket.timeout: + print("接收数据超时") + except Exception as e: + print(f"处理客户端数据错误: {e}") + finally: + client_socket.close() + + def stop_server(self, port: int) -> Tuple[bool, str]: + """ + 停止指定端口的服务器 + + Args: + port: 要停止的端口 + + Returns: + Tuple[bool, str]: (是否成功, 错误信息) + """ + if port not in self.servers: + return False, f"端口 {port} 未在监听中" + + try: + server_socket = self.servers[port] + server_socket.close() + del self.servers[port] + + # 如果所有服务器都停止了,设置监听标志为False + if not self.servers: + self.is_listening = False + + return True, f"端口 {port} 服务器已停止" + except Exception as e: + return False, f"停止服务器失败: {e}" + + def stop_all_servers(self) -> Tuple[bool, str]: + """停止所有服务器""" + success_count = 0 + error_count = 0 + error_msgs = [] + + ports = list(self.servers.keys()) + for port in ports: + success, msg = self.stop_server(port) + if success: + success_count += 1 + else: + error_count += 1 + error_msgs.append(msg) + + if error_count == 0: + return True, f"成功停止 {success_count} 个服务器" + else: + return False, f"成功停止 {success_count} 个,失败 {error_count} 个: {', '.join(error_msgs)}" + + def get_listening_ports(self) -> list: + """获取当前正在监听的端口列表""" + return list(self.servers.keys()) + + def is_port_listening(self, port: int) -> bool: + """检查指定端口是否在监听中""" + return port in self.servers diff --git a/src/rsa.py b/src/rsa.py new file mode 100644 index 0000000..c994060 --- /dev/null +++ b/src/rsa.py @@ -0,0 +1,184 @@ + + +import os +from cryptography.hazmat.primitives import serialization, hashes +from cryptography.hazmat.primitives.asymmetric import rsa, padding +from cryptography.hazmat.backends import default_backend + +class RSACrypto: + # RSA加密的最大数据块大小(2048位密钥) + MAX_BLOCK_SIZE = 190 # 2048/8 - 42(填充开销) + + @staticmethod + def load_public_key(public_key_path): + """ + 从文件加载公钥 + + Args: + public_key_path: 公钥文件路径 + + Returns: + PublicKey: 加载的公钥对象 + """ + try: + with open(public_key_path, 'rb') as f: + pem_data = f.read() + return serialization.load_pem_public_key( + pem_data, + backend=default_backend() + ) + except Exception as e: + raise ValueError(f"加载公钥失败: {e}") + + @staticmethod + def load_private_key(private_key_path): + """ + 从文件加载私钥 + + Args: + private_key_path: 私钥文件路径 + + Returns: + PrivateKey: 加载的私钥对象 + """ + try: + with open(private_key_path, 'rb') as f: + pem_data = f.read() + return serialization.load_pem_private_key( + pem_data, + password=None, + backend=default_backend() + ) + except Exception as e: + raise ValueError(f"加载私钥失败: {e}") + + @staticmethod + def encrypt_block(block_data, public_key_path): + """ + 使用公钥加密单个数据块 + + Args: + block_data: 要加密的数据块(不超过190字节) + public_key_path: 公钥文件路径 + + Returns: + bytes: 加密后的数据块 + """ + # 验证数据块大小 + if len(block_data) > RSACrypto.MAX_BLOCK_SIZE: + raise ValueError(f"数据块大小超过限制: {len(block_data)} > {RSACrypto.MAX_BLOCK_SIZE}") + + # 加载公钥 + public_key = RSACrypto.load_public_key(public_key_path) + + # 加密数据块 + try: + encrypted_block = public_key.encrypt( + block_data, + padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None + ) + ) + return encrypted_block + except Exception as e: + raise ValueError(f"加密数据块失败: {e}") + + @staticmethod + def decrypt_block(encrypted_block, private_key_path): + """ + 使用私钥解密单个数据块 + + Args: + encrypted_block: 加密的数据块 + private_key_path: 私钥文件路径 + + Returns: + bytes: 解密后的原始数据块 + """ + # 加载私钥 + private_key = RSACrypto.load_private_key(private_key_path) + + # 解密数据块 + try: + decrypted_block = private_key.decrypt( + encrypted_block, + padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None + ) + ) + return decrypted_block + except Exception as e: + raise ValueError(f"解密数据块失败: {e}") + + @staticmethod + def encrypt_blocks(blocks, public_key_path): + """ + 批量加密多个数据块 + + Args: + blocks: 数据块列表 + public_key_path: 公钥文件路径 + + Returns: + list: 加密后的数据块列表 + """ + encrypted_blocks = [] + + for i, block in enumerate(blocks): + try: + encrypted_block = RSACrypto.encrypt_block(block, public_key_path) + encrypted_blocks.append(encrypted_block) + except Exception as e: + raise ValueError(f"加密第 {i} 个数据块失败: {e}") + + return encrypted_blocks + + @staticmethod + def decrypt_blocks(encrypted_blocks, private_key_path): + """ + 批量解密多个数据块 + + Args: + encrypted_blocks: 加密的数据块列表 + private_key_path: 私钥文件路径 + + Returns: + list: 解密后的原始数据块列表 + """ + decrypted_blocks = [] + + for i, encrypted_block in enumerate(encrypted_blocks): + try: + decrypted_block = RSACrypto.decrypt_block(encrypted_block, private_key_path) + decrypted_blocks.append(decrypted_block) + except Exception as e: + raise ValueError(f"解密第 {i} 个数据块失败: {e}") + + return decrypted_blocks + + @staticmethod + def get_max_block_size(): + """ + 获取最大数据块大小 + + Returns: + int: 最大数据块大小(字节) + """ + return RSACrypto.MAX_BLOCK_SIZE + + @staticmethod + def validate_block_size(block_data): + """ + 验证数据块大小是否合法 + + Args: + block_data: 数据块 + + Returns: + bool: 是否合法 + """ + return len(block_data) <= RSACrypto.MAX_BLOCK_SIZE