glider/proxy/ws/ws.go

87 lines
1.6 KiB
Go
Raw Normal View History

2018-07-21 22:56:37 +08:00
package ws
import (
2020-10-19 20:45:57 +08:00
"crypto/rand"
"crypto/sha1"
"encoding/base64"
2018-07-21 22:56:37 +08:00
"net/url"
2020-10-19 20:45:57 +08:00
"strings"
2018-07-21 22:56:37 +08:00
"github.com/nadoo/glider/log"
2020-10-19 20:45:57 +08:00
"github.com/nadoo/glider/pool"
2018-07-21 22:56:37 +08:00
"github.com/nadoo/glider/proxy"
)
2020-10-19 20:45:57 +08:00
var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
2019-09-07 17:17:38 +08:00
// WS is the base ws proxy struct.
2018-07-21 22:56:37 +08:00
type WS struct {
dialer proxy.Dialer
2020-10-19 20:45:57 +08:00
proxy proxy.Proxy
2018-07-21 22:56:37 +08:00
addr string
host string
2020-10-19 20:45:57 +08:00
path string
origin string
2020-10-19 20:45:57 +08:00
server proxy.Server
}
2018-07-21 22:56:37 +08:00
// NewWS returns a websocket proxy.
2020-10-19 20:45:57 +08:00
func NewWS(s string, d proxy.Dialer, p proxy.Proxy) (*WS, error) {
2018-07-21 22:56:37 +08:00
u, err := url.Parse(s)
if err != nil {
log.F("[ws] parse url err: %s", err)
2018-07-21 22:56:37 +08:00
return nil, err
}
addr := u.Host
if addr == "" && d != nil {
addr = d.Addr()
}
2020-10-19 20:45:57 +08:00
w := &WS{
dialer: d,
2020-10-19 20:45:57 +08:00
proxy: p,
addr: addr,
host: u.Query().Get("host"),
2020-10-19 20:45:57 +08:00
path: u.Path,
origin: u.Query().Get("origin"),
}
2020-10-19 20:45:57 +08:00
if w.host == "" {
w.host = addr
}
2020-10-19 20:45:57 +08:00
if w.path == "" {
w.path = "/"
2018-07-21 22:56:37 +08:00
}
2020-10-19 20:45:57 +08:00
return w, nil
2018-07-21 22:56:37 +08:00
}
2020-10-19 20:45:57 +08:00
// parseFirstLine parses "GET /foo HTTP/1.1" OR "HTTP/1.1 200 OK" into its three parts.
// TODO: move to separate http lib package for reuse(also for http proxy module)
func parseFirstLine(line string) (r1, r2, r3 string, ok bool) {
s1 := strings.Index(line, " ")
s2 := strings.Index(line[s1+1:], " ")
if s1 < 0 || s2 < 0 {
return
}
2020-10-19 20:45:57 +08:00
s2 += s1 + 1
return line[:s1], line[s1+1 : s2], line[s2+1:], true
}
2020-10-19 20:45:57 +08:00
func generateClientKey() string {
p := pool.GetBuffer(16)
defer pool.PutBuffer(p)
rand.Read(p)
return base64.StdEncoding.EncodeToString(p)
}
2020-10-19 20:45:57 +08:00
func computeServerKey(clientKey string) string {
h := sha1.New()
h.Write([]byte(clientKey))
h.Write(keyGUID)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}