| 1 | package net |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net" |
| 6 | "net/url" |
| 7 | |
| 8 | libnet "github.com/fatedier/golib/net" |
| 9 | "golang.org/x/net/websocket" |
| 10 | ) |
| 11 | |
| 12 | func DialHookCustomTLSHeadByte(enableTLS bool, disableCustomTLSHeadByte bool) libnet.AfterHookFunc { |
| 13 | return func(ctx context.Context, c net.Conn, addr string) (context.Context, net.Conn, error) { |
| 14 | if enableTLS && !disableCustomTLSHeadByte { |
| 15 | _, err := c.Write([]byte{byte(FRPTLSHeadByte)}) |
| 16 | if err != nil { |
| 17 | return nil, nil, err |
| 18 | } |
| 19 | } |
| 20 | return ctx, c, nil |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | func DialHookWebsocket(protocol string, host string) libnet.AfterHookFunc { |
| 25 | return func(ctx context.Context, c net.Conn, addr string) (context.Context, net.Conn, error) { |
| 26 | if protocol != "wss" { |
| 27 | protocol = "ws" |
| 28 | } |
| 29 | if host == "" { |
| 30 | host = addr |
| 31 | } |
| 32 | addr = protocol + "://" + host + FrpWebsocketPath |
| 33 | uri, err := url.Parse(addr) |
| 34 | if err != nil { |
| 35 | return nil, nil, err |
| 36 | } |
| 37 | |
| 38 | origin := "http://" + uri.Host |
| 39 | cfg, err := websocket.NewConfig(addr, origin) |
| 40 | if err != nil { |
| 41 | return nil, nil, err |
| 42 | } |
| 43 | |
| 44 | conn, err := websocket.NewClient(cfg, c) |
| 45 | if err != nil { |
| 46 | return nil, nil, err |
| 47 | } |
| 48 | // The tunnel payload is a raw byte stream (yamux), not UTF-8 text. |
| 49 | // Send it as binary frames; otherwise RFC 6455-compliant intermediaries |
| 50 | // (e.g. API gateways/reverse proxies) UTF-8-validate the default text |
| 51 | // frames and close the connection on invalid bytes. |
| 52 | conn.PayloadType = websocket.BinaryFrame |
| 53 | return ctx, conn, nil |
| 54 | } |
| 55 | } |