1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-27 22:36:12 -04:00
v2fly/app/router/rules/router.go

96 lines
1.8 KiB
Go
Raw Normal View History

2015-11-14 08:24:56 -05:00
package rules
2015-11-22 06:05:21 -05:00
import (
"errors"
2015-12-14 08:40:13 -05:00
"time"
2015-11-22 06:05:21 -05:00
"github.com/v2ray/v2ray-core/app/router"
2015-12-14 08:40:13 -05:00
"github.com/v2ray/v2ray-core/common/collect"
2015-11-22 06:05:21 -05:00
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
2015-11-22 11:41:52 -05:00
InvalidRule = errors.New("Invalid Rule")
NoRuleApplicable = errors.New("No rule applicable")
2015-11-22 06:05:21 -05:00
)
2015-12-14 08:40:13 -05:00
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)
}
2015-11-22 06:05:21 -05:00
type Router struct {
2015-12-07 16:47:47 -05:00
rules []Rule
2015-12-14 08:40:13 -05:00
cache *collect.ValidityMap
2015-12-07 16:47:47 -05:00
}
func NewRouter() *Router {
return &Router{
rules: make([]Rule, 0, 16),
2015-12-14 08:40:13 -05:00
cache: collect.NewValidityMap(3600),
2015-12-07 16:47:47 -05:00
}
}
func (this *Router) AddRule(rule Rule) *Router {
this.rules = append(this.rules, rule)
return this
2015-11-22 06:05:21 -05:00
}
2015-12-14 08:40:13 -05:00
func (this *Router) takeDetourWithoutCache(dest v2net.Destination) (string, error) {
2015-11-22 06:05:21 -05:00
for _, rule := range this.rules {
if rule.Apply(dest) {
return rule.Tag(), nil
}
}
return "", NoRuleApplicable
2015-11-22 06:05:21 -05:00
}
2015-12-14 08:40:13 -05:00
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
}
2015-11-22 06:05:21 -05:00
type RouterFactory struct {
}
func (this *RouterFactory) Create(rawConfig interface{}) (router.Router, error) {
2015-12-07 16:47:47 -05:00
config := rawConfig.(RouterRuleConfig)
2015-11-22 06:05:21 -05:00
rules := config.Rules()
2015-12-07 16:47:47 -05:00
router := NewRouter()
2015-11-22 06:05:21 -05:00
for _, rule := range rules {
if rule == nil {
return nil, InvalidRule
}
2015-12-07 16:47:47 -05:00
router.AddRule(rule)
2015-11-22 06:05:21 -05:00
}
2015-12-07 16:47:47 -05:00
return router, nil
2015-11-22 06:05:21 -05:00
}
func init() {
router.RegisterRouter("rules", &RouterFactory{})
}