lazydns 0.2.63

A light and fast DNS server/forwarder implementation in Rust
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
# Domain Matching Rules Guide

## Overview

The Domain Set plugin in lazydns supports sophisticated domain name matching with multiple rule types and priority-based evaluation. This document describes the complete domain matching rule system.

## Quick Start

### Basic Examples

```yaml
# Load a domain list file with default (domain) matching
- name: domain_set
  tag: direct
  args:
    files:
      - direct-list.txt

# With specific match type
- name: domain_set
  tag: gfw
  args:
    files:
      - gfw-list.txt
    default_match_type: domain
    auto_reload: true
```

### Rule Formats in Files

```
# Comments start with #
# This is a comment

# Exact match only
full:google.com

# Domain match (default)
domain:example.com
example.com              # No prefix = uses default_match_type

# Keyword substring match
keyword:facebook

# Regular expression match
regexp:.*\.google\.com$

# Empty lines are ignored

```

## Match Types

### 1. Full Match (`full:`)

**Exact domain matching only, no subdomains.**

- Syntax: `full:example.com`
- Matches: `example.com`, `EXAMPLE.COM` (case-insensitive)
- Does NOT match: `www.example.com`, `sub.example.com`, `example.com.hk`
- Performance: **O(1)** - constant time lookup
- Use case: Block specific exact domains, whitelist specific services

#### Examples

```
full:google.com         → matches only "google.com"
full:api.github.com     → matches only "api.github.com"
                        → does NOT match "github.com" or "www.api.github.com"
```

### 2. Domain Match (`domain:`)

**Match domain and all its subdomains.**

- Syntax: `domain:example.com` or just `example.com` (uses default)
- Matches: `example.com`, `www.example.com`, `api.example.com`, `a.b.c.example.com`
- Does NOT match: `notexample.com`, `example.com.hk`, `examplecom`
- Performance: **O(levels)** - logarithmic in domain depth
- Use case: Block entire domain hierarchies (most common use)

#### Subdomain Priority

When multiple domain rules could match, the most specific (longest) rule wins:

```
Rules: com, example.com, api.example.com

Query www.example.com:
  ✓ Matches api.example.com? No
  ✓ Matches example.com? Yes (return true)
  ✗ Would also match com, but already found more specific match

Query api.example.com:
  ✓ Matches api.example.com? Yes (return true)

Query other.com:
  ✓ Matches api.example.com? No
  ✓ Matches example.com? No
  ✓ Matches com? Yes (return true)
```

#### Examples

```
domain:google.com       → matches google.com, www.google.com, maps.google.com, etc.
domain:co.uk            → matches all .co.uk domains
example.com             → equivalent to domain:example.com (if default is domain)
```

### 3. Keyword Match (`keyword:`)

**Substring/keyword matching anywhere in the domain.**

- Syntax: `keyword:google`
- Matches: `google.com`, `www.google.com`, `google.com.hk`, `mygoogle.net`, `my-google-service.org`
- Does NOT match: `gogle.com` (typo), `notgooglelike.com` (keyword not present as substring)
- Performance: **O(n)** - linear traversal
- Evaluation order: Import order (first match wins)
- Use case: Catch variations and domain names containing keywords, less precise
- Warning: Can produce false positives (e.g., `keyword:ad` matches `add.com`, `advertisement.com`, `badword.com`)

#### Examples

```
keyword:facebook        → matches facebook.com, www.facebook.com, facebook.com.cn, myfacebook.net, etc.
keyword:google          → matches google.com, mygoogle.com, google.com.hk, googlechrome.com, etc.
keyword:cdn             → matches cdn.com, mycdn.net, ocdn.org, etc. (be careful!)
```

### 4. Regexp Match (`regexp:`)

**Regular expression pattern matching using Rust regex syntax (compatible with Go stdlib).**

- Syntax: `regexp:^[a-z]+\.google\.com$`
- Pattern: Standard Rust regex syntax
- Performance: **O(n·regex_complexity)** - can be CPU-intensive with complex patterns
- Evaluation order: Import order (first match wins)
- Use case: Complex pattern matching, flexible rules

#### Regex Basics

| Pattern | Matches | Does NOT match |
|---------|---------|----------------|
| `.+\.google\.com$` | `www.google.com`, `maps.google.com` | `google.com` (no prefix) |
| `^google\.` | `google.com`, `google.co.uk` | `www.google.com` |
| `(baidu\|google)` | `baidu.com`, `google.com` | `notbaidu.com` |
| `test-[0-9]+` | `test-123.com`, `test-1.org` | `test-abc.com` |

#### Examples

```
regexp:.+\.github\.io$          → matches *.github.io (personal GitHub Pages)
regexp:^api\.                   → matches api.example.com, api.service.com, etc.
regexp:(qq\|wechat)             → matches qq.com, wechat.com
regexp:.*cdn.*                  → matches any domain containing "cdn"
```

#### Performance Warning

Regexp matching is CPU-intensive, especially with:
- Complex backtracking patterns
- Overlapping quantifiers (`.*.*`, `.+.+`)
- Large number of rules

**Best practices:**
- Use simpler alternatives when possible (full/domain match)
- Avoid complex patterns with many regexp rules
- Order rules by likelihood of match (common patterns first)
- Use anchors `^` and `$` to improve performance

## Matching Priority

Rules are evaluated in strict priority order. The first matching rule determines the result.

### Priority Order (Highest to Lowest)

```
Full > Domain > Regexp > Keyword
```

#### Example

```yaml
Rules:
  - full:example.com
  - domain:example.com
  - keyword:example
  - regexp:.*example.*
```

Query `example.com`:
```
1. Check Full rules → matches full:example.com ✓ RETURN TRUE
   (Never reaches Domain, Regexp, or Keyword checks)
```

Query `sub.example.com`:
```
1. Check Full rules → no match
2. Check Domain rules → matches domain:example.com ✓ RETURN TRUE
   (Never reaches Regexp or Keyword checks)
```

Query `myexample.org`:
```
1. Check Full rules → no match
2. Check Domain rules → no match
3. Check Regexp rules → matches .*example.* ✓ RETURN TRUE
   (Never reaches Keyword check)
```

## Performance Characteristics

### Time Complexity

| Match Type | Complexity | Notes |
|------------|-----------|-------|
| Full | O(1) | HashMap lookup |
| Domain | O(d) | d = domain depth, typically 3-4 |
| Regexp | O(n·r) | n = rules, r = regex complexity |
| Keyword | O(n·s) | n = rules, s = string length |

### Space Complexity (Approximate)

| Match Type | Memory per 10,000 rules |
|------------|----------------------|
| Full | ~1 MB |
| Domain | ~1 MB |
| Regexp | ~2-5 MB (includes compiled regex) |
| Keyword | ~0.5-1 MB |

### Benchmarks

```
Rule set size: 100,000 domains

Match type    | Avg Query Time | Remarks
-----------------------------------
Full          | < 1 µs         | Instant
Domain        | < 5 µs         | Very fast
Regexp        | 100-1000 µs    | Slow with complex patterns
Keyword       | 50-500 µs      | Linear scan
```

## Rule Evaluation Order

### Full and Domain Rules

When **multiple** full or domain rules could match, the most specific match wins:

```
Rules:
  - domain:com
  - domain:example.com
  - domain:api.example.com

Query api.example.com:
  Evaluation: Longest match wins
  → Matches api.example.com (most specific) ✓
```

### Regexp and Keyword Rules

Rules are evaluated in **import order** (file order). The **first match** wins:

```
Rules (in order):
  - regexp:google
  - regexp:.*oogle
  - keyword:abc

Query "google.com":
  → Matches first regexp:google ✓ (returns true immediately)
  → Never evaluates remaining rules
```

## Configuration Examples

### Basic Configuration

```yaml
- name: domain_set
  tag: direct
  args:
    files:
      - direct-list.txt
```

With default domain matching (rules without prefix use domain match).

### With Custom Default Match Type

```yaml
- name: domain_set
  tag: gfw
  args:
    files:
      - gfw.txt
    default_match_type: keyword
    auto_reload: true
```

All rules without a prefix will use keyword matching.

### Multiple Files with Auto-Reload

```yaml
- name: domain_set
  tag: combined
  args:
    files:
      - blocklist.txt
      - custom-domains.txt
      - regex-patterns.txt
    default_match_type: domain
    auto_reload: true
    # Auto-reload checks files every ~200ms
```

### Inline Domain Expressions (exps Parameter)

You can also specify domain rules inline using the `exps` parameter instead of external files:

**Single rule (string format):**
```yaml
- name: domain_set
  tag: direct
  args:
    exps: "example.com"
```

**Multiple rules (array format):**
```yaml
- name: domain_set
  tag: combined
  args:
    exps:
      - "example.com"
      - "full:github.com"
      - "regexp:.+\.google\.com$"
      - "keyword:facebook"
```

**Mixed files and inline expressions:**
```yaml
- name: domain_set
  tag: comprehensive
  args:
    files:
      - blocklist.txt
    exps:
      - "example.com"
      - "full:special.service.com"
      - "regexp:^internal-.*\.local$"
    default_match_type: domain
    auto_reload: true
```

The `exps` parameter supports the same rule format as files:
- Prefix with `full:`, `domain:`, `keyword:`, or `regexp:` for specific match types
- Rules without prefix use the `default_match_type`
- All inline rules are processed after file rules

### Recommended File Format

```
# Direct access (fast, no censorship)
# Domain format (matches subdomains)
domain:example.com
github.com
www.wikipedia.org

# Exact matches for specific services
full:dns.google

# Keywords for broad categories
keyword:cdn

# Complex patterns
regexp:.+\.local$
regexp:^192-168-.*\.nip\.io$
```

## File Format

### Supported Formats

1. **Domain (default)**
   ```
   example.com
   sub.example.com
   ```

2. **With Prefix**
   ```
   full:exact.com
   domain:parent.com
   keyword:google
   regexp:.+\.example\.com$
   ```

3. **Comments**
   ```
   # This is a comment
   # Comments must be on their own line
   example.com
   ```

4. **Whitespace**
   ```
   Leading and trailing whitespace is trimmed
     example.com     →  matches "example.com"
   ```

5. **Empty Lines**
   ```
   Empty lines are silently ignored
   ```

### Example File

```
# Direct access domains (no blocking)
# Updated: 2024-12-26

# GitHub and services
github.com
www.github.io
api.github.com

# Exact services
full:dns.google.com
full:8.8.8.8

# CDN and infrastructure
keyword:cdn
keyword:cloudflare

# User agent patterns
regexp:.*bot.*
regexp:.*crawler.*

# Personal domains
domain:*.example.com
```

## Best Practices

### 1. Rule Organization

```
1. Full matches (most specific, fastest)
2. Domain matches (common case)
3. Regexp patterns (complex logic)
4. Keyword matches (broad patterns)
```

### 2. Performance Optimization

- Use Full/Domain matches for known domains (O(1))
- Place frequently matched rules early in Regexp/Keyword sections
- Avoid excessive Regexp rules with complex backtracking
- Don't use Keyword matches for everything (use Domain instead)

### 3. Accuracy vs Coverage

- **High accuracy**: Use `full:` and specific `domain:` rules
- **Coverage**: Use `keyword:` and `regexp:` patterns
- **Balance**: Mix all types appropriately for your use case

### 4. Maintenance

- Organize rules by category with comments
- Use `auto_reload: true` for frequently updated lists
- Test rule changes (benchmark and functional tests)
- Document complex regexp patterns

## Troubleshooting

### Rule Not Matching

1. Check case sensitivity (all rules are case-insensitive)
2. Verify prefix is correct (`full:`, `domain:`, etc.)
3. Check trailing dots (automatically normalized)
4. Verify rule priority (check previous rules)

Example:
```
# These all match "example.com":
domain:example.com
DOMAIN:EXAMPLE.COM
example.com.              # trailing dot normalized
Example.Com              # case normalized

# These do NOT match "example.com":
full:www.example.com     # full requires exact match
keyword:exam             # keyword is substring, would match but rule is for "exam"
```

### Performance Issues

1. **Slow query matching**: Check Regexp/Keyword rule count
2. **Large memory usage**: Consider splitting into multiple file sets
3. **File reload delays**: Auto-reload debounce is 200ms (configurable)

### Debugging

Enable tracing to see matching details:
```
RUST_LOG=debug lazydns
```

## API Reference

### Rust Code

```rust
use lazydns::plugins::dataset::{DomainRules, MatchType};

let mut rules = DomainRules::new();

// Add rules
rules.add_rule(MatchType::Full, "exact.com");
rules.add_rule(MatchType::Domain, "example.com");
rules.add_rule(MatchType::Keyword, "google");
rules.add_rule(MatchType::Regexp, r".+\.github\.io$");

// Parse lines
rules.add_line("domain:test.com", MatchType::Domain);

// Check matches
assert!(rules.matches("exact.com"));
assert!(rules.matches("sub.example.com"));
assert!(rules.matches("test-google.com"));
assert!(rules.matches("mysite.github.io"));
```

### Statistics

```rust
let stats = rules.stats();
println!("Full: {}", stats.full_count);
println!("Domain: {}", stats.domain_count);
println!("Regexp: {}", stats.regexp_count);
println!("Keyword: {}", stats.keyword_count);
```

## See Also

- [IP Matching Rules]IP_MATCHING_RULES.md
- [Plugins Overview]IMPLEMENTATION.md
- [Configuration Guide]UPSTREAM_FEATURES.md