idoh 0.2.6

Async DoH client for Rust / Rust 异步 DoH 客户端
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
[English]#en | [中文]#zh

---

<a id="en"></a>

# idoh : Async DoH Client for Rust

## Table of Contents

- [Introduction]#introduction
- [Features]#features
- [Usage]#usage
- [Design]#design
- [API Reference]#api-reference
- [Tech Stack]#tech-stack
- [Directory Structure]#directory-structure
- [History]#history
- [About]#about

## Introduction

`idoh` is an async Rust library for DNS over HTTPS (DoH) resolution.

Built on [idns](https://crates.io/crates/idns), which provides `DnsRace`, `Cache`, `Parse` trait, and more.

## Features

- Multiple DoH providers (Tencent, Google, Cloudflare, DNS.SB, 360, NextDNS, AliDNS)
- Simple API with direct DNS answer access
- Async/await based on `tokio`
- Robust error handling for provider failures
- Optional static initialization for global DoH client
- Strong type safety

## Usage

Add to `Cargo.toml`:

```toml
[dependencies]
idoh = "0.2"
idns = "0.2"
```

### Basic Query

```rust
use idns::QType;
use idoh::Doh;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let doh = Doh::new("dns.google/resolve");
  let answers = doh.query("google.com", QType::A).await?;

  if let Some(answers) = answers {
    for answer in answers {
      println!("IP: {}", answer.val);
    }
  }
  Ok(())
}
```

### TXT Record Lookup

```rust
use idns::QType;
use idoh::Doh;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let doh = Doh::new("dns.google/resolve");
  let answers = doh.query("qq.com", QType::TXT).await?;

  if let Some(answers) = answers {
    for answer in answers {
      if answer.val.starts_with("v=spf1") {
        println!("SPF: {}", answer.val);
      }
    }
  }
  Ok(())
}
```

### DnsRace + Cache (Recommended)

Race multiple DoH servers and cache results:

```rust
use idoh::{DOH_LI, doh_li};
use idns::{Cache, DnsRace, Mx, Query};
use std::time::Instant;

#[tokio::main]
async fn main() {
  let race = DnsRace::new(doh_li(DOH_LI));
  let cache: Cache<Mx> = Cache::new(60); // 60s TTL

  // First query (cache miss)
  let t1 = Instant::now();
  let r1 = cache.query(&race, "gmail.com").await;
  let d1 = t1.elapsed();
  println!("First: {}ms", d1.as_millis());
  if let Some(mx_list) = &*r1.unwrap() {
    for mx in mx_list {
      println!("  {} {}", mx.priority, mx.server);
    }
  }

  // Second query (cache hit)
  let t2 = Instant::now();
  let _ = cache.query(&race, "gmail.com").await;
  let d2 = t2.elapsed();
  println!("Cache: {}μs", d2.as_micros());
}
```

Output:

```
First: 744ms
  5 gmail-smtp-in.l.google.com
  10 alt1.gmail-smtp-in.l.google.com
  20 alt2.gmail-smtp-in.l.google.com
  30 alt3.gmail-smtp-in.l.google.com
  40 alt4.gmail-smtp-in.l.google.com
Cache: 1μs
```

### Performance

| Operation | Time | Notes |
|-----------|------|-------|
| Network Lookup | ~744 ms | Depends on provider latency |
| Cache Lookup | ~1.8 µs | Zero-copy, >400,000x faster |

## Design

`idoh` prioritizes latency minimization through concurrent queries to multiple DoH providers. The first valid response wins, mitigating network jitter and single-provider slowness.

### Call Flow

```mermaid
graph TD
  A[User: doh.query] --> B[Doh::query]
  B --> C[Build URL with name & qtype]
  C --> D[ireq::req HTTP GET]
  D --> E[DoH Server]
  E --> F[JSON Response]
  F --> G[serde_json::from_slice]
  G --> H{Status == 0?}
  H -- Yes --> I[Parse Answer array]
  H -- No --> J[Return None]
  I --> K[Convert DnsAnswer to Answer]
  K --> L[Return Ok Some Vec Answer]
```

### With DnsRace (idns)

```mermaid
graph TD
  A[User: race.answer_li] --> B[DnsRace::answer_li]
  B --> C[Spawn concurrent tasks]
  C --> D[Doh 1: query]
  C --> E[Doh 2: query]
  C --> F[Doh N: query]
  D --> G[Channel]
  E --> G
  F --> G
  G --> H[First Success]
  H --> I[Cancel pending]
  I --> J[Return Result]
```

## API Reference

### Struct: Doh

DoH client for DNS resolution.

```rust
pub struct Doh {
  pub url: String,
}

impl Doh {
  pub fn new(url: impl Into<String>) -> Self;
  pub async fn query(&self, name: &str, qtype: QType) -> Result<Option<Vec<Answer>>>;
}
```

Implements `idns::Query` trait for integration with `DnsRace` and `Cache`.

### Struct: Answer (from idns)

DNS answer record.

```rust
pub struct Answer {
  pub name: String,
  pub type_id: u16,
  pub ttl: u32,
  pub val: String,
}
```

### Enum: Error

```rust
pub enum Error {
  Http(ireq::Error),
  Json(serde_json::Error),
}
```

### Function: doh_li

Create DoH clients from URL list.

```rust
pub fn doh_li(li: &[&str]) -> Vec<Doh>
```

### Constant: DOH_LI

Pre-configured DoH provider URLs:

```rust
pub static DOH_LI: &[&str] = &[
  "doh.pub/resolve",              // Tencent
  "dns.google/resolve",           // Google
  "cloudflare-dns.com/dns-query", // Cloudflare
  "doh.sb/dns-query",             // DNS.SB
  "doh.360.cn/resolve",           // 360
  "dns.nextdns.io",               // NextDNS
  "dns.alidns.com/resolve",       // AliDNS
];
```

### Static: DOH (feature = "static")

Global `DnsRace<Doh>` instance for convenient access.

```rust
pub static DOH: idns::DnsRace<Doh>
```

## Tech Stack

| Component | Crate | Purpose |
|-----------|-------|---------|
| Runtime | tokio | Async execution |
| HTTP | ireq | Lightweight client with proxy support |
| JSON | serde_json | Response parsing |
| Error | thiserror | Error handling |
| Static Init | static_init | Optional global client |

## Directory Structure

```
├── src/
│   ├── lib.rs      # Module exports, Doh struct, DOH_LI constant
│   └── error.rs    # Error and Result types
├── tests/
│   └── main.rs     # Integration tests
├── Cargo.toml
└── readme/
    ├── en.md       # English documentation
    └── zh.md       # Chinese documentation
```

## History

DNS, the phonebook of the Internet, was designed in the 1980s without encryption. Every website visit leaked destinations in plaintext.

In 2018, IETF standardized DNS over HTTPS (RFC 8484). By wrapping DNS queries in encrypted HTTPS traffic, DoH prevents eavesdropping and manipulation.

Paul Mockapetris invented DNS in 1983 (RFC 882/883). He later reflected that security was not considered because "the Internet was a friendly place." Thirty-five years later, DoH finally addressed this oversight.

The name "idoh" follows the naming convention of the js0.site project: "i" prefix + functionality. Here, "doh" represents DNS over HTTPS.

---

## About

This project is part of [js0.site · Refactoring the Internet Plan](https://js0.site).

- [Google Group]https://groups.google.com/g/js0-site
- [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social

---

## About

This project is an open-source component of [js0.site ⋅ Refactoring the Internet Plan](https://js0.site).

We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:

* [Google Group]https://groups.google.com/g/js0-site
* [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social

---

<a id="zh"></a>

# idoh : Rust 异步 DoH 客户端

## 目录

- [简介]#简介
- [特性]#特性
- [使用]#使用
- [设计]#设计
- [API 参考]#api-参考
- [技术栈]#技术栈
- [目录结构]#目录结构
- [历史]#历史
- [关于]#关于

## 简介

`idoh` 是 Rust 异步 DNS over HTTPS (DoH) 解析库。

基于 [idns](https://crates.io/crates/idns) 构建,idns 提供 `DnsRace`、`Cache`、`Parse` trait 等功能。

## 特性

- 多 DoH 提供商支持(腾讯、Google、Cloudflare、DNS.SB、360、NextDNS、阿里)
- 简洁 API,直接返回 DNS 应答
- 基于 `tokio` 的异步设计
- 健壮的错误处理
- 可选静态初始化全局客户端
- 强类型安全

## 使用

添加到 `Cargo.toml`:

```toml
[dependencies]
idoh = "0.2"
idns = "0.2"
```

### 基础查询

```rust
use idns::QType;
use idoh::Doh;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let doh = Doh::new("dns.google/resolve");
  let answers = doh.query("google.com", QType::A).await?;

  if let Some(answers) = answers {
    for answer in answers {
      println!("IP: {}", answer.val);
    }
  }
  Ok(())
}
```

### TXT 记录查询

```rust
use idns::QType;
use idoh::Doh;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let doh = Doh::new("dns.google/resolve");
  let answers = doh.query("qq.com", QType::TXT).await?;

  if let Some(answers) = answers {
    for answer in answers {
      if answer.val.starts_with("v=spf1") {
        println!("SPF: {}", answer.val);
      }
    }
  }
  Ok(())
}
```

### DnsRace + Cache(推荐)

竞速查询多 DoH 服务器并缓存结果:

```rust
use idoh::{DOH_LI, doh_li};
use idns::{Cache, DnsRace, Mx, Query};
use std::time::Instant;

#[tokio::main]
async fn main() {
  let race = DnsRace::new(doh_li(DOH_LI));
  let cache: Cache<Mx> = Cache::new(60); // 60 秒 TTL

  // 首次查询(缓存未命中)
  let t1 = Instant::now();
  let r1 = cache.query(&race, "gmail.com").await;
  let d1 = t1.elapsed();
  println!("首次: {}ms", d1.as_millis());
  if let Some(mx_list) = &*r1.unwrap() {
    for mx in mx_list {
      println!("  {} {}", mx.priority, mx.server);
    }
  }

  // 再次查询(缓存命中)
  let t2 = Instant::now();
  let _ = cache.query(&race, "gmail.com").await;
  let d2 = t2.elapsed();
  println!("缓存: {}μs", d2.as_micros());
}
```

输出:

```
首次: 744ms
  5 gmail-smtp-in.l.google.com
  10 alt1.gmail-smtp-in.l.google.com
  20 alt2.gmail-smtp-in.l.google.com
  30 alt3.gmail-smtp-in.l.google.com
  40 alt4.gmail-smtp-in.l.google.com
缓存: 1μs
```

### 性能

| 操作 | 耗时 | 说明 |
|------|------|------|
| 网络查询 | ~744 ms | 取决于提供商延迟 |
| 缓存查询 | ~1.8 µs | 零拷贝,快 40 万倍以上 |

## 设计

`idoh` 通过并发查询多 DoH 提供商实现延迟最小化。首个有效响应胜出,规避网络抖动和单点故障。

### 调用流程

```mermaid
graph TD
  A[用户: doh.query] --> B[Doh::query]
  B --> C[构建 URL: name + qtype]
  C --> D[ireq::req HTTP GET]
  D --> E[DoH 服务器]
  E --> F[JSON 响应]
  F --> G[serde_json::from_slice]
  G --> H{Status == 0?}
  H -- 是 --> I[解析 Answer 数组]
  H -- 否 --> J[返回 None]
  I --> K[DnsAnswer 转 Answer]
  K --> L[返回 Ok Some Vec Answer]
```

### 配合 DnsRace (idns)

```mermaid
graph TD
  A[用户: race.answer_li] --> B[DnsRace::answer_li]
  B --> C[启动并发任务]
  C --> D[Doh 1: query]
  C --> E[Doh 2: query]
  C --> F[Doh N: query]
  D --> G[通道]
  E --> G
  F --> G
  G --> H[首个成功]
  H --> I[取消待处理]
  I --> J[返回结果]
```

## API 参考

### 结构体: Doh

DoH 客户端。

```rust
pub struct Doh {
  pub url: String,
}

impl Doh {
  pub fn new(url: impl Into<String>) -> Self;
  pub async fn query(&self, name: &str, qtype: QType) -> Result<Option<Vec<Answer>>>;
}
```

实现 `idns::Query` trait,可与 `DnsRace`、`Cache` 集成。

### 结构体: Answer (来自 idns)

DNS 应答记录。

```rust
pub struct Answer {
  pub name: String,
  pub type_id: u16,
  pub ttl: u32,
  pub val: String,
}
```

### 枚举: Error

```rust
pub enum Error {
  Http(ireq::Error),
  Json(serde_json::Error),
}
```

### 函数: doh_li

从 URL 列表创建 DoH 客户端。

```rust
pub fn doh_li(li: &[&str]) -> Vec<Doh>
```

### 常量: DOH_LI

预配置 DoH 提供商 URL:

```rust
pub static DOH_LI: &[&str] = &[
  "doh.pub/resolve",              // 腾讯
  "dns.google/resolve",           // Google
  "cloudflare-dns.com/dns-query", // Cloudflare
  "doh.sb/dns-query",             // DNS.SB
  "doh.360.cn/resolve",           // 360
  "dns.nextdns.io",               // NextDNS
  "dns.alidns.com/resolve",       // 阿里
];
```

### 静态变量: DOH (feature = "static")

全局 `DnsRace<Doh>` 实例。

```rust
pub static DOH: idns::DnsRace<Doh>
```

## 技术栈

| 组件 | Crate | 用途 |
|------|-------|------|
| 运行时 | tokio | 异步执行 |
| HTTP | ireq | 轻量客户端,支持代理 |
| JSON | serde_json | 响应解析 |
| 错误 | thiserror | 错误处理 |
| 静态初始化 | static_init | 可选全局客户端 |

## 目录结构

```
├── src/
│   ├── lib.rs      # 模块导出、Doh 结构体、DOH_LI 常量
│   └── error.rs    # Error 和 Result 类型
├── tests/
│   └── main.rs     # 集成测试
├── Cargo.toml
└── readme/
    ├── en.md       # 英文文档
    └── zh.md       # 中文文档
```

## 历史

DNS 作为互联网电话簿,设计于 1980 年代,未考虑加密。每次网站访问都明文暴露目的地。

2018 年,IETF 标准化 DNS over HTTPS (RFC 8484)。通过将 DNS 查询封装在加密 HTTPS 流量中,DoH 防止窃听和篡改。

Paul Mockapetris 于 1983 年发明 DNS (RFC 882/883)。他后来回忆,当时未考虑安全是因为"互联网是友好的地方"。三十五年后,DoH 终于弥补了这一疏漏。

"idoh" 命名遵循 js0.site 项目惯例:"i" 前缀 + 功能。此处 "doh" 代表 DNS over HTTPS。

---

## 关于

本项目为 [js0.site · 重构互联网计划](https://js0.site) 开源组件。

- [谷歌邮件列表]https://groups.google.com/g/js0-site
- [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social

---

## 关于

本项目为 [js0.site ⋅ 重构互联网计划](https://js0.site) 的开源组件。

我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注:

* [谷歌邮件列表]https://groups.google.com/g/js0-site
* [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social