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

82 lines
1.6 KiB
Go
Raw Normal View History

2015-11-14 13:24:56 +00:00
package rules
2015-11-22 11:05:21 +00:00
import (
"errors"
2015-12-14 13:40:13 +00:00
"time"
2015-11-22 11:05:21 +00:00
"github.com/v2ray/v2ray-core/app/router"
2015-12-14 13:40:13 +00:00
"github.com/v2ray/v2ray-core/common/collect"
2015-11-22 11:05:21 +00:00
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
2016-01-30 11:32:38 +00:00
ErrorInvalidRule = errors.New("Invalid Rule")
ErrorNoRuleApplicable = errors.New("No rule applicable")
2015-11-22 11:05:21 +00:00
)
2015-12-14 13:40:13 +00: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 11:05:21 +00:00
type Router struct {
2016-02-01 22:21:54 +00:00
config *RouterRuleConfig
cache *collect.ValidityMap
2015-12-07 21:47:47 +00:00
}
2016-02-01 22:21:54 +00:00
func NewRouter(config *RouterRuleConfig) *Router {
2015-12-07 21:47:47 +00:00
return &Router{
2016-02-01 22:21:54 +00:00
config: config,
cache: collect.NewValidityMap(3600),
2015-12-07 21:47:47 +00:00
}
}
2015-12-14 13:40:13 +00:00
func (this *Router) takeDetourWithoutCache(dest v2net.Destination) (string, error) {
2016-02-01 22:21:54 +00:00
for _, rule := range this.config.Rules {
2015-11-22 11:05:21 +00:00
if rule.Apply(dest) {
2016-01-17 15:20:49 +00:00
return rule.Tag, nil
2015-11-22 11:05:21 +00:00
}
}
2016-01-30 11:32:38 +00:00
return "", ErrorNoRuleApplicable
2015-11-22 11:05:21 +00:00
}
2015-12-14 13:40:13 +00: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 11:05:21 +00:00
type RouterFactory struct {
}
func (this *RouterFactory) Create(rawConfig interface{}) (router.Router, error) {
2016-02-01 22:21:54 +00:00
return NewRouter(rawConfig.(*RouterRuleConfig)), nil
2015-11-22 11:05:21 +00:00
}
func init() {
router.RegisterRouter("rules", &RouterFactory{})
}