给每个tunnel加ID

Signed-off-by: dmy@lab <dmy@lab.com>
This commit is contained in:
dmy@lab 2015-10-10 18:28:19 +08:00
parent 9c4dafc07d
commit e7bdc58c97
2 changed files with 30 additions and 12 deletions

View File

@ -5,6 +5,12 @@ import (
"fmt"
)
func Tunnel() {
trans := NewTransTCP()
trans.Start("1200", "127.0.0.1", "8118")
}
func main() {
fmt.Println("Hello World!")
Tunnel()
}

36
tcp.go
View File

@ -1,20 +1,26 @@
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"github.com/TransX/tscipher"
// "io"
"log"
"net"
"strconv"
"sync/atomic"
"time"
)
type TransTCP struct {
// serverConn *net.Conn
// clientConn net.Conn
// cache []byte
seed int32
}
func NewTransTCP() *TransTCP {
return &TransTCP{}
return &TransTCP{
0,
}
}
func (this *TransTCP) createTCPClient(ip, port string) (conn net.Conn, err error) {
@ -40,7 +46,7 @@ func (this *TransTCP) createTCPListener(ip, port string) (listen net.Listener, e
return
}
func (this *TransTCP) tunnel(src, dest net.Conn) {
func (this *TransTCP) tunnel(src, dest net.Conn, id string) {
defer func() {
if r := recover(); r != nil {
if src != nil {
@ -62,9 +68,9 @@ func (this *TransTCP) tunnel(src, dest net.Conn) {
}
nByte, err := tscipher.ReceiveData(revCarrier)
if err != nil {
log.Panicln("Read panic", err, src.RemoteAddr().String())
log.Panicln("Read panic", id, err, src.RemoteAddr().String())
}
log.Println("Reived ", string(cache[:nByte]))
log.Println("Reived ", id, string(cache[:nByte]))
sendCarrier := &tscipher.Carrier{
dest,
tscipher.NewCipher("default"),
@ -73,12 +79,19 @@ func (this *TransTCP) tunnel(src, dest net.Conn) {
_, err = tscipher.SendData(sendCarrier, nByte)
log.Println("Write")
if err != nil {
log.Panicln("Write panic", err, dest.RemoteAddr().String())
log.Panicln("Write panic", id, err, dest.RemoteAddr().String())
}
}
}
func (this *TransTCP) tunnelID() string {
nowString := time.Now().String() + strconv.Itoa(int(this.seed))
atomic.AddInt32(&this.seed, 1) //避免多线程情况下获得的种子相同
md5Byte := md5.Sum(bytes.NewBufferString(nowString).Bytes())
return hex.EncodeToString(md5Byte[:])
}
func (this *TransTCP) Start(listenPort, destIP, destPort string) {
listener, err := this.createTCPListener("0.0.0.0", listenPort)
@ -94,11 +107,10 @@ func (this *TransTCP) Start(listenPort, destIP, destPort string) {
log.Fatalln("Failed to connect to destination.", err)
}
log.Println("Dial", destConn.RemoteAddr().String())
go this.tunnel(listenerConn, destConn)
go this.tunnel(destConn, listenerConn)
go this.tunnel(listenerConn, destConn, this.tunnelID())
go this.tunnel(destConn, listenerConn, this.tunnelID())
} else {
log.Println("Failed to accept incoming connection.", err)
}
}
}