project initialized

This commit is contained in:
crusader
2018-08-22 17:37:12 +09:00
commit e78f235740
50 changed files with 6749 additions and 0 deletions

View File

@@ -0,0 +1,534 @@
package client
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
olog "git.loafle.net/overflow/log-go"
"git.loafle.net/overflow/server-go/socket"
"git.loafle.net/overflow/server-go/socket/client"
"git.loafle.net/overflow/server-go/socket/web"
)
var errMalformedURL = errors.New("malformed ws or wss URL")
type Connectors struct {
client.Connectors
URL string `json:"url,omitempty"`
RequestHeader func() http.Header `json:"-"`
Subprotocols []string `json:"subprotocols,omitempty"`
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
CookieJar http.CookieJar `json:"-"`
ResponseHandler func(*http.Response) `json:"-"`
// NetDial specifies the dial function for creating TCP connections. If
// NetDial is nil, net.Dial is used.
NetDial func(network, addr string) (net.Conn, error) `json:"-"`
// 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.
Proxy func(*http.Request) (*url.URL, error) `json:"-"`
serverURL *url.URL
stopChan chan struct{}
stopWg sync.WaitGroup
readChan chan socket.SocketMessage
writeChan chan socket.SocketMessage
disconnectedChan chan struct{}
reconnectedChan chan socket.Conn
crw socket.ClientReadWriter
validated atomic.Value
}
func (c *Connectors) Connect() (readChan <-chan socket.SocketMessage, writeChan chan<- socket.SocketMessage, err error) {
var (
conn socket.Conn
res *http.Response
)
if c.stopChan != nil {
return nil, nil, fmt.Errorf("%s already connected", c.logHeader())
}
conn, res, err = c.connect()
if nil != err {
return nil, nil, err
}
resH := c.ResponseHandler
if nil != resH {
resH(res)
}
c.readChan = make(chan socket.SocketMessage, 256)
c.writeChan = make(chan socket.SocketMessage, 256)
c.disconnectedChan = make(chan struct{})
c.reconnectedChan = make(chan socket.Conn)
c.stopChan = make(chan struct{})
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
c.stopWg.Add(1)
go c.handleReconnect()
c.stopWg.Add(1)
go c.crw.HandleConnection(conn)
return c.readChan, c.writeChan, nil
}
func (c *Connectors) Disconnect() error {
if c.stopChan == nil {
return fmt.Errorf("%s must be connected before disconnection it", c.logHeader())
}
close(c.stopChan)
c.stopWg.Wait()
c.stopChan = nil
return nil
}
func (c *Connectors) logHeader() string {
return fmt.Sprintf("Connector[%s]:", c.Name)
}
func (c *Connectors) onDisconnected() {
close(c.readChan)
close(c.writeChan)
c.reconnectedChan <- nil
onDisconnected := c.OnDisconnected
if nil != onDisconnected {
go func() {
onDisconnected(c)
}()
}
}
func (c *Connectors) handleReconnect() {
defer func() {
c.stopWg.Done()
}()
RC_LOOP:
for {
select {
case <-c.disconnectedChan:
case <-c.stopChan:
return
}
if 0 >= c.GetReconnectTryTime() {
c.onDisconnected()
return
}
olog.Logger().Debugf("%s connection lost", c.logHeader())
for indexI := 0; indexI < c.GetReconnectTryTime(); indexI++ {
olog.Logger().Debugf("%s trying reconnect[%d]", c.logHeader(), indexI)
conn, res, err := c.connect()
if nil == err {
resH := c.ResponseHandler
if nil != resH {
resH(res)
}
olog.Logger().Debugf("%s reconnected", c.logHeader())
c.reconnectedChan <- conn
continue RC_LOOP
}
time.Sleep(c.GetReconnectInterval())
}
olog.Logger().Debugf("%s reconnecting has been failed", c.logHeader())
c.onDisconnected()
return
}
}
func (c *Connectors) connect() (socket.Conn, *http.Response, error) {
conn, res, err := c.dial()
if nil != err {
return nil, nil, err
}
conn.SetCloseHandler(func(code int, text string) error {
olog.Logger().Debugf("%s close", c.logHeader())
return nil
})
return conn, res, nil
}
func (c *Connectors) dial() (socket.Conn, *http.Response, error) {
var (
err error
challengeKey string
netConn net.Conn
)
challengeKey, err = web.GenerateChallengeKey()
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,
}
cookieJar := c.CookieJar
// Set the cookies present in the cookie jar of the dialer
if nil != cookieJar {
for _, cookie := range cookieJar.Cookies(c.serverURL) {
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"}
subprotocols := c.Subprotocols
if len(subprotocols) > 0 {
req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(subprotocols, ", ")}
}
for k, vs := range c.RequestHeader() {
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" ||
(k == "Sec-Websocket-Protocol" && len(subprotocols) > 0):
return nil, nil, fmt.Errorf("%s duplicate header not allowed: %s", c.logHeader(), k)
default:
req.Header[k] = vs
}
}
if c.IsEnableCompression() {
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
proxy := c.Proxy
if nil != proxy {
proxyURL, err = proxy(req)
if err != nil {
return nil, nil, err
}
}
var targetHostPort string
if proxyURL != nil {
targetHostPort, _ = hostPortNoPort(proxyURL)
} else {
targetHostPort = hostPort
}
var deadline time.Time
handshakeTimeout := c.GetHandshakeTimeout()
if 0 != handshakeTimeout {
deadline = time.Now().Add(handshakeTimeout)
}
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 {
cfg := cloneTLSConfig(c.GetTLSConfig())
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
}
}
}
conn := socket.NewConn(netConn, false, c.GetReadBufferSize(), c.GetWriteBufferSize())
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
}
if nil != cookieJar {
if rc := resp.Cookies(); len(rc) > 0 {
cookieJar.SetCookies(c.serverURL, rc)
}
}
if resp.StatusCode != 101 ||
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
resp.Header.Get("Sec-Websocket-Accept") != web.ComputeAcceptKey(challengeKey) {
// 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]))
return nil, resp, socket.ErrBadHandshake
}
for _, ext := range web.HttpParseExtensions(resp.Header) {
if ext[""] != "permessage-deflate" {
continue
}
_, snct := ext["server_no_context_takeover"]
_, cnct := ext["client_no_context_takeover"]
if !snct || !cnct {
return nil, resp, socket.ErrInvalidCompression
}
conn.SetNewCompressionWriter(socket.CompressNoContextTakeover)
conn.SetNewDecompressionReader(socket.DecompressNoContextTakeover)
break
}
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
conn.SetSubprotocol(resp.Header.Get("Sec-Websocket-Protocol"))
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()
}
func (c *Connectors) Clone() client.Connector {
return &Connectors{
Connectors: *c.Connectors.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,
validated: c.validated,
}
}
func (c *Connectors) Validate() error {
if nil != c.validated.Load() {
return nil
}
c.validated.Store(true)
if err := c.Connectors.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
}

View File

@@ -0,0 +1,126 @@
package web
import (
"net/http"
"sync/atomic"
"git.loafle.net/overflow/server-go"
"git.loafle.net/overflow/server-go/socket"
"github.com/valyala/fasthttp"
)
type ServerHandler interface {
socket.ServerHandler
OnError(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx, status int, reason error)
RegisterServlet(path string, servlet Servlet)
Servlet(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx) Servlet
CheckOrigin(ctx *fasthttp.RequestCtx) bool
}
type ServerHandlers struct {
socket.ServerHandlers
servlets map[string]Servlet
validated atomic.Value
}
func (sh *ServerHandlers) Init(serverCtx server.ServerCtx) error {
if err := sh.ServerHandlers.Init(serverCtx); nil != err {
return err
}
if nil != sh.servlets {
for _, servlet := range sh.servlets {
if err := servlet.Init(serverCtx); nil != err {
return err
}
}
}
return nil
}
func (sh *ServerHandlers) OnStart(serverCtx server.ServerCtx) error {
if err := sh.ServerHandlers.OnStart(serverCtx); nil != err {
return err
}
if nil != sh.servlets {
for _, servlet := range sh.servlets {
if err := servlet.OnStart(serverCtx); nil != err {
return err
}
}
}
return nil
}
func (sh *ServerHandlers) OnStop(serverCtx server.ServerCtx) {
if nil != sh.servlets {
for _, servlet := range sh.servlets {
servlet.OnStop(serverCtx)
}
}
sh.ServerHandlers.OnStop(serverCtx)
}
func (sh *ServerHandlers) Destroy(serverCtx server.ServerCtx) {
if nil != sh.servlets {
for _, servlet := range sh.servlets {
servlet.Destroy(serverCtx)
}
}
sh.ServerHandlers.Destroy(serverCtx)
}
func (sh *ServerHandlers) OnError(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx, status int, reason error) {
ctx.Response.Header.Set("Sec-Websocket-Version", "13")
ctx.Error(http.StatusText(status), status)
}
func (sh *ServerHandlers) RegisterServlet(path string, servlet Servlet) {
if nil == sh.servlets {
sh.servlets = make(map[string]Servlet)
}
sh.servlets[path] = servlet
}
func (sh *ServerHandlers) Servlet(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx) Servlet {
path := string(ctx.Path())
var servlet Servlet
if path == "" && len(sh.servlets) == 1 {
for _, s := range sh.servlets {
servlet = s
}
} else if servlet = sh.servlets[path]; nil == servlet {
return nil
}
return servlet
}
func (sh *ServerHandlers) CheckOrigin(ctx *fasthttp.RequestCtx) bool {
return true
}
func (sh *ServerHandlers) Validate() error {
if nil != sh.validated.Load() {
return nil
}
sh.validated.Store(true)
if err := sh.ServerHandlers.Validate(); nil != err {
return err
}
return nil
}

197
socket/web/server.go Normal file
View File

@@ -0,0 +1,197 @@
package web
import (
"context"
"fmt"
"net"
"net/http"
"sync"
"sync/atomic"
olog "git.loafle.net/overflow/log-go"
"git.loafle.net/overflow/server-go"
"git.loafle.net/overflow/server-go/socket"
"github.com/valyala/fasthttp"
)
type Server struct {
ServerHandler ServerHandler
ctx server.ServerCtx
stopChan chan struct{}
stopWg sync.WaitGroup
srw socket.ServerReadWriter
hs *fasthttp.Server
upgrader *Upgrader
}
func (s *Server) ListenAndServe() error {
var (
err error
listener net.Listener
)
if nil == s.ServerHandler {
return fmt.Errorf("%s server handler must be specified", s.logHeader())
}
s.ServerHandler.Validate()
if s.stopChan != nil {
return fmt.Errorf("%s already running. Stop it before starting it again", s.logHeader())
}
s.ctx = s.ServerHandler.ServerCtx()
if nil == s.ctx {
return fmt.Errorf("%s ServerCtx is nil", s.logHeader())
}
s.hs = &fasthttp.Server{
Handler: s.httpHandler,
Name: s.ServerHandler.GetName(),
Concurrency: s.ServerHandler.GetConcurrency(),
ReadBufferSize: s.ServerHandler.GetReadBufferSize(),
WriteBufferSize: s.ServerHandler.GetWriteBufferSize(),
ReadTimeout: s.ServerHandler.GetReadTimeout(),
WriteTimeout: s.ServerHandler.GetWriteTimeout(),
}
s.upgrader = &Upgrader{
HandshakeTimeout: s.ServerHandler.GetHandshakeTimeout(),
ReadBufferSize: s.ServerHandler.GetReadBufferSize(),
WriteBufferSize: s.ServerHandler.GetWriteBufferSize(),
CheckOrigin: s.ServerHandler.(ServerHandler).CheckOrigin,
Error: s.onError,
EnableCompression: s.ServerHandler.IsEnableCompression(),
CompressionLevel: s.ServerHandler.GetCompressionLevel(),
}
if err = s.ServerHandler.Init(s.ctx); nil != err {
olog.Logger().Errorf("%s Init has been failed %v", s.logHeader(), err)
return err
}
if listener, err = s.ServerHandler.Listener(s.ctx); nil != err {
return err
}
s.stopChan = make(chan struct{})
s.srw.ReadwriteHandler = s.ServerHandler
s.srw.ServerStopChan = s.stopChan
s.srw.ServerStopWg = &s.stopWg
s.stopWg.Add(1)
return s.handleServer(listener)
}
func (s *Server) Shutdown(ctx context.Context) error {
if s.stopChan == nil {
return fmt.Errorf("%s must be started before stopping it", s.logHeader())
}
close(s.stopChan)
s.stopWg.Wait()
s.ServerHandler.Destroy(s.ctx)
s.stopChan = nil
return nil
}
func (s *Server) logHeader() string {
return fmt.Sprintf("Server[%s]:", s.ServerHandler.GetName())
}
func (s *Server) handleServer(listener net.Listener) error {
var (
err error
stopping atomic.Value
)
defer func() {
if nil != listener {
listener.Close()
}
s.ServerHandler.OnStop(s.ctx)
olog.Logger().Infof("%s Stopped", s.logHeader())
s.stopWg.Done()
}()
if err = s.ServerHandler.OnStart(s.ctx); nil != err {
olog.Logger().Errorf("%s OnStart has been failed %v", s.logHeader(), err)
return err
}
hsCloseChan := make(chan error)
go func() {
if err := s.hs.Serve(listener); nil != err {
if nil == stopping.Load() {
hsCloseChan <- err
return
}
}
hsCloseChan <- nil
}()
olog.Logger().Infof("%s Started", s.logHeader())
select {
case err, _ := <-hsCloseChan:
if nil != err {
return err
}
case <-s.stopChan:
stopping.Store(true)
listener.Close()
<-hsCloseChan
listener = nil
}
return nil
}
func (s *Server) httpHandler(ctx *fasthttp.RequestCtx) {
var (
servlet Servlet
err error
)
if 0 < s.ServerHandler.GetConcurrency() {
sz := s.srw.ConnectionSize()
if sz >= s.ServerHandler.GetConcurrency() {
olog.Logger().Warnf("%s max connections size %d, refuse", s.logHeader(), sz)
s.onError(ctx, fasthttp.StatusServiceUnavailable, err)
return
}
}
if servlet = s.ServerHandler.Servlet(s.ctx, ctx); nil == servlet {
s.onError(ctx, fasthttp.StatusInternalServerError, err)
return
}
var responseHeader *fasthttp.ResponseHeader
servletCtx := servlet.ServletCtx(s.ctx)
if responseHeader, err = servlet.Handshake(servletCtx, ctx); nil != err {
s.onError(ctx, http.StatusNotAcceptable, fmt.Errorf("Handshake err: %v", err))
return
}
s.upgrader.Upgrade(ctx, responseHeader, func(conn *socket.SocketConn, err error) {
if err != nil {
s.onError(ctx, fasthttp.StatusInternalServerError, err)
return
}
s.stopWg.Add(1)
s.srw.HandleConnection(servlet, servletCtx, conn)
})
}
func (s *Server) onError(ctx *fasthttp.RequestCtx, status int, reason error) {
s.ServerHandler.(ServerHandler).OnError(s.ctx, ctx, status, reason)
}

53
socket/web/servlet.go Normal file
View File

@@ -0,0 +1,53 @@
package web
import (
"git.loafle.net/overflow/server-go"
"git.loafle.net/overflow/server-go/socket"
"github.com/valyala/fasthttp"
)
type Servlet interface {
socket.Servlet
Handshake(servletCtx server.ServletCtx, ctx *fasthttp.RequestCtx) (*fasthttp.ResponseHeader, error)
}
type Servlets struct {
Servlet
}
func (s *Servlets) ServletCtx(serverCtx server.ServerCtx) server.ServletCtx {
return server.NewServletContext(nil, serverCtx)
}
func (s *Servlets) Init(serverCtx server.ServerCtx) error {
return nil
}
func (s *Servlets) OnStart(serverCtx server.ServerCtx) error {
return nil
}
func (s *Servlets) OnStop(serverCtx server.ServerCtx) {
//
}
func (s *Servlets) Destroy(serverCtx server.ServerCtx) {
//
}
func (s *Servlets) Handshake(servletCtx server.ServletCtx, ctx *fasthttp.RequestCtx) (*fasthttp.ResponseHeader, error) {
return nil, nil
}
func (s *Servlets) OnConnect(servletCtx server.ServletCtx, conn socket.Conn) {
//
}
func (s *Servlets) Handle(servletCtx server.ServletCtx, stopChan <-chan struct{}, doneChan chan<- struct{}, readChan <-chan socket.SocketMessage, writeChan chan<- socket.SocketMessage) {
}
func (s *Servlets) OnDisconnect(servletCtx server.ServletCtx) {
//
}

279
socket/web/upgrade.go Normal file
View File

@@ -0,0 +1,279 @@
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"net"
"net/http"
"net/url"
"strings"
"time"
"git.loafle.net/overflow/server-go/socket"
"github.com/valyala/fasthttp"
)
type (
OnUpgradeFunc func(*socket.SocketConn, error)
)
// HandshakeError describes an error with the handshake from the peer.
type HandshakeError struct {
message string
}
func (e HandshakeError) Error() string { return e.message }
// Upgrader specifies parameters for upgrading an HTTP connection to a
// WebSocket connection.
type Upgrader struct {
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
// size is zero, then buffers allocated by the HTTP server are used. The
// I/O buffer sizes do not limit the size of the messages that can be sent
// or received.
ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the server's supported protocols in order of
// preference. If this field is set, then the Upgrade method negotiates a
// subprotocol by selecting the first match in this list with a protocol
// requested by the client.
Subprotocols []string
// Error specifies the function for generating HTTP error responses. If Error
// is nil, then http.Error is used to generate the HTTP response.
Error func(ctx *fasthttp.RequestCtx, status int, reason error)
// CheckOrigin returns true if the request Origin header is acceptable. If
// CheckOrigin is nil, the host in the Origin header must not be set or
// must match the host of the request.
CheckOrigin func(ctx *fasthttp.RequestCtx) bool
// EnableCompression specify if the server should attempt to negotiate per
// message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
CompressionLevel int
}
func (u *Upgrader) returnError(ctx *fasthttp.RequestCtx, status int, reason string) (*socket.SocketConn, error) {
err := HandshakeError{reason}
if u.Error != nil {
u.Error(ctx, status, err)
} else {
ctx.Response.Header.Set("Sec-Websocket-Version", "13")
ctx.Error(http.StatusText(status), status)
}
return nil, err
}
// checkSameOrigin returns true if the origin is not set or is equal to the request host.
func checkSameOrigin(ctx *fasthttp.RequestCtx) bool {
origin := string(ctx.Request.Header.Peek("Origin"))
if len(origin) == 0 {
return true
}
u, err := url.Parse(origin)
if err != nil {
return false
}
return u.Host == string(ctx.Host())
}
func (u *Upgrader) selectSubprotocol(ctx *fasthttp.RequestCtx, responseHeader *fasthttp.ResponseHeader) string {
if u.Subprotocols != nil {
clientProtocols := Subprotocols(ctx)
for _, serverProtocol := range u.Subprotocols {
for _, clientProtocol := range clientProtocols {
if clientProtocol == serverProtocol {
return clientProtocol
}
}
}
} else if responseHeader != nil {
return string(responseHeader.Peek("Sec-Websocket-Protocol"))
}
return ""
}
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
//
// The responseHeader is included in the response to the client's upgrade
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
// application negotiated subprotocol (Sec-Websocket-Protocol).
//
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
// response.
func (u *Upgrader) Upgrade(ctx *fasthttp.RequestCtx, responseHeader *fasthttp.ResponseHeader, cb OnUpgradeFunc) {
if !ctx.IsGet() {
cb(u.returnError(ctx, fasthttp.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET"))
return
}
if nil != responseHeader {
if v := responseHeader.Peek("Sec-Websocket-Extensions"); nil != v {
cb(u.returnError(ctx, fasthttp.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported"))
return
}
}
if !tokenListContainsValue(&ctx.Request.Header, "Connection", "upgrade") {
cb(u.returnError(ctx, fasthttp.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header"))
return
}
if !tokenListContainsValue(&ctx.Request.Header, "Upgrade", "websocket") {
cb(u.returnError(ctx, fasthttp.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header"))
return
}
if !tokenListContainsValue(&ctx.Request.Header, "Sec-Websocket-Version", "13") {
cb(u.returnError(ctx, fasthttp.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header"))
return
}
checkOrigin := u.CheckOrigin
if checkOrigin == nil {
checkOrigin = checkSameOrigin
}
if !checkOrigin(ctx) {
cb(u.returnError(ctx, fasthttp.StatusForbidden, "websocket: 'Origin' header value not allowed"))
return
}
challengeKey := string(ctx.Request.Header.Peek("Sec-Websocket-Key"))
if challengeKey == "" {
cb(u.returnError(ctx, fasthttp.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank"))
return
}
subprotocol := u.selectSubprotocol(ctx, responseHeader)
// Negotiate PMCE
var compress bool
if u.EnableCompression {
for _, ext := range parseExtensions(&ctx.Request.Header) {
if ext[""] != "permessage-deflate" {
continue
}
compress = true
break
}
}
ctx.SetStatusCode(fasthttp.StatusSwitchingProtocols)
ctx.Response.Header.Set("Upgrade", "websocket")
ctx.Response.Header.Set("Connection", "Upgrade")
ctx.Response.Header.Set("Sec-Websocket-Accept", ComputeAcceptKey(challengeKey))
if subprotocol != "" {
ctx.Response.Header.Set("Sec-Websocket-Protocol", subprotocol)
}
if compress {
ctx.Response.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
}
if nil != responseHeader {
responseHeader.VisitAll(func(key, value []byte) {
k := string(key)
v := string(value)
if k == "Sec-Websocket-Protocol" {
return
}
ctx.Response.Header.Set(k, v)
})
}
h := &fasthttp.RequestHeader{}
//copy request headers in order to have access inside the Conn after
ctx.Request.Header.CopyTo(h)
ctx.Hijack(func(netConn net.Conn) {
c := socket.NewConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)
c.SetSubprotocol(subprotocol)
if compress {
c.SetCompressionLevel(u.CompressionLevel)
c.SetNewCompressionWriter(socket.CompressNoContextTakeover)
c.SetNewDecompressionReader(socket.DecompressNoContextTakeover)
}
// Clear deadlines set by HTTP server.
netConn.SetDeadline(time.Time{})
if u.HandshakeTimeout > 0 {
netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
}
if u.HandshakeTimeout > 0 {
netConn.SetWriteDeadline(time.Time{})
}
cb(c, nil)
})
}
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
//
// This function is deprecated, use websocket.Upgrader instead.
//
// The application is responsible for checking the request origin before
// calling Upgrade. An example implementation of the same origin policy is:
//
// if req.Header.Get("Origin") != "http://"+req.Host {
// http.Error(w, "Origin not allowed", 403)
// return
// }
//
// If the endpoint supports subprotocols, then the application is responsible
// for negotiating the protocol used on the connection. Use the Subprotocols()
// function to get the subprotocols requested by the client. Use the
// Sec-Websocket-Protocol response header to specify the subprotocol selected
// by the application.
//
// The responseHeader is included in the response to the client's upgrade
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
// negotiated subprotocol (Sec-Websocket-Protocol).
//
// The connection buffers IO to the underlying network connection. The
// readBufSize and writeBufSize parameters specify the size of the buffers to
// use. Messages can be larger than the buffers.
//
// If the request is not a valid WebSocket handshake, then Upgrade returns an
// error of type HandshakeError. Applications should handle this error by
// replying to the client with an HTTP error response.
func Upgrade(ctx *fasthttp.RequestCtx, responseHeader *fasthttp.ResponseHeader, readBufSize, writeBufSize int, cb OnUpgradeFunc) {
u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
u.Error = func(ctx *fasthttp.RequestCtx, status int, reason error) {
// don't return errors to maintain backwards compatibility
}
u.CheckOrigin = func(ctx *fasthttp.RequestCtx) bool {
// allow all connections by default
return true
}
u.Upgrade(ctx, responseHeader, cb)
}
// Subprotocols returns the subprotocols requested by the client in the
// Sec-Websocket-Protocol header.
func Subprotocols(ctx *fasthttp.RequestCtx) []string {
h := strings.TrimSpace(string(ctx.Request.Header.Peek("Sec-Websocket-Protocol")))
if h == "" {
return nil
}
protocols := strings.Split(h, ",")
for i := range protocols {
protocols[i] = strings.TrimSpace(protocols[i])
}
return protocols
}
// IsWebSocketUpgrade returns true if the client requested upgrade to the
// WebSocket protocol.
func IsWebSocketUpgrade(ctx *fasthttp.RequestCtx) bool {
return tokenListContainsValue(&ctx.Request.Header, "Connection", "upgrade") &&
tokenListContainsValue(&ctx.Request.Header, "Upgrade", "websocket")
}

272
socket/web/util.go Normal file
View File

@@ -0,0 +1,272 @@
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"io"
"net/http"
"strings"
"github.com/valyala/fasthttp"
)
var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
func ComputeAcceptKey(challengeKey string) string {
h := sha1.New()
h.Write([]byte(challengeKey))
h.Write(keyGUID)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func GenerateChallengeKey() (string, error) {
p := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, p); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(p), nil
}
// Octet types from RFC 2616.
var octetTypes [256]byte
const (
isTokenOctet = 1 << iota
isSpaceOctet
)
func init() {
// From RFC 2616
//
// OCTET = <any 8-bit sequence of data>
// CHAR = <any US-ASCII character (octets 0 - 127)>
// CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
// CR = <US-ASCII CR, carriage return (13)>
// LF = <US-ASCII LF, linefeed (10)>
// SP = <US-ASCII SP, space (32)>
// HT = <US-ASCII HT, horizontal-tab (9)>
// <"> = <US-ASCII double-quote mark (34)>
// CRLF = CR LF
// LWS = [CRLF] 1*( SP | HT )
// TEXT = <any OCTET except CTLs, but including LWS>
// separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <">
// | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
// token = 1*<any CHAR except CTLs or separators>
// qdtext = <any TEXT except <">>
for c := 0; c < 256; c++ {
var t byte
isCtl := c <= 31 || c == 127
isChar := 0 <= c && c <= 127
isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0
if strings.IndexRune(" \t\r\n", rune(c)) >= 0 {
t |= isSpaceOctet
}
if isChar && !isCtl && !isSeparator {
t |= isTokenOctet
}
octetTypes[c] = t
}
}
func skipSpace(s string) (rest string) {
i := 0
for ; i < len(s); i++ {
if octetTypes[s[i]]&isSpaceOctet == 0 {
break
}
}
return s[i:]
}
func nextToken(s string) (token string, rest string) {
i := 0
for ; i < len(s); i++ {
if octetTypes[s[i]]&isTokenOctet == 0 {
break
}
}
return s[:i], s[i:]
}
func nextTokenOrQuoted(s string) (value string, rest string) {
if !strings.HasPrefix(s, "\"") {
return nextToken(s)
}
s = s[1:]
for i := 0; i < len(s); i++ {
switch s[i] {
case '"':
return s[:i], s[i+1:]
case '\\':
p := make([]byte, len(s)-1)
j := copy(p, s[:i])
escape := true
for i = i + 1; i < len(s); i++ {
b := s[i]
switch {
case escape:
escape = false
p[j] = b
j++
case b == '\\':
escape = true
case b == '"':
return string(p[:j]), s[i+1:]
default:
p[j] = b
j++
}
}
return "", ""
}
}
return "", ""
}
// tokenListContainsValue returns true if the 1#token header with the given
// name contains token.
func tokenListContainsValue(header *fasthttp.RequestHeader, name string, value string) bool {
s := string(header.Peek(name))
for {
var t string
t, s = nextToken(skipSpace(s))
if t == "" {
break
}
s = skipSpace(s)
if s != "" && s[0] != ',' {
break
}
if strings.EqualFold(t, value) {
return true
}
if s == "" {
break
}
s = s[1:]
}
return false
}
// parseExtensiosn parses WebSocket extensions from a header.
func parseExtensions(header *fasthttp.RequestHeader) []map[string]string {
// From RFC 6455:
//
// Sec-WebSocket-Extensions = extension-list
// extension-list = 1#extension
// extension = extension-token *( ";" extension-param )
// extension-token = registered-token
// registered-token = token
// extension-param = token [ "=" (token | quoted-string) ]
// ;When using the quoted-string syntax variant, the value
// ;after quoted-string unescaping MUST conform to the
// ;'token' ABNF.
s := string(header.Peek("Sec-Websocket-Extensions"))
var result []map[string]string
headers:
for {
var t string
t, s = nextToken(skipSpace(s))
if t == "" {
break headers
}
ext := map[string]string{"": t}
for {
s = skipSpace(s)
if !strings.HasPrefix(s, ";") {
break
}
var k string
k, s = nextToken(skipSpace(s[1:]))
if k == "" {
break headers
}
s = skipSpace(s)
var v string
if strings.HasPrefix(s, "=") {
v, s = nextTokenOrQuoted(skipSpace(s[1:]))
s = skipSpace(s)
}
if s != "" && s[0] != ',' && s[0] != ';' {
break headers
}
ext[k] = v
}
if s != "" && s[0] != ',' {
break headers
}
result = append(result, ext)
if s == "" {
break headers
}
s = s[1:]
}
return result
}
// parseExtensiosn parses WebSocket extensions from a header.
func HttpParseExtensions(header http.Header) []map[string]string {
// From RFC 6455:
//
// Sec-WebSocket-Extensions = extension-list
// extension-list = 1#extension
// extension = extension-token *( ";" extension-param )
// extension-token = registered-token
// registered-token = token
// extension-param = token [ "=" (token | quoted-string) ]
// ;When using the quoted-string syntax variant, the value
// ;after quoted-string unescaping MUST conform to the
// ;'token' ABNF.
var result []map[string]string
headers:
for _, s := range header["Sec-Websocket-Extensions"] {
for {
var t string
t, s = nextToken(skipSpace(s))
if t == "" {
continue headers
}
ext := map[string]string{"": t}
for {
s = skipSpace(s)
if !strings.HasPrefix(s, ";") {
break
}
var k string
k, s = nextToken(skipSpace(s[1:]))
if k == "" {
continue headers
}
s = skipSpace(s)
var v string
if strings.HasPrefix(s, "=") {
v, s = nextTokenOrQuoted(skipSpace(s[1:]))
s = skipSpace(s)
}
if s != "" && s[0] != ',' && s[0] != ';' {
continue headers
}
ext[k] = v
}
if s != "" && s[0] != ',' {
continue headers
}
result = append(result, ext)
if s == "" {
continue headers
}
s = s[1:]
}
}
return result
}