udptun: fixed a bug in nat mapping. #91

This commit is contained in:
nadoo committed 2019-03-12 23:32:23 +08:00
1 parent 4ece9ece25
commit 47406ce4ce
9 files changed
+84 -65

No files matched your search

+6 -6
View File
@@ -5,7 +5,7 @@ import (
"time"
)
// LongTTL is 50 years duration in seconds, used for none-expired items
// LongTTL is 50 years duration in seconds, used for none-expired items.
const LongTTL = 50 * 365 * 24 * 3600
type item struct {
@@ -13,13 +13,13 @@ type item struct {
expire time.Time
}
// Cache is the struct of cache
// Cache is the struct of cache.
type Cache struct {
m map[string]*item
l sync.RWMutex
}
// NewCache returns a new cache
// NewCache returns a new cache.
func NewCache() (c *Cache) {
c = &Cache{m: make(map[string]*item)}
go func() {
@@ -36,12 +36,12 @@ func NewCache() (c *Cache) {
return
}
// Len returns the length of cache
// Len returns the length of cache.
func (c *Cache) Len() int {
return len(c.m)
}
// Put an item into cache, invalid after ttl seconds
// Put an item into cache, invalid after ttl seconds.
func (c *Cache) Put(k string, v []byte, ttl int) {
if len(v) != 0 {
c.l.Lock()
@@ -55,7 +55,7 @@ func (c *Cache) Put(k string, v []byte, ttl int) {
}
}
// Get an item from cache
// Get an item from cache.
func (c *Cache) Get(k string) (v []byte) {
c.l.RLock()
if it, ok := c.m[k]; ok {
+11 -11
View File
@@ -13,10 +13,10 @@ import (
"github.com/nadoo/glider/proxy"
)
// HandleFunc function handles the dns TypeA or TypeAAAA answer
// HandleFunc function handles the dns TypeA or TypeAAAA answer.
type HandleFunc func(Domain, ip string) error
// Config for dns
// Config for dns.
type Config struct {
Servers []string
Timeout int
@@ -26,7 +26,7 @@ type Config struct {
AlwaysTCP bool
}
// Client is a dns client struct
// Client is a dns client struct.
type Client struct {
dialer proxy.Dialer
cache *Cache
@@ -36,7 +36,7 @@ type Client struct {
handlers []HandleFunc
}
// NewClient returns a new dns client
// NewClient returns a new dns client.
func NewClient(dialer proxy.Dialer, config *Config) (*Client, error) {
c := &Client{
dialer: dialer,
@@ -54,7 +54,7 @@ func NewClient(dialer proxy.Dialer, config *Config) (*Client, error) {
return c, nil
}
// Exchange handles request msg and returns response msg
// Exchange handles request message and returns response message.
// reqBytes = reqLen + reqMsg
func (c *Client) Exchange(reqBytes []byte, clientAddr string, preferTCP bool) ([]byte, error) {
req, err := UnmarshalMessage(reqBytes[2:])
@@ -122,7 +122,7 @@ func (c *Client) Exchange(reqBytes []byte, clientAddr string, preferTCP bool) ([
return respBytes, nil
}
// exchange choose a upstream dns server based on qname, communicate with it on the network
// exchange choose a upstream dns server based on qname, communicate with it on the network.
func (c *Client) exchange(qname string, reqBytes []byte, preferTCP bool) (server, network string, respBytes []byte, err error) {
// use tcp to connect upstream server default
network = "tcp"
@@ -170,7 +170,7 @@ func (c *Client) exchange(qname string, reqBytes []byte, preferTCP bool) (server
return server, network, respBytes, err
}
// exchangeTCP exchange with server over tcp
// exchangeTCP exchange with server over tcp.
func (c *Client) exchangeTCP(rc net.Conn, reqBytes []byte) ([]byte, error) {
if _, err := rc.Write(reqBytes); err != nil {
log.F("[dns] failed to write req message: %v", err)
@@ -195,7 +195,7 @@ func (c *Client) exchangeTCP(rc net.Conn, reqBytes []byte) ([]byte, error) {
return respBytes, nil
}
// exchangeUDP exchange with server over udp
// exchangeUDP exchange with server over udp.
func (c *Client) exchangeUDP(rc net.Conn, reqBytes []byte) ([]byte, error) {
if _, err := rc.Write(reqBytes[2:]); err != nil {
log.F("[dns] failed to write req message: %v", err)
@@ -212,7 +212,7 @@ func (c *Client) exchangeUDP(rc net.Conn, reqBytes []byte) ([]byte, error) {
return reqBytes[:2+n], nil
}
// SetServers sets upstream dns servers for the given domain
// SetServers sets upstream dns servers for the given domain.
func (c *Client) SetServers(domain string, servers ...string) {
c.upServerMap[domain] = append(c.upServerMap[domain], servers...)
}
@@ -232,7 +232,7 @@ func (c *Client) GetServers(domain string) []string {
return c.upServers
}
// AddHandler adds a custom handler to handle the resolved result (A and AAAA)
// AddHandler adds a custom handler to handle the resolved result (A and AAAA).
func (c *Client) AddHandler(h HandleFunc) {
c.handlers = append(c.handlers, h)
}
@@ -258,7 +258,7 @@ func (c *Client) AddRecord(record string) error {
return nil
}
// GenResponse generates a dns response message for the given domani an ip address
// GenResponse generates a dns response message for the given domain and ip address.
func (c *Client) GenResponse(domain string, ip string) (*Message, error) {
ipb := net.ParseIP(ip)
if ipb == nil {
+22 -22
View File
@@ -16,7 +16,7 @@ import (
// the header.
const UDPMaxLen = 512
// HeaderLen is the length of dns msg header
// HeaderLen is the length of dns msg header.
const HeaderLen = 12
// Message types
@@ -25,7 +25,7 @@ const (
Response = 1
)
// QType .
// Query types
const (
QTypeA uint16 = 1 //ipv4
QTypeAAAA uint16 = 28 ///ipv6
@@ -62,7 +62,7 @@ type Message struct {
unMarshaled []byte
}
// NewMessage returns a new message
// NewMessage returns a new message.
func NewMessage(id uint16, msgType int) *Message {
if id == 0 {
id = uint16(rand.Uint32())
@@ -74,20 +74,20 @@ func NewMessage(id uint16, msgType int) *Message {
return m
}
// SetQuestion sets a question to dns message,
// SetQuestion sets a question to dns message.
func (m *Message) SetQuestion(q *Question) error {
m.Question = q
m.Header.SetQdcount(1)
return nil
}
// AddAnswer adds an answer to dns message
// AddAnswer adds an answer to dns message.
func (m *Message) AddAnswer(rr *RR) error {
m.Answers = append(m.Answers, rr)
return nil
}
// Marshal marshals message struct to []byte
// Marshal marshals message struct to []byte.
func (m *Message) Marshal() ([]byte, error) {
var buf bytes.Buffer
@@ -117,7 +117,7 @@ func (m *Message) Marshal() ([]byte, error) {
return buf.Bytes(), nil
}
// UnmarshalMessage unmarshals []bytes to Message
// UnmarshalMessage unmarshals []bytes to Message.
func UnmarshalMessage(b []byte) (*Message, error) {
if len(b) < HeaderLen {
return nil, errors.New("UnmarshalMessage: not enough data")
@@ -183,22 +183,22 @@ type Header struct {
ARCOUNT uint16
}
// SetMsgType .
// SetMsgType sets the message type.
func (h *Header) SetMsgType(qr int) {
h.Bits |= uint16(qr) << 15
}
// SetTC .
// SetTC sets the tc flag.
func (h *Header) SetTC(tc int) {
h.Bits |= uint16(tc) << 9
}
// SetQdcount sets query count, most dns servers only support 1 query per request
// SetQdcount sets query count, most dns servers only support 1 query per request.
func (h *Header) SetQdcount(qdcount int) {
h.QDCOUNT = uint16(qdcount)
}
// SetAncount sets answers count
// SetAncount sets answers count.
func (h *Header) SetAncount(ancount int) {
h.ANCOUNT = uint16(ancount)
}
@@ -208,14 +208,14 @@ func (h *Header) setFlag(QR uint16, Opcode uint16, AA uint16,
h.Bits = QR<<15 + Opcode<<11 + AA<<10 + TC<<9 + RD<<8 + RA<<7 + RCODE
}
// Marshal marshals header struct to []byte
// Marshal marshals header struct to []byte.
func (h *Header) Marshal() ([]byte, error) {
var buf bytes.Buffer
err := binary.Write(&buf, binary.BigEndian, h)
return buf.Bytes(), err
}
// UnmarshalHeader unmarshals []bytes to Header
// UnmarshalHeader unmarshals []bytes to Header.
func UnmarshalHeader(b []byte, h *Header) error {
if h == nil {
return errors.New("unmarshal header must not be nil")
@@ -258,7 +258,7 @@ type Question struct {
QCLASS uint16
}
// NewQuestion returns a new dns question
// NewQuestion returns a new dns question.
func NewQuestion(qtype uint16, domain string) *Question {
return &Question{
QNAME: domain,
@@ -267,7 +267,7 @@ func NewQuestion(qtype uint16, domain string) *Question {
}
}
// Marshal marshals Question struct to []byte
// Marshal marshals Question struct to []byte.
func (q *Question) Marshal() ([]byte, error) {
var buf bytes.Buffer
@@ -278,7 +278,7 @@ func (q *Question) Marshal() ([]byte, error) {
return buf.Bytes(), nil
}
// UnmarshalQuestion unmarshals []bytes to Question
// UnmarshalQuestion unmarshals []bytes to Question.
func (m *Message) UnmarshalQuestion(b []byte, q *Question) (n int, err error) {
if q == nil {
return 0, errors.New("unmarshal question must not be nil")
@@ -339,13 +339,13 @@ type RR struct {
IP string
}
// NewRR returns a new dns rr
// NewRR returns a new dns rr.
func NewRR() *RR {
rr := &RR{}
return rr
}
// Marshal marshals RR struct to []byte
// Marshal marshals RR struct to []byte.
func (rr *RR) Marshal() ([]byte, error) {
var buf bytes.Buffer
@@ -359,7 +359,7 @@ func (rr *RR) Marshal() ([]byte, error) {
return buf.Bytes(), nil
}
// UnmarshalRR unmarshals []bytes to RR
// UnmarshalRR unmarshals []bytes to RR.
func (m *Message) UnmarshalRR(start int, rr *RR) (n int, err error) {
if rr == nil {
return 0, errors.New("unmarshal rr must not be nil")
@@ -399,7 +399,7 @@ func (m *Message) UnmarshalRR(start int, rr *RR) (n int, err error) {
return n, nil
}
// MarshalDomain marshals domain string struct to []byte
// MarshalDomain marshals domain string struct to []byte.
func MarshalDomain(domain string) []byte {
var buf bytes.Buffer
@@ -412,7 +412,7 @@ func MarshalDomain(domain string) []byte {
return buf.Bytes()
}
// UnmarshalDomain gets domain from bytes
// UnmarshalDomain gets domain from bytes.
func (m *Message) UnmarshalDomain(b []byte) (string, int, error) {
var idx, size int
var labels = []string{}
@@ -457,7 +457,7 @@ func (m *Message) UnmarshalDomain(b []byte) (string, int, error) {
return domain, idx, nil
}
// UnmarshalDomainPoint gets domain from offset point
// UnmarshalDomainPoint gets domain from offset point.
func (m *Message) UnmarshalDomainPoint(offset int) (string, error) {
if offset > len(m.unMarshaled) {
return "", errors.New("UnmarshalDomainPoint: offset larger than msg length")
+6 -6
View File
@@ -14,14 +14,14 @@ import (
// conn timeout, seconds
const timeout = 30
// Server is a dns server struct
// Server is a dns server struct.
type Server struct {
addr string
// Client is used to communicate with upstream dns servers
*Client
}
// NewServer returns a new dns server
// NewServer returns a new dns server.
func NewServer(addr string, dialer proxy.Dialer, config *Config) (*Server, error) {
c, err := NewClient(dialer, config)
s := &Server{
@@ -32,7 +32,7 @@ func NewServer(addr string, dialer proxy.Dialer, config *Config) (*Server, error
return s, err
}
// Start starts the dns forwarding server
// Start starts the dns forwarding server.
// We use WaitGroup here to ensure both udp and tcp serer are completly running,
// so we can start any other services later, since they may rely on dns service.
func (s *Server) Start() {
@@ -43,7 +43,7 @@ func (s *Server) Start() {
wg.Wait()
}
// ListenAndServeUDP .
// ListenAndServeUDP listen and serves on udp port.
func (s *Server) ListenAndServeUDP(wg *sync.WaitGroup) {
c, err := net.ListenPacket("udp", s.addr)
wg.Done()
@@ -88,7 +88,7 @@ func (s *Server) ListenAndServeUDP(wg *sync.WaitGroup) {
}
// ListenAndServeTCP .
// ListenAndServeTCP listen and serves on tcp port.
func (s *Server) ListenAndServeTCP(wg *sync.WaitGroup) {
l, err := net.Listen("tcp", s.addr)
wg.Done()
@@ -110,7 +110,7 @@ func (s *Server) ListenAndServeTCP(wg *sync.WaitGroup) {
}
}
// ServeTCP .
// ServeTCP serves a tcp connection.
func (s *Server) ServeTCP(c net.Conn) {
defer c.Close()