update structure according to proper go project

This commit is contained in:
Adrien Marquès 2018-09-29 14:36:47 +02:00
parent 53de261a43
commit a9986c3123
10 changed files with 356 additions and 399 deletions

View File

@ -1,13 +1,13 @@
package ws
package websocket
import (
"time"
"sync"
"bufio"
"encoding/binary"
"git.xdrm.io/gws/internal/http/upgrade/request"
"net"
"fmt"
"git.xdrm.io/go/websocket/internal/http/upgrade/request"
"net"
"sync"
"time"
)
// Represents a client socket utility (reader, writer, ..)
@ -35,9 +35,6 @@ type client struct {
status MessageError // close status ; 0 = nothing ; else -> must close
}
// Create creates a new client
func buildClient(s net.Conn, ctl ControllerSet, serverCh serverChannelSet) (*client, error) {
@ -60,7 +57,6 @@ func buildClient(s net.Conn, ctl ControllerSet, serverCh serverChannelSet) (*cli
return nil, fmt.Errorf("Upgrade error (HTTP %d)\n", res.GetStatusCode())
}
/* (2) Initialise client
---------------------------------------------------------*/
/* (1) Get upgrade data */
@ -86,12 +82,10 @@ func buildClient(s net.Conn, ctl ControllerSet, serverCh serverChannelSet) (*cli
},
}
/* (3) Find controller by URI
---------------------------------------------------------*/
/* (1) Try to find one */
controller, arguments := ctl.Match(clientURI);
controller, arguments := ctl.Match(clientURI)
/* (2) If nothing found -> error */
if controller == nil {
@ -101,8 +95,6 @@ func buildClient(s net.Conn, ctl ControllerSet, serverCh serverChannelSet) (*cli
/* (3) Copy arguments */
cli.iface.Arguments = arguments
/* (4) Launch client routines
---------------------------------------------------------*/
/* (1) Launch client controller */
@ -123,9 +115,6 @@ func buildClient(s net.Conn, ctl ControllerSet, serverCh serverChannelSet) (*cli
}
// reader reads and parses messages from the buffer
func clientReader(c *client) {
var frag *Message
@ -149,7 +138,9 @@ func clientReader(c *client){
if err == ErrUnmaskedFrame || err == ErrReservedBits {
closeStatus = PROTOCOL_ERR
}
if err != nil { break }
if err != nil {
break
}
/* (3) Fail on invalid message */
msgErr := msg.check(frag != nil)
@ -184,7 +175,9 @@ func clientReader(c *client){
mustClose = true
}
if mustClose { break }
if mustClose {
break
}
}
@ -248,8 +241,6 @@ func clientReader(c *client){
}
// writer writes into websocket
// and is triggered by client.ch.send channel
func clientWriter(c *client) {
@ -278,9 +269,6 @@ func clientWriter(c *client){
}
// closes the connection
// send CLOSE frame is 'status' is not NONE
// wait for the next message (CLOSE acknowledge) if 'clientACK'
@ -307,8 +295,6 @@ func (c *client) close(status MessageError, clientACK bool){
c.io.sock.SetReadDeadline(time.Now().Add(time.Second * -1))
c.io.reading.Wait()
if status != NONE {
/* (3) Build message */
@ -328,7 +314,6 @@ func (c *client) close(status MessageError, clientACK bool){
}
/* (2) Wait for client CLOSE if needed */
if clientACK {
@ -358,4 +343,3 @@ func (c *client) close(status MessageError, clientACK bool){
return
}

View File

@ -1,12 +1,11 @@
package main
package iface
import (
"git.xdrm.io/gws/ws"
"time"
"fmt"
ws "git.xdrm.io/go/websocket"
"time"
)
func main() {
startTime := time.Now().UnixNano()
@ -18,7 +17,7 @@ func main(){
serv.BindDefault(func(cli *ws.Client, receiver <-chan ws.Message, sender chan<- ws.Message, bc chan<- ws.Message) {
defer func() {
if (recover() != nil) {
if recover() != nil {
fmt.Printf("*** PANIC\n")
}
}()
@ -48,7 +47,9 @@ func main(){
fmt.Printf("[uri] unexpectedly closed\n")
})
if err != nil { panic(err) }
if err != nil {
panic(err)
}
/* (4) Launch the server */
err = serv.Launch()
@ -57,7 +58,6 @@ func main(){
return
}
fmt.Printf("+ elapsed: %1.1f us\n", float32(time.Now().UnixNano()-startTime)/1e3)
}

View File

@ -1,7 +1,7 @@
package ws
package websocket
import (
"git.xdrm.io/gws/internal/uri/parser"
"git.xdrm.io/go/websocket/internal/uri/parser"
)
// Represents available information about a client
@ -26,7 +26,6 @@ type ControllerSet struct {
Uri []*Controller // uri controllers
}
// Match finds a controller for a given URI
// also it returns the matching string patterns
func (s *ControllerSet) Match(uri string) (*Controller, [][]string) {
@ -34,7 +33,6 @@ func (s *ControllerSet) Match(uri string) (*Controller, [][]string){
/* (1) Initialise argument list */
arguments := [][]string{[]string{uri}}
/* (2) Try each controller */
for _, c := range s.Uri {

View File

@ -1,15 +1,13 @@
package request
import (
"git.xdrm.io/gws/internal/http/upgrade/response"
"git.xdrm.io/gws/internal/http/upgrade/request/parser/header"
"fmt"
"git.xdrm.io/go/websocket/internal/http/upgrade/request/parser/header"
"git.xdrm.io/go/websocket/internal/http/upgrade/response"
"strconv"
"strings"
)
// checkHost checks and extracts the Host header
func (r *T) extractHostPort(bb header.HeaderValue) error {
@ -52,12 +50,13 @@ func (r *T) extractHostPort(bb header.HeaderValue) error {
}
// checkOrigin checks the Origin Header
func (r *T) extractOrigin(bb header.HeaderValue) error {
// bypass
if bypassOriginPolicy { return nil }
if bypassOriginPolicy {
return nil
}
if len(bb) != 1 {
r.code = response.FORBIDDEN
@ -152,7 +151,6 @@ func (r *T) extractKey(bb header.HeaderValue) error {
}
// extractProtocols extracts the 'Sec-WebSocket-Protocol' header
// it can contain multiple values
func (r *T) extractProtocols(bb header.HeaderValue) error {

View File

@ -1,12 +1,11 @@
package request
import (
"git.xdrm.io/gws/internal/http/upgrade/response"
"fmt"
"git.xdrm.io/gws/internal/http/upgrade/request/parser/header"
"git.xdrm.io/go/websocket/internal/http/upgrade/request/parser/header"
"git.xdrm.io/go/websocket/internal/http/upgrade/response"
)
// parseHeader parses any http request line
// (header and request-line)
func (r *T) parseHeader(b []byte) error {
@ -27,8 +26,6 @@ func (r *T) parseHeader(b []byte) error {
}
/* (2) Other lines -> Header-Name: Header-Value
---------------------------------------------------------*/
/* (1) Try to parse header */
@ -40,19 +37,25 @@ func (r *T) parseHeader(b []byte) error {
/* (2) Manage header */
switch head.Name {
case header.HOST: err = r.extractHostPort(head.Values)
case header.ORIGIN: err = r.extractOrigin(head.Values)
case header.UPGRADE: err = r.checkUpgrade(head.Values)
case header.CONNECTION: err = r.checkConnection(head.Values)
case header.WSVERSION: err = r.checkVersion(head.Values)
case header.WSKEY: err = r.extractKey(head.Values)
case header.WSPROTOCOL: err = r.extractProtocols(head.Values)
case header.HOST:
err = r.extractHostPort(head.Values)
case header.ORIGIN:
err = r.extractOrigin(head.Values)
case header.UPGRADE:
err = r.checkUpgrade(head.Values)
case header.CONNECTION:
err = r.checkConnection(head.Values)
case header.WSVERSION:
err = r.checkVersion(head.Values)
case header.WSKEY:
err = r.extractKey(head.Values)
case header.WSPROTOCOL:
err = r.extractProtocols(head.Values)
default:
return nil
}
// dispatch error
if err != nil {
return err
@ -62,8 +65,6 @@ func (r *T) parseHeader(b []byte) error {
}
// isComplete returns whether the Upgrade Request
// is complete (no missing required item)
func (r T) isComplete() error {

View File

@ -1,9 +1,9 @@
package request
import (
"git.xdrm.io/gws/internal/http/upgrade/response"
"git.xdrm.io/gws/internal/http/reader"
"fmt"
"git.xdrm.io/go/websocket/internal/http/reader"
"git.xdrm.io/go/websocket/internal/http/upgrade/response"
"io"
)
@ -14,7 +14,6 @@ func Parse(r io.Reader) (request *T, err error) {
req := new(T)
req.code = 500
/* (1) Parse request
---------------------------------------------------------*/
/* (1) Get chunk reader */
@ -50,21 +49,16 @@ func Parse(r io.Reader) (request *T, err error) {
return req, err
}
req.code = response.SWITCHING_PROTOCOLS
return req, nil
}
// StatusCode returns the status current
func (r T) StatusCode() response.StatusCode {
return r.code
}
// BuildResponse builds a response.T from the request
func (r *T) BuildResponse() *response.T {
@ -84,8 +78,6 @@ func (r *T) BuildResponse() *response.T{
return inst
}
// GetURI returns the actual URI
func (r T) GetURI() string {
return r.request.GetURI()

View File

@ -1,6 +1,6 @@
package request
import "git.xdrm.io/gws/internal/http/upgrade/response"
import "git.xdrm.io/go/websocket/internal/http/upgrade/response"
// If origin is required
const bypassOriginPolicy = true

View File

@ -1,10 +1,10 @@
package ws
package websocket
import (
"unicode/utf8"
"encoding/binary"
"fmt"
"io"
"encoding/binary"
"unicode/utf8"
)
var ErrUnmaskedFrame = fmt.Errorf("Received unmasked frame")
@ -18,7 +18,6 @@ var ErrInvalidOpCode = fmt.Errorf("Received invalid OpCode")
var ErrReservedBits = fmt.Errorf("Received reserved bits")
var CloseFrame = fmt.Errorf("Received close Frame")
// Maximum Header Size = Final/OpCode + isMask/Length + Length + Mask
const maximumHeaderSize = 1 + 1 + 8 + 4
const maxWriteChunk = 0x7fff
@ -46,8 +45,7 @@ const (
CLOSE MessageType = 0x08
PING MessageType = 0x09
PONG MessageType = 0x0a
);
)
// Represents a websocket message
type Message struct {
@ -57,7 +55,6 @@ type Message struct {
Data []byte
}
// receive reads a message form reader
func readMessage(reader io.Reader) (*Message, error) {
@ -71,8 +68,9 @@ func readMessage(reader io.Reader) (*Message, error){
/* (2) Byte 1: FIN and OpCode */
tmpBuf = make([]byte, 1)
err = readBytes(reader, tmpBuf)
if err != nil { return m, err }
if err != nil {
return m, err
}
// check reserved bits
if tmpBuf[0]&0x70 != 0 {
@ -85,7 +83,9 @@ func readMessage(reader io.Reader) (*Message, error){
/* (3) Byte 2: Mask and Length[0] */
tmpBuf = make([]byte, 1)
err = readBytes(reader, tmpBuf)
if err != nil { return m, err }
if err != nil {
return m, err
}
// if mask, byte array not nil
if tmpBuf[0]&0x80 == 0x80 {
@ -100,7 +100,9 @@ func readMessage(reader io.Reader) (*Message, error){
tmpBuf = make([]byte, 8)
err := readBytes(reader, tmpBuf)
if err != nil { return m, err }
if err != nil {
return m, err
}
m.Size = uint(binary.BigEndian.Uint64(tmpBuf))
@ -108,7 +110,9 @@ func readMessage(reader io.Reader) (*Message, error){
tmpBuf = make([]byte, 2)
err := readBytes(reader, tmpBuf)
if err != nil { return m, err }
if err != nil {
return m, err
}
m.Size = uint(binary.BigEndian.Uint16(tmpBuf))
@ -119,7 +123,9 @@ func readMessage(reader io.Reader) (*Message, error){
tmpBuf = make([]byte, 4)
err := readBytes(reader, tmpBuf)
if err != nil { return m, err }
if err != nil {
return m, err
}
mask = make([]byte, 4)
copy(mask, tmpBuf)
@ -166,9 +172,6 @@ func readMessage(reader io.Reader) (*Message, error){
}
// Send sends a frame over a socket
func (m Message) Send(writer io.Writer) error {
@ -226,7 +229,9 @@ func (m Message) Send(writer io.Writer) error {
// Try to wrote (at max 1024 bytes) //
nbwritten, err := writer.Write(writeBuf[cursor:maxBoundary])
if err != nil { return err }
if err != nil {
return err
}
// Update cursor //
cursor += nbwritten
@ -236,9 +241,6 @@ func (m Message) Send(writer io.Writer) error {
return nil
}
// Check for message errors with:
// (m) the current message
// (fragment) whether there is a fragment in construction
@ -312,8 +314,6 @@ func (m *Message) check(fragment bool) error{
return nil
}
// readBytes reads from a reader into a byte array
// until the byte length is fully filled with data
// loops while there is no error

View File

@ -1,12 +1,11 @@
package ws
package websocket
import (
"io"
"bytes"
"io"
"testing"
)
func TestSimpleMessageReading(t *testing.T) {
cases := []struct {
@ -108,7 +107,6 @@ func TestSimpleMessageReading(t *testing.T) {
}
func TestReadEOF(t *testing.T) {
cases := []struct {
@ -207,8 +205,6 @@ func TestReadEOF(t *testing.T) {
}
func TestSimpleMessageSending(t *testing.T) {
m4b1 := make([]byte, 0x7e-1)
@ -263,7 +259,7 @@ func TestSimpleMessageSending(t *testing.T) {
}, {
"10000 > extended 64 bits length",
Message{true, TEXT, uint(len(m16b3)), m16b3},
append([]byte{0x81,127, 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,}, m16b3...),
append([]byte{0x81, 127, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}, m16b3...),
},
}
@ -291,9 +287,6 @@ func TestSimpleMessageSending(t *testing.T) {
}
func TestMessageCheck(t *testing.T) {
type Case struct {
@ -516,27 +509,26 @@ func TestMessageCheck(t *testing.T) {
}, {
Name: "OpCode check",
Cases: []Case{
{ "0", Message{true, 0, 0, []byte{}}, false, ErrUnexpectedContinuation, },
{ "1", Message{true, 1, 0, []byte{}}, false, nil, },
{ "2", Message{true, 2, 0, []byte{}}, false, nil, },
{ "3", Message{true, 3, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "4", Message{true, 4, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "5", Message{true, 5, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "6", Message{true, 6, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "7", Message{true, 7, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "8", Message{true, 8, 0, []byte{}}, false, CloseFrame, },
{ "9", Message{true, 9, 0, []byte{}}, false, nil, },
{ "10", Message{true, 10, 0, []byte{}}, false, nil, },
{ "11", Message{true, 11, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "12", Message{true, 12, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "13", Message{true, 13, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "14", Message{true, 14, 0, []byte{}}, false, ErrInvalidOpCode, },
{ "15", Message{true, 15, 0, []byte{}}, false, ErrInvalidOpCode, },
{"0", Message{true, 0, 0, []byte{}}, false, ErrUnexpectedContinuation},
{"1", Message{true, 1, 0, []byte{}}, false, nil},
{"2", Message{true, 2, 0, []byte{}}, false, nil},
{"3", Message{true, 3, 0, []byte{}}, false, ErrInvalidOpCode},
{"4", Message{true, 4, 0, []byte{}}, false, ErrInvalidOpCode},
{"5", Message{true, 5, 0, []byte{}}, false, ErrInvalidOpCode},
{"6", Message{true, 6, 0, []byte{}}, false, ErrInvalidOpCode},
{"7", Message{true, 7, 0, []byte{}}, false, ErrInvalidOpCode},
{"8", Message{true, 8, 0, []byte{}}, false, CloseFrame},
{"9", Message{true, 9, 0, []byte{}}, false, nil},
{"10", Message{true, 10, 0, []byte{}}, false, nil},
{"11", Message{true, 11, 0, []byte{}}, false, ErrInvalidOpCode},
{"12", Message{true, 12, 0, []byte{}}, false, ErrInvalidOpCode},
{"13", Message{true, 13, 0, []byte{}}, false, ErrInvalidOpCode},
{"14", Message{true, 14, 0, []byte{}}, false, ErrInvalidOpCode},
{"15", Message{true, 15, 0, []byte{}}, false, ErrInvalidOpCode},
},
},
}
for _, tcc := range cases {
t.Run(tcc.Name, func(t *testing.T) {

View File

@ -1,9 +1,9 @@
package ws
package websocket
import (
"net"
"fmt"
"git.xdrm.io/gws/internal/uri/parser"
"git.xdrm.io/go/websocket/internal/uri/parser"
"net"
)
// Represents all channels that need a server
@ -13,7 +13,6 @@ type serverChannelSet struct{
broadcast chan Message
}
// Represents a websocket server
type Server struct {
sock net.Listener // listen socket
@ -27,9 +26,6 @@ type Server struct {
ch serverChannelSet
}
// CreateServer creates a server for a specific HOST and PORT
func CreateServer(host string, port uint16) *Server {
@ -53,7 +49,6 @@ func CreateServer(host string, port uint16) *Server{
}
// BindDefault binds a default controller
// it will be called if the URI does not
// match another controller
@ -66,13 +61,14 @@ func (s *Server) BindDefault(f ControllerFunc){
}
// Bind binds a controller to an URI scheme
func (s *Server) Bind(uri string, f ControllerFunc) error {
/* (1) Build URI parser */
uriScheme, err := parser.Build(uri)
if err != nil { return fmt.Errorf("Cannot build URI: %s", err) }
if err != nil {
return fmt.Errorf("Cannot build URI: %s", err)
}
/* (2) Create controller */
s.ctl.Uri = append(s.ctl.Uri, &Controller{
@ -84,7 +80,6 @@ func (s *Server) Bind(uri string, f ControllerFunc) error {
}
// Launch launches the websocket server
func (s *Server) Launch() error {
@ -108,8 +103,6 @@ func (s *Server) Launch() error {
/* (3) Launch scheduler */
go s.scheduler()
/* (2) For each incoming connection (client)
---------------------------------------------------------*/
for {
@ -140,7 +133,6 @@ func (s *Server) Launch() error {
}
// Scheduler schedules clients registration and broadcast
func (s *Server) scheduler() {