root | 59a69f8 | 2025-06-05 08:35:22 +0000 | [diff] [blame] | 1 | package tracker; |
| 2 | |
| 3 | import java.io.InputStream; |
| 4 | import java.io.OutputStream; |
| 5 | import java.net.HttpURLConnection; |
| 6 | import java.net.URL; |
| 7 | |
| 8 | import org.simpleframework.http.Request; |
| 9 | import org.simpleframework.http.Response; |
| 10 | import org.simpleframework.http.core.Container; |
| 11 | |
| 12 | /** |
| 13 | * 拦截 announce 请求,打印参数后转发给真实 Tracker。 |
| 14 | */ |
| 15 | public 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 | } |