Parse Ctfile shares with the new url API and ALTCHA v2

The legacy getfile.php and getdir.php endpoints now answer every share
with Cloudflare Turnstile. Password-free files and folders use ALTCHA
PBKDF2 instead: solve it off the event loop, reuse access_pass for the
same owner, and fetch the direct link from POST /url/download. Password
shares stay on Turnstile and are reported separately from missing links
and wrong or missing passwords.

Co-authored-by: qaiu <[email protected]>
This commit is contained in:
Cursor Agentandqaiu committed 2026-11-24 04:10:50 +00:00
1 parent a7d41b0107
commit 0d133ee437
7 files changed
+1607 -567

No files matched your search

@@ -0,0 +1,264 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ALTCHA v2(PBKDF2/SHA-256)挑战解算。
* <p>
* 口令是 nonce 的原始字节再拼上大端 uint32 计数器,盐是 salt 的原始字节。
* 找到派生密钥以 keyPrefix 开头的计数器后,按官方 widget 的方式拼出
* {@code base64({"challenge":{parameters,signature},"solution":{counter,derivedKey,time}})}。
* 计算是 CPU 密集的,调用方必须放在 Vert.x worker 上,不能占用 event loop。
*/
final class AltchaV2Solver {
static final int DEFAULT_MAX_COUNTER = 200_000;
static final long DEFAULT_TIMEOUT_MILLIS = 25_000L;
/** 城通当前 cost=1200。更高的 cost 会把解析线程占满,直接拒绝。 */
static final int MAX_COST = 20_000;
static final int MAX_KEY_LENGTH = 64;
private static final int MAX_THREADS = 4;
private AltchaV2Solver() {
}
static final class Solution {
final int counter;
final String derivedKeyHex;
final long tookMillis;
Solution(int counter, String derivedKeyHex, long tookMillis) {
this.counter = counter;
this.derivedKeyHex = derivedKeyHex;
this.tookMillis = tookMillis;
}
}
static Solution solve(JsonObject challenge) {
return solve(challenge, DEFAULT_MAX_COUNTER, DEFAULT_TIMEOUT_MILLIS);
}
static Solution solve(JsonObject challenge, int maxCounter, long timeoutMillis) {
if (challenge == null || challenge.getJsonObject("parameters") == null) {
throw new IllegalArgumentException("ALTCHA 挑战为空");
}
JsonObject parameters = challenge.getJsonObject("parameters");
String algorithm = parameters.getString("algorithm", "");
if (!"PBKDF2/SHA-256".equals(algorithm)) {
throw new IllegalArgumentException("不支持的 ALTCHA 算法: " + algorithm);
}
int cost = intValue(parameters.getValue("cost"), -1);
int keyLength = intValue(parameters.getValue("keyLength"), 32);
if (cost < 1 || cost > MAX_COST) {
throw new IllegalArgumentException("ALTCHA cost 超出可解范围: " + cost);
}
if (keyLength < 16 || keyLength > MAX_KEY_LENGTH) {
throw new IllegalArgumentException("ALTCHA keyLength 超出可解范围: " + keyLength);
}
byte[] nonce = decodeHex(parameters.getString("nonce", ""), "nonce");
byte[] salt = decodeHex(parameters.getString("salt", ""), "salt");
byte[] prefix = decodeHex(parameters.getString("keyPrefix", ""), "keyPrefix");
if (prefix.length == 0 || prefix.length > keyLength) {
throw new IllegalArgumentException("ALTCHA keyPrefix 长度无效");
}
int limit = Math.max(1, maxCounter);
long budget = Math.max(1L, timeoutMillis);
int threads = Math.min(MAX_THREADS, Math.max(1, Runtime.getRuntime().availableProcessors()));
threads = Math.min(threads, limit);
AtomicInteger winner = new AtomicInteger(-1);
AtomicBoolean stop = new AtomicBoolean(false);
String[] derivedHex = new String[1];
long started = System.nanoTime();
long deadline = started + TimeUnit.MILLISECONDS.toNanos(budget);
ExecutorService pool = Executors.newFixedThreadPool(threads, runnable -> {
Thread thread = new Thread(runnable, "ctfile-altcha");
thread.setDaemon(true);
return thread;
});
try {
Future<?>[] tasks = new Future<?>[threads];
for (int i = 0; i < threads; i++) {
int start = i;
int stride = threads;
tasks[i] = pool.submit((Callable<Void>) () -> {
search(start, stride, limit, deadline, nonce, salt, prefix, cost, keyLength, winner, stop, derivedHex);
return null;
});
}
for (Future<?> task : tasks) {
task.get(budget + 2000L, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
stop.set(true);
throw new IllegalStateException("ALTCHA 解算被中断");
} catch (IllegalStateException e) {
stop.set(true);
throw e;
} catch (Exception e) {
stop.set(true);
throw new IllegalStateException("ALTCHA 解算失败: " + e.getMessage());
} finally {
stop.set(true);
pool.shutdownNow();
}
int counter = winner.get();
if (counter < 0 || derivedHex[0] == null) {
throw new IllegalStateException("ALTCHA 人机验证解算超时,请稍后重试");
}
long took = Math.max(1L, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
return new Solution(counter, derivedHex[0], took);
}
/**
* 官方 altcha widget 成功后提交的 payload:标准 Base64(含填充),不是 URL-safe。
*/
static String payload(JsonObject challenge, Solution solution) {
JsonObject body = new JsonObject()
.put("challenge", new JsonObject()
.put("parameters", challenge.getJsonObject("parameters"))
.put("signature", challenge.getString("signature")))
.put("solution", new JsonObject()
.put("counter", solution.counter)
.put("derivedKey", solution.derivedKeyHex)
.put("time", solution.tookMillis));
return Base64.getEncoder().encodeToString(body.encode().getBytes(StandardCharsets.UTF_8));
}
/**
* PBKDF2-HMAC-SHA256,口令是原始字节。
* JDK 的 {@code SecretKeyFactory("PBKDF2WithHmacSHA256")} 会把 char[] 口令按 UTF-8 编码,
* nonce 里大于 0x7F 的字节会被展开,和 ALTCHA / WebCrypto 的原始字节口令对不上。
*/
static byte[] pbkdf2(byte[] password, byte[] salt, int cost, int keyLength) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(password, "HmacSHA256"));
return pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
}
private static void search(int start, int stride, int limit, long deadline, byte[] nonce, byte[] salt,
byte[] prefix, int cost, int keyLength, AtomicInteger winner, AtomicBoolean stop,
String[] derivedHex) {
Mac mac;
try {
mac = Mac.getInstance("HmacSHA256");
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 初始化失败: " + e.getMessage());
}
for (int counter = start; counter < limit && winner.get() < 0 && !stop.get(); counter += stride) {
if ((counter & 31) == start && System.nanoTime() > deadline) {
return;
}
byte[] derived;
try {
mac.init(new SecretKeySpec(password(nonce, counter), "HmacSHA256"));
derived = pbkdf2(mac, salt, cost, keyLength);
} catch (Exception e) {
throw new IllegalStateException("PBKDF2 计算失败: " + e.getMessage());
}
if (startsWith(derived, prefix) && winner.compareAndSet(-1, counter)) {
derivedHex[0] = toHex(derived);
return;
}
}
}
private static byte[] pbkdf2(Mac mac, byte[] salt, int iterations, int keyLength) throws Exception {
int hashLength = mac.getMacLength();
byte[] result = new byte[keyLength];
byte[] block = new byte[salt.length + 4];
System.arraycopy(salt, 0, block, 0, salt.length);
int offset = 0;
for (int index = 1; offset < keyLength; index++) {
block[salt.length] = (byte) (index >>> 24);
block[salt.length + 1] = (byte) (index >>> 16);
block[salt.length + 2] = (byte) (index >>> 8);
block[salt.length + 3] = (byte) index;
byte[] mixed = mac.doFinal(block);
byte[] digest = mixed.clone();
for (int round = 1; round < iterations; round++) {
mixed = mac.doFinal(mixed);
for (int i = 0; i < mixed.length; i++) {
digest[i] ^= mixed[i];
}
}
int length = Math.min(hashLength, keyLength - offset);
System.arraycopy(digest, 0, result, offset, length);
offset += length;
}
return result;
}
private static byte[] password(byte[] nonce, int counter) {
byte[] password = Arrays.copyOf(nonce, nonce.length + 4);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
private static boolean startsWith(byte[] value, byte[] prefix) {
if (prefix.length > value.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if (value[i] != prefix[i]) {
return false;
}
}
return true;
}
static byte[] decodeHex(String hex, String name) {
if (hex == null || hex.length() % 2 != 0 || !hex.matches("[0-9a-fA-F]*")) {
throw new IllegalArgumentException("ALTCHA " + name + " 不是合法十六进制");
}
byte[] out = new byte[hex.length() / 2];
for (int i = 0; i < out.length; i++) {
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return out;
}
static String toHex(byte[] bytes) {
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
builder.append(Character.forDigit((value >> 4) & 0xF, 16));
builder.append(Character.forDigit(value & 0xF, 16));
}
return builder.toString();
}
private static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
}
@@ -1,345 +1,113 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.PanBase;
import cn.qaiu.parser.impl.CtfileSession.CtfileException;
import cn.qaiu.parser.impl.CtfileSession.DirectLink;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import cn.qaiu.parser.impl.CtfileSession.VerificationMismatch;
import cn.qaiu.util.CommonUtils;
import cn.qaiu.util.FileSizeConverter;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.WorkerExecutor;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.uritemplate.UriTemplate;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <a href="https://www.ctfile.com">诚通网盘</a>
* 城通网盘。分享页已经改成 {@code api.ctfile.com/url/*}:
* 免密分享先解 ALTCHA v2,再取 {@code access_pass} 和下载地址;
* 带密码分享由 Cloudflare Turnstile 拦住,服务端解不开。
*/
public class CtTool extends PanBase {
private static final String API_URL_PREFIX = "https://webapi.ctfile.com";
private static final String SHARE_FILE_URL_PREFIX = "https://ctfile.com/file/";
private static final String AJAX_ACCEPT = "application/json, text/javascript, */*; q=0.01";
private static final String BROWSER_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
private static final int FILE_LIST_PAGE_SIZE = 200;
private static final int MAX_FILE_LIST_PAGES = 50;
private static final int DEFAULT_MAX_LIST_PAGES = 50;
// https://webapi.ctfile.com/getfile.php?path=f&f=64115194-17569800420720-06c697&
// passcode=7609&r=0.6611183001986635&ref=&url=https%3A%2F%2Furl94.ctfile.com%2Ff%2F64115194-17569800420720-06c697%3Fp%3D7609
private static final String API1 = API_URL_PREFIX + "/getfile.php?path={path}" +
"&f={shareKey}&passcode={pwd}&r={rand}&ref=&url={url}";
private static final Object WORKER_LOCK = new Object();
private static volatile WorkerExecutor sharedWorker;
private static volatile boolean workerShutdown;
// https://webapi.ctfile.com/get_down_url.php?uid=64115194&fid=17569800420720&
// file_chk=af5c8757a49cbc69a557eb3da59b246c&start_time=1780471868&wait_seconds=0&rd=0.36...
private static final String API2 = API_URL_PREFIX + "/get_down_url.php?" +
"uid={uid}&fid={fid}&file_chk={file_chk}" +
"&start_time={start_time}&wait_seconds={wait_seconds}&rd={rand}";
// https://webapi.ctfile.com/getdir.php?path=d&d=64115194-164803691-48508c&
// folder_id=164803691&fk=decb36&passcode=7609&r=0.23...&ref=&url=https://url94.ctfile.com/d/...
private static final String API_GETDIR = API_URL_PREFIX + "/getdir.php?path={path}" +
"&d={shareKey}&folder_id={folder_id}&fk={fk}&passcode={pwd}&r={rand}&ref=&url={url}";
// DataTables参数,用于获取目录文件列表
private static final String FILE_LIST_PARAMS_TEMPLATE = "&sEcho=1&iColumns=4&sColumns=%2C%2C%2C" +
"&iDisplayStart={start}&iDisplayLength={length}" +
"&mDataProp_0=0&sSearch_0=&bRegex_0=false&bSearchable_0=true&bSortable_0=false" +
"&mDataProp_1=1&sSearch_1=&bRegex_1=false&bSearchable_1=true&bSortable_1=true" +
"&mDataProp_2=2&sSearch_2=&bRegex_2=false&bSearchable_2=true&bSortable_2=true" +
"&mDataProp_3=3&sSearch_3=&bRegex_3=false&bSearchable_3=true&bSortable_3=true" +
"&sSearch=&bRegex=false" +
"&iSortCol_0=3&sSortDir_0=desc&iSortingCols=1";
// 文件列表HTML解析正则
private static final Pattern FILE_ID_PATTERN = Pattern.compile("value=[\"']f(\\d+)[\"']");
private static final Pattern FOLDER_ID_PATTERN = Pattern.compile("value=[\"']d(\\d+)[\"']");
private static final Pattern FILE_HREF_PATTERN = Pattern.compile("href=[\"']#/f/([^\"']+)[\"']");
private static final Pattern FILE_NAME_PATTERN = Pattern.compile("<a\\b[^>]*>([^<]+)</a>", Pattern.CASE_INSENSITIVE);
private static final Pattern FILE_ICON_PATTERN = Pattern.compile("alt=[\"']([^\"']+)[\"']");
private static final Pattern SUBDIR_PATTERN = Pattern.compile("load_subdir\\s*\\((\\d+)\\s*,\\s*['\"]([^'\"]+)['\"]\\)");
/**
* 子类重写此构造方法不需要添加额外逻辑
* 如:
* <blockquote><pre>
* public XxTool(String key, String pwd) {
* super(key, pwd);
* }
* </pre></blockquote>
*
* @param shareLinkInfo 分享链接信息
*/
public CtTool(ShareLinkInfo shareLinkInfo) {
super(shareLinkInfo);
}
public static void shutdownWorkerExecutor() {
synchronized (WORKER_LOCK) {
workerShutdown = true;
if (sharedWorker != null) {
sharedWorker.close();
sharedWorker = null;
}
}
}
@Override
public Future<String> parse() {
final String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.indexOf('-') == -1) {
fail("shareKey格式不正确找不到'-': {}", shareKey);
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
fail("shareKey为空");
return promise.future();
}
String[] split = shareKey.split("-");
if (split.length < 2 || split[0].isBlank() || split[1].isBlank()) {
fail("shareKey格式不正确: {}", shareKey);
return promise.future();
}
String fallbackUid = split[0], fallbackFid = split[1];
String path = extractPath(shareLinkInfo.getShareUrl());
HttpRequest<Buffer> bufferHttpRequest1 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API1))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("pwd", shareLinkInfo.getSharePassword())
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareLinkInfo.getShareUrl()), shareLinkInfo.getShareUrl());
bufferHttpRequest1
.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 上游返回空响应或非JSON响应");
return;
}
Object fileValue = resJson.getValue("file");
if (!(fileValue instanceof JsonObject)) {
fail("解析失败, 文件信息为空或格式错误, 可能分享已失效: {}", resJson);
return;
}
var fileJson = (JsonObject) fileValue;
String uid = resolveDownloadUid(fileJson, fallbackUid);
String fid = resolveDownloadFid(fileJson, fallbackFid);
String fileChk = fileJson.getString("file_chk");
String startTime = valueToString(fileJson.getValue("start_time"));
String waitSeconds = valueToString(fileJson.getValue("wait_seconds"));
if (uid.isBlank() || fid.isBlank() || fileChk == null || fileChk.isBlank()
|| startTime.isBlank() || waitSeconds.isBlank()) {
fail("解析失败, 下载参数不完整, 可能分享已失效或者分享密码不对: {}", fileJson);
return;
}
// 提取文件信息并存储
FileInfo fileInfo = new FileInfo()
.setFileName(fileJson.getString("file_name"))
.setFileId(fid)
.setSizeStr(fileJson.getString("file_size"))
.setCreateTime(fileJson.getString("file_time"))
.setCreateBy(fileJson.getString("username"))
.setFileType("file")
.setPanType(shareLinkInfo.getType());
shareLinkInfo.getOtherParam().put("fileInfo", fileInfo);
HttpRequest<Buffer> bufferHttpRequest2 = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API2))
.setTemplateParam("uid", uid)
.setTemplateParam("fid", fid)
.setTemplateParam("file_chk", fileChk)
.setTemplateParam("start_time", startTime)
.setTemplateParam("wait_seconds", waitSeconds)
.setTemplateParam("rand", String.valueOf(Math.random())), shareLinkInfo.getShareUrl());
bufferHttpRequest2
.send().onSuccess(res2 -> handleDownloadUrlResponse(res2))
.onFailure(t -> fail("下载链接请求失败: {}", t.getMessage()));
} catch (Exception e) {
fail("解析失败: {}", e.getMessage());
}
}).onFailure(t -> fail("文件信息请求失败: {}", t.getMessage()));
return promise.future();
}
private void handleDownloadUrlResponse(io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
JsonObject resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
fail("解析失败, 下载接口返回空响应或非JSON响应");
return;
}
String downloadUrl = resJson.getString("downurl");
if (downloadUrl == null || downloadUrl.isBlank()) {
fail("解析失败, 可能分享已失效: json: {} 字段 {} 不存在", resJson, "downurl");
return;
}
// 存储下载元数据,包括必要的请求头
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", BROWSER_UA);
if (shareLinkInfo.getShareUrl() != null && !shareLinkInfo.getShareUrl().isBlank()) {
headers.put("Referer", shareLinkInfo.getShareUrl());
}
// 使用新的 completeWithMeta 方法
completeWithMeta(downloadUrl, headers);
} catch (Exception e) {
fail("解析失败, 下载接口响应处理异常: {}", e.getMessage());
worker().executeBlocking(() -> {
ParsedDownload link = resolveDownload(shareKey);
shareLinkInfo.getOtherParam().put("fileInfo", fileInfoFrom(link.file));
if (link.fileDir != null && !link.fileDir.isBlank()) {
shareLinkInfo.getOtherParam().put("ctFileDir", link.fileDir);
}
return link;
}, false).onSuccess(link -> {
if (link.headers == null || link.headers.isEmpty()) {
complete(link.url);
} else {
completeWithMeta(link.url, link.headers);
}
}).onFailure(error -> fail("{}", rootMessage(error)));
} catch (RuntimeException e) {
fail("{}", e.getMessage());
}
return promise.future();
}
@Override
public Future<List<FileInfo>> parseFileList() {
Promise<List<FileInfo>> listPromise = Promise.promise();
final String shareKey = shareLinkInfo.getShareKey();
final String shareUrl = shareLinkInfo.getShareUrl();
final String pwd = shareLinkInfo.getSharePassword();
// shareKey格式: uid-folder_id-hash (例如 64115194-164803691-48508c)
if (shareKey == null) {
listPromise.fail(baseMsg() + " shareKey为空");
String shareKey = shareLinkInfo.getShareKey();
if (shareKey == null || shareKey.isBlank()) {
listPromise.fail(baseMsg() + " - 解析异常: shareKey为空");
return listPromise.future();
}
String[] split = shareKey.split("-");
if (split.length < 2) {
listPromise.fail(baseMsg() + " shareKey格式不正确: " + shareKey);
return listPromise.future();
try {
worker().executeBlocking(() -> listDirectory(shareKey), false)
.onSuccess(listPromise::complete)
.onFailure(error -> {
if (!listPromise.future().isComplete()) {
listPromise.fail(baseMsg() + " - 解析异常: " + rootMessage(error));
}
});
} catch (RuntimeException e) {
listPromise.fail(baseMsg() + " - 解析异常: " + e.getMessage());
}
String path = extractPath(shareUrl);
Object dirId = shareLinkInfo.getOtherParam() == null ? null : shareLinkInfo.getOtherParam().get("dirId");
DirectoryContext directoryContext = resolveDirectoryContext(shareUrl, dirId);
HttpRequest<Buffer> getDirRequest = withCtAjaxHeaders(clientSession.getAbs(UriTemplate.of(API_GETDIR))
.setTemplateParam("path", path)
.setTemplateParam("shareKey", shareKey)
.setTemplateParam("folder_id", directoryContext.folderId)
.setTemplateParam("fk", directoryContext.folderKey)
.setTemplateParam("pwd", pwd != null ? pwd : "")
.setTemplateParam("rand", String.valueOf(Math.random()))
.setTemplateParam("url", shareUrl), shareUrl);
getDirRequest.send().onSuccess(res -> {
try {
var resJson = asJson(res);
if (resJson == null || resJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: 上游返回空响应或非JSON响应");
return;
}
if (!resJson.containsKey("file")) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + resJson.encode());
return;
}
Object dirInfoValue = resJson.getValue("file");
if (!(dirInfoValue instanceof JsonObject)) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: file字段格式错误: " + resJson.encode());
return;
}
JsonObject dirInfo = (JsonObject) dirInfoValue;
Object fileListUrlValue = dirInfo.getValue("url");
String fileListRelUrl = fileListUrlValue instanceof String ? ((String) fileListUrlValue).trim() : "";
if (fileListRelUrl.isBlank()) {
failListPromise(listPromise, baseMsg() + " " + buildDirectoryFailureMessage(resJson, dirInfo));
return;
}
fetchFileListPage(toCtApiUrl(fileListRelUrl), 0, 0, new ArrayList<>(), listPromise,
shareLinkInfo.getType(), getDomainName(), shareUrl, pwd);
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 目录解析失败: " + e.getMessage());
}
}).onFailure(t -> failListPromise(listPromise, t));
return listPromise.future();
}
private void fetchFileListPage(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd) {
try {
if (pageIndex >= MAX_FILE_LIST_PAGES) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 分页超过最大限制 " + MAX_FILE_LIST_PAGES
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
String fileListUrl = appendQueryParams(fileListBaseUrl,
buildFileListParams(start, FILE_LIST_PAGE_SIZE) + "&_=" + System.currentTimeMillis());
withCtAjaxHeaders(clientSession.getAbs(fileListUrl), shareUrl)
.send()
.onSuccess(res -> handleFileListPageResponse(fileListBaseUrl, start, pageIndex, fileList,
listPromise, panType, domainName, shareUrl, pwd, res))
.onFailure(t -> failListPromise(listPromise, t));
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
private void handleFileListPageResponse(String fileListBaseUrl, int start, int pageIndex, List<FileInfo> fileList,
Promise<List<FileInfo>> listPromise, String panType, String domainName,
String shareUrl, String pwd, io.vertx.ext.web.client.HttpResponse<Buffer> res) {
try {
var listJson = asJson(res);
if (listJson == null || listJson.isEmpty()) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空响应或非JSON响应"
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
return;
}
Object aaDataValue = listJson.getValue("aaData");
if (!(aaDataValue instanceof JsonArray)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: aaData为空: " + listJson.encode());
return;
}
JsonArray aaData = (JsonArray) aaDataValue;
for (int i = 0; i < aaData.size(); i++) {
try {
Object rowValue = aaData.getValue(i);
if (!(rowValue instanceof JsonArray)) {
log.warn("城通文件列表行格式错误: {}", rowValue);
continue;
}
FileInfo fileInfo = parseFileListRow((JsonArray) rowValue, panType,
domainName, shareUrl, pwd);
if (fileInfo != null) {
fileList.add(fileInfo);
}
} catch (Exception e) {
log.warn("解析文件行失败: {}", e.getMessage());
}
}
int nextStart = start + aaData.size();
int total = parseFileListTotal(listJson);
if (isUnexpectedEmptyFileListPage(start, aaData.size(), total)) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: 上游返回空分页"
+ " (start=" + start + ", total=" + total + ")");
return;
}
if (shouldFetchNextFileListPage(start, aaData.size(), total)) {
fetchFileListPage(fileListBaseUrl, nextStart, pageIndex + 1, fileList,
listPromise, panType, domainName, shareUrl, pwd);
} else {
completeListPromise(listPromise, fileList);
}
} catch (Exception e) {
failListPromise(listPromise, baseMsg() + " 文件列表解析失败: " + e.getMessage()
+ " (start=" + start + ", length=" + FILE_LIST_PAGE_SIZE + ")");
}
}
@Override
public Future<String> parseById() {
Object paramValue = shareLinkInfo.getOtherParam().get("paramJson");
if (!(paramValue instanceof JsonObject)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 缺少下载参数paramJson");
return parsePromise.future();
fail("缺少下载参数paramJson");
return promise.future();
}
JsonObject paramJson = (JsonObject) paramValue;
if (!applyFileParam(shareLinkInfo, paramJson)) {
Promise<String> parsePromise = Promise.promise();
parsePromise.fail(baseMsg() + " 下载参数id为空");
return parsePromise.future();
if (!applyFileParam(shareLinkInfo, (JsonObject) paramValue)) {
fail("下载参数id为空");
return promise.future();
}
return parse();
}
@@ -356,318 +124,233 @@ public class CtTool extends PanBase {
return true;
}
static String resolveDownloadUid(JsonObject fileJson, String fallbackUid) {
return firstNonBlank(valueToString(fileJson.getValue("userid")), fallbackUid);
}
static String resolveDownloadFid(JsonObject fileJson, String fallbackFid) {
return firstNonBlank(valueToString(fileJson.getValue("file_id")), fallbackFid);
}
private HttpRequest<Buffer> withCtAjaxHeaders(HttpRequest<Buffer> request, String shareUrl) {
request.putHeader("User-Agent", BROWSER_UA)
.putHeader("Accept", AJAX_ACCEPT)
.putHeader("X-Requested-With", "XMLHttpRequest");
if (shareUrl != null && !shareUrl.isBlank()) {
request.putHeader("Referer", shareUrl);
}
String origin = extractOrigin(shareUrl);
if (!origin.isBlank()) {
request.putHeader("Origin", origin);
}
return request;
}
static FileInfo parseFileListRow(JsonArray row, String panType, String domainName, String shareUrl, String pwd) {
if (row == null || row.size() < 2) {
return null;
}
String checkboxHtml = rowString(row, 0);
String nameCellHtml = rowString(row, 1);
String sizeStr = rowString(row, 2).trim();
String dateStr = rowString(row, 3).trim();
if (nameCellHtml.isBlank()) {
return null;
}
String fileName = matchFirst(FILE_NAME_PATTERN, nameCellHtml);
String fileIcon = matchFirst(FILE_ICON_PATTERN, nameCellHtml);
if (fileName == null || fileName.isBlank()) {
return null;
}
Matcher subdirMatcher = SUBDIR_PATTERN.matcher(nameCellHtml);
boolean hasSubdirCall = subdirMatcher.find();
if (hasSubdirCall || "folder".equalsIgnoreCase(fileIcon)) {
String folderId = hasSubdirCall ? subdirMatcher.group(1) : null;
String folderKey = hasSubdirCall ? subdirMatcher.group(2) : "";
if (folderId == null) {
folderId = matchFirst(FOLDER_ID_PATTERN, checkboxHtml);
private ParsedDownload resolveDownload(String shareKey) throws Exception {
VerificationMismatch mismatch = null;
for (int attempt = 0; attempt < 2; attempt++) {
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
try {
return downloadOnce(session, shareKey);
} catch (VerificationMismatch retryable) {
// verifycode 和签发它的那次连接绑在一起。换一个客户端再取一次。
mismatch = retryable;
}
}
if (folderId == null || folderId.isBlank()) {
}
throw mismatch == null ? new CtfileException("未返回下载地址") : mismatch;
}
private ParsedDownload downloadOnce(CtfileSession session, String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
JsonObject resource = session.loadResource("file", shareKey, target, password, turnstileToken());
JsonObject data = CtfileSession.dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
DirectLink link = session.download(shareKey, target, password, resource);
return new ParsedDownload(link.url, link.headers, file, file.getString("file_dir", ""));
}
private List<FileInfo> listDirectory(String shareKey) throws Exception {
String password = shareLinkInfo.getSharePassword();
ShareTarget target = ShareTarget.from(shareLinkInfo);
int maxPages = maxListPages();
try (CtfileSession session = CtfileSession.open(shareLinkInfo)) {
JsonObject resource = session.loadResource("dir", shareKey, target, password, turnstileToken());
List<FileInfo> files = new ArrayList<>();
int start = 0;
for (int page = 0; page < maxPages; page++) {
JsonObject listing = session.listing("dir", shareKey, target, password, resource, start,
CtfileSession.pageSize());
int code = CtfileSession.intValue(listing.getValue("code"), 200);
if (code != 200) {
throw new CtfileException(CtfileSession.classify(listing, code, password).message);
}
JsonArray rows = CtfileSession.rowsOf(listing);
for (int i = 0; i < rows.size(); i++) {
if (rows.getValue(i) instanceof JsonObject row) {
FileInfo info = toFileInfo(row, shareLinkInfo);
if (info != null) {
files.add(info);
}
}
}
if (rows.isEmpty() || !CtfileSession.hasMore(listing, rows.size())) {
return files;
}
start += rows.size();
}
if (maxPages != DEFAULT_MAX_LIST_PAGES || shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return files;
}
throw new CtfileException("目录文件过多,已超过 " + maxPages + " 页");
}
}
static FileInfo toFileInfo(JsonObject row, ShareLinkInfo info) {
if (row == null) {
return null;
}
String name = row.getString("name", "").trim();
if (name.isBlank()) {
return null;
}
String kind = row.getString("kind", "");
String password = info.getSharePassword() == null ? "" : info.getSharePassword();
FileInfo fileInfo = new FileInfo()
.setFileName(name)
.setPanType(info.getType())
.setCreateBy(CtfileSession.text(row.getValue("ownerId")));
String date = row.getString("date", "");
if (!date.isBlank()) {
fileInfo.setCreateTime(date).setUpdateTime(date);
}
if ("folder".equals(kind)) {
String folderId = CtfileSession.text(row.getValue("folderId"));
if (folderId.isBlank()) {
return null;
}
String dirId = folderId + ":" + folderKey;
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(folderId)
.setSize(0L)
.setSizeStr(sizeStr.isBlank() ? "0B" : sizeStr)
String folderKey = row.getString("folderKey", "");
fileInfo.setFileId(folderId)
.setFileType("folder")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(buildFolderParserUrl(domainName, shareUrl, dirId, pwd));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
}
.setSize(0L)
.setSizeStr("0B")
.setParserUrl(buildFolderParserUrl(info, folderId + ":" + (folderKey == null ? "" : folderKey), password));
return fileInfo;
}
String fileShareKey = matchFirst(FILE_HREF_PATTERN, nameCellHtml);
if (fileShareKey == null || fileShareKey.isBlank()) {
if (!"file".equals(kind)) {
return null;
}
String fileId = matchFirst(FILE_ID_PATTERN, checkboxHtml);
JsonObject paramJson = new JsonObject()
.put("id", fileShareKey)
.put("fileName", fileName.trim())
.put("pwd", pwd == null ? "" : pwd);
String param = CommonUtils.urlBase64Encode(paramJson.encode());
long sizeBytes = 0;
try {
sizeBytes = sizeStr.isBlank() ? 0 : FileSizeConverter.convertToBytes(sizeStr);
} catch (Exception ignored) {
String fileKey = fileKeyFromHref(row.getString("href", ""));
if (fileKey.isBlank()) {
fileKey = CtfileSession.text(row.getValue("fileId"));
}
FileInfo fileInfo = new FileInfo()
.setFileName(fileName.trim())
.setFileId(fileId)
.setSizeStr(sizeStr)
.setSize(sizeBytes)
.setFileType(fileIcon != null ? fileIcon : "file")
.setFileIcon(fileIcon)
.setPanType(panType)
.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s",
domainName, panType, param));
if (!dateStr.isBlank()) {
fileInfo.setCreateTime(dateStr).setUpdateTime(dateStr);
if (fileKey.isBlank()) {
return null;
}
long size = CtfileSession.longValue(row.getValue("size_bytes"), 0L);
JsonObject param = new JsonObject()
.put("id", fileKey)
.put("fileName", name)
.put("pwd", password);
String encoded = CommonUtils.urlBase64Encode(param.encode());
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
fileInfo.setFileId(CtfileSession.firstNonBlank(CtfileSession.text(row.getValue("fileId")), fileKey))
.setFileType(CtfileSession.firstNonBlank(row.getString("extension"), "file"))
.setSize(size)
.setSizeStr(row.getString("size", ""))
.setParserUrl(domain + "/v2/redirectUrl/" + info.getType() + "/" + encoded);
return fileInfo;
}
private static String buildFolderParserUrl(String domainName, String shareUrl, String dirId, String pwd) {
String url = String.format("%s/v2/getFileList?url=%s&dirId=%s",
domainName, urlEncode(shareUrl), urlEncode(dirId));
if (pwd != null && !pwd.isBlank()) {
url += "&pwd=" + urlEncode(pwd);
private static String buildFolderParserUrl(ShareLinkInfo info, String dirId, String password) {
String domain = info.getOtherParam() == null ? "" : info.getOtherParam().getOrDefault("domainName", "").toString();
String shareUrl = info.getShareUrl() == null ? "" : info.getShareUrl();
String url = domain + "/v2/getFileList?url=" + urlEncode(shareUrl) + "&dirId=" + urlEncode(dirId);
if (password != null && !password.isBlank()) {
url += "&pwd=" + urlEncode(password);
}
return url;
}
static String extractQueryParam(String url, String paramName) {
if (url == null || paramName == null) return null;
int qIdx = url.indexOf('?');
if (qIdx < 0) return null;
String query = url.substring(qIdx + 1);
int fragmentIdx = query.indexOf('#');
if (fragmentIdx >= 0) {
query = query.substring(0, fragmentIdx);
private static String fileKeyFromHref(String href) {
if (href == null || href.isBlank()) {
return "";
}
for (String param : query.split("&")) {
int eqIdx = param.indexOf('=');
if (eqIdx > 0 && urlDecode(param.substring(0, eqIdx)).equals(paramName)) {
return urlDecode(param.substring(eqIdx + 1));
int marker = href.indexOf("/f/");
int skip = 3;
if (marker < 0) {
marker = href.indexOf("/file/");
skip = 6;
}
if (marker < 0) {
return "";
}
String rest = href.substring(marker + skip);
int cut = rest.length();
for (int i = 0; i < rest.length(); i++) {
char c = rest.charAt(i);
if (c == '?' || c == '#' || c == '/') {
cut = i;
break;
}
}
return null;
return rest.substring(0, cut);
}
static String extractPath(String shareUrl) {
if (shareUrl == null) {
private FileInfo fileInfoFrom(JsonObject file) {
long size = CtfileSession.longValue(file.getValue("file_size_bytes"), 0L);
FileInfo info = new FileInfo()
.setFileName(file.getString("file_name", ""))
.setFileId(CtfileSession.text(file.getValue("file_id")))
.setSize(size)
.setSizeStr(file.getString("file_size", ""))
.setFileType("file")
.setCreateBy(file.getString("username", ""))
.setPanType(shareLinkInfo.getType());
String created = file.getString("file_time", "");
if (!created.isBlank()) {
info.setCreateTime(created);
}
return info;
}
private String turnstileToken() {
if (shareLinkInfo.getOtherParam() == null) {
return "";
}
int comIdx = shareUrl.indexOf("com/");
if (comIdx < 0) {
return "";
Object value = shareLinkInfo.getOtherParam().get("turnstileToken");
return value == null ? "" : value.toString().trim();
}
private int maxListPages() {
if (shareLinkInfo.getOtherParam() == null || !shareLinkInfo.getOtherParam().containsKey("ctMaxListPages")) {
return DEFAULT_MAX_LIST_PAGES;
}
int configured = CtfileSession.intValue(shareLinkInfo.getOtherParam().get("ctMaxListPages"), DEFAULT_MAX_LIST_PAGES);
return configured < 1 ? 1 : configured;
}
int pathStart = comIdx + 4;
int pathEnd = shareUrl.indexOf('/', pathStart);
if (pathEnd < 0) {
pathEnd = shareUrl.indexOf('?', pathStart);
private static String rootMessage(Throwable error) {
Throwable current = error;
while (current.getCause() != null && current.getCause() != current
&& (current.getMessage() == null || current.getMessage().isBlank()
|| current.getClass().getName().contains("CompletionException")
|| current.getClass().getName().contains("ExecutionException"))) {
current = current.getCause();
}
if (pathEnd < 0) {
pathEnd = shareUrl.length();
}
return shareUrl.substring(pathStart, pathEnd);
}
static String extractFolderKey(String shareUrl) {
return trimToEmpty(extractQueryParam(shareUrl, "fk"));
}
static DirectoryContext resolveDirectoryContext(String shareUrl, Object dirIdObj) {
String dirId = dirIdObj == null ? "" : urlDecode(String.valueOf(dirIdObj).trim());
if (!dirId.isBlank()) {
String[] split = dirId.split(":", 2);
return new DirectoryContext(trimToDefault(split[0], "undefined"),
split.length > 1 ? trimToEmpty(split[1]) : "");
}
String queryFolderId = firstNonBlank(extractQueryParam(shareUrl, "folder_id"), extractQueryParam(shareUrl, "d"));
String queryFk = extractFolderKey(shareUrl);
if (!queryFolderId.isBlank() || !queryFk.isBlank()) {
return new DirectoryContext(trimToDefault(queryFolderId, "undefined"), queryFk);
}
return new DirectoryContext("undefined", "");
}
static String buildDirectoryFailureMessage(JsonObject resJson, JsonObject dirInfo) {
String code = valueToString(resJson.getValue("code"));
String message = valueToString(dirInfo.getValue("message"));
if (message != null && !message.isBlank()) {
return "目录解析失败: " + message + " (code=" + code + ")";
}
if ("423".equals(code)) {
return "目录解析失败: 需要访问密码或该分享受限 (code=423)";
}
return "目录解析失败: 文件列表URL为空, 上游响应: " + resJson.encode();
}
static String buildFileListParams(int start, int length) {
return FILE_LIST_PARAMS_TEMPLATE
.replace("{start}", String.valueOf(Math.max(0, start)))
.replace("{length}", String.valueOf(Math.max(1, length)));
}
static int parseFileListTotal(JsonObject listJson) {
int displayTotal = parseInteger(listJson.getValue("iTotalDisplayRecords"), -1);
return displayTotal >= 0 ? displayTotal : parseInteger(listJson.getValue("iTotalRecords"), -1);
}
static boolean shouldFetchNextFileListPage(int start, int rowCount, int total) {
if (rowCount <= 0) {
return false;
}
int fetchedThrough = start + rowCount;
return total < 0 ? rowCount >= FILE_LIST_PAGE_SIZE : fetchedThrough < total;
}
static boolean isUnexpectedEmptyFileListPage(int start, int rowCount, int total) {
return total >= 0 && start < total && rowCount <= 0;
}
private static int parseInteger(Object value, int defaultValue) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return defaultValue;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, String message) {
if (!listPromise.future().isComplete()) {
listPromise.fail(message);
}
}
private static void failListPromise(Promise<List<FileInfo>> listPromise, Throwable throwable) {
if (!listPromise.future().isComplete()) {
listPromise.fail(throwable);
}
}
private static void completeListPromise(Promise<List<FileInfo>> listPromise, List<FileInfo> fileList) {
if (!listPromise.future().isComplete()) {
listPromise.complete(fileList);
}
}
private static String toCtApiUrl(String url) {
if (url.startsWith("http://") || url.startsWith("https://")) {
return url;
}
return API_URL_PREFIX + url;
}
private static String appendQueryParams(String url, String params) {
String normalizedParams = params != null && params.startsWith("&") ? params.substring(1) : params;
return url + (url.contains("?") ? "&" : "?") + normalizedParams;
}
private static String rowString(JsonArray row, int index) {
if (row == null || index >= row.size()) {
return "";
}
return valueToString(row.getValue(index));
}
private static String valueToString(Object value) {
return value == null ? "" : value.toString();
}
private static String matchFirst(Pattern pattern, String text) {
if (text == null) {
return null;
}
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group(1) : null;
}
private static String firstNonBlank(String first, String second) {
return !trimToEmpty(first).isBlank() ? trimToEmpty(first) : trimToEmpty(second);
}
private static String trimToDefault(String value, String defaultValue) {
String result = trimToEmpty(value);
return result.isBlank() ? defaultValue : result;
}
private static String trimToEmpty(String value) {
return value == null ? "" : value.trim();
String message = current.getMessage();
return message == null || message.isBlank() ? current.getClass().getSimpleName() : message;
}
private static String urlEncode(String value) {
return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
}
private static String urlDecode(String value) {
if (value == null) {
return "";
}
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static String extractOrigin(String shareUrl) {
try {
URI uri = URI.create(shareUrl);
if (uri.getScheme() == null || uri.getHost() == null) {
return "";
private static WorkerExecutor worker() {
synchronized (WORKER_LOCK) {
if (workerShutdown) {
throw new IllegalStateException("城通解析线程池已关闭");
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
if (sharedWorker == null) {
sharedWorker = WebClientVertxInit.get().createSharedWorkerExecutor("ctfile-worker", 4);
}
return sharedWorker;
}
}
static final class DirectoryContext {
final String folderId;
final String folderKey;
private static final class ParsedDownload {
final String url;
final java.util.Map<String, String> headers;
final JsonObject file;
final String fileDir;
DirectoryContext(String folderId, String folderKey) {
this.folderId = folderId;
this.folderKey = folderKey;
ParsedDownload(String url, java.util.Map<String, String> headers, JsonObject file, String fileDir) {
this.url = url;
this.headers = headers;
this.file = file;
this.fileDir = fileDir;
}
}
}
@@ -0,0 +1,685 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 城通新版分享接口(api.ctfile.com/url/*)。
* <p>
* 一次解析专用一个 HttpClient:资源接口签发的 verifycode 绑定本次连接的出口 IP,
* 下载必须跟在同一次连接上的 resource 之后。访问令牌 access_pass 约 24 小时、按分享者复用,
* 用来跳过重复的 ALTCHA 计算。
*/
final class CtfileSession implements AutoCloseable {
static final String API = "https://api.ctfile.com";
private static final String CHALLENGE_PATH = "/url/captcha/altcha?captcha_action=share_passcode";
private static final String UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(20);
private static final int PAGE_SIZE = 200;
private static final long PASS_SKEW_MILLIS = 60_000L;
private static final ConcurrentHashMap<String, CachedPass> ACCESS_PASSES = new ConcurrentHashMap<>();
private final HttpClient client;
private final String origin;
private final String referer;
private CtfileSession(HttpClient client, String origin, String referer) {
this.client = client;
this.origin = origin;
this.referer = referer;
}
static CtfileSession open(ShareLinkInfo info) {
String shareUrl = info == null ? "" : info.getShareUrl();
String origin = originOf(shareUrl);
if (origin.isBlank()) {
origin = "https://www.ctfile.com";
}
String referer = shareUrl == null || shareUrl.isBlank() ? origin + "/" : shareUrl;
return new CtfileSession(newClient(info), origin, referer);
}
JsonObject loadResource(String kind, String id, ShareTarget target, String password, String turnstileToken)
throws Exception {
JsonObject body = getResource(kind, id, target, password, null, null, null);
Decision decision = classify(body, 200, password);
if (decision.kind == Kind.OK) {
remember(decision, password, null);
return body;
}
if (decision.kind == Kind.ALTCHA) {
String cached = cachedPass(decision.ownerId, password);
if (cached != null) {
JsonObject retry = getResource(kind, id, target, password, null, null, cached);
Decision again = classify(retry, 200, password);
if (again.kind == Kind.OK) {
remember(again, password, cached);
return retry;
}
forget(decision.ownerId, password);
}
JsonObject challenge = challenge();
if (expiresSoon(challenge)) {
challenge = challenge();
}
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge);
String token = AltchaV2Solver.payload(challenge, solution);
JsonObject retry = getResource(kind, id, target, password, token, null, null);
Decision solved = classify(retry, 200, password);
if (solved.kind != Kind.OK) {
if (solved.kind == Kind.ALTCHA) {
throw new CtfileException("ALTCHA 人机验证未通过,请重试");
}
throw new CtfileException(solved.message);
}
remember(solved, password, null);
return retry;
}
if (decision.kind == Kind.TURNSTILE && turnstileToken != null && !turnstileToken.isBlank()) {
JsonObject retry = getResource(kind, id, target, password, null, turnstileToken, null);
Decision again = classify(retry, 200, password);
if (again.kind == Kind.OK) {
remember(again, password, null);
return retry;
}
throw new CtfileException(again.message);
}
throw new CtfileException(decision.message);
}
DirectLink download(String id, ShareTarget target, String password, JsonObject resource) throws Exception {
JsonObject data = dataOf(resource);
JsonObject file = data == null ? null : data.getJsonObject("file");
if (file == null) {
throw new CtfileException("下载参数不完整:上游没有返回文件信息");
}
String pass = firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
return postDownload(id, target, password, file, pass, 0);
}
JsonObject listing(String kind, String id, ShareTarget target, String password, JsonObject resource,
int start, int length) throws Exception {
JsonObject data = dataOf(resource);
String pass = data == null ? null : firstNonBlank(data.getString("access_pass"), cachedPass(ownerId(data), password));
Map<String, String> query = resourceQuery(kind, id, target, password, null, null, pass);
query.put("start", String.valueOf(Math.max(0, start)));
query.put("length", String.valueOf(Math.max(1, length)));
return exchange("GET", "/url/listing?" + form(query), null, origin, referer);
}
static int pageSize() {
return PAGE_SIZE;
}
private DirectLink postDownload(String id, ShareTarget target, String password, JsonObject file, String pass,
int waitedSeconds) throws Exception {
if (waitedSeconds > 120) {
throw new CtfileException("下载需要等待的时间过长");
}
String verify = file.getString("verifycode", "");
String fileChk = file.getString("file_chk", "");
if (verify.isBlank() || fileChk.isBlank() || file.getValue("file_id") == null || file.getValue("userid") == null) {
throw new CtfileException("下载参数不完整:缺少 file_chk 或 verifycode");
}
JsonObject context = new JsonObject()
.put("kind", "file")
.put("id", id)
.put("folder_id", target.folderId)
.put("fk", target.fk)
.put("passcode", password == null ? "" : password)
.put("type_id", target.typeId);
if (pass != null && !pass.isBlank()) {
context.put("access_pass", pass);
}
JsonObject original = new JsonObject()
.put("file_id", file.getValue("file_id"))
.put("userid", file.getValue("userid"))
.put("file_chk", fileChk)
.put("start_time", file.getValue("start_time"))
.put("wait_seconds", file.getValue("wait_seconds"));
JsonObject body = new JsonObject()
.put("context", context)
.put("app", false)
.put("verifycode", verify)
.put("original_file", original)
.put("carrier", 0);
JsonObject response = exchange("POST", "/url/download", body.encode().getBytes(StandardCharsets.UTF_8),
origin, referer);
int top = codeOf(response, 200);
JsonObject data = dataOf(response);
int code = data != null && data.getValue("code") != null ? codeOf(data, top) : top;
String message = firstNonBlank(response.getString("msg"), response.getString("message"),
data == null ? "" : firstNonBlank(data.getString("msg"), data.getString("message")));
if (code == 218) {
int remaining = intValue(data == null ? null : data.getValue("remaining_seconds"),
intValue(response.getValue("remaining_seconds"), 1));
remaining = Math.max(1, Math.min(remaining, 30));
sleepSeconds(remaining);
return postDownload(id, target, password, file, pass, waitedSeconds + remaining);
}
if (code == 219) {
throw new CtfileException("需要登录后才能下载");
}
if (code == 403 && message.toLowerCase().contains("verification")) {
throw new VerificationMismatch("下载校验未通过或已过期,请重试");
}
String downurl = data == null ? null : data.getString("downurl");
if (code != 200 || downurl == null || downurl.isBlank()) {
throw new CtfileException(message.isBlank()
? "未返回下载地址 (code=" + code + ")"
: "未返回下载地址: " + message);
}
Map<String, String> headers = new LinkedHashMap<>();
if (data.getValue("headers") instanceof JsonObject headerJson) {
for (String key : headerJson.fieldNames()) {
Object value = headerJson.getValue(key);
if (key != null && value != null && !value.toString().isBlank()) {
headers.put(key, value.toString());
}
}
}
return new DirectLink(downurl, headers);
}
private JsonObject getResource(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) throws Exception {
Map<String, String> params = resourceQuery(kind, id, target, password, altchaToken, turnstileToken, accessPass);
return exchange("GET", "/url/resource?" + form(params), null, origin, referer);
}
private JsonObject challenge() throws Exception {
return exchange("GET", CHALLENGE_PATH, null, "https://h5.ctfile.com",
"https://h5.ctfile.com/captcha/altcha.html");
}
private JsonObject exchange(String method, String path, byte[] body, String requestOrigin, String requestReferer)
throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(API + path))
.timeout(REQUEST_TIMEOUT)
.header("User-Agent", UA)
.header("Accept", "application/json, text/plain, */*")
.header("Origin", requestOrigin)
.header("Referer", requestReferer);
if (body == null) {
builder.method(method, HttpRequest.BodyPublishers.noBody());
} else {
builder.header("Content-Type", "application/json");
builder.method(method, HttpRequest.BodyPublishers.ofByteArray(body));
}
HttpResponse<String> response;
try {
response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("请求被中断");
} catch (IOException e) {
throw new CtfileException("请求失败: " + e.getMessage());
}
String text = response.body();
if (text == null || text.isBlank()) {
throw new CtfileException("上游返回空响应 (HTTP " + response.statusCode() + ")");
}
try {
return new JsonObject(text);
} catch (Exception e) {
throw new CtfileException("上游返回了无法识别的响应 (HTTP " + response.statusCode() + ")");
}
}
static Map<String, String> resourceQuery(String kind, String id, ShareTarget target, String password,
String altchaToken, String turnstileToken, String accessPass) {
Map<String, String> query = new LinkedHashMap<>();
query.put("kind", kind == null || kind.isBlank() ? "file" : kind);
query.put("id", id == null ? "" : id);
query.put("folder_id", target.folderId);
query.put("fk", target.fk);
query.put("passcode", password == null ? "" : password);
query.put("type_id", target.typeId);
if (altchaToken != null && !altchaToken.isBlank()) {
query.put("altcha_token", altchaToken);
}
if (turnstileToken != null && !turnstileToken.isBlank()) {
query.put("turnstile_token", turnstileToken);
}
if (accessPass != null && !accessPass.isBlank()) {
query.put("access_pass", accessPass);
}
return query;
}
static String form(Map<String, String> query) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : query.entrySet()) {
if (entry.getValue() == null) {
continue;
}
if (builder.length() > 0) {
builder.append('&');
}
builder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8));
builder.append('=');
builder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
}
return builder.toString();
}
static Decision classify(JsonObject body, int httpStatus, String password) {
int code = codeOf(body, httpStatus);
JsonObject data = dataOf(body);
String message = firstNonBlank(body == null ? "" : body.getString("msg"),
body == null ? "" : body.getString("message"));
String errorType = data == null ? "" : text(data.getValue("error_type"));
String captcha = data == null ? "" : text(data.getValue("captcha_type"));
JsonObject capabilities = data == null ? null : data.getJsonObject("capabilities");
boolean passcodeRequired = capabilities != null && Boolean.TRUE.equals(capabilities.getValue("passcodeRequired"));
String owner = capabilities == null ? "" : text(capabilities.getValue("ownerId"));
boolean passwordMissing = password == null || password.isBlank();
boolean captchaAsked = "captcha_required".equals(errorType) || errorType.startsWith("captcha_");
if (code == 200) {
return Decision.ok(owner, accessPass(data));
}
if (code == 404) {
return Decision.of(Kind.NOT_FOUND, owner, "分享不存在或已过期" + suffix(message));
}
if (code == 403) {
return Decision.of(Kind.INVALID, owner, "分享链接无效或已失效" + suffix(message));
}
if (code == 423) {
if ("passcode_incorrect".equals(errorType)) {
return Decision.of(Kind.BAD_PASSWORD, owner, "访问密码不正确" + suffix(message));
}
if (passwordMissing && passcodeRequired && !captchaAsked) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
if ("turnstile".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.TURNSTILE, owner, "触发 Cloudflare Turnstile 人机验证,暂不支持服务端自动通过");
}
if ("altcha".equalsIgnoreCase(captcha)) {
return Decision.of(Kind.ALTCHA, owner, "需要完成 ALTCHA 人机验证");
}
if (passwordMissing && passcodeRequired) {
return Decision.of(Kind.NEED_PASSWORD, owner, "需要访问密码");
}
return Decision.of(Kind.OTHER, owner, "分享暂时无法访问" + suffix(message) + " (code=423)");
}
return Decision.of(Kind.OTHER, owner,
"上游返回异常 (code=" + code + ")" + suffix(message));
}
private static void remember(Decision decision, String password, String fallbackPass) {
String token = firstNonBlank(decision.accessPass, fallbackPass);
if (decision.ownerId == null || decision.ownerId.isBlank() || token == null || token.isBlank()) {
return;
}
long expiry = passExpiry(token);
if (expiry < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
return;
}
ACCESS_PASSES.put(cacheKey(decision.ownerId, password), new CachedPass(token, expiry));
}
private static String cachedPass(String ownerId, String password) {
if (ownerId == null || ownerId.isBlank()) {
return null;
}
CachedPass cached = ACCESS_PASSES.get(cacheKey(ownerId, password));
if (cached == null) {
return null;
}
if (cached.expiresAtMillis < System.currentTimeMillis() + PASS_SKEW_MILLIS) {
ACCESS_PASSES.remove(cacheKey(ownerId, password), cached);
return null;
}
return cached.token;
}
private static void forget(String ownerId, String password) {
if (ownerId != null && !ownerId.isBlank()) {
ACCESS_PASSES.remove(cacheKey(ownerId, password));
}
}
static void clearCachedPasses() {
ACCESS_PASSES.clear();
}
private static String cacheKey(String ownerId, String password) {
return ownerId + "\n" + (password == null ? "" : password);
}
private static long passExpiry(String token) {
try {
String[] parts = token.split("\\.");
if (parts.length < 2) {
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
byte[] json = Base64.getUrlDecoder().decode(padBase64(parts[1]));
JsonObject payload = new JsonObject(new String(json, StandardCharsets.UTF_8));
Object expiry = payload.getValue("e");
if (expiry instanceof Number) {
return ((Number) expiry).longValue() * 1000L;
}
} catch (Exception ignored) {
// 解析不了有效期时按半小时使用,失效后会重新计算 ALTCHA。
}
return System.currentTimeMillis() + Duration.ofMinutes(30).toMillis();
}
private static boolean expiresSoon(JsonObject challenge) {
JsonObject parameters = challenge.getJsonObject("parameters");
if (parameters == null) {
return false;
}
Object expiry = parameters.getValue("expiresAt");
if (!(expiry instanceof Number)) {
return false;
}
long expiresAtMillis = ((Number) expiry).longValue() * 1000L;
return expiresAtMillis < System.currentTimeMillis() + 15_000L;
}
private static String accessPass(JsonObject data) {
return data == null ? "" : text(data.getValue("access_pass"));
}
private static String ownerId(JsonObject data) {
if (data == null) {
return "";
}
JsonObject capabilities = data.getJsonObject("capabilities");
return capabilities == null ? "" : text(capabilities.getValue("ownerId"));
}
static JsonObject dataOf(JsonObject body) {
if (body == null || !(body.getValue("data") instanceof JsonObject)) {
return null;
}
return body.getJsonObject("data");
}
static JsonArray rowsOf(JsonObject listing) {
JsonObject data = dataOf(listing);
if (data == null || !(data.getValue("rows") instanceof JsonArray)) {
return new JsonArray();
}
return data.getJsonArray("rows");
}
static boolean hasMore(JsonObject listing, int rowCount) {
JsonObject data = dataOf(listing);
if (data != null && data.getValue("hasMore") instanceof Boolean) {
return data.getBoolean("hasMore");
}
return rowCount >= PAGE_SIZE;
}
private static int codeOf(JsonObject body, int fallback) {
if (body == null) {
return fallback;
}
return intValue(body.getValue("code"), fallback);
}
static int intValue(Object value, int fallback) {
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value == null) {
return fallback;
}
try {
return Integer.parseInt(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
static long longValue(Object value, long fallback) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value == null) {
return fallback;
}
try {
return Long.parseLong(value.toString());
} catch (NumberFormatException e) {
return fallback;
}
}
private static String suffix(String message) {
return message == null || message.isBlank() ? "" : "(" + message + ")";
}
static String text(Object value) {
return value == null ? "" : value.toString().trim();
}
static String firstNonBlank(String... values) {
if (values == null) {
return "";
}
for (String value : values) {
if (value != null && !value.isBlank()) {
return value;
}
}
return "";
}
private static String padBase64(String value) {
int mod = value.length() % 4;
if (mod == 0) {
return value;
}
return value + "=".repeat(4 - mod);
}
private static void sleepSeconds(int seconds) throws CtfileException {
try {
Thread.sleep(seconds * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CtfileException("下载等待被中断");
}
}
private static String originOf(String shareUrl) {
if (shareUrl == null || shareUrl.isBlank()) {
return "";
}
try {
URI uri = URI.create(shareUrl);
if (uri.getScheme() == null || uri.getHost() == null) {
return "";
}
String origin = uri.getScheme() + "://" + uri.getHost();
return uri.getPort() > 0 ? origin + ":" + uri.getPort() : origin;
} catch (Exception e) {
return "";
}
}
static String queryParam(String url, String name) {
if (url == null || name == null) {
return "";
}
int query = url.indexOf('?');
if (query < 0) {
return "";
}
String raw = url.substring(query + 1);
int hash = raw.indexOf('#');
if (hash >= 0) {
raw = raw.substring(0, hash);
}
for (String part : raw.split("&")) {
int eq = part.indexOf('=');
if (eq <= 0) {
continue;
}
String key = decode(part.substring(0, eq));
if (name.equals(key)) {
return decode(part.substring(eq + 1));
}
}
return "";
}
private static String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (Exception e) {
return value;
}
}
private static HttpClient newClient(ShareLinkInfo info) {
HttpClient.Builder builder = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NEVER);
Object proxyValue = info == null || info.getOtherParam() == null ? null : info.getOtherParam().get("proxy");
if (proxyValue instanceof JsonObject proxy) {
String host = proxy.getString("host");
Integer port = proxy.getInteger("port");
if (host != null && !host.isBlank() && port != null) {
builder.proxy(ProxySelector.of(new InetSocketAddress(host, port)));
String username = proxy.getString("username");
String password = proxy.getString("password", "");
if (username != null && !username.isBlank()) {
builder.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(username, password.toCharArray());
}
return null;
}
});
}
}
}
return builder.build();
}
@Override
public void close() {
try {
client.getClass().getMethod("close").invoke(client);
} catch (NoSuchMethodException ignored) {
// JDK 17 的 HttpClient 还不能关闭,连接会按空闲超时回收。
} catch (Exception ignored) {
// 关闭失败不影响解析结果。
}
}
static final class ShareTarget {
final String folderId;
final String fk;
final String typeId;
ShareTarget(String folderId, String fk, String typeId) {
this.folderId = folderId == null || folderId.isBlank() ? "0" : folderId;
this.fk = fk == null ? "" : fk;
this.typeId = typeId == null || typeId.isBlank() ? "0" : typeId;
}
static ShareTarget from(ShareLinkInfo info) {
String dirId = "";
if (info.getOtherParam() != null && info.getOtherParam().get("dirId") != null) {
dirId = decode(info.getOtherParam().get("dirId").toString().trim());
}
if (!dirId.isBlank()) {
String[] parts = dirId.split(":", 2);
return new ShareTarget(parts[0], parts.length > 1 ? parts[1] : "",
queryParam(info.getShareUrl(), "type_id"));
}
String shareUrl = info.getShareUrl();
String folderId = firstNonBlank(queryParam(shareUrl, "folder_id"), queryParam(shareUrl, "d"));
return new ShareTarget(folderId, queryParam(shareUrl, "fk"), queryParam(shareUrl, "type_id"));
}
}
static final class DirectLink {
final String url;
final Map<String, String> headers;
DirectLink(String url, Map<String, String> headers) {
this.url = url;
this.headers = headers;
}
}
enum Kind {
OK, NOT_FOUND, INVALID, NEED_PASSWORD, BAD_PASSWORD, TURNSTILE, ALTCHA, OTHER
}
static final class Decision {
final Kind kind;
final String ownerId;
final String accessPass;
final String message;
private Decision(Kind kind, String ownerId, String accessPass, String message) {
this.kind = kind;
this.ownerId = ownerId == null ? "" : ownerId;
this.accessPass = accessPass == null ? "" : accessPass;
this.message = message == null ? "" : message;
}
static Decision ok(String ownerId, String accessPass) {
return new Decision(Kind.OK, ownerId, accessPass, "");
}
static Decision of(Kind kind, String ownerId, String message) {
return new Decision(kind, ownerId, "", message);
}
}
static class CtfileException extends Exception {
CtfileException(String message) {
super(message);
}
}
static final class VerificationMismatch extends CtfileException {
VerificationMismatch(String message) {
super(message);
}
}
private static final class CachedPass {
final String token;
final long expiresAtMillis;
CachedPass(String token, long expiresAtMillis) {
this.token = token;
this.expiresAtMillis = expiresAtMillis;
}
}
}
@@ -0,0 +1,96 @@
package cn.qaiu.parser.impl;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class AltchaV2SolverTest {
private static final String NONCE = "00112233445566778899aabbccddeeff";
private static final String SALT = "0102030405060708090a0b0c0d0e0f10";
@Test
public void pbkdf2MatchesAltchaVector() {
byte[] password = password(NONCE, 7);
byte[] derived = AltchaV2Solver.pbkdf2(password, AltchaV2Solver.decodeHex(SALT, "salt"), 100, 32);
assertEquals("dce8b41d12bd8245a12f9fbca56d1d5db2924c1bfe02b924be69f6d89dc1721b",
AltchaV2Solver.toHex(derived));
}
@Test
public void productionCostMatchesCounterZero() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 0),
AltchaV2Solver.decodeHex(SALT, "salt"), 1200, 32);
assertEquals("c24bb34595d0df8688c53e6be3b63e4a0fb0f2d9f732b5c4daebc46fba958bf7",
AltchaV2Solver.toHex(derived));
}
@Test
public void solverFindsPrefixedCounterAndBuildsPayload() {
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 3),
AltchaV2Solver.decodeHex(SALT, "salt"), 50, 32);
String prefix = AltchaV2Solver.toHex(derived).substring(0, 8);
JsonObject challenge = challenge(50, prefix, "sig-test");
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge, 20, 5_000);
assertEquals(3, solution.counter);
assertTrue(solution.derivedKeyHex.startsWith(prefix));
JsonObject payload = new JsonObject(new String(Base64.getDecoder().decode(AltchaV2Solver.payload(challenge, solution))));
assertEquals("sig-test", payload.getJsonObject("challenge").getString("signature"));
assertEquals("PBKDF2/SHA-256", payload.getJsonObject("challenge").getJsonObject("parameters").getString("algorithm"));
assertEquals(3, payload.getJsonObject("solution").getInteger("counter").intValue());
assertEquals(solution.derivedKeyHex, payload.getJsonObject("solution").getString("derivedKey"));
}
@Test
public void impossiblePrefixStopsAtTheCounterCap() {
byte[] beyondCap = AltchaV2Solver.pbkdf2(password(NONCE, 40),
AltchaV2Solver.decodeHex(SALT, "salt"), 20, 32);
JsonObject challenge = challenge(20, AltchaV2Solver.toHex(beyondCap).substring(0, 8), "sig");
try {
AltchaV2Solver.solve(challenge, 8, 5_000);
fail("expected the search to stop");
} catch (IllegalStateException e) {
assertTrue(e.getMessage().contains("超时"));
}
}
@Test
public void rejectsCostAboveTheSafetyCap() {
JsonObject challenge = challenge(AltchaV2Solver.MAX_COST + 1, "00", "sig");
try {
AltchaV2Solver.solve(challenge, 1, 1_000);
fail("expected cost to be rejected");
} catch (IllegalArgumentException e) {
assertTrue(e.getMessage().contains("cost"));
}
}
private static JsonObject challenge(int cost, String keyPrefix, String signature) {
return new JsonObject()
.put("parameters", new JsonObject()
.put("algorithm", "PBKDF2/SHA-256")
.put("cost", cost)
.put("keyLength", 32)
.put("nonce", NONCE)
.put("salt", SALT)
.put("keyPrefix", keyPrefix))
.put("signature", signature);
}
private static byte[] password(String nonceHex, int counter) {
byte[] nonce = AltchaV2Solver.decodeHex(nonceHex, "nonce");
byte[] password = new byte[nonce.length + 4];
System.arraycopy(nonce, 0, password, 0, nonce.length);
password[nonce.length] = (byte) (counter >>> 24);
password[nonce.length + 1] = (byte) (counter >>> 16);
password[nonce.length + 2] = (byte) (counter >>> 8);
password[nonce.length + 3] = (byte) counter;
return password;
}
}
@@ -0,0 +1,177 @@
package cn.qaiu.parser.impl;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.ParserCreate;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Test;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* 城通真实联调。默认不跑:
* mvn -pl parser -DskipTests=false -Dctfile.live=true -Dtest=CtToolLiveTest test
*/
public class CtToolLiveTest {
private static final String FREE_FILE = "https://474b.com/file/4015376-131945810";
private static final String PASSWORD_FILE =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=7609";
private static final String PASSWORD_FILE_WITHOUT_PASSWORD =
"https://url94.ctfile.com/f/64115194-17569800420720-06c697";
private static final String PASSWORD_DIR =
"https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609&d=164803691&fk=decb36";
private static Vertx vertx;
@AfterClass
public static void tearDown() throws Exception {
CtfileSession.clearCachedPasses();
if (vertx != null) {
CtTool.shutdownWorkerExecutor();
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
}
}
@Test
public void freeFileDownloadsRealPdfBytes() throws Exception {
liveOnly();
CtTool tool = tool(FREE_FILE);
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
assertNotNull(info);
assertTrue(info.getFileName().endsWith(".pdf"));
assertTrue(info.getSize() > 1000);
assertTrue(url.startsWith("https://"));
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
HttpResponse<byte[]> head = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=0-15")
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
assertTrue("head status " + head.statusCode(), head.statusCode() == 206 || head.statusCode() == 200);
String magic = new String(head.body(), 0, Math.min(5, head.body().length), StandardCharsets.ISO_8859_1);
assertEquals("%PDF-", magic);
String range = head.headers().firstValue("content-range").orElse("");
String length = head.headers().firstValue("content-length").orElse("");
assertTrue(range.endsWith("/" + info.getSize()) || length.equals(String.valueOf(info.getSize()))
|| range.contains("/" + info.getSize()));
long size = info.getSize();
HttpResponse<byte[]> tail = client.send(HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(30))
.header("Range", "bytes=" + Math.max(0, size - 20) + "-" + (size - 1))
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
String ending = new String(tail.body(), StandardCharsets.ISO_8859_1);
assertTrue(ending.contains("%%EOF"));
}
@Test
public void sameSessionListsParentDirectory() throws Exception {
liveOnly();
ShareLinkInfo info = ParserCreate.fromShareUrl(FREE_FILE).getShareLinkInfo();
try (CtfileSession session = CtfileSession.open(info)) {
JsonObject resource = session.loadResource("file", info.getShareKey(),
CtfileSession.ShareTarget.from(info), "", "");
JsonObject file = CtfileSession.dataOf(resource).getJsonObject("file");
String fileDir = file.getString("file_dir", "");
int marker = fileDir.indexOf("/d/");
assertTrue(fileDir, marker >= 0);
String dirId = fileDir.substring(marker + 3);
int query = dirId.indexOf('?');
if (query >= 0) {
dirId = dirId.substring(0, query);
}
JsonObject listing = session.listing("dir", dirId, new CtfileSession.ShareTarget("0", "", "0"),
"", resource, 0, 20);
JsonArray rows = CtfileSession.rowsOf(listing);
assertTrue(rows.size() > 0);
ShareLinkInfo directory = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey(dirId)
.shareUrl("https://474b.com/d/" + dirId)
.build();
directory.getOtherParam().put("domainName", "https://nfd.example");
int named = 0;
for (int i = 0; i < rows.size(); i++) {
FileInfo item = CtTool.toFileInfo(rows.getJsonObject(i), directory);
if (item != null && item.getFileName() != null && !item.getFileName().isBlank()) {
named++;
assertNotNull(item.getParserUrl());
}
}
assertTrue(named > 0);
}
}
@Test
public void passwordShareIsTurnstileAndMissingShareIsNotFound() throws Exception {
liveOnly();
String withPassword = failure(tool(PASSWORD_FILE).parse());
assertTrue(withPassword, withPassword.contains("Turnstile"));
assertFalse(withPassword, withPassword.contains("密码不正确"));
assertFalse(withPassword, withPassword.contains("已过期"));
String withoutPassword = failure(tool(PASSWORD_FILE_WITHOUT_PASSWORD).parse());
assertTrue(withoutPassword, withoutPassword.contains("需要访问密码"));
CtTool directory = (CtTool) ParserCreate.fromShareUrl(PASSWORD_DIR).createTool();
String directoryFailure = failure(directory.parseFileList());
assertTrue(directoryFailure, directoryFailure.contains("Turnstile"));
String missingFile = failure(tool("https://474b.com/file/4015376-1").parse());
assertTrue(missingFile, missingFile.contains("不存在或已过期"));
String missingOwner = failure(tool("https://474b.com/file/0-0").parse());
assertTrue(missingOwner, missingOwner.contains("不存在或已过期"));
}
private static void liveOnly() {
Assume.assumeTrue("set -Dctfile.live=true to call ctfile", Boolean.getBoolean("ctfile.live"));
if (vertx == null) {
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
}
private static CtTool tool(String url) {
return (CtTool) ParserCreate.fromShareUrl(url).createTool();
}
private static String failure(io.vertx.core.Future<?> future) throws Exception {
try {
future.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
return "";
} catch (Exception e) {
Throwable current = e;
StringBuilder message = new StringBuilder();
while (current != null) {
if (current.getMessage() != null) {
message.append(current.getMessage()).append('\n');
}
current = current.getCause();
}
if (message.length() == 0) {
throw e;
}
return message.toString();
}
}
}
@@ -0,0 +1,134 @@
package cn.qaiu.parser.impl;
import cn.qaiu.entity.FileInfo;
import cn.qaiu.entity.ShareLinkInfo;
import cn.qaiu.parser.impl.CtfileSession.Decision;
import cn.qaiu.parser.impl.CtfileSession.Kind;
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class CtfileResponseTest {
@Test
public void classifiesNotFoundInvalidPasswordAndCaptcha() {
Decision missing = CtfileSession.classify(json(404, null, "File was not found."), 404, "");
assertEquals(Kind.NOT_FOUND, missing.kind);
assertTrue(missing.message.contains("不存在或已过期"));
assertFalse(missing.message.contains("密码"));
Decision unsigned = CtfileSession.classify(json(403, null, "Unsigned file link is not accepted."), 403, "");
assertEquals(Kind.INVALID, unsigned.kind);
Decision needPassword = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"captcha_type\":\"turnstile\",\"capabilities\":{\"passcodeRequired\":true}},"
+ "\"msg\":\"Share passcode is required.\"}"), 423, "");
assertEquals(Kind.NEED_PASSWORD, needPassword.kind);
assertTrue(needPassword.message.contains("需要访问密码"));
Decision wrong = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"incorrect\"}"), 423, "7609");
assertEquals(Kind.BAD_PASSWORD, wrong.kind);
Decision turnstile = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
+ "\"capabilities\":{\"passcodeRequired\":true,\"ownerId\":64115194}},"
+ "\"msg\":\"Share passcode needs a new human check.\"}"), 423, "7609");
assertEquals(Kind.TURNSTILE, turnstile.kind);
assertEquals("64115194", turnstile.ownerId);
assertTrue(turnstile.message.contains("Turnstile"));
assertFalse(turnstile.message.contains("密码"));
Decision altcha = CtfileSession.classify(new JsonObject(
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"altcha\","
+ "\"capabilities\":{\"passcodeRequired\":false,\"ownerId\":4015376}},"
+ "\"msg\":\"Share access needs a human check.\"}"), 423, "");
assertEquals(Kind.ALTCHA, altcha.kind);
assertEquals("4015376", altcha.ownerId);
Decision ok = CtfileSession.classify(new JsonObject(
"{\"code\":200,\"data\":{\"access_pass\":\"v1.aaa.bbb\",\"capabilities\":{\"ownerId\":4015376}}}"), 200, "");
assertEquals(Kind.OK, ok.kind);
assertEquals("v1.aaa.bbb", ok.accessPass);
}
@Test
public void resourceQueryKeepsTokensAndEncodesThem() {
Map<String, String> query = CtfileSession.resourceQuery("file", "4015376-131945810",
new ShareTarget("0", "", "0"), "7609", "a+b/c=", "turn stile", "v1.aaa.bbb");
String form = CtfileSession.form(query);
assertTrue(form.contains("kind=file"));
assertTrue(form.contains("passcode=7609"));
assertTrue(form.contains("altcha_token=a%2Bb%2Fc%3D"));
assertTrue(form.contains("turnstile_token=turn+stile") || form.contains("turnstile_token=turn%20stile"));
assertTrue(form.contains("access_pass=v1.aaa.bbb"));
}
@Test
public void listingRowBecomesFileAndFolderLinks() {
ShareLinkInfo info = ShareLinkInfo.newBuilder()
.type("ctd")
.panName("城通网盘-目录")
.shareKey("64115194-164803691-48508c")
.sharePassword("7609")
.shareUrl("https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609")
.build();
info.getOtherParam().put("domainName", "https://nfd.example");
FileInfo folder = CtTool.toFileInfo(new JsonObject()
.put("kind", "folder")
.put("name", "2022")
.put("folderId", 54597713)
.put("folderKey", "bf0603")
.put("date", "2023-02-22"), info);
assertEquals("folder", folder.getFileType());
assertTrue(folder.getParserUrl().contains("dirId="));
assertTrue(folder.getParserUrl().contains("54597713"));
assertTrue(folder.getParserUrl().contains("pwd=7609"));
FileInfo file = CtTool.toFileInfo(new JsonObject()
.put("kind", "file")
.put("name", "notes.pdf")
.put("href", "#/f/t-token")
.put("fileId", 415670738)
.put("extension", "pdf")
.put("size", "1 MB")
.put("size_bytes", 1048576)
.put("date", "2019-12-31"), info);
assertEquals("t-token", fileId(file));
assertEquals(Long.valueOf(1048576L), file.getSize());
assertEquals("pdf", file.getFileType());
assertTrue(file.getParserUrl().startsWith("https://nfd.example/v2/redirectUrl/ctd/"));
}
private static JsonObject json(int code, JsonObject data, String message) {
JsonObject body = new JsonObject().put("code", code).put("msg", message);
if (data != null) {
body.put("data", data);
}
return body;
}
private static String fileId(FileInfo file) {
String url = file.getParserUrl();
String encoded = url.substring(url.lastIndexOf('/') + 1);
return new JsonObject(decodeUrlBase64(encoded)).getString("id");
}
private static String decodeUrlBase64(String value) {
String padded = value;
int mod = padded.length() % 4;
if (mod != 0) {
padded += "=".repeat(4 - mod);
}
byte[] bytes = java.util.Base64.getUrlDecoder().decode(padded);
return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
}
}
@@ -54,6 +54,7 @@ public class AppMain {
deploy.addPostShutdownTask(cn.qaiu.parser.PanBase::shutdownSharedClients);
deploy.addPostShutdownTask(cn.qaiu.parser.IPanTool::shutdownCloseAfterScheduler);
deploy.addPostShutdownTask(cn.qaiu.parser.impl.PodTool::shutdownWorkerExecutor);
deploy.addPostShutdownTask(cn.qaiu.parser.impl.CtTool::shutdownWorkerExecutor);
// start
deploy.start(args, AppMain::exec);
}