Browse Source

some cleanup

pull/15/head
Jason 5 years ago
parent
commit
6479d3219b
  1. 82
      cmd/tun2socks/main.go
  2. 4
      cmd/tun2socks/main_d.go
  3. 3
      cmd/tun2socks/main_redirect.go
  4. 7
      cmd/tun2socks/main_socks.go
  5. 1
      cmd/tun2socks/main_stats.go
  6. 114
      common/dns/cache/cache.go
  7. 12
      common/dns/fakedns/util.go

82
cmd/tun2socks/main.go

@ -12,26 +12,27 @@ import (
"github.com/xjasonlyu/tun2socks/common/dns"
"github.com/xjasonlyu/tun2socks/common/log"
_ "github.com/xjasonlyu/tun2socks/common/log/simple" // Register a simple logger.
_ "github.com/xjasonlyu/tun2socks/common/log/simple"
"github.com/xjasonlyu/tun2socks/common/stats"
"github.com/xjasonlyu/tun2socks/core"
"github.com/xjasonlyu/tun2socks/filter"
"github.com/xjasonlyu/tun2socks/tun"
)
var Version = "unknown version"
const MTU = 1500
var handlerCreator = make(map[string]func(), 0)
var (
version = "unknown version"
buildTime = "unknown time"
func registerHandlerCreator(name string, creator func()) {
handlerCreator[name] = creator
}
var postFlagsInitFn = make([]func(), 0)
args = new(CmdArgs)
postFlagsInitFn = make([]func(), 0)
handlerCreator = make(map[string]func(), 0)
func addPostFlagsInitFn(fn func()) {
postFlagsInitFn = append(postFlagsInitFn, fn)
}
lwipWriter io.Writer
fakeDns dns.FakeDns
sessionStater stats.SessionStater
)
type CmdArgs struct {
Version *bool
@ -41,13 +42,7 @@ type CmdArgs struct {
TunMask *string
TunDns *string
ProxyType *string
VConfig *string
SniffingType *string
ProxyServer *string
ProxyHost *string
ProxyPort *uint16
ProxyCipher *string
ProxyPassword *string
DelayICMP *int
UdpTimeout *time.Duration
LogLevel *string
@ -61,51 +56,18 @@ type CmdArgs struct {
StatsAddr *string
}
type cmdFlag uint
const (
fProxyServer cmdFlag = iota
fUdpTimeout
fStats
)
var flagCreators = map[cmdFlag]func(){
fProxyServer: func() {
if args.ProxyServer == nil {
args.ProxyServer = flag.String("proxyServer", "1.2.3.4:1087", "Proxy server address")
}
},
fUdpTimeout: func() {
if args.UdpTimeout == nil {
args.UdpTimeout = flag.Duration("udpTimeout", 1*time.Minute, "UDP session timeout")
}
},
fStats: func() {
if args.Stats == nil {
args.Stats = flag.Bool("stats", false, "Enable statistics")
}
},
func addPostFlagsInitFn(fn func()) {
postFlagsInitFn = append(postFlagsInitFn, fn)
}
func (a *CmdArgs) addFlag(f cmdFlag) {
if fn, found := flagCreators[f]; found && fn != nil {
fn()
} else {
log.Fatalf("unsupported flag")
}
func registerHandlerCreator(name string, creator func()) {
handlerCreator[name] = creator
}
var args = new(CmdArgs)
var lwipWriter io.Writer
var fakeDns dns.FakeDns
var sessionStater stats.SessionStater
const (
MTU = 1500
)
func showVersion() {
fmt.Println("Tun2Socks", version)
fmt.Println("Build Time", buildTime)
}
func main() {
args.Version = flag.Bool("version", false, "Print version")
@ -113,7 +75,7 @@ func main() {
args.TunAddr = flag.String("tunAddr", "240.0.0.2", "TUN interface address")
args.TunGw = flag.String("tunGw", "240.0.0.1", "TUN interface gateway")
args.TunMask = flag.String("tunMask", "255.255.255.0", "TUN interface netmask, it should be a prefixlen (a number) for IPv6 address")
args.TunDns = flag.String("tunDns", "8.8.8.8,8.8.4.4", "DNS resolvers for TUN interface (only need on Windows)")
args.TunDns = flag.String("tunDns", "1.1.1.1", "DNS resolvers for TUN interface (Windows Only)")
args.ProxyType = flag.String("proxyType", "socks", "Proxy handler type")
args.DelayICMP = flag.Int("delayICMP", 10, "Delay ICMP packets for a short period of time, in milliseconds")
args.LogLevel = flag.String("loglevel", "info", "Logging level. (debug, info, warn, error, none)")
@ -121,7 +83,7 @@ func main() {
flag.Parse()
if *args.Version {
fmt.Println("TUN2SOCKS", Version)
showVersion()
os.Exit(0)
}

4
cmd/tun2socks/main_d.go

@ -14,10 +14,6 @@ import (
)
func init() {
args.addFlag(fProxyServer)
args.addFlag(fUdpTimeout)
args.addFlag(fStats)
args.ExceptionApps = flag.String("exceptionApps", "", "A list of exception apps separated by commas")
args.ExceptionSendThrough = flag.String("exceptionSendThrough", "192.168.1.101:0", "Exception send through address")

3
cmd/tun2socks/main_redirect.go

@ -8,9 +8,6 @@ import (
)
func init() {
args.addFlag(fProxyServer)
args.addFlag(fUdpTimeout)
registerHandlerCreator("redirect", func() {
core.RegisterTCPConnHandler(redirect.NewTCPHandler(*args.ProxyServer))
core.RegisterUDPConnHandler(redirect.NewUDPHandler(*args.ProxyServer, *args.UdpTimeout))

7
cmd/tun2socks/main_socks.go

@ -3,7 +3,9 @@
package main
import (
"flag"
"net"
"time"
"github.com/xjasonlyu/tun2socks/common/log"
"github.com/xjasonlyu/tun2socks/core"
@ -11,9 +13,8 @@ import (
)
func init() {
args.addFlag(fProxyServer)
args.addFlag(fUdpTimeout)
args.addFlag(fStats)
args.ProxyServer = flag.String("proxyServer", "1.2.3.4:1087", "Proxy server address")
args.UdpTimeout = flag.Duration("udpTimeout", 1*time.Minute, "UDP session timeout")
registerHandlerCreator("socks", func() {
// Verify proxy server address.

1
cmd/tun2socks/main_stats.go

@ -9,6 +9,7 @@ import (
)
func init() {
args.Stats = flag.Bool("stats", false, "Enable statistics")
args.StatsAddr = flag.String("statsAddr", "localhost:6001", "listen address of stats, open in your browser to view statistics")
addPostFlagsInitFn(func() {

114
common/dns/cache/cache.go

@ -1,114 +0,0 @@
// This file is copied from https://github.com/yinghuocho/gotun2socks/blob/master/udp.go
package cache
import (
"sync"
"time"
"github.com/miekg/dns"
cdns "github.com/xjasonlyu/tun2socks/common/dns"
"github.com/xjasonlyu/tun2socks/common/log"
)
const minCleanupInterval = 5 * time.Minute
type dnsCacheEntry struct {
msg []byte
exp time.Time
}
type simpleDnsCache struct {
mutex sync.Mutex
storage map[string]*dnsCacheEntry
lastCleanup time.Time
}
func NewSimpleDnsCache() cdns.DnsCache {
return &simpleDnsCache{
storage: make(map[string]*dnsCacheEntry),
lastCleanup: time.Now(),
}
}
func packUint16(i uint16) []byte { return []byte{byte(i >> 8), byte(i)} }
func cacheKey(q dns.Question) string {
return string(append([]byte(q.Name), packUint16(q.Qtype)...))
}
func (c *simpleDnsCache) cleanup() {
newStorage := make(map[string]*dnsCacheEntry)
log.Debugf("cleaning up dns %v cache entries", len(c.storage))
for key, entry := range c.storage {
if time.Now().Before(entry.exp) {
newStorage[key] = entry
}
}
c.storage = newStorage
log.Debugf("cleanup done, remaining %v entries", len(c.storage))
}
func (c *simpleDnsCache) Query(payload []byte) []byte {
request := new(dns.Msg)
e := request.Unpack(payload)
if e != nil {
return nil
}
if len(request.Question) == 0 {
return nil
}
c.mutex.Lock()
defer c.mutex.Unlock()
key := cacheKey(request.Question[0])
entry := c.storage[key]
if entry == nil {
return nil
}
if time.Now().After(entry.exp) {
delete(c.storage, key)
return nil
}
resp := new(dns.Msg)
resp.Unpack(entry.msg)
resp.Id = request.Id
var buf [1024]byte
dnsAnswer, err := resp.PackBuffer(buf[:])
if err != nil {
return nil
}
log.Debugf("got dns answer from cache with key: %v", key)
return append([]byte(nil), dnsAnswer...)
}
func (c *simpleDnsCache) Store(payload []byte) {
resp := new(dns.Msg)
e := resp.Unpack(payload)
if e != nil {
return
}
if resp.Rcode != dns.RcodeSuccess {
return
}
if len(resp.Question) == 0 || len(resp.Answer) == 0 {
return
}
c.mutex.Lock()
defer c.mutex.Unlock()
key := cacheKey(resp.Question[0])
c.storage[key] = &dnsCacheEntry{
msg: payload,
exp: time.Now().Add(time.Duration(resp.Answer[0].Header().Ttl) * time.Second),
}
log.Debugf("stored dns answer with key: %v, ttl: %v sec", key, resp.Answer[0].Header().Ttl)
now := time.Now()
if now.Sub(c.lastCleanup) > minCleanupInterval {
c.cleanup()
c.lastCleanup = now
}
}

12
common/dns/fakedns/util.go

@ -1,8 +1,6 @@
package fakedns
import (
"encoding/binary"
"net"
"time"
D "github.com/miekg/dns"
@ -37,13 +35,3 @@ func setMsgTTL(msg *D.Msg, ttl uint32) {
extra.Header().Ttl = ttl
}
}
/*
func uint322ip(n uint32) net.IP {
return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
}
*/
func ip2uint32(ip net.IP) uint32 {
return binary.BigEndian.Uint32([]byte(ip)[net.IPv6len-net.IPv4len:])
}

Loading…
Cancel
Save