You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/app/router/router.go

117 lines
2.4 KiB

9 years ago
package router
import (
8 years ago
"context"
"v2ray.com/core/app"
8 years ago
"v2ray.com/core/app/dns"
"v2ray.com/core/app/log"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
8 years ago
"v2ray.com/core/common/net"
"v2ray.com/core/proxy"
9 years ago
)
8 years ago
var (
ErrNoRuleApplicable = errors.New("No rule applicable")
)
type Router struct {
domainStrategy Config_DomainStrategy
rules []Rule
dnsServer dns.Server
9 years ago
}
8 years ago
func NewRouter(ctx context.Context, config *Config) (*Router, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("Router: No space in context.")
}
8 years ago
r := &Router{
domainStrategy: config.DomainStrategy,
rules: make([]Rule, len(config.Rule)),
8 years ago
}
space.OnInitialize(func() error {
8 years ago
for idx, rule := range config.Rule {
r.rules[idx].Tag = rule.Tag
cond, err := rule.BuildCondition()
if err != nil {
return err
}
r.rules[idx].Condition = cond
}
r.dnsServer = dns.FromSpace(space)
if r.dnsServer == nil {
return errors.New("Router: DNS is not found in the space.")
8 years ago
}
return nil
})
8 years ago
return r, nil
9 years ago
}
func (v *Router) resolveIP(dest net.Destination) []net.Address {
8 years ago
ips := v.dnsServer.Get(dest.Address.Domain())
8 years ago
if len(ips) == 0 {
return nil
}
dests := make([]net.Address, len(ips))
8 years ago
for idx, ip := range ips {
dests[idx] = net.IPAddress(ip)
8 years ago
}
return dests
}
func (v *Router) TakeDetour(ctx context.Context) (string, error) {
8 years ago
for _, rule := range v.rules {
if rule.Apply(ctx) {
8 years ago
return rule.Tag, nil
}
}
dest, ok := proxy.TargetFromContext(ctx)
if !ok {
return "", ErrNoRuleApplicable
}
8 years ago
if v.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() {
8 years ago
log.Info("Router: Looking up IP for ", dest)
ipDests := v.resolveIP(dest)
8 years ago
if ipDests != nil {
ctx = proxy.ContextWithResolveIPs(ctx, ipDests)
for _, rule := range v.rules {
if rule.Apply(ctx) {
return rule.Tag, nil
8 years ago
}
}
}
}
return "", ErrNoRuleApplicable
9 years ago
}
8 years ago
func (Router) Interface() interface{} {
return (*Router)(nil)
}
func (Router) Start() error {
return nil
}
func (Router) Close() {}
func FromSpace(space app.Space) *Router {
8 years ago
app := space.GetApplication((*Router)(nil))
if app == nil {
return nil
}
return app.(*Router)
}
func init() {
8 years ago
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewRouter(ctx, config.(*Config))
}))
}