| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- package ws
- import (
- "crypto/tls"
- "fmt"
- "io/ioutil"
- "net"
- "github.com/gorilla/websocket"
- "v2ray.com/core/common/log"
- v2net "v2ray.com/core/common/net"
- "v2ray.com/core/transport/internet"
- )
- var (
- globalCache = NewConnectionCache()
- )
- func Dial(src v2net.Address, dest v2net.Destination) (internet.Connection, error) {
- log.Info("WebSocket|Dailer: Creating connection to ", dest)
- if src == nil {
- src = v2net.AnyIP
- }
- id := src.String() + "-" + dest.NetAddr()
- var conn *wsconn
- if dest.Network() == v2net.TCPNetwork && effectiveConfig.ConnectionReuse {
- connt := globalCache.Get(id)
- if connt != nil {
- conn = connt.(*wsconn)
- }
- }
- if conn == nil {
- var err error
- conn, err = wsDial(src, dest)
- if err != nil {
- log.Warning("WebSocket|Dialer: Dial failed: ", err)
- return nil, err
- }
- }
- return NewConnection(id, conn, globalCache), nil
- }
- func init() {
- internet.WSDialer = Dial
- }
- func wsDial(src v2net.Address, dest v2net.Destination) (*wsconn, error) {
- commonDial := func(network, addr string) (net.Conn, error) {
- return internet.DialToDest(src, dest)
- }
- tlsconf := &tls.Config{ServerName: dest.Address().Domain(), InsecureSkipVerify: effectiveConfig.DeveloperInsecureSkipVerify}
- dialer := websocket.Dialer{NetDial: commonDial, ReadBufferSize: 65536, WriteBufferSize: 65536, TLSClientConfig: tlsconf}
- effpto := calcPto(dest)
- uri := func(dst v2net.Destination, pto string, path string) string {
- return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
- }(dest, effpto, effectiveConfig.Path)
- conn, resp, err := dialer.Dial(uri, nil)
- if err != nil {
- if resp != nil {
- reason, reasonerr := ioutil.ReadAll(resp.Body)
- log.Info(string(reason), reasonerr)
- }
- return nil, err
- }
- return func() internet.Connection {
- connv2ray := &wsconn{wsc: conn, connClosing: false}
- connv2ray.setup()
- return connv2ray
- }().(*wsconn), nil
- }
- func calcPto(dst v2net.Destination) string {
- if effectiveConfig.Pto != "" {
- return effectiveConfig.Pto
- }
- switch dst.Port().Value() {
- /*
- Since the value is not given explicitly,
- We are guessing it now.
- HTTP Port:
- 80
- 8080
- 8880
- 2052
- 2082
- 2086
- 2095
- HTTPS Port:
- 443
- 2053
- 2083
- 2087
- 2096
- 8443
- if the port you are using is not well-known,
- specify it to avoid this process.
- We will return "CRASH"turn "unknown" if we can't guess it, cause Dial to fail.
- */
- case 80, 8080, 8880, 2052, 2082, 2086, 2095:
- return "ws"
- case 443, 2053, 2083, 2087, 2096, 8443:
- return "wss"
- default:
- return "unknown"
- }
- }
|