server-go/socket/web/client/connector.go

545 lines
12 KiB
Go
Raw Normal View History

2018-04-12 01:23:40 +00:00
package client
2018-04-04 04:01:26 +00:00
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
2018-04-04 05:31:10 +00:00
"sync"
2018-04-13 07:11:43 +00:00
"sync/atomic"
2018-04-04 04:01:26 +00:00
"time"
2018-04-04 05:47:10 +00:00
"git.loafle.net/commons/logging-go"
2018-04-12 01:23:40 +00:00
"git.loafle.net/commons/server-go/client"
2018-04-05 15:15:29 +00:00
"git.loafle.net/commons/server-go/socket"
2018-04-12 01:23:40 +00:00
"git.loafle.net/commons/server-go/socket/web"
2018-04-04 04:01:26 +00:00
)
var errMalformedURL = errors.New("malformed ws or wss URL")
2018-04-12 01:23:40 +00:00
type Connectors struct {
2018-04-12 05:55:01 +00:00
client.Connectors
2018-04-05 16:21:13 +00:00
socket.ClientConnHandlers
2018-04-05 15:15:29 +00:00
socket.ReadWriteHandlers
2018-04-04 13:28:35 +00:00
2018-04-14 08:49:33 +00:00
URL string `json:"url,omitempty"`
2018-04-04 04:01:26 +00:00
2018-04-14 08:38:15 +00:00
RequestHeader func() http.Header `json:"-"`
2018-04-14 08:49:33 +00:00
Subprotocols []string `json:"subprotocols,omitempty"`
2018-04-04 05:31:10 +00:00
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
2018-04-13 11:48:45 +00:00
CookieJar http.CookieJar `json:"-"`
2018-04-04 04:01:26 +00:00
2018-04-13 11:48:45 +00:00
ResponseHandler func(*http.Response) `json:"-"`
2018-04-04 17:08:07 +00:00
2018-04-04 04:01:26 +00:00
// NetDial specifies the dial function for creating TCP connections. If
// NetDial is nil, net.Dial is used.
2018-04-13 11:48:45 +00:00
NetDial func(network, addr string) (net.Conn, error) `json:"-"`
2018-04-04 04:01:26 +00:00
// Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
// If Proxy is nil or returns a nil *URL, no proxy is used.
2018-04-13 11:48:45 +00:00
Proxy func(*http.Request) (*url.URL, error) `json:"-"`
2018-04-04 04:01:26 +00:00
serverURL *url.URL
2018-04-04 05:31:10 +00:00
2018-04-04 13:28:35 +00:00
stopChan chan struct{}
stopWg sync.WaitGroup
2018-04-04 05:31:10 +00:00
readChan chan []byte
writeChan chan []byte
2018-04-04 13:28:35 +00:00
disconnectedChan chan struct{}
2018-04-05 15:15:29 +00:00
reconnectedChan chan socket.Conn
2018-04-04 13:28:35 +00:00
2018-04-05 15:15:29 +00:00
crw socket.ClientReadWriter
2018-04-13 07:11:43 +00:00
validated atomic.Value
2018-04-04 05:31:10 +00:00
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) Connect() (readChan <-chan []byte, writeChan chan<- []byte, err error) {
2018-04-04 05:31:10 +00:00
var (
2018-04-05 15:15:29 +00:00
conn socket.Conn
2018-04-04 17:08:07 +00:00
res *http.Response
2018-04-04 05:31:10 +00:00
)
if c.stopChan != nil {
2018-04-12 01:23:40 +00:00
return nil, nil, fmt.Errorf("%s already connected", c.logHeader())
2018-04-04 05:31:10 +00:00
}
conn, res, err = c.connect()
if nil != err {
2018-04-04 17:08:07 +00:00
return nil, nil, err
}
resH := c.ResponseHandler
if nil != resH {
resH(res)
2018-04-04 05:31:10 +00:00
}
c.readChan = make(chan []byte, 256)
c.writeChan = make(chan []byte, 256)
2018-04-04 13:28:35 +00:00
c.disconnectedChan = make(chan struct{})
2018-04-05 15:15:29 +00:00
c.reconnectedChan = make(chan socket.Conn)
2018-04-04 05:31:10 +00:00
c.stopChan = make(chan struct{})
2018-04-04 13:28:35 +00:00
2018-04-04 13:50:34 +00:00
c.crw.ReadwriteHandler = c
c.crw.ReadChan = c.readChan
c.crw.WriteChan = c.writeChan
c.crw.ClientStopChan = c.stopChan
c.crw.ClientStopWg = &c.stopWg
c.crw.DisconnectedChan = c.disconnectedChan
c.crw.ReconnectedChan = c.reconnectedChan
2018-04-04 13:28:35 +00:00
2018-04-27 07:22:23 +00:00
c.stopWg.Add(1)
2018-04-04 14:10:09 +00:00
go c.handleReconnect()
2018-04-27 07:22:23 +00:00
c.stopWg.Add(1)
2018-04-04 13:50:34 +00:00
go c.crw.HandleConnection(conn)
2018-04-04 05:31:10 +00:00
2018-04-04 17:08:07 +00:00
return c.readChan, c.writeChan, nil
2018-04-04 05:31:10 +00:00
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) Disconnect() error {
2018-04-04 05:31:10 +00:00
if c.stopChan == nil {
2018-04-12 01:23:40 +00:00
return fmt.Errorf("%s must be connected before disconnection it", c.logHeader())
2018-04-04 05:31:10 +00:00
}
close(c.stopChan)
c.stopWg.Wait()
c.stopChan = nil
return nil
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) logHeader() string {
return fmt.Sprintf("Connector[%s]:", c.Name)
2018-04-04 05:31:10 +00:00
}
2018-04-26 12:48:01 +00:00
func (c *Connectors) onDisconnected() {
2018-04-27 06:24:22 +00:00
close(c.readChan)
close(c.writeChan)
2018-04-26 12:48:01 +00:00
c.reconnectedChan <- nil
onDisconnected := c.OnDisconnected
if nil != onDisconnected {
2018-04-27 07:22:23 +00:00
go func() {
onDisconnected(c)
}()
2018-04-26 12:48:01 +00:00
}
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) handleReconnect() {
2018-04-04 14:10:09 +00:00
defer func() {
c.stopWg.Done()
}()
RC_LOOP:
for {
select {
case <-c.disconnectedChan:
case <-c.stopChan:
return
}
2018-04-12 05:55:01 +00:00
if 0 >= c.GetReconnectTryTime() {
2018-04-26 12:48:01 +00:00
c.onDisconnected()
return
2018-04-04 14:10:09 +00:00
}
2018-04-12 01:23:40 +00:00
logging.Logger().Debugf("%s connection lost", c.logHeader())
2018-04-04 14:22:22 +00:00
2018-04-12 05:55:01 +00:00
for indexI := 0; indexI < c.GetReconnectTryTime(); indexI++ {
2018-04-12 01:23:40 +00:00
logging.Logger().Debugf("%s trying reconnect[%d]", c.logHeader(), indexI)
2018-04-04 14:22:22 +00:00
2018-04-04 17:08:07 +00:00
conn, res, err := c.connect()
2018-04-04 14:10:09 +00:00
if nil == err {
2018-04-04 17:08:07 +00:00
resH := c.ResponseHandler
if nil != resH {
resH(res)
}
2018-04-12 01:23:40 +00:00
logging.Logger().Debugf("%s reconnected", c.logHeader())
2018-04-04 14:10:09 +00:00
c.reconnectedChan <- conn
continue RC_LOOP
}
2018-04-12 05:55:01 +00:00
time.Sleep(c.GetReconnectInterval())
2018-04-04 14:10:09 +00:00
}
2018-04-12 01:23:40 +00:00
logging.Logger().Debugf("%s reconnecting has been failed", c.logHeader())
2018-04-18 12:11:52 +00:00
2018-04-26 12:48:01 +00:00
c.onDisconnected()
return
2018-04-04 14:10:09 +00:00
}
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) connect() (socket.Conn, *http.Response, error) {
2018-04-04 17:08:07 +00:00
conn, res, err := c.dial()
2018-04-04 05:31:10 +00:00
if nil != err {
return nil, nil, err
}
conn.SetCloseHandler(func(code int, text string) error {
2018-04-12 01:23:40 +00:00
logging.Logger().Debugf("%s close", c.logHeader())
2018-04-04 05:31:10 +00:00
return nil
})
return conn, res, nil
}
2018-04-12 01:23:40 +00:00
func (c *Connectors) dial() (socket.Conn, *http.Response, error) {
2018-04-04 04:01:26 +00:00
var (
err error
challengeKey string
netConn net.Conn
)
2018-04-12 01:23:40 +00:00
challengeKey, err = web.GenerateChallengeKey()
2018-04-04 04:01:26 +00:00
if err != nil {
return nil, nil, err
}
req := &http.Request{
Method: "GET",
URL: c.serverURL,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Host: c.serverURL.Host,
}
2018-04-12 05:55:01 +00:00
cookieJar := c.CookieJar
2018-04-04 04:01:26 +00:00
// Set the cookies present in the cookie jar of the dialer
2018-04-12 05:55:01 +00:00
if nil != cookieJar {
for _, cookie := range cookieJar.Cookies(c.serverURL) {
2018-04-04 04:01:26 +00:00
req.AddCookie(cookie)
}
}
// Set the request headers using the capitalization for names and values in
// RFC examples. Although the capitalization shouldn't matter, there are
// servers that depend on it. The Header.Set method is not used because the
// method canonicalizes the header names.
req.Header["Upgrade"] = []string{"websocket"}
req.Header["Connection"] = []string{"Upgrade"}
req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
req.Header["Sec-WebSocket-Version"] = []string{"13"}
2018-04-12 05:55:01 +00:00
subprotocols := c.Subprotocols
if len(subprotocols) > 0 {
req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(subprotocols, ", ")}
2018-04-04 04:01:26 +00:00
}
2018-04-14 08:38:15 +00:00
for k, vs := range c.RequestHeader() {
2018-04-04 04:01:26 +00:00
switch {
case k == "Host":
if len(vs) > 0 {
req.Host = vs[0]
}
case k == "Upgrade" ||
k == "Connection" ||
k == "Sec-Websocket-Key" ||
k == "Sec-Websocket-Version" ||
k == "Sec-Websocket-Extensions" ||
2018-04-12 05:55:01 +00:00
(k == "Sec-Websocket-Protocol" && len(subprotocols) > 0):
2018-04-12 01:23:40 +00:00
return nil, nil, fmt.Errorf("%s duplicate header not allowed: %s", c.logHeader(), k)
2018-04-04 04:01:26 +00:00
default:
req.Header[k] = vs
}
}
2018-04-12 05:55:01 +00:00
if c.IsEnableCompression() {
2018-04-04 04:01:26 +00:00
req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
}
hostPort, hostNoPort := hostPortNoPort(c.serverURL)
var proxyURL *url.URL
// Check wether the proxy method has been configured
2018-04-12 05:55:01 +00:00
proxy := c.Proxy
if nil != proxy {
proxyURL, err = proxy(req)
2018-04-04 04:01:26 +00:00
if err != nil {
return nil, nil, err
}
}
var targetHostPort string
if proxyURL != nil {
targetHostPort, _ = hostPortNoPort(proxyURL)
} else {
targetHostPort = hostPort
}
var deadline time.Time
2018-04-12 05:55:01 +00:00
handshakeTimeout := c.GetHandshakeTimeout()
if 0 != handshakeTimeout {
deadline = time.Now().Add(handshakeTimeout)
2018-04-04 04:01:26 +00:00
}
netDial := c.NetDial
if netDial == nil {
netDialer := &net.Dialer{Deadline: deadline}
netDial = netDialer.Dial
}
netConn, err = netDial("tcp", targetHostPort)
if err != nil {
return nil, nil, err
}
defer func() {
if nil != netConn {
netConn.Close()
}
}()
err = netConn.SetDeadline(deadline)
if nil != err {
return nil, nil, err
}
if nil != proxyURL {
connectHeader := make(http.Header)
if user := proxyURL.User; nil != user {
proxyUser := user.Username()
if proxyPassword, passwordSet := user.Password(); passwordSet {
credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
connectHeader.Set("Proxy-Authorization", "Basic "+credential)
}
}
connectReq := &http.Request{
Method: "CONNECT",
URL: &url.URL{Opaque: hostPort},
Host: hostPort,
Header: connectHeader,
}
connectReq.Write(netConn)
// Read response.
// Okay to use and discard buffered reader here, because
// TLS server will not speak until spoken to.
br := bufio.NewReader(netConn)
resp, err := http.ReadResponse(br, connectReq)
if err != nil {
return nil, nil, err
}
if resp.StatusCode != 200 {
f := strings.SplitN(resp.Status, " ", 2)
return nil, nil, errors.New(f[1])
}
}
if "https" == c.serverURL.Scheme {
2018-04-12 05:55:01 +00:00
cfg := cloneTLSConfig(c.GetTLSConfig())
2018-04-04 04:01:26 +00:00
if cfg.ServerName == "" {
cfg.ServerName = hostNoPort
}
tlsConn := tls.Client(netConn, cfg)
netConn = tlsConn
if err := tlsConn.Handshake(); err != nil {
return nil, nil, err
}
if !cfg.InsecureSkipVerify {
if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
return nil, nil, err
}
}
}
2018-04-12 05:55:01 +00:00
conn := socket.NewConn(netConn, false, c.GetReadBufferSize(), c.GetWriteBufferSize())
2018-04-04 04:01:26 +00:00
if err := req.Write(netConn); err != nil {
return nil, nil, err
}
resp, err := http.ReadResponse(conn.BuffReader, req)
if err != nil {
return nil, nil, err
}
2018-04-12 05:55:01 +00:00
if nil != cookieJar {
2018-04-04 04:01:26 +00:00
if rc := resp.Cookies(); len(rc) > 0 {
2018-04-12 05:55:01 +00:00
cookieJar.SetCookies(c.serverURL, rc)
2018-04-04 04:01:26 +00:00
}
}
if resp.StatusCode != 101 ||
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
2018-04-12 01:23:40 +00:00
resp.Header.Get("Sec-Websocket-Accept") != web.ComputeAcceptKey(challengeKey) {
2018-04-04 04:01:26 +00:00
// Before closing the network connection on return from this
// function, slurp up some of the response to aid application
// debugging.
buf := make([]byte, 1024)
n, _ := io.ReadFull(resp.Body, buf)
resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
2018-04-05 15:15:29 +00:00
return nil, resp, socket.ErrBadHandshake
2018-04-04 04:01:26 +00:00
}
2018-04-12 01:23:40 +00:00
for _, ext := range web.HttpParseExtensions(resp.Header) {
2018-04-04 04:01:26 +00:00
if ext[""] != "permessage-deflate" {
continue
}
_, snct := ext["server_no_context_takeover"]
_, cnct := ext["client_no_context_takeover"]
if !snct || !cnct {
2018-04-05 15:15:29 +00:00
return nil, resp, socket.ErrInvalidCompression
2018-04-04 04:01:26 +00:00
}
2018-04-05 15:15:29 +00:00
conn.SetNewCompressionWriter(socket.CompressNoContextTakeover)
conn.SetNewDecompressionReader(socket.DecompressNoContextTakeover)
2018-04-04 04:01:26 +00:00
break
}
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
2018-04-04 16:51:34 +00:00
conn.SetSubprotocol(resp.Header.Get("Sec-Websocket-Protocol"))
2018-04-04 04:01:26 +00:00
netConn.SetDeadline(time.Time{})
netConn = nil // to avoid close in defer.
return conn, resp, nil
}
// parseURL parses the URL.
//
// This function is a replacement for the standard library url.Parse function.
// In Go 1.4 and earlier, url.Parse loses information from the path.
func parseURL(s string) (*url.URL, error) {
// From the RFC:
//
// ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
// wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
var u url.URL
switch {
case strings.HasPrefix(s, "ws://"):
u.Scheme = "ws"
s = s[len("ws://"):]
case strings.HasPrefix(s, "wss://"):
u.Scheme = "wss"
s = s[len("wss://"):]
default:
return nil, errMalformedURL
}
if i := strings.Index(s, "?"); i >= 0 {
u.RawQuery = s[i+1:]
s = s[:i]
}
if i := strings.Index(s, "/"); i >= 0 {
u.Opaque = s[i:]
s = s[:i]
} else {
u.Opaque = "/"
}
u.Host = s
if strings.Contains(u.Host, "@") {
// Don't bother parsing user information because user information is
// not allowed in websocket URIs.
return nil, errMalformedURL
}
return &u, nil
}
func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
hostPort = u.Host
hostNoPort = u.Host
if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
hostNoPort = hostNoPort[:i]
} else {
switch u.Scheme {
case "wss":
hostPort += ":443"
case "https":
hostPort += ":443"
default:
hostPort += ":80"
}
}
return hostPort, hostNoPort
}
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return cfg.Clone()
}
2018-04-12 05:55:01 +00:00
2018-04-12 08:19:39 +00:00
func (c *Connectors) Clone() client.Connector {
2018-04-12 05:55:01 +00:00
return &Connectors{
Connectors: *c.Connectors.Clone(),
ClientConnHandlers: *c.ClientConnHandlers.Clone(),
ReadWriteHandlers: *c.ReadWriteHandlers.Clone(),
URL: c.URL,
RequestHeader: c.RequestHeader,
Subprotocols: c.Subprotocols,
CookieJar: c.CookieJar,
ResponseHandler: c.ResponseHandler,
NetDial: c.NetDial,
Proxy: c.Proxy,
serverURL: c.serverURL,
2018-04-13 07:11:43 +00:00
validated: c.validated,
2018-04-12 05:55:01 +00:00
}
}
func (c *Connectors) Validate() error {
2018-04-13 07:11:43 +00:00
if nil != c.validated.Load() {
return nil
}
c.validated.Store(true)
2018-04-12 05:55:01 +00:00
if err := c.Connectors.Validate(); nil != err {
return err
}
if err := c.ClientConnHandlers.Validate(); nil != err {
return err
}
if err := c.ReadWriteHandlers.Validate(); nil != err {
return err
}
if "" == c.URL {
return fmt.Errorf("URL is not valid")
}
u, err := parseURL(c.URL)
if nil != err {
return err
}
switch u.Scheme {
case "ws":
u.Scheme = "http"
case "wss":
u.Scheme = "https"
default:
return errMalformedURL
}
if nil != u.User {
// User name and password are not allowed in websocket URIs.
return errMalformedURL
}
c.serverURL = u
if nil == c.Proxy {
c.Proxy = http.ProxyFromEnvironment
}
return nil
}