You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
2.5 KiB
Go

4 years ago
package main
import (
"io"
"net"
"net/url"
log "github.com/fangdingjun/go-log/v5"
"github.com/gorilla/websocket"
)
4 years ago
func forwardWS2WS(conn1, conn2 *websocket.Conn) {
4 years ago
ch := make(chan struct{}, 2)
4 years ago
4 years ago
go func() {
for {
4 years ago
t, data, err := conn1.ReadMessage()
4 years ago
if err != nil {
log.Errorln(err)
break
}
4 years ago
err = conn2.WriteMessage(t, data)
4 years ago
if err != nil {
log.Errorln(err)
break
}
}
ch <- struct{}{}
}()
4 years ago
4 years ago
go func() {
for {
4 years ago
t, data, err := conn2.ReadMessage()
4 years ago
if err != nil {
log.Errorln(err)
break
}
4 years ago
err = conn1.WriteMessage(t, data)
4 years ago
if err != nil {
log.Errorln(err)
break
}
}
ch <- struct{}{}
}()
4 years ago
4 years ago
<-ch
}
func forwardWS2TCP(conn1 *websocket.Conn, conn2 net.Conn) {
ch := make(chan struct{}, 2)
4 years ago
4 years ago
defer func() {
log.Debugf("forward to %s finished", conn2.RemoteAddr())
}()
4 years ago
go func() {
for {
_, data, err := conn1.ReadMessage()
if err != nil {
log.Errorln(err)
break
}
4 years ago
4 years ago
_, err = conn2.Write(data)
if err != nil {
log.Errorln(err)
break
}
}
ch <- struct{}{}
}()
4 years ago
4 years ago
go func() {
buf := make([]byte, 1024)
4 years ago
4 years ago
for {
n, err := conn2.Read(buf)
if err != nil {
if err != io.EOF {
log.Errorln(err)
}
4 years ago
break
}
4 years ago
4 years ago
err = conn1.WriteMessage(websocket.BinaryMessage, buf[:n])
if err != nil {
log.Errorln(err)
break
}
}
ch <- struct{}{}
}()
4 years ago
4 years ago
<-ch
}
func forwardTCP2TCP(c1, c2 net.Conn) {
ch := make(chan struct{}, 2)
4 years ago
4 years ago
go func() {
_, err := io.Copy(c1, c2)
if err != nil {
log.Errorln(err)
}
ch <- struct{}{}
}()
4 years ago
4 years ago
go func() {
_, err := io.Copy(c2, c1)
if err != nil {
log.Errorln(err)
}
ch <- struct{}{}
}()
4 years ago
4 years ago
<-ch
}
4 years ago
func makeServers(cfg conf) {
var wsservers = []wsServer{}
var tcpservers = []tcpServer{}
4 years ago
4 years ago
for _, c := range cfg.ProxyConfig {
u, err := url.Parse(c.Listen)
4 years ago
if err != nil {
4 years ago
log.Fatalf("parse %s, error %s", c.Listen, err)
4 years ago
}
4 years ago
4 years ago
switch u.Scheme {
case "ws":
exists := false
for i := 0; i < len(wsservers); i++ {
if wsservers[i].addr == u.Host {
exists = true
wsservers[i].rule = append(wsservers[i].rule, forwardRule{u.Path, c.Remote})
break
}
}
if !exists {
wsservers = append(wsservers, wsServer{u.Host, []forwardRule{{u.Path, c.Remote}}})
}
case "tcp":
tcpservers = append(tcpservers, tcpServer{u.Host, c.Remote})
default:
log.Fatalf("unsupported scheme %s", u.Scheme)
4 years ago
}
}
4 years ago
for _, srv := range wsservers {
go srv.run()
4 years ago
}
4 years ago
for _, srv := range tcpservers {
go srv.run()
4 years ago
}
}