forked from v2ray/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
81 lines (67 loc) · 1.63 KB
/
router.go
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
package rules
import (
"errors"
"time"
"github.com/v2ray/v2ray-core/app/router"
"github.com/v2ray/v2ray-core/common/collect"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
ErrorInvalidRule = errors.New("Invalid Rule")
ErrorNoRuleApplicable = errors.New("No rule applicable")
)
type cacheEntry struct {
tag string
err error
validUntil time.Time
}
func newCacheEntry(tag string, err error) *cacheEntry {
this := &cacheEntry{
tag: tag,
err: err,
}
this.Extend()
return this
}
func (this *cacheEntry) IsValid() bool {
return this.validUntil.Before(time.Now())
}
func (this *cacheEntry) Extend() {
this.validUntil = time.Now().Add(time.Hour)
}
type Router struct {
config *RouterRuleConfig
cache *collect.ValidityMap
}
func NewRouter(config *RouterRuleConfig) *Router {
return &Router{
config: config,
cache: collect.NewValidityMap(3600),
}
}
func (this *Router) takeDetourWithoutCache(dest v2net.Destination) (string, error) {
for _, rule := range this.config.Rules {
if rule.Apply(dest) {
return rule.Tag, nil
}
}
return "", ErrorNoRuleApplicable
}
func (this *Router) TakeDetour(dest v2net.Destination) (string, error) {
rawEntry := this.cache.Get(dest)
if rawEntry == nil {
tag, err := this.takeDetourWithoutCache(dest)
this.cache.Set(dest, newCacheEntry(tag, err))
return tag, err
}
entry := rawEntry.(*cacheEntry)
return entry.tag, entry.err
}
type RouterFactory struct {
}
func (this *RouterFactory) Create(rawConfig interface{}) (router.Router, error) {
return NewRouter(rawConfig.(*RouterRuleConfig)), nil
}
func init() {
router.RegisterRouter("rules", &RouterFactory{})
}