-
Notifications
You must be signed in to change notification settings - Fork 0
Add ad blocking backed by sing-box ruleset #214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
atavism
wants to merge
11
commits into
main
Choose a base branch
from
atavism/adblock-rule
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
4462610
update comments
atavism 69d27e7
add adblocker
atavism 41ed47c
clean-ups
atavism 190d513
update comments
atavism 22cd517
update comments
atavism 341f39a
Fix tests and save default rule set
atavism 8df00a3
merge latest
atavism b28fea2
clean-ups
atavism e534463
merge latest
atavism ed7dca1
fix test
atavism ee0014e
fix test
atavism File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,208 @@ | ||
| // file: vpn/adblocker.go | ||
| package vpn | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "io/fs" | ||
| "log/slog" | ||
| "os" | ||
| "path/filepath" | ||
| "sync" | ||
| "sync/atomic" | ||
|
|
||
| C "github.com/sagernet/sing-box/constant" | ||
| "github.com/sagernet/sing/common/json" | ||
|
|
||
| "github.com/getlantern/radiance/common" | ||
| "github.com/getlantern/radiance/common/atomicfile" | ||
| "github.com/getlantern/radiance/internal" | ||
| ) | ||
|
|
||
| const ( | ||
| adBlockTag = "adblock" | ||
| // remote list (updated by sing-box) | ||
| adBlockListTag = "adblock-list" | ||
| adBlockFile = adBlockTag + ".json" | ||
| ) | ||
|
|
||
| type adblockRuleSetFile struct { | ||
| Version int `json:"version"` | ||
| Rules []adblockRule `json:"rules"` | ||
| } | ||
|
|
||
| type adblockRule struct { | ||
| Type string `json:"type,omitempty"` | ||
|
|
||
| // logical | ||
| Mode string `json:"mode,omitempty"` | ||
| Rules []adblockRule `json:"rules,omitempty"` | ||
|
|
||
| // default match fields we need | ||
| Domain []string `json:"domain,omitempty"` | ||
| Invert bool `json:"invert,omitempty"` | ||
| } | ||
|
|
||
| // AdBlocker tracks whether ad blocking is on and where its rules live | ||
| type AdBlocker struct { | ||
| mode string | ||
| ruleFile string | ||
|
|
||
| enabled atomic.Bool | ||
| access sync.Mutex | ||
| } | ||
|
|
||
| // NewAdBlocker creates a new instance of ad blocker, wired to the data directory | ||
| // and loads (or creates) the adblock rule file | ||
| func NewAdBlocker() (*AdBlocker, error) { | ||
| a := newAdBlocker(common.DataPath()) | ||
|
|
||
| // Create parent dir if needed (defensive for early startup paths) | ||
| if err := os.MkdirAll(filepath.Dir(a.ruleFile), 0o755); err != nil { | ||
| return nil, fmt.Errorf("create adblock dir: %w", err) | ||
| } | ||
|
|
||
| if _, err := os.Stat(a.ruleFile); errors.Is(err, fs.ErrNotExist) { | ||
| if err := a.save(); err != nil { | ||
| return nil, fmt.Errorf("write adblock file: %w", err) | ||
| } | ||
| } else if err != nil { | ||
| return nil, fmt.Errorf("stat adblock file: %w", err) | ||
| } | ||
|
|
||
| if err := a.load(); err != nil { | ||
| return nil, fmt.Errorf("load adblock file: %w", err) | ||
| } | ||
| return a, nil | ||
| } | ||
|
|
||
| func newAdBlocker(path string) *AdBlocker { | ||
| return &AdBlocker{ | ||
| mode: C.LogicalTypeAnd, | ||
| ruleFile: filepath.Join(path, adBlockFile), | ||
| } | ||
| } | ||
|
|
||
| // createAdBlockRuleFile creates the adblock rules file if it does not exist | ||
| func createAdBlockRuleFile(basePath string) error { | ||
| if basePath == "" { | ||
| return fmt.Errorf("basePath is empty") | ||
| } | ||
| if err := os.MkdirAll(basePath, 0o755); err != nil { | ||
| return fmt.Errorf("create basePath: %w", err) | ||
| } | ||
|
|
||
| a := newAdBlocker(basePath) | ||
|
|
||
| _, err := os.Stat(a.ruleFile) | ||
| switch { | ||
| case err == nil: | ||
| return nil | ||
| case errors.Is(err, fs.ErrNotExist): | ||
| if err := a.save(); err != nil { | ||
| slog.Warn("Failed to save default adblock rule set", "path", a.ruleFile, "error", err) | ||
| return err | ||
| } | ||
| return nil | ||
| default: | ||
| slog.Warn("Failed to stat adblock rule set", "path", a.ruleFile, "error", err) | ||
| return err | ||
| } | ||
| } | ||
|
|
||
| // IsEnabled returns whether or not ad blocking is currently on. | ||
| func (a *AdBlocker) IsEnabled() bool { return a.enabled.Load() } | ||
|
|
||
| // SetEnabled flips ad blocking on or off. | ||
| func (a *AdBlocker) SetEnabled(enabled bool) error { | ||
| a.access.Lock() | ||
| defer a.access.Unlock() | ||
|
|
||
| if a.enabled.Load() == enabled { | ||
| return nil | ||
| } | ||
|
|
||
| prevMode := a.mode | ||
| if enabled { | ||
| a.mode = C.LogicalTypeOr | ||
| } else { | ||
| a.mode = C.LogicalTypeAnd | ||
| } | ||
|
|
||
| if err := a.saveLocked(); err != nil { | ||
| a.mode = prevMode | ||
| return err | ||
| } | ||
|
|
||
| a.enabled.Store(enabled) | ||
| slog.Log(context.Background(), internal.LevelTrace, "updated adblock", "enabled", enabled) | ||
| return nil | ||
| } | ||
|
|
||
| // save updates the current mode in the adblock ruleset JSON and saves it to disk. | ||
| func (a *AdBlocker) save() error { | ||
| a.access.Lock() | ||
| defer a.access.Unlock() | ||
| return a.saveLocked() | ||
| } | ||
|
|
||
| func (a *AdBlocker) saveLocked() error { | ||
| rs := adblockRuleSetFile{ | ||
| Version: 3, | ||
| Rules: []adblockRule{ | ||
| { | ||
| Type: "logical", | ||
| Mode: a.mode, // AND disables, OR enables | ||
| Rules: []adblockRule{ | ||
| // always-false “disable” gate | ||
| { | ||
| Type: "logical", | ||
| Mode: C.LogicalTypeAnd, | ||
| Rules: []adblockRule{ | ||
| {Type: "default", Domain: []string{"disable.rule"}}, | ||
| {Type: "default", Domain: []string{"disable.rule"}, Invert: true}, | ||
| }, | ||
| }, | ||
| {Type: "default", Domain: []string{"disable.rule"}, Invert: true}, | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| buf, err := json.Marshal(rs) | ||
| if err != nil { | ||
| return fmt.Errorf("marshal adblock ruleset: %w", err) | ||
| } | ||
| if err := atomicfile.WriteFile(a.ruleFile, buf, 0o644); err != nil { | ||
| return fmt.Errorf("write adblock file: %w", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // load reads the adblock ruleset from disk and updates the mode | ||
| func (a *AdBlocker) load() error { | ||
| a.access.Lock() | ||
| defer a.access.Unlock() | ||
| return a.loadLocked() | ||
| } | ||
|
|
||
| func (a *AdBlocker) loadLocked() error { | ||
| content, err := atomicfile.ReadFile(a.ruleFile) | ||
| if err != nil { | ||
| return fmt.Errorf("read adblock file: %w", err) | ||
| } | ||
|
|
||
| var rs adblockRuleSetFile | ||
| if err := json.Unmarshal(content, &rs); err != nil { | ||
| return fmt.Errorf("unmarshal adblock: %w", err) | ||
| } | ||
|
|
||
| if len(rs.Rules) == 0 || rs.Rules[0].Type != "logical" { | ||
| return fmt.Errorf("adblock file missing logical rule") | ||
| } | ||
|
|
||
| a.mode = rs.Rules[0].Mode | ||
| a.enabled.Store(a.mode == C.LogicalTypeOr) | ||
| return nil | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If
vpn.NewAdBlocker()fails, the error is logged but execution continues with a niladBlocker. This meansr.adBlockerwill be nil, but the Radiance instance is still created and returned successfully. While the public methodsAdBlockEnabled()andSetAdBlockEnabled()do handle nil checks, it would be clearer to either:NewRadiance()if ad blocker initialization is critical, or