blob: 4d2737f64757629b543a31d5d5c3fea22d593348 [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;
19
20 public DataCaptureProxy(String trackerHost, int trackerPort) {
21 this.trackerHost = trackerHost;
22 this.trackerPort = trackerPort;
23 }
24
25 @Override
26 public void handle(Request req, Response resp) {
27 try {
28 // 提取并打印关键参数
29 String infoHash = req.getParameter("info_hash");
30 String uploaded = req.getParameter("uploaded");
31 String downloaded= req.getParameter("downloaded");
32 String passkey = req.getParameter("passkey");
33 System.out.println(
34 "Captured announce → info_hash=" + infoHash +
35 ", uploaded=" + uploaded +
36 ", downloaded=" + downloaded +
37 ", passkey=" + passkey
38 );
39
40 // 构造转发 URL
41 String path = req.getPath().getPath();
42 String query = req.getQuery().toString();
43 String targetUrl = "http://" + trackerHost + ":" + trackerPort
44 + path + "?" + query;
45
46 HttpURLConnection connection =
47 (HttpURLConnection) new URL(targetUrl).openConnection();
48 connection.setRequestMethod("GET");
49
50 // 转发响应码和类型
51 resp.setCode(connection.getResponseCode());
52 String ct = connection.getContentType();
53 if (ct != null) resp.setValue("Content-Type", ct);
54
55 // 转发响应体
56 try (InputStream in = connection.getInputStream();
57 OutputStream out = resp.getOutputStream()) {
58 byte[] buf = new byte[8192];
59 int len;
60 while ((len = in.read(buf)) != -1) {
61 out.write(buf, 0, len);
62 }
63 }
64
65 } catch (Exception e) {
66 try {
67 resp.setCode(500);
68 resp.close();
69 } catch (Exception ignore) {}
70 e.printStackTrace();
71 }
72 }
73}