blob: be7d9f6b0cb59685ba91f750b9a3ba1baa5f734c [file] [log] [blame]
root59a69f82025-06-05 08:35:22 +00001package tracker;
2
3import java.io.InputStream;
4import java.io.OutputStream;
5import java.net.HttpURLConnection;
6import java.net.URL;
7
8import org.simpleframework.http.Request;
9import org.simpleframework.http.Response;
10import org.simpleframework.http.core.Container;
11
12/**
13 * 拦截 announce 请求,打印参数后转发给真实 Tracker。
14 */
15public class DataCaptureProxy implements Container {
16
17 private final String trackerHost;
18 private final int trackerPort;
TRM-codingcdfe5482025-06-06 17:31:01 +080019 private final Tracker tracker;
root59a69f82025-06-05 08:35:22 +000020
21 public DataCaptureProxy(String trackerHost, int trackerPort) {
22 this.trackerHost = trackerHost;
23 this.trackerPort = trackerPort;
TRM-codingcdfe5482025-06-06 17:31:01 +080024 this.tracker = new Tracker(); // 初始化Tracker实例
root59a69f82025-06-05 08:35:22 +000025 }
26
27 @Override
28 public void handle(Request req, Response resp) {
29 try {
30 // 提取并打印关键参数
31 String infoHash = req.getParameter("info_hash");
32 String uploaded = req.getParameter("uploaded");
33 String downloaded= req.getParameter("downloaded");
34 String passkey = req.getParameter("passkey");
35 System.out.println(
36 "Captured announce → info_hash=" + infoHash +
37 ", uploaded=" + uploaded +
38 ", downloaded=" + downloaded +
39 ", passkey=" + passkey
40 );
41
TRM-codingcdfe5482025-06-06 17:31:01 +080042 // 调用Tracker方法更新上传和下载数据
43 if (passkey != null && !passkey.isEmpty()) {
44 try {
45 if (uploaded != null && !uploaded.isEmpty()) {
46 int uploadValue = Integer.parseInt(uploaded);
47 if (uploadValue > 0) {
48 tracker.AddUpLoad(passkey, uploadValue);
49 }
50 }
51
52 if (downloaded != null && !downloaded.isEmpty()) {
53 int downloadValue = Integer.parseInt(downloaded);
54 if (downloadValue > 0) {
55 tracker.AddDownload(passkey, downloadValue);
56 }
57 }
58 } catch (NumberFormatException e) {
59 System.err.println("Error parsing upload/download values: " + e.getMessage());
60 }
61 }
62
root59a69f82025-06-05 08:35:22 +000063 // 构造转发 URL
64 String path = req.getPath().getPath();
65 String query = req.getQuery().toString();
66 String targetUrl = "http://" + trackerHost + ":" + trackerPort
67 + path + "?" + query;
68
69 HttpURLConnection connection =
70 (HttpURLConnection) new URL(targetUrl).openConnection();
71 connection.setRequestMethod("GET");
72
73 // 转发响应码和类型
74 resp.setCode(connection.getResponseCode());
75 String ct = connection.getContentType();
76 if (ct != null) resp.setValue("Content-Type", ct);
77
78 // 转发响应体
79 try (InputStream in = connection.getInputStream();
80 OutputStream out = resp.getOutputStream()) {
81 byte[] buf = new byte[8192];
82 int len;
83 while ((len = in.read(buf)) != -1) {
84 out.write(buf, 0, len);
85 }
86 }
87
88 } catch (Exception e) {
89 try {
90 resp.setCode(500);
91 resp.close();
92 } catch (Exception ignore) {}
93 e.printStackTrace();
94 }
95 }
96}