cfprobe 0.1.0

Cloudflare reverse proxy and CDN detection engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::net::{IpAddr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures::StreamExt;

use reqwest::{
    Client,
    header::{ACCEPT, ACCEPT_ENCODING, HOST, HeaderName, HeaderValue, LOCATION, USER_AGENT},
    redirect,
};

use serde::{Deserialize, Serialize};

use crate::{error::CfProbeError, probe::Target};

use super::model::{
    CloudflareHttpSignals, HttpDetection, HttpHeader, HttpProbeStatus, format_http_version,
};

/// 目标协议 scheme。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HttpScheme {
    /// 明文 HTTP(通常端口 80)。
    Http,
    /// TLS 加密 HTTPS(通常端口 443)。
    Https,
}

impl HttpScheme {
    /// 返回 scheme 字符串("http" / "https")。
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Http => "http",
            Self::Https => "https",
        }
    }

    /// scheme 对应的默认端口。
    pub fn default_port(&self) -> u16 {
        match self {
            Self::Http => 80,
            Self::Https => 443,
        }
    }
}

/// HTTP 探测器配置。
#[derive(Debug, Clone)]
pub struct HttpProbeConfig {
    /// 默认使用的 scheme(HTTP 或 HTTPS)。
    pub scheme: HttpScheme,

    /// 默认探测端口。
    pub port: u16,

    /// 整次请求(含读取响应体前缀)的超时。
    pub timeout: Duration,

    /// TCP 连接建立的超时。
    pub connect_timeout: Duration,

    /// 最多读取的响应体字节数(防止大响应阻塞)。
    pub max_body_bytes: u64,

    /// 是否跟随 `Location` 重定向。
    pub follow_redirects: bool,

    /// 最多跟随的重定向次数。
    pub max_redirects: usize,

    /// 是否接受无效证书(自签、过期等)。
    pub accept_invalid_certs: bool,

    /// 是否接受证书 SAN / CN 与 hostname 不匹配。
    pub accept_invalid_hostnames: bool,

    /// 请求 User-Agent。
    pub user_agent: String,

    /// 单个 Header Value 允许的最大字节数。
    pub max_header_value_bytes: usize,

    /// 内部允许缓存的 reqwest Client 数量。
    pub max_cached_clients: usize,

    /// 连接池中连接空闲超时。
    pub pool_idle_timeout: Duration,

    /// 每个 host 允许保留的最大空闲连接数。
    pub pool_max_idle_per_host: usize,
}

impl Default for HttpProbeConfig {
    fn default() -> Self {
        Self {
            scheme: HttpScheme::Https,

            port: 443,

            timeout: Duration::from_secs(10),

            connect_timeout: Duration::from_secs(5),

            max_body_bytes: 1024 * 1024,

            follow_redirects: false,

            max_redirects: 1,

            accept_invalid_certs: true,

            accept_invalid_hostnames: true,

            user_agent: "cfprobe/0.1".to_string(),

            max_header_value_bytes: 4096,

            max_cached_clients: 64,

            pool_idle_timeout: Duration::from_secs(90),

            pool_max_idle_per_host: 4,
        }
    }
}

#[derive(Debug, Clone, Eq)]
struct HttpClientKey {
    ip: IpAddr,

    hostname: String,

    scheme: HttpScheme,

    port: u16,
}

impl PartialEq for HttpClientKey {
    fn eq(&self, other: &Self) -> bool {
        self.ip == other.ip
            && self.hostname == other.hostname
            && self.scheme == other.scheme
            && self.port == other.port
    }
}

impl Hash for HttpClientKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ip.hash(state);

        self.hostname.hash(state);

        self.scheme.hash(state);

        self.port.hash(state);
    }
}

/// HTTP 探测器。
///
/// 内部会按 `(ip, hostname, scheme, port)` 缓存 reqwest `Client`,
/// 以复用 TCP/TLS 连接池。
#[derive(Clone)]
pub struct HttpProber {
    config: HttpProbeConfig,

    clients: Arc<Mutex<HashMap<HttpClientKey, Client>>>,
}

impl HttpProber {
    /// 根据配置创建 HttpProber,参数不合法时返回错误。
    pub fn new(config: HttpProbeConfig) -> Result<Self, CfProbeError> {
        if config.port == 0 {
            return Err(CfProbeError::InvalidResponse(
                "HTTP port cannot be 0".to_string(),
            ));
        }

        if config.max_body_bytes == 0 {
            return Err(CfProbeError::InvalidResponse(
                "max_body_bytes cannot be 0".to_string(),
            ));
        }

        if config.connect_timeout > config.timeout {
            return Err(CfProbeError::InvalidResponse(
                "connect_timeout cannot be greater than timeout".to_string(),
            ));
        }

        if config.max_cached_clients == 0 {
            return Err(CfProbeError::InvalidResponse(
                "max_cached_clients cannot be 0".to_string(),
            ));
        }

        if config.pool_max_idle_per_host == 0 {
            return Err(CfProbeError::InvalidResponse(
                "pool_max_idle_per_host cannot be 0".to_string(),
            ));
        }

        Ok(Self {
            config,

            clients: Arc::new(Mutex::new(HashMap::new())),
        })
    }

    /// 获取当前配置。
    pub fn config(&self) -> &HttpProbeConfig {
        &self.config
    }

    /// 当前已缓存的 reqwest Client 数量(用于观测连接池大小)。
    pub fn cached_client_count(&self) -> usize {
        self.clients.lock().map(|cache| cache.len()).unwrap_or(0)
    }

    /// 使用配置中的默认 scheme 和端口探测目标。
    pub async fn probe(&self, ip: IpAddr, hostname: &str) -> Result<HttpDetection, CfProbeError> {
        self.probe_with_target_params(ip, hostname, self.config.scheme, self.config.port)
            .await
    }

    pub async fn probe_target(&self, target: &Target) -> Result<HttpDetection, CfProbeError> {
        target.validate()?;

        self.probe_with_target_params(target.ip, &target.hostname, target.scheme, target.port)
            .await
    }

    pub async fn probe_with_target_params(
        &self,
        ip: IpAddr,
        hostname: &str,
        scheme: HttpScheme,
        port: u16,
    ) -> Result<HttpDetection, CfProbeError> {
        if port == 0 {
            return Err(CfProbeError::InvalidResponse(
                "HTTP port cannot be 0".to_string(),
            ));
        }

        let hostname = normalize_hostname(hostname)?;

        let url = build_url(scheme, &hostname, port);

        let client = self.get_or_create_client(&hostname, ip, scheme, port)?;

        let host_header = build_host_header(&hostname, scheme, port);

        let response = client
            .get(&url)
            .header(
                HOST,
                HeaderValue::from_str(&host_header).map_err(|error| {
                    CfProbeError::InvalidResponse(format!("invalid Host header: {error}"))
                })?,
            )
            .header(USER_AGENT, self.config.user_agent.clone())
            .header(ACCEPT, "*/*")
            .header(ACCEPT_ENCODING, "identity")
            .send()
            .await;

        let response = match response {
            Ok(response) => response,

            Err(error) => {
                return Ok(HttpDetection::failed(
                    ip,
                    hostname,
                    port,
                    url,
                    format!("HTTP request failed: {error}"),
                ));
            }
        };

        let status_code = response.status().as_u16();

        let http_version = format_http_version(response.version());

        let final_url = response.url().to_string();

        let headers = collect_headers(response.headers(), self.config.max_header_value_bytes);

        let signals =
            collect_cloudflare_signals(response.headers(), self.config.max_header_value_bytes);

        let content_type = header_string(
            response.headers(),
            "content-type",
            self.config.max_header_value_bytes,
        );

        let content_length = response.content_length();

        let redirect_location = header_string(
            response.headers(),
            LOCATION.as_str(),
            self.config.max_header_value_bytes,
        );

        let (body_bytes_read, body_truncated) =
            read_limited_body(response, self.config.max_body_bytes).await;

        let status = if body_truncated {
            HttpProbeStatus::ResponseBodyLimitReached
        } else {
            HttpProbeStatus::ResponseReceived
        };

        Ok(HttpDetection {
            ip,
            hostname,
            port,
            url,
            final_url: Some(final_url),
            status_code: Some(status_code),
            http_version: Some(http_version),
            status,
            headers,
            signals,
            content_type,
            content_length,
            body_bytes_read,
            body_truncated,
            redirect_location,
            error: None,
        })
    }

    fn get_or_create_client(
        &self,
        hostname: &str,
        ip: IpAddr,
        scheme: HttpScheme,
        port: u16,
    ) -> Result<Client, CfProbeError> {
        let key = HttpClientKey {
            ip,
            hostname: hostname.to_string(),
            scheme,
            port,
        };

        {
            let cache = self.clients.lock().map_err(|_| {
                CfProbeError::InvalidResponse("HTTP client cache mutex poisoned".to_string())
            })?;

            if let Some(client) = cache.get(&key) {
                return Ok(client.clone());
            }
        }

        let socket_addr = SocketAddr::new(ip, port);

        let client = self.build_client(hostname, socket_addr)?;

        let mut cache = self.clients.lock().map_err(|_| {
            CfProbeError::InvalidResponse("HTTP client cache mutex poisoned".to_string())
        })?;

        if let Some(existing) = cache.get(&key) {
            return Ok(existing.clone());
        }

        if cache.len() >= self.config.max_cached_clients {
            cache.clear();
        }

        cache.insert(key, client.clone());

        Ok(client)
    }

    fn build_client(
        &self,
        hostname: &str,
        socket_addr: SocketAddr,
    ) -> Result<Client, CfProbeError> {
        crate::init_rustls_crypto();

        let client = reqwest::Client::builder()
            .no_proxy()
            .user_agent(self.config.user_agent.clone())
            .connect_timeout(self.config.connect_timeout)
            .timeout(self.config.timeout)
            .pool_idle_timeout(self.config.pool_idle_timeout)
            .pool_max_idle_per_host(self.config.pool_max_idle_per_host)
            .resolve(hostname, socket_addr)
            .danger_accept_invalid_certs(self.config.accept_invalid_certs)
            .danger_accept_invalid_hostnames(self.config.accept_invalid_hostnames)
            .redirect(if self.config.follow_redirects {
                redirect::Policy::limited(self.config.max_redirects)
            } else {
                redirect::Policy::none()
            })
            .build()
            .map_err(|error| {
                CfProbeError::InvalidResponse(format!("failed to build HTTP client: {error}"))
            })?;

        Ok(client)
    }
}

fn normalize_hostname(hostname: &str) -> Result<String, CfProbeError> {
    let hostname = hostname.trim();

    if hostname.is_empty() {
        return Err(CfProbeError::Dns {
            message: "hostname is empty".to_string(),
        });
    }

    let hostname = hostname.trim_end_matches('.');

    if hostname.is_empty() {
        return Err(CfProbeError::Dns {
            message: "hostname is empty".to_string(),
        });
    }

    hickory_resolver::proto::rr::Name::from_utf8(&format!("{hostname}.")).map_err(|error| {
        CfProbeError::Dns {
            message: format!("invalid hostname `{hostname}`: {error}"),
        }
    })?;

    Ok(hostname.to_ascii_lowercase())
}

fn build_url(scheme: HttpScheme, hostname: &str, port: u16) -> String {
    let default_port = scheme.default_port();

    if port == default_port {
        format!("{}://{}/", scheme.as_str(), hostname,)
    } else {
        format!("{}://{}:{}/", scheme.as_str(), hostname, port,)
    }
}

fn build_host_header(hostname: &str, scheme: HttpScheme, port: u16) -> String {
    if port == scheme.default_port() {
        hostname.to_string()
    } else {
        format!("{}:{}", hostname, port,)
    }
}

fn collect_headers(
    headers: &reqwest::header::HeaderMap,
    max_value_bytes: usize,
) -> Vec<HttpHeader> {
    headers
        .iter()
        .filter_map(|(name, value)| {
            let value = value.to_str().ok()?;

            Some(HttpHeader {
                name: name.as_str().to_string(),
                value: truncate_header_value(value, max_value_bytes),
            })
        })
        .collect()
}

fn collect_cloudflare_signals(
    headers: &reqwest::header::HeaderMap,
    max_value_bytes: usize,
) -> CloudflareHttpSignals {
    let server = header_string(headers, "server", max_value_bytes);

    let server_cloudflare = server
        .as_deref()
        .map(|value| value.to_ascii_lowercase().contains("cloudflare"))
        .unwrap_or(false);

    CloudflareHttpSignals {
        cf_ray: header_string(headers, "cf-ray", max_value_bytes),

        cf_cache_status: header_string(headers, "cf-cache-status", max_value_bytes),

        server,

        server_cloudflare,

        cf_connecting_ip: header_string(headers, "cf-connecting-ip", max_value_bytes),

        cf_ip_country: header_string(headers, "cf-ipcountry", max_value_bytes),

        age: header_string(headers, "age", max_value_bytes),

        via: header_string(headers, "via", max_value_bytes),

        cdn_cache_control: header_string(headers, "cdn-cache-control", max_value_bytes),

        cf_mitigated: header_string(headers, "cf-mitigated", max_value_bytes),
    }
}

fn header_string(
    headers: &reqwest::header::HeaderMap,
    name: &str,
    max_value_bytes: usize,
) -> Option<String> {
    let name = HeaderName::from_bytes(name.as_bytes()).ok()?;

    let value = headers.get(name)?.to_str().ok()?;

    Some(truncate_header_value(value, max_value_bytes))
}

fn truncate_header_value(value: &str, max_bytes: usize) -> String {
    if value.len() <= max_bytes {
        return value.to_string();
    }

    let mut end = max_bytes.min(value.len());

    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }

    let mut result = value[..end].to_string();

    result.push_str("...[truncated]");

    result
}

async fn read_limited_body(response: reqwest::Response, max_body_bytes: u64) -> (u64, bool) {
    let mut stream = response.bytes_stream();

    let mut total = 0u64;

    while let Some(chunk_result) = stream.next().await {
        let Ok(chunk) = chunk_result else {
            break;
        };

        total = total.saturating_add(chunk.len() as u64);

        if total >= max_body_bytes {
            return (max_body_bytes, true);
        }
    }

    (total.min(max_body_bytes), false)
}