1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-01 03:25:23 +00:00
v2fly/app/proxyman/inbound/dynamic.go

204 lines
5.4 KiB
Go
Raw Normal View History

package inbound
import (
"context"
"sync"
"time"
2021-02-16 20:31:50 +00:00
core "github.com/v2fly/v2ray-core/v4"
"github.com/v2fly/v2ray-core/v4/app/proxyman"
"github.com/v2fly/v2ray-core/v4/common/dice"
"github.com/v2fly/v2ray-core/v4/common/mux"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/task"
"github.com/v2fly/v2ray-core/v4/proxy"
"github.com/v2fly/v2ray-core/v4/transport/internet"
)
type DynamicInboundHandler struct {
tag string
2018-02-08 14:39:46 +00:00
v *core.Instance
proxyConfig interface{}
receiverConfig *proxyman.ReceiverConfig
2018-09-07 12:50:25 +00:00
streamSettings *internet.MemoryStreamConfig
2017-01-30 20:35:34 +00:00
portMutex sync.Mutex
portsInUse map[net.Port]bool
2017-01-30 20:35:34 +00:00
workerMutex sync.RWMutex
worker []worker
lastRefresh time.Time
2017-04-02 12:06:20 +00:00
mux *mux.Server
2018-05-27 11:02:29 +00:00
task *task.Periodic
2020-06-18 04:37:10 +00:00
ctx context.Context
}
func NewDynamicInboundHandler(ctx context.Context, tag string, receiverConfig *proxyman.ReceiverConfig, proxyConfig interface{}) (*DynamicInboundHandler, error) {
2018-02-21 16:05:29 +00:00
v := core.MustFromContext(ctx)
h := &DynamicInboundHandler{
tag: tag,
proxyConfig: proxyConfig,
receiverConfig: receiverConfig,
portsInUse: make(map[net.Port]bool),
2017-04-02 12:06:20 +00:00
mux: mux.NewServer(ctx),
2018-02-08 14:39:46 +00:00
v: v,
2020-06-18 04:37:10 +00:00
ctx: ctx,
2018-02-08 14:39:46 +00:00
}
2018-09-07 12:50:25 +00:00
mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings)
if err != nil {
return nil, newError("failed to parse stream settings").Base(err).AtWarning()
}
2018-09-17 13:12:58 +00:00
if receiverConfig.ReceiveOriginalDestination {
if mss.SocketSettings == nil {
mss.SocketSettings = &internet.SocketConfig{}
}
if mss.SocketSettings.Tproxy == internet.SocketConfig_Off {
mss.SocketSettings.Tproxy = internet.SocketConfig_Redirect
}
mss.SocketSettings.ReceiveOriginalDestAddress = true
}
2018-09-07 12:50:25 +00:00
h.streamSettings = mss
2018-05-27 11:02:29 +00:00
h.task = &task.Periodic{
2018-02-08 14:39:46 +00:00
Interval: time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()),
Execute: h.refresh,
}
return h, nil
}
func (h *DynamicInboundHandler) allocatePort() net.Port {
from := int(h.receiverConfig.PortRange.From)
delta := int(h.receiverConfig.PortRange.To) - from + 1
2017-01-30 20:35:34 +00:00
h.portMutex.Lock()
defer h.portMutex.Unlock()
for {
r := dice.Roll(delta)
port := net.Port(from + r)
_, used := h.portsInUse[port]
if !used {
h.portsInUse[port] = true
return port
}
}
}
2018-02-08 14:39:46 +00:00
func (h *DynamicInboundHandler) closeWorkers(workers []worker) {
ports2Del := make([]net.Port, len(workers))
2017-01-30 20:35:34 +00:00
for idx, worker := range workers {
ports2Del[idx] = worker.Port()
2018-05-31 09:55:11 +00:00
if err := worker.Close(); err != nil {
newError("failed to close worker").Base(err).WriteToLog()
}
}
2017-01-30 20:35:34 +00:00
h.portMutex.Lock()
for _, port := range ports2Del {
delete(h.portsInUse, port)
}
2017-01-30 20:35:34 +00:00
h.portMutex.Unlock()
}
func (h *DynamicInboundHandler) refresh() error {
h.lastRefresh = time.Now()
2017-01-30 20:37:50 +00:00
timeout := time.Minute * time.Duration(h.receiverConfig.AllocationStrategy.GetRefreshValue()) * 2
concurrency := h.receiverConfig.AllocationStrategy.GetConcurrencyValue()
workers := make([]worker, 0, concurrency)
2017-01-27 22:52:29 +00:00
address := h.receiverConfig.Listen.AsAddress()
if address == nil {
address = net.AnyIP
2017-01-27 22:52:29 +00:00
}
2018-04-11 22:10:14 +00:00
uplinkCounter, downlinkCounter := getStatCounter(h.v, h.tag)
2017-01-30 20:37:50 +00:00
for i := uint32(0); i < concurrency; i++ {
port := h.allocatePort()
2018-05-31 09:55:11 +00:00
rawProxy, err := core.CreateObject(h.v, h.proxyConfig)
if err != nil {
2017-12-19 20:28:12 +00:00
newError("failed to create proxy instance").Base(err).AtWarning().WriteToLog()
continue
}
2018-02-08 14:39:46 +00:00
p := rawProxy.(proxy.Inbound)
nl := p.Network()
2018-11-20 15:58:26 +00:00
if net.HasNetwork(nl, net.Network_TCP) {
worker := &tcpWorker{
2018-04-11 22:10:14 +00:00
tag: h.tag,
address: address,
port: port,
proxy: p,
2018-09-07 12:50:25 +00:00
stream: h.streamSettings,
2018-04-11 22:10:14 +00:00
recvOrigDest: h.receiverConfig.ReceiveOriginalDestination,
dispatcher: h.mux,
2018-07-16 11:47:00 +00:00
sniffingConfig: h.receiverConfig.GetEffectiveSniffingSettings(),
2018-04-11 22:10:14 +00:00
uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter,
2020-06-18 04:37:10 +00:00
ctx: h.ctx,
}
if err := worker.Start(); err != nil {
2017-12-19 20:28:12 +00:00
newError("failed to create TCP worker").Base(err).AtWarning().WriteToLog()
2017-01-30 20:35:34 +00:00
continue
}
2017-01-30 20:35:34 +00:00
workers = append(workers, worker)
}
2018-11-20 15:58:26 +00:00
if net.HasNetwork(nl, net.Network_UDP) {
worker := &udpWorker{
Feature: Fake DNS support (#406) * Add fake dns A new config object "fake" in DnsObject for toggling fake dns function Compare with sniffing, fake dns is not limited to http and tls traffic. It works across all inbounds. For example, when dns request come from one inbound, the local DNS server of v2ray will response with a unique fake IP for every unique domain name. Then later on v2ray received a request to one of the fake IP from any inbounds, it will override the request destination with the previously saved domain. By default, v2ray cache up to 65535 addresses. The old records will be discarded bases on LRU. The fake IP will be 240.x.x.x * fix an edge case when encounter a fake IP in use * Move lru to common.cache package * Added the necessary change to obtain request IP from sniffer * Refactor the code so that it may stop depending on global variables in the future. * Replace string manipulation code with more generic codes, hopefully this will work for both IPv4 and IPv6 networks. * Try to use IPv4 version of address if possible * Added Test Case for Fake Dns * Added More Test Case for Fake Dns * Stop user from creating a instance with LRU size more than subnet size, it will create a infinite loop * Move Fake DNS to a separate package * Generated Code for fakedns * Encapsulate Fake DNS as a Instance wide service * Added Support for metadata sniffer, which will be used for Fake DNS * Dependency injection for fake dns * Fake DNS As a Sniffer * Remove stub object * Remove global variable * Update generated protobuf file for metadata only sniffing * Apply Fake DNS config to session * Loading for fake dns settings * Bug fix * Include fake dns in all * Fix FakeDns Lint Condition * Fix sniffer config * Fix lint message * Fix dependency resolution * Fix fake dns not loaded as sniffer * reduce ttl for fake dns * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Fix crashed when no fake dns * Apply Coding Style * Fix Fake DNS do not apply to UDP socket * Fixed a bug prevent FakeDNS App Setting from become effective * Fixed a caveat prevent FakeDNS App Setting from become effective * Use log comparison to reduce in issue when it comes to really high value typical for ipv6 subnet * Add build tag for fakedns * Removal of FakeDNS specific logic at DNS client: making it a standard dns client * Regenerate auto generated file * Amended version of configure file * Bug fixes for fakeDNS * Bug fixes for fakeDNS * Fix test: remove reference to removed attribute * Test: fix codacy issue * Conf: Remove old field support * Test: fix codacy issue * Change test scale for TestFakeDnsHolderCreateMappingAndRollOver * Test: fix codacy issue Co-authored-by: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Co-authored-by: loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com> Co-authored-by: kslr <kslrwang@gmail.com>
2021-02-08 10:18:52 +00:00
ctx: h.ctx,
2018-04-11 22:10:14 +00:00
tag: h.tag,
proxy: p,
address: address,
port: port,
dispatcher: h.mux,
Feature: Fake DNS support (#406) * Add fake dns A new config object "fake" in DnsObject for toggling fake dns function Compare with sniffing, fake dns is not limited to http and tls traffic. It works across all inbounds. For example, when dns request come from one inbound, the local DNS server of v2ray will response with a unique fake IP for every unique domain name. Then later on v2ray received a request to one of the fake IP from any inbounds, it will override the request destination with the previously saved domain. By default, v2ray cache up to 65535 addresses. The old records will be discarded bases on LRU. The fake IP will be 240.x.x.x * fix an edge case when encounter a fake IP in use * Move lru to common.cache package * Added the necessary change to obtain request IP from sniffer * Refactor the code so that it may stop depending on global variables in the future. * Replace string manipulation code with more generic codes, hopefully this will work for both IPv4 and IPv6 networks. * Try to use IPv4 version of address if possible * Added Test Case for Fake Dns * Added More Test Case for Fake Dns * Stop user from creating a instance with LRU size more than subnet size, it will create a infinite loop * Move Fake DNS to a separate package * Generated Code for fakedns * Encapsulate Fake DNS as a Instance wide service * Added Support for metadata sniffer, which will be used for Fake DNS * Dependency injection for fake dns * Fake DNS As a Sniffer * Remove stub object * Remove global variable * Update generated protobuf file for metadata only sniffing * Apply Fake DNS config to session * Loading for fake dns settings * Bug fix * Include fake dns in all * Fix FakeDns Lint Condition * Fix sniffer config * Fix lint message * Fix dependency resolution * Fix fake dns not loaded as sniffer * reduce ttl for fake dns * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Fix crashed when no fake dns * Apply Coding Style * Fix Fake DNS do not apply to UDP socket * Fixed a bug prevent FakeDNS App Setting from become effective * Fixed a caveat prevent FakeDNS App Setting from become effective * Use log comparison to reduce in issue when it comes to really high value typical for ipv6 subnet * Add build tag for fakedns * Removal of FakeDNS specific logic at DNS client: making it a standard dns client * Regenerate auto generated file * Amended version of configure file * Bug fixes for fakeDNS * Bug fixes for fakeDNS * Fix test: remove reference to removed attribute * Test: fix codacy issue * Conf: Remove old field support * Test: fix codacy issue * Change test scale for TestFakeDnsHolderCreateMappingAndRollOver * Test: fix codacy issue Co-authored-by: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Co-authored-by: loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com> Co-authored-by: kslr <kslrwang@gmail.com>
2021-02-08 10:18:52 +00:00
sniffingConfig: h.receiverConfig.GetEffectiveSniffingSettings(),
2018-04-11 22:10:14 +00:00
uplinkCounter: uplinkCounter,
downlinkCounter: downlinkCounter,
2018-09-17 13:12:58 +00:00
stream: h.streamSettings,
}
if err := worker.Start(); err != nil {
2017-12-19 20:28:12 +00:00
newError("failed to create UDP worker").Base(err).AtWarning().WriteToLog()
2017-01-30 20:35:34 +00:00
continue
}
2017-01-30 20:35:34 +00:00
workers = append(workers, worker)
}
}
2017-01-30 20:35:34 +00:00
h.workerMutex.Lock()
h.worker = workers
h.workerMutex.Unlock()
2018-02-08 14:39:46 +00:00
time.AfterFunc(timeout, func() {
h.closeWorkers(workers)
})
2017-01-30 20:35:34 +00:00
return nil
}
func (h *DynamicInboundHandler) Start() error {
2018-02-08 14:39:46 +00:00
return h.task.Start()
}
2018-02-08 14:39:46 +00:00
func (h *DynamicInboundHandler) Close() error {
return h.task.Close()
}
func (h *DynamicInboundHandler) GetRandomInboundProxy() (interface{}, net.Port, int) {
2017-01-30 20:35:34 +00:00
h.workerMutex.RLock()
defer h.workerMutex.RUnlock()
if len(h.worker) == 0 {
return nil, 0, 0
}
w := h.worker[dice.Roll(len(h.worker))]
expire := h.receiverConfig.AllocationStrategy.GetRefreshValue() - uint32(time.Since(h.lastRefresh)/time.Minute)
2017-01-30 20:35:34 +00:00
return w.Proxy(), w.Port(), int(expire)
}
func (h *DynamicInboundHandler) Tag() string {
return h.tag
}