V0.2.0 (#37)
* refactor go files, add headless telemost support * js crap -> ts crap * docker-build (#32) Co-authored-by: Mimocro <suzumagefag@gmail.com> * add headless telemost for creator app * UX improvements (#39) * Add search in split tunneling app list * Add captcha detection * Add autoclick settings * headless vk joiner * add headless telemost joiner * refactor go modules * redesign settings dialog * headless option in settings * headless joiner support in MainActivity * display headless vk status in statusBar * update ux for headless in creator app * fix double log render for headless mode in creator * unicode for cyrillic * add socks auth * put socksPort inf prefs, verify that port is free on start * proxy only mode * mask addresses in go network errors * update docker build, add file write logic for headless * increment release version, add make-release script --------- Co-authored-by: kulikov <user@Mac.lan> Co-authored-by: Mimocro <67226986+Mimocro@users.noreply.github.com> Co-authored-by: Mimocro <suzumagefag@gmail.com> Co-authored-by: senya <76913432+senya-sh@users.noreply.github.com>
This commit is contained in:
122 files changed
+9938
-3284
No files matched your search
@@ -0,0 +1,258 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pion/datachannel"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
// Telemost chunk size
|
||||
const chunkSize = 994
|
||||
const dcStatsEnabled = false
|
||||
|
||||
type chunkBuf struct {
|
||||
chunks [][]byte
|
||||
count int
|
||||
size int
|
||||
}
|
||||
|
||||
type DCTunnel struct {
|
||||
dc *webrtc.DataChannel
|
||||
raw datachannel.ReadWriteCloser
|
||||
writeRaw datachannel.ReadWriteCloser
|
||||
logFn func(string, ...any)
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
chunked bool
|
||||
readBuf int
|
||||
|
||||
recvBufs sync.Map
|
||||
sendMsgID uint32
|
||||
|
||||
recvBytes atomic.Uint64
|
||||
sendBytes atomic.Uint64
|
||||
recvMsgs atomic.Uint64
|
||||
sendMsgs atomic.Uint64
|
||||
}
|
||||
|
||||
func NewDCTunnel(dc *webrtc.DataChannel, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, readBuf: readBuf, logFn: logFn}
|
||||
|
||||
raw, err := dc.Detach()
|
||||
if err != nil {
|
||||
logFn("dctunnel: detach failed, using callback mode: %v", err)
|
||||
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
if t.onData != nil {
|
||||
t.recvBytes.Add(uint64(len(msg.Data)))
|
||||
t.recvMsgs.Add(1)
|
||||
frame := make([]byte, 4+len(msg.Data))
|
||||
binary.BigEndian.PutUint32(frame[0:4], uint32(len(msg.Data)))
|
||||
copy(frame[4:], msg.Data)
|
||||
t.onData(frame)
|
||||
}
|
||||
})
|
||||
dc.OnClose(func() {
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
})
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
t.raw = raw
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewDCTunnelFromRaw(dc *webrtc.DataChannel, raw datachannel.ReadWriteCloser, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
t := &DCTunnel{dc: dc, raw: raw, readBuf: readBuf, logFn: logFn}
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func NewChunkedDCTunnel(readRaw datachannel.ReadWriteCloser, writeDC *webrtc.DataChannel, readBuf int, logFn func(string, ...any)) *DCTunnel {
|
||||
writeRaw, err := writeDC.Detach()
|
||||
if err != nil {
|
||||
logFn("dctunnel: write DC detach failed: %v", err)
|
||||
return nil
|
||||
}
|
||||
t := &DCTunnel{raw: readRaw, writeRaw: writeRaw, readBuf: readBuf, logFn: logFn, chunked: true}
|
||||
go t.readLoop()
|
||||
go t.statsLoop()
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *DCTunnel) readLoop() {
|
||||
buf := make([]byte, t.readBuf)
|
||||
for {
|
||||
n, isString, err := t.raw.ReadDataChannel(buf)
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
t.logFn("dctunnel: read error: %v", err)
|
||||
}
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
return
|
||||
}
|
||||
if isString {
|
||||
continue
|
||||
}
|
||||
t.recvBytes.Add(uint64(n))
|
||||
t.recvMsgs.Add(1)
|
||||
if t.chunked && n >= 6 {
|
||||
t.handleChunk(buf[:n])
|
||||
} else if n > 0 {
|
||||
t.deliverMessage(buf[:n])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) handleChunk(data []byte) {
|
||||
id := uint16(data[0])<<8 | uint16(data[1])
|
||||
idx := int(uint16(data[2])<<8 | uint16(data[3]))
|
||||
total := int(uint16(data[4])<<8 | uint16(data[5]))
|
||||
payload := data[6:]
|
||||
|
||||
if total == 1 {
|
||||
cp := make([]byte, len(payload))
|
||||
copy(cp, payload)
|
||||
t.deliverMessage(cp)
|
||||
return
|
||||
}
|
||||
|
||||
val, _ := t.recvBufs.LoadOrStore(id, &chunkBuf{chunks: make([][]byte, total)})
|
||||
cb := val.(*chunkBuf)
|
||||
if idx < len(cb.chunks) && cb.chunks[idx] == nil {
|
||||
cp := make([]byte, len(payload))
|
||||
copy(cp, payload)
|
||||
cb.chunks[idx] = cp
|
||||
cb.count++
|
||||
cb.size += len(cp)
|
||||
}
|
||||
if cb.count == total {
|
||||
t.recvBufs.Delete(id)
|
||||
out := make([]byte, 0, cb.size)
|
||||
for _, c := range cb.chunks {
|
||||
out = append(out, c...)
|
||||
}
|
||||
t.deliverMessage(out)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) deliverMessage(data []byte) {
|
||||
if t.onData != nil && len(data) > 0 {
|
||||
frame := make([]byte, 4+len(data))
|
||||
binary.BigEndian.PutUint32(frame[0:4], uint32(len(data)))
|
||||
copy(frame[4:], data)
|
||||
t.onData(frame)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) sendChunked(data []byte) {
|
||||
w := t.writeRaw
|
||||
if w == nil {
|
||||
w = t.raw
|
||||
}
|
||||
if w == nil {
|
||||
return
|
||||
}
|
||||
total := int(math.Ceil(float64(len(data)) / float64(chunkSize)))
|
||||
if total == 0 {
|
||||
total = 1
|
||||
}
|
||||
id := uint16(atomic.AddUint32(&t.sendMsgID, 1)) & 0xFFFF
|
||||
for i := 0; i < total; i++ {
|
||||
start := i * chunkSize
|
||||
end := start + chunkSize
|
||||
if end > len(data) {
|
||||
end = len(data)
|
||||
}
|
||||
p := data[start:end]
|
||||
f := make([]byte, 6+len(p))
|
||||
f[0] = byte(id >> 8)
|
||||
f[1] = byte(id & 0xFF)
|
||||
f[2] = byte(i >> 8)
|
||||
f[3] = byte(i & 0xFF)
|
||||
f[4] = byte(total >> 8)
|
||||
f[5] = byte(total & 0xFF)
|
||||
copy(f[6:], p)
|
||||
t.sendBytes.Add(uint64(len(f)))
|
||||
t.sendMsgs.Add(1)
|
||||
w.Write(f)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DCTunnel) sendRaw(data []byte) {
|
||||
w := t.writeRaw
|
||||
if w == nil {
|
||||
w = t.raw
|
||||
}
|
||||
if w != nil {
|
||||
t.sendBytes.Add(uint64(len(data)))
|
||||
t.sendMsgs.Add(1)
|
||||
w.Write(data)
|
||||
return
|
||||
}
|
||||
if t.dc == nil || t.dc.ReadyState() != webrtc.DataChannelStateOpen {
|
||||
return
|
||||
}
|
||||
t.sendBytes.Add(uint64(len(data)))
|
||||
t.sendMsgs.Add(1)
|
||||
t.dc.Send(data)
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SendData(data []byte) {
|
||||
DecodeFrames(data, func(connID uint32, msgType byte, payload []byte) {
|
||||
buf := make([]byte, 5+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], connID)
|
||||
buf[4] = msgType
|
||||
copy(buf[5:], payload)
|
||||
if t.chunked {
|
||||
t.sendChunked(buf)
|
||||
} else {
|
||||
t.sendRaw(buf)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *DCTunnel) SetOnData(fn func([]byte)) { t.onData = fn }
|
||||
func (t *DCTunnel) SetOnClose(fn func()) { t.onClose = fn }
|
||||
|
||||
func (t *DCTunnel) statsLoop() {
|
||||
if !dcStatsEnabled {
|
||||
return
|
||||
}
|
||||
var lastRecv, lastSend uint64
|
||||
var lastRecvMsgs, lastSendMsgs uint64
|
||||
for {
|
||||
time.Sleep(2 * time.Second)
|
||||
recv := t.recvBytes.Load()
|
||||
send := t.sendBytes.Load()
|
||||
recvMsgs := t.recvMsgs.Load()
|
||||
sendMsgs := t.sendMsgs.Load()
|
||||
recvDelta := recv - lastRecv
|
||||
sendDelta := send - lastSend
|
||||
recvMsgsDelta := recvMsgs - lastRecvMsgs
|
||||
sendMsgsDelta := sendMsgs - lastSendMsgs
|
||||
lastRecv = recv
|
||||
lastSend = send
|
||||
lastRecvMsgs = recvMsgs
|
||||
lastSendMsgs = sendMsgs
|
||||
if recvDelta > 0 || sendDelta > 0 {
|
||||
fmt.Printf("DC-STATS: recv=%dKB/s(%dmsg) send=%dKB/s(%dmsg)\n",
|
||||
recvDelta/2/1024, recvMsgsDelta/2,
|
||||
sendDelta/2/1024, sendMsgsDelta/2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package tunnel
|
||||
|
||||
import "encoding/binary"
|
||||
|
||||
const (
|
||||
MsgConnect byte = 0x01
|
||||
MsgConnectOK byte = 0x02
|
||||
MsgConnectErr byte = 0x03
|
||||
MsgData byte = 0x04
|
||||
MsgClose byte = 0x05
|
||||
MsgUDP byte = 0x06
|
||||
MsgUDPReply byte = 0x07
|
||||
)
|
||||
|
||||
type DataTunnel interface {
|
||||
SendData(data []byte)
|
||||
SetOnData(fn func([]byte))
|
||||
SetOnClose(fn func())
|
||||
}
|
||||
|
||||
func EncodeFrame(connID uint32, msgType byte, payload []byte) []byte {
|
||||
buf := make([]byte, 4+5+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], uint32(5+len(payload)))
|
||||
binary.BigEndian.PutUint32(buf[4:8], connID)
|
||||
buf[8] = msgType
|
||||
copy(buf[9:], payload)
|
||||
return buf
|
||||
}
|
||||
|
||||
func DecodeFrames(data []byte, cb func(connID uint32, msgType byte, payload []byte)) {
|
||||
for len(data) >= 4 {
|
||||
frameLen := int(binary.BigEndian.Uint32(data[0:4]))
|
||||
if frameLen < 5 || 4+frameLen > len(data) {
|
||||
return
|
||||
}
|
||||
connID := binary.BigEndian.Uint32(data[4:8])
|
||||
msgType := data[8]
|
||||
payload := data[9 : 4+frameLen]
|
||||
cb(connID, msgType, payload)
|
||||
data = data[4+frameLen:]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
)
|
||||
|
||||
type udpClient struct {
|
||||
udpConn *net.UDPConn
|
||||
clientAddr *net.UDPAddr
|
||||
socksHdr []byte
|
||||
}
|
||||
|
||||
type RelayBridge struct {
|
||||
tunnel DataTunnel
|
||||
conns sync.Map
|
||||
udpClients sync.Map
|
||||
nextID atomic.Uint32
|
||||
logFn func(string, ...any)
|
||||
mode string
|
||||
readBuf int
|
||||
ready chan struct{}
|
||||
once sync.Once
|
||||
socksUser string
|
||||
socksPass string
|
||||
}
|
||||
|
||||
func NewRelayBridgeWithAuth(tunnel DataTunnel, mode string, readBuf int, logFn func(string, ...any), socksUser, socksPass string) *RelayBridge {
|
||||
rb := NewRelayBridge(tunnel, mode, readBuf, logFn)
|
||||
rb.socksUser = socksUser
|
||||
rb.socksPass = socksPass
|
||||
return rb
|
||||
}
|
||||
|
||||
func NewRelayBridge(tunnel DataTunnel, mode string, readBuf int, logFn func(string, ...any)) *RelayBridge {
|
||||
rb := &RelayBridge{
|
||||
tunnel: tunnel,
|
||||
logFn: logFn,
|
||||
mode: mode,
|
||||
readBuf: readBuf,
|
||||
ready: make(chan struct{}),
|
||||
}
|
||||
tunnel.SetOnData(rb.handleTunnelData)
|
||||
tunnel.SetOnClose(rb.closeAll)
|
||||
return rb
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) closeAll() {
|
||||
rb.logFn("relay: closing all connections")
|
||||
rb.conns.Range(func(key, value any) bool {
|
||||
switch v := value.(type) {
|
||||
case net.Conn:
|
||||
v.Close()
|
||||
case *socksConn:
|
||||
v.conn.Close()
|
||||
}
|
||||
rb.conns.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) MarkReady() {
|
||||
rb.once.Do(func() { close(rb.ready) })
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) send(connID uint32, msgType byte, payload []byte) {
|
||||
frame := EncodeFrame(connID, msgType, payload)
|
||||
rb.tunnel.SendData(frame)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleTunnelData(data []byte) {
|
||||
DecodeFrames(data, func(connID uint32, msgType byte, payload []byte) {
|
||||
switch rb.mode {
|
||||
case "joiner":
|
||||
rb.handleJoinerMessage(connID, msgType, payload)
|
||||
case "creator":
|
||||
rb.handleCreatorMessage(connID, msgType, payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleJoinerMessage(connID uint32, msgType byte, payload []byte) {
|
||||
if msgType == MsgUDPReply {
|
||||
uval, ok := rb.udpClients.Load(connID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
uc := uval.(*udpClient)
|
||||
reply := make([]byte, len(uc.socksHdr)+len(payload))
|
||||
copy(reply, uc.socksHdr)
|
||||
copy(reply[len(uc.socksHdr):], payload)
|
||||
uc.udpConn.WriteToUDP(reply, uc.clientAddr)
|
||||
rb.udpClients.Delete(connID)
|
||||
return
|
||||
}
|
||||
val, ok := rb.conns.Load(connID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sc := val.(*socksConn)
|
||||
switch msgType {
|
||||
case MsgConnectOK:
|
||||
sc.rdy <- nil
|
||||
case MsgConnectErr:
|
||||
sc.rdy <- fmt.Errorf("%s", payload)
|
||||
case MsgData:
|
||||
sc.conn.Write(payload)
|
||||
case MsgClose:
|
||||
sc.conn.Close()
|
||||
rb.conns.Delete(connID)
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload []byte) {
|
||||
switch msgType {
|
||||
case MsgConnect:
|
||||
go rb.connectTCP(connID, string(payload))
|
||||
case MsgUDP:
|
||||
go rb.handleUDP(connID, payload)
|
||||
case MsgData:
|
||||
if val, ok := rb.conns.Load(connID); ok {
|
||||
if c, ok := val.(net.Conn); ok {
|
||||
c.Write(payload)
|
||||
}
|
||||
}
|
||||
case MsgClose:
|
||||
if val, ok := rb.conns.LoadAndDelete(connID); ok {
|
||||
if c, ok := val.(net.Conn); ok {
|
||||
c.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
if len(payload) < 2 {
|
||||
return
|
||||
}
|
||||
addrLen := int(payload[0])
|
||||
if addrLen == 0 || len(payload) < 1+addrLen {
|
||||
return
|
||||
}
|
||||
if bytes.IndexByte(payload[1:1+addrLen], 0) != -1 {
|
||||
return
|
||||
}
|
||||
addr := string(payload[1 : 1+addrLen])
|
||||
data := payload[1+addrLen:]
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
buf := make([]byte, common.UDPBufSize)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rb.send(connID, MsgUDPReply, buf[:n])
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
||||
rb.logFn("relay: CONNECT %d -> %s", connID, common.MaskAddr(addr))
|
||||
conn, err := net.DialTimeout("tcp", addr, 10e9)
|
||||
if err != nil {
|
||||
rb.logFn("relay: CONNECT %d failed: %s", connID, common.MaskError(err))
|
||||
rb.send(connID, MsgConnectErr, []byte(common.MaskError(err)))
|
||||
return
|
||||
}
|
||||
rb.conns.Store(connID, conn)
|
||||
rb.send(connID, MsgConnectOK, nil)
|
||||
rb.logFn("relay: CONNECTED %d -> %s", connID, common.MaskAddr(addr))
|
||||
|
||||
buf := make([]byte, rb.readBuf)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
rb.send(connID, MsgData, buf[:n])
|
||||
}
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
rb.logFn("relay: conn %d read error: %s", connID, common.MaskError(err))
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
rb.send(connID, MsgClose, nil)
|
||||
rb.conns.Delete(connID)
|
||||
}
|
||||
|
||||
type socksConn struct {
|
||||
id uint32
|
||||
conn net.Conn
|
||||
rb *RelayBridge
|
||||
rdy chan error
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) ListenSOCKS(addr string) error {
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rb.logFn("relay: SOCKS5 on %s", addr)
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
rb.logFn("relay: accept error: %v", err)
|
||||
continue
|
||||
}
|
||||
go rb.handleSOCKS(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
<-rb.ready
|
||||
buf := make([]byte, common.HandshakeBuf)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil || n < 2 || buf[0] != common.Ver {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
if !common.NegotiateAuth(conn, buf, n, rb.socksUser, rb.socksPass) {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
n, err = conn.Read(buf)
|
||||
if err != nil || n < 7 || buf[0] != common.Ver {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
cmd := buf[1]
|
||||
if cmd == common.CmdUDP {
|
||||
rb.handleUDPAssociate(conn)
|
||||
return
|
||||
}
|
||||
if cmd != common.CmdTCP {
|
||||
conn.Write(common.CmdErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
host, _, err := common.ParseAddress(buf, n)
|
||||
if err != nil {
|
||||
conn.Write(common.AddrErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
id := rb.nextID.Add(1)
|
||||
sc := &socksConn{id: id, conn: conn, rb: rb, rdy: make(chan error, 1)}
|
||||
rb.conns.Store(id, sc)
|
||||
rb.logFn("relay: SOCKS CONNECT %d -> %s", id, common.MaskAddr(host))
|
||||
rb.send(id, MsgConnect, []byte(host))
|
||||
|
||||
if err := <-sc.rdy; err != nil {
|
||||
rb.logFn("relay: SOCKS CONNECT %d failed: %s", id, common.MaskError(err))
|
||||
conn.Write(common.ConnFail)
|
||||
conn.Close()
|
||||
rb.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
conn.Write(common.OK)
|
||||
rb.logFn("relay: SOCKS CONNECTED %d -> %s", id, common.MaskAddr(host))
|
||||
|
||||
go func() {
|
||||
readBuf := make([]byte, rb.readBuf)
|
||||
for {
|
||||
rn, rerr := conn.Read(readBuf)
|
||||
if rn > 0 {
|
||||
rb.send(id, MsgData, readBuf[:rn])
|
||||
}
|
||||
if rerr != nil {
|
||||
rb.send(id, MsgClose, nil)
|
||||
rb.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
tcpConn.Write(common.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
tcpConn.Write(common.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
localAddr := udpConn.LocalAddr().(*net.UDPAddr)
|
||||
reply := []byte{common.Ver, 0x00, 0x00, common.AtypIPv4, 127, 0, 0, 1, 0, 0}
|
||||
binary.BigEndian.PutUint16(reply[8:10], uint16(localAddr.Port))
|
||||
tcpConn.Write(reply)
|
||||
|
||||
go func() {
|
||||
buf := make([]byte, 1)
|
||||
tcpConn.Read(buf)
|
||||
udpConn.Close()
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer udpConn.Close()
|
||||
defer tcpConn.Close()
|
||||
buf := make([]byte, common.UDPBufSize)
|
||||
for {
|
||||
n, addr, err := udpConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if n < 10 {
|
||||
continue
|
||||
}
|
||||
frag := buf[2]
|
||||
if frag != 0 {
|
||||
continue
|
||||
}
|
||||
dstAddr, headerLen, addrErr := common.ParseAddress(buf, n)
|
||||
if addrErr != nil {
|
||||
continue
|
||||
}
|
||||
id := rb.nextID.Add(1)
|
||||
payload := make([]byte, len(dstAddr)+1+n-headerLen)
|
||||
payload[0] = byte(len(dstAddr))
|
||||
copy(payload[1:], dstAddr)
|
||||
copy(payload[1+len(dstAddr):], buf[headerLen:n])
|
||||
rb.udpClients.Store(id, &udpClient{udpConn: udpConn, clientAddr: addr, socksHdr: buf[:headerLen]})
|
||||
rb.send(id, MsgUDP, payload)
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package tunnel
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
"github.com/pion/webrtc/v4/pkg/media"
|
||||
)
|
||||
|
||||
var vp8Keyframe = []byte{
|
||||
16, 2, 0, 157, 1, 42, 2, 0, 2, 0, 2, 7, 8, 133, 133, 136,
|
||||
153, 132, 136, 11, 2, 0, 12, 13, 96, 0, 254, 252, 173, 16,
|
||||
}
|
||||
|
||||
var vp8Interframe = []byte{
|
||||
177, 1, 0, 8, 17, 24, 0, 24, 0, 24, 88, 47, 244, 0, 8, 0, 0,
|
||||
}
|
||||
|
||||
const DataFrameMarker = 0xFF
|
||||
|
||||
type VP8DataTunnel struct {
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
mu sync.Mutex
|
||||
logFn func(string, ...any)
|
||||
frameCount uint64
|
||||
running bool
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
OnData func([]byte)
|
||||
OnClose func()
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) SetOnData(fn func([]byte)) { t.OnData = fn }
|
||||
func (t *VP8DataTunnel) SetOnClose(fn func()) { t.OnClose = fn }
|
||||
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
return &VP8DataTunnel{
|
||||
track: track,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, 256),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) buildFrame(data []byte) []byte {
|
||||
t.frameCount++
|
||||
if len(data) == 0 {
|
||||
if t.frameCount%60 == 0 {
|
||||
return vp8Keyframe
|
||||
}
|
||||
return vp8Interframe
|
||||
}
|
||||
frame := make([]byte, 1+4+len(data))
|
||||
frame[0] = DataFrameMarker
|
||||
binary.BigEndian.PutUint32(frame[1:5], uint32(len(data)))
|
||||
copy(frame[5:], data)
|
||||
return frame
|
||||
}
|
||||
|
||||
var sendCount atomic.Uint64
|
||||
|
||||
func (t *VP8DataTunnel) SendData(data []byte) {
|
||||
n := sendCount.Add(1)
|
||||
if n <= 5 || n%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", n, len(data), len(t.sendQueue))
|
||||
}
|
||||
t.sendQueue <- data
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Start(fps int) {
|
||||
t.running = true
|
||||
keepaliveInterval := time.Second / time.Duration(fps)
|
||||
lastSend := time.Now()
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(keepaliveInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return
|
||||
case data := <-t.sendQueue:
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(lastSend)
|
||||
minInterval := 5 * time.Millisecond
|
||||
if elapsed < minInterval {
|
||||
time.Sleep(minInterval - elapsed)
|
||||
}
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(data)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
if err != nil {
|
||||
t.logFn("vp8tunnel: WriteSample DATA error: %v (frame %d, %d bytes)", err, t.frameCount-1, len(frame))
|
||||
} else if t.frameCount <= 10 || t.frameCount%100 == 0 {
|
||||
t.logFn("vp8tunnel: WriteSample DATA ok frame=%d size=%d dataLen=%d first=0x%02x", t.frameCount-1, len(frame), len(data), frame[0])
|
||||
}
|
||||
if t.frameCount%60 == 0 {
|
||||
kf := t.buildFrame(nil)
|
||||
t.track.WriteSample(media.Sample{Data: kf, Duration: keepaliveInterval})
|
||||
}
|
||||
ticker.Reset(keepaliveInterval)
|
||||
case <-ticker.C:
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(nil)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
if t.frameCount <= 3 || t.frameCount%500 == 0 {
|
||||
t.logFn("vp8tunnel: KEEPALIVE frame=%d first=0x%02x err=%v", t.frameCount-1, frame[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Stop() {
|
||||
if t.running {
|
||||
close(t.stopCh)
|
||||
t.running = false
|
||||
if t.OnClose != nil {
|
||||
t.OnClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ExtractDataFromPayload(payload []byte) []byte {
|
||||
if len(payload) < 5 {
|
||||
return nil
|
||||
}
|
||||
if payload[0] != DataFrameMarker {
|
||||
return nil
|
||||
}
|
||||
dataLen := binary.BigEndian.Uint32(payload[1:5])
|
||||
if dataLen == 0 || int(dataLen) > len(payload)-5 {
|
||||
return nil
|
||||
}
|
||||
return payload[5 : 5+dataLen]
|
||||
}
|
||||
Reference in new issue
Block a user