Added server for web sockets, plus some refactoring

This commit is contained in:
amit bezalel 2017-07-01 23:01:58 +03:00
parent 66c322c164
commit 076d8bb4cf
28 changed files with 1774 additions and 1716 deletions

View File

@ -5,6 +5,7 @@
<root url="file://$PROJECT_DIR$/../gopkg.in" /> <root url="file://$PROJECT_DIR$/../gopkg.in" />
<root url="file://$PROJECT_DIR$/../vncproxy1" /> <root url="file://$PROJECT_DIR$/../vncproxy1" />
<root url="file://$PROJECT_DIR$/../GoProjExample" /> <root url="file://$PROJECT_DIR$/../GoProjExample" />
<root url="file://$PROJECT_DIR$/../govmomi-fork" />
<root url="file://$PROJECT_DIR$/../srf.opb" /> <root url="file://$PROJECT_DIR$/../srf.opb" />
<root url="file://$PROJECT_DIR$/../vshpere-cli" /> <root url="file://$PROJECT_DIR$/../vshpere-cli" />
<root url="file://$PROJECT_DIR$/../sourcegraph.com" /> <root url="file://$PROJECT_DIR$/../sourcegraph.com" />
@ -26,6 +27,7 @@
<root url="file://$PROJECT_DIR$/../gopkg.in" /> <root url="file://$PROJECT_DIR$/../gopkg.in" />
<root url="file://$PROJECT_DIR$/../vncproxy1" /> <root url="file://$PROJECT_DIR$/../vncproxy1" />
<root url="file://$PROJECT_DIR$/../GoProjExample" /> <root url="file://$PROJECT_DIR$/../GoProjExample" />
<root url="file://$PROJECT_DIR$/../govmomi-fork" />
<root url="file://$PROJECT_DIR$/../srf.opb" /> <root url="file://$PROJECT_DIR$/../srf.opb" />
<root url="file://$PROJECT_DIR$/../vshpere-cli" /> <root url="file://$PROJECT_DIR$/../vshpere-cli" />
<root url="file://$PROJECT_DIR$/../sourcegraph.com" /> <root url="file://$PROJECT_DIR$/../sourcegraph.com" />

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"bytes" "bytes"
@ -8,7 +8,7 @@ import (
"net" "net"
"unicode" "unicode"
"vncproxy/common" "vncproxy/common"
"vncproxy/listeners" "vncproxy/tee-listeners"
) )
// A ServerMessage implements a message sent from the server to the client. // A ServerMessage implements a message sent from the server to the client.

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"net" "net"

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"testing" "testing"

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package vnc package client
// Color represents a single color in a color map. // Color represents a single color in a color map.
type Color struct { type Color struct {

BIN
client/debug.test Normal file

Binary file not shown.

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package vnc package client
// ButtonMask represents a mask of pointer presses/releases. // ButtonMask represents a mask of pointer presses/releases.
type ButtonMask uint8 type ButtonMask uint8

View File

@ -1,4 +1,4 @@
package vnc package client
import ( import (
"encoding/binary" "encoding/binary"

View File

@ -1,9 +1,6 @@
package common package common
import ( import "io"
"io"
"net"
)
type ClientMessageType uint8 type ClientMessageType uint8
@ -31,8 +28,8 @@ type Color struct {
type ColorMap [256]Color type ColorMap [256]Color
type Conn interface { type Conn interface {
io.ReadWriteCloser io.ReadWriter
Conn() net.Conn Conn() io.ReadWriter
Protocol() string Protocol() string
PixelFormat() *PixelFormat PixelFormat() *PixelFormat
SetPixelFormat(*PixelFormat) error SetPixelFormat(*PixelFormat) error
@ -46,7 +43,7 @@ type Conn interface {
SetHeight(uint16) SetHeight(uint16)
DesktopName() string DesktopName() string
SetDesktopName(string) SetDesktopName(string)
Flush() error //Flush() error
SetProtoVersion(string) SetProtoVersion(string)
} }

10
main.go
View File

@ -6,7 +6,7 @@ import (
"time" "time"
"vncproxy/common" "vncproxy/common"
"vncproxy/encodings" "vncproxy/encodings"
"vncproxy/vnc" "vncproxy/client"
) )
func main() { func main() {
@ -17,12 +17,12 @@ func main() {
if err != nil { if err != nil {
fmt.Printf("error connecting to vnc server: %s", err) fmt.Printf("error connecting to vnc server: %s", err)
} }
var noauth vnc.ClientAuthNone var noauth client.ClientAuthNone
authArr := []vnc.ClientAuth{&vnc.PasswordAuth{Password: "Ch_#!T@8"}, &noauth} authArr := []client.ClientAuth{&client.PasswordAuth{Password: "Ch_#!T@8"}, &noauth}
vncSrvMessagesChan := make(chan common.ServerMessage) vncSrvMessagesChan := make(chan common.ServerMessage)
clientConn, err := vnc.Client(nc, clientConn, err := client.Client(nc,
&vnc.ClientConfig{ &client.ClientConfig{
Auth: authArr, Auth: authArr,
ServerMessageCh: vncSrvMessagesChan, ServerMessageCh: vncSrvMessagesChan,
Exclusive: true, Exclusive: true,

View File

@ -39,7 +39,7 @@ func (msg *SetPixelFormat) Write(c common.Conn) error {
c.SetColorMap(&common.ColorMap{}) c.SetColorMap(&common.ColorMap{})
} }
return c.Flush() return nil
} }
func (*SetPixelFormat) Read(c common.Conn) (common.ClientMessage, error) { func (*SetPixelFormat) Read(c common.Conn) (common.ClientMessage, error) {
@ -103,7 +103,7 @@ func (msg *SetEncodings) Write(c common.Conn) error {
return err return err
} }
} }
return c.Flush() return nil
} }
// FramebufferUpdateRequest holds the wire format message. // FramebufferUpdateRequest holds the wire format message.
@ -132,7 +132,7 @@ func (msg *FramebufferUpdateRequest) Write(c common.Conn) error {
if err := binary.Write(c, binary.BigEndian, msg); err != nil { if err := binary.Write(c, binary.BigEndian, msg); err != nil {
return err return err
} }
return c.Flush() return nil
} }
// KeyEvent holds the wire format message. // KeyEvent holds the wire format message.
@ -161,7 +161,7 @@ func (msg *KeyEvent) Write(c common.Conn) error {
if err := binary.Write(c, binary.BigEndian, msg); err != nil { if err := binary.Write(c, binary.BigEndian, msg); err != nil {
return err return err
} }
return c.Flush() return nil
} }
// PointerEventMessage holds the wire format message. // PointerEventMessage holds the wire format message.
@ -189,7 +189,7 @@ func (msg *PointerEvent) Write(c common.Conn) error {
if err := binary.Write(c, binary.BigEndian, msg); err != nil { if err := binary.Write(c, binary.BigEndian, msg); err != nil {
return err return err
} }
return c.Flush() return nil
} }
// ClientCutText holds the wire format message, sans the text field. // ClientCutText holds the wire format message, sans the text field.
@ -243,5 +243,5 @@ func (msg *ClientCutText) Write(c common.Conn) error {
return err return err
} }
return c.Flush() return nil
} }

Binary file not shown.

View File

@ -7,20 +7,6 @@ import (
"io" "io"
) )
// // ClientMessage is the interface
// type ClientMessage interface {
// Type() ClientMessageType
// Read(Conn) (ClientMessage, error)
// Write(Conn) error
// }
// // ServerMessage is the interface
// type ServerMessage interface {
// Type() ServerMessageType
// Read(Conn) (ServerMessage, error)
// Write(Conn) error
// }
const ProtoVersionLength = 12 const ProtoVersionLength = 12
const ( const (
@ -47,45 +33,14 @@ func ParseProtoVersion(pv []byte) (uint, uint, error) {
return major, minor, nil return major, minor, nil
} }
// func ClientVersionHandler(cfg *ClientConfig, c ServerConn) error {
// var version [ProtoVersionLength]byte
// if err := binary.Read(c, binary.BigEndian, &version); err != nil {
// return err
// }
// major, minor, err := ParseProtoVersion(version[:])
// if err != nil {
// return err
// }
// pv := ProtoVersionUnknown
// if major == 3 {
// if minor >= 8 {
// pv = ProtoVersion38
// } else if minor >= 3 {
// pv = ProtoVersion38
// }
// }
// if pv == ProtoVersionUnknown {
// return fmt.Errorf("ProtocolVersion handshake failed; unsupported version '%v'", string(version[:]))
// }
// c.SetProtoVersion(string(version[:]))
// if err := binary.Write(c, binary.BigEndian, []byte(pv)); err != nil {
// return err
// }
// return c.Flush()
// }
func ServerVersionHandler(cfg *ServerConfig, c *ServerConn) error { func ServerVersionHandler(cfg *ServerConfig, c *ServerConn) error {
var version [ProtoVersionLength]byte var version [ProtoVersionLength]byte
if err := binary.Write(c, binary.BigEndian, []byte(ProtoVersion38)); err != nil { if err := binary.Write(c, binary.BigEndian, []byte(ProtoVersion38)); err != nil {
return err return err
} }
if err := c.Flush(); err != nil { // if err := c.Flush(); err != nil {
return err // return err
} // }
if err := binary.Read(c, binary.BigEndian, &version); err != nil { if err := binary.Read(c, binary.BigEndian, &version); err != nil {
return err return err
} }
@ -111,58 +66,6 @@ func ServerVersionHandler(cfg *ServerConfig, c *ServerConn) error {
return nil return nil
} }
// func ClientSecurityHandler(cfg *ClientConfig, c Conn) error {
// var numSecurityTypes uint8
// if err := binary.Read(c, binary.BigEndian, &numSecurityTypes); err != nil {
// return err
// }
// secTypes := make([]SecurityType, numSecurityTypes)
// if err := binary.Read(c, binary.BigEndian, &secTypes); err != nil {
// return err
// }
// var secType SecurityHandler
// for _, st := range cfg.SecurityHandlers {
// for _, sc := range secTypes {
// if st.Type() == sc {
// secType = st
// }
// }
// }
// if err := binary.Write(c, binary.BigEndian, cfg.SecurityHandlers[0].Type()); err != nil {
// return err
// }
// if err := c.Flush(); err != nil {
// return err
// }
// err := secType.Auth(c)
// if err != nil {
// return err
// }
// var authCode uint32
// if err := binary.Read(c, binary.BigEndian, &authCode); err != nil {
// return err
// }
// if authCode == 1 {
// var reasonLength uint32
// if err := binary.Read(c, binary.BigEndian, &reasonLength); err != nil {
// return err
// }
// reasonText := make([]byte, reasonLength)
// if err := binary.Read(c, binary.BigEndian, &reasonText); err != nil {
// return err
// }
// return fmt.Errorf("%s", reasonText)
// }
// return nil
// }
func ServerSecurityHandler(cfg *ServerConfig, c *ServerConn) error { func ServerSecurityHandler(cfg *ServerConfig, c *ServerConn) error {
if err := binary.Write(c, binary.BigEndian, uint8(len(cfg.SecurityHandlers))); err != nil { if err := binary.Write(c, binary.BigEndian, uint8(len(cfg.SecurityHandlers))); err != nil {
return err return err
@ -174,9 +77,9 @@ func ServerSecurityHandler(cfg *ServerConfig, c *ServerConn) error {
} }
} }
if err := c.Flush(); err != nil { // if err := c.Flush(); err != nil {
return err // return err
} // }
var secType SecurityType var secType SecurityType
if err := binary.Read(c, binary.BigEndian, &secType); err != nil { if err := binary.Read(c, binary.BigEndian, &secType); err != nil {
@ -202,9 +105,9 @@ func ServerSecurityHandler(cfg *ServerConfig, c *ServerConn) error {
if err := binary.Write(c, binary.BigEndian, authCode); err != nil { if err := binary.Write(c, binary.BigEndian, authCode); err != nil {
return err return err
} }
if err := c.Flush(); err != nil { // if err := c.Flush(); err != nil {
return err // return err
} // }
if authErr != nil { if authErr != nil {
if err := binary.Write(c, binary.BigEndian, len(authErr.Error())); err != nil { if err := binary.Write(c, binary.BigEndian, len(authErr.Error())); err != nil {
@ -213,44 +116,15 @@ func ServerSecurityHandler(cfg *ServerConfig, c *ServerConn) error {
if err := binary.Write(c, binary.BigEndian, []byte(authErr.Error())); err != nil { if err := binary.Write(c, binary.BigEndian, []byte(authErr.Error())); err != nil {
return err return err
} }
if err := c.Flush(); err != nil { // if err := c.Flush(); err != nil {
return err // return err
} // }
return authErr return authErr
} }
return nil return nil
} }
// func ClientServerInitHandler(cfg *ClientConfig, c *ServerConn) error {
// srvInit := &ServerInit{}
// if err := binary.Read(c, binary.BigEndian, &srvInit.FBWidth); err != nil {
// return err
// }
// if err := binary.Read(c, binary.BigEndian, &srvInit.FBHeight); err != nil {
// return err
// }
// if err := binary.Read(c, binary.BigEndian, &srvInit.PixelFormat); err != nil {
// return err
// }
// if err := binary.Read(c, binary.BigEndian, &srvInit.NameLength); err != nil {
// return err
// }
// nameText := make([]byte, srvInit.NameLength)
// if err := binary.Read(c, binary.BigEndian, nameText); err != nil {
// return err
// }
// srvInit.NameText = nameText
// c.SetDesktopName(string(srvInit.NameText))
// c.SetWidth(srvInit.FBWidth)
// c.SetHeight(srvInit.FBHeight)
// c.SetPixelFormat(&srvInit.PixelFormat)
// return nil
// }
func ServerServerInitHandler(cfg *ServerConfig, c *ServerConn) error { func ServerServerInitHandler(cfg *ServerConfig, c *ServerConn) error {
srvInit := &ServerInit{ srvInit := &ServerInit{
FBWidth: c.Width(), FBWidth: c.Width(),
@ -293,7 +167,7 @@ func ServerServerInitHandler(cfg *ServerConfig, c *ServerConn) error {
//} //}
//tightInit.WriteTo(c) //tightInit.WriteTo(c)
return c.Flush() return nil
} }
const ( const (
@ -465,19 +339,6 @@ func (t *TightCapability) ReadFrom(r io.Reader) error {
return nil return nil
} }
// func ClientClientInitHandler(cfg *ClientConfig, c *ServerConn) error {
// var shared uint8
// if cfg.Exclusive {
// shared = 0
// } else {
// shared = 1
// }
// if err := binary.Write(c, binary.BigEndian, shared); err != nil {
// return err
// }
// return c.Flush()
// }
func ServerClientInitHandler(cfg *ServerConfig, c *ServerConn) error { func ServerClientInitHandler(cfg *ServerConfig, c *ServerConn) error {
var shared uint8 var shared uint8
if err := binary.Read(c, binary.BigEndian, &shared); err != nil { if err := binary.Read(c, binary.BigEndian, &shared); err != nil {

View File

@ -184,7 +184,9 @@ func (*ServerAuthNone) SubType() SecuritySubType {
// } // }
// ServerAuthVNC is the standard password authentication. See 7.2.2. // ServerAuthVNC is the standard password authentication. See 7.2.2.
type ServerAuthVNC struct{} type ServerAuthVNC struct {
pass string
}
func (*ServerAuthVNC) Type() SecurityType { func (*ServerAuthVNC) Type() SecurityType {
return SecTypeVNC return SecTypeVNC
@ -208,14 +210,14 @@ func (auth *ServerAuthVNC) Auth(c common.Conn) error {
log.Printf("The full 16 byte challenge was not sent!\n") log.Printf("The full 16 byte challenge was not sent!\n")
return errors.New("The full 16 byte challenge was not sent") return errors.New("The full 16 byte challenge was not sent")
} }
c.Flush() //c.Flush()
buf2 := make([]byte, 16) buf2 := make([]byte, 16)
_, err = c.Read(buf2) _, err = c.Read(buf2)
if err != nil { if err != nil {
log.Printf("The authentication result was not read: %s\n", err.Error()) log.Printf("The authentication result was not read: %s\n", err.Error())
return errors.New("The authentication result was not read" + err.Error()) return errors.New("The authentication result was not read" + err.Error())
} }
AuthText := "1234" AuthText := auth.pass
bk, err := des.NewCipher([]byte(fixDesKey(AuthText))) bk, err := des.NewCipher([]byte(fixDesKey(AuthText)))
if err != nil { if err != nil {
log.Printf("Error generating authentication cipher: %s\n", err.Error()) log.Printf("Error generating authentication cipher: %s\n", err.Error())
@ -229,7 +231,7 @@ func (auth *ServerAuthVNC) Auth(c common.Conn) error {
SetUint32(buf, 4, uint32(len([]byte(AUTH_FAIL)))) SetUint32(buf, 4, uint32(len([]byte(AUTH_FAIL))))
copy(buf[8:], []byte(AUTH_FAIL)) copy(buf[8:], []byte(AUTH_FAIL))
c.Write(buf) c.Write(buf)
c.Flush() //c.Flush()
return errors.New("Authentication failed") return errors.New("Authentication failed")
} }
return nil return nil

View File

@ -1,17 +1,16 @@
package server package server
import ( import (
"bufio" "io"
"net"
"sync" "sync"
"vncproxy/common" "vncproxy/common"
) )
type ServerConn struct { type ServerConn struct {
c net.Conn c io.ReadWriter
cfg *ServerConfig cfg *ServerConfig
br *bufio.Reader //br *bufio.Reader
bw *bufio.Writer //bw *bufio.Writer
protocol string protocol string
m sync.Mutex m sync.Mutex
// If the pixel format uses a color map, then this is the color // If the pixel format uses a color map, then this is the color
@ -41,11 +40,11 @@ type ServerConn struct {
quit chan struct{} quit chan struct{}
} }
func (c *ServerConn) UnreadByte() error { // func (c *ServerConn) UnreadByte() error {
return c.br.UnreadByte() // return c.br.UnreadByte()
} // }
func (c *ServerConn) Conn() net.Conn { func (c *ServerConn) Conn() io.ReadWriter {
return c.c return c.c
} }
@ -66,14 +65,14 @@ func (c *ServerConn) SetProtoVersion(pv string) {
c.protocol = pv c.protocol = pv
} }
func (c *ServerConn) Flush() error { // func (c *ServerConn) Flush() error {
// c.m.Lock() // // c.m.Lock()
// defer c.m.Unlock() // // defer c.m.Unlock()
return c.bw.Flush() // return c.bw.Flush()
} // }
func (c *ServerConn) Close() error { func (c *ServerConn) Close() error {
return c.c.Close() return c.c.(io.ReadWriteCloser).Close()
} }
/* /*
@ -86,13 +85,13 @@ func (c *ServerConn) Output() chan *ClientMessage {
} }
*/ */
func (c *ServerConn) Read(buf []byte) (int, error) { func (c *ServerConn) Read(buf []byte) (int, error) {
return c.br.Read(buf) return c.c.Read(buf)
} }
func (c *ServerConn) Write(buf []byte) (int, error) { func (c *ServerConn) Write(buf []byte) (int, error) {
// c.m.Lock() // c.m.Lock()
// defer c.m.Unlock() // defer c.m.Unlock()
return c.bw.Write(buf) return c.c.Write(buf)
} }
func (c *ServerConn) ColorMap() *common.ColorMap { func (c *ServerConn) ColorMap() *common.ColorMap {

View File

@ -1,12 +1,12 @@
package server package server
import ( import (
"bufio"
"context" "context"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io"
"log"
"net" "net"
"sync"
"vncproxy/common" "vncproxy/common"
) )
@ -71,7 +71,7 @@ type ServerConfig struct {
Width uint16 Width uint16
} }
func NewServerConn(c net.Conn, cfg *ServerConfig) (*ServerConn, error) { func newServerConn(c io.ReadWriter, cfg *ServerConfig) (*ServerConn, error) {
if cfg.ClientMessageCh == nil { if cfg.ClientMessageCh == nil {
return nil, fmt.Errorf("ClientMessageCh nil") return nil, fmt.Errorf("ClientMessageCh nil")
} }
@ -82,8 +82,8 @@ func NewServerConn(c net.Conn, cfg *ServerConfig) (*ServerConn, error) {
return &ServerConn{ return &ServerConn{
c: c, c: c,
br: bufio.NewReader(c), //br: bufio.NewReader(c),
bw: bufio.NewWriter(c), //bw: bufio.NewWriter(c),
cfg: cfg, cfg: cfg,
quit: make(chan struct{}), quit: make(chan struct{}),
encodings: cfg.Encodings, encodings: cfg.Encodings,
@ -92,76 +92,111 @@ func NewServerConn(c net.Conn, cfg *ServerConfig) (*ServerConn, error) {
fbHeight: cfg.Height, fbHeight: cfg.Height,
}, nil }, nil
} }
func wsHandlerFunc(ws io.ReadWriter, cfg *ServerConfig) {
// header := ws.Request().Header
// url := ws.Request().URL
// //stam := header.Get("Origin")
// fmt.Printf("header: %v\nurl: %v\n", header, url)
// io.Copy(ws, ws)
func Serve(ctx context.Context, ln net.Listener, cfg *ServerConfig) error { err := attachNewServerConn(ws, cfg)
if err != nil {
log.Fatalf("Error attaching new connection. %v", err)
}
}
func WsServe(url string, ctx context.Context, cfg *ServerConfig) error {
//server := WsServer1{cfg}
server := WsServer{cfg}
server.Listen(url, WsHandler(wsHandlerFunc))
return nil
}
func TcpServe(url string, ctx context.Context, cfg *ServerConfig) error {
ln, err := net.Listen("tcp", ":5903")
if err != nil {
log.Fatalf("Error listen. %v", err)
}
for { for {
c, err := ln.Accept() c, err := ln.Accept()
if err != nil { if err != nil {
continue return err
} }
go attachNewServerConn(c, cfg)
// if err != nil {
// return err
// }
}
return nil
}
conn, err := NewServerConn(c, cfg) func attachNewServerConn(c io.ReadWriter, cfg *ServerConfig) error {
conn, err := newServerConn(c, cfg)
if err != nil { if err != nil {
continue return err
} }
if err := ServerVersionHandler(cfg, conn); err != nil { if err := ServerVersionHandler(cfg, conn); err != nil {
fmt.Errorf("err: %v\n", err)
conn.Close() conn.Close()
continue return err
} }
if err := ServerSecurityHandler(cfg, conn); err != nil { if err := ServerSecurityHandler(cfg, conn); err != nil {
conn.Close() conn.Close()
continue return err
} }
if err := ServerClientInitHandler(cfg, conn); err != nil { if err := ServerClientInitHandler(cfg, conn); err != nil {
conn.Close() conn.Close()
continue return err
} }
if err := ServerServerInitHandler(cfg, conn); err != nil { if err := ServerServerInitHandler(cfg, conn); err != nil {
conn.Close() conn.Close()
continue return err
} }
go conn.Handle() //go
} conn.handle()
return nil
} }
func (c *ServerConn) Handle() error { func (c *ServerConn) handle() error {
//var err error //var err error
var wg sync.WaitGroup //var wg sync.WaitGroup
defer c.Close() //defer c.Close()
//create a map of all message types //create a map of all message types
clientMessages := make(map[common.ClientMessageType]common.ClientMessage) clientMessages := make(map[common.ClientMessageType]common.ClientMessage)
for _, m := range c.cfg.ClientMessages { for _, m := range c.cfg.ClientMessages {
clientMessages[m.Type()] = m clientMessages[m.Type()] = m
} }
wg.Add(2) //wg.Add(2)
// server // server
go func() error { // go func() error {
defer wg.Done() // defer wg.Done()
for { // for {
select { // select {
case msg := <-c.cfg.ServerMessageCh: // case msg := <-c.cfg.ServerMessageCh:
fmt.Printf("%v", msg) // fmt.Printf("%v", msg)
// if err = msg.Write(c); err != nil { // // if err = msg.Write(c); err != nil {
// return err // // return err
// // }
// case <-c.quit:
// c.Close()
// return nil
// } // }
case <-c.quit: // }
return nil // }()
}
}
}()
// client // client
go func() error { //go func() error {
defer wg.Done() //defer wg.Done()
for { for {
select { select {
case <-c.quit: case <-c.quit:
@ -169,6 +204,7 @@ func (c *ServerConn) Handle() error {
default: default:
var messageType common.ClientMessageType var messageType common.ClientMessageType
if err := binary.Read(c, binary.BigEndian, &messageType); err != nil { if err := binary.Read(c, binary.BigEndian, &messageType); err != nil {
fmt.Printf("Error: %v\n", err)
return err return err
} }
msg, ok := clientMessages[messageType] msg, ok := clientMessages[messageType]
@ -181,186 +217,12 @@ func (c *ServerConn) Handle() error {
fmt.Printf("srv err %s\n", err.Error()) fmt.Printf("srv err %s\n", err.Error())
return err return err
} }
fmt.Printf("message:%s, %v\n",parsedMsg.Type(), parsedMsg) fmt.Printf("message:%s, %v\n", parsedMsg.Type(), parsedMsg)
//c.cfg.ClientMessageCh <- parsedMsg //c.cfg.ClientMessageCh <- parsedMsg
} }
} }
}() //}()
wg.Wait() //wg.Wait()
return nil //return nil
} }
// type ServerCutText struct {
// _ [1]byte
// Length uint32
// Text []byte
// }
// func (*ServerCutText) Type() ServerMessageType {
// return ServerCutTextMsgType
// }
// func (*ServerCutText) Read(c common.Conn) (common.ServerMessage, error) {
// msg := ServerCutText{}
// var pad [1]byte
// if err := binary.Read(c, binary.BigEndian, &pad); err != nil {
// return nil, err
// }
// if err := binary.Read(c, binary.BigEndian, &msg.Length); err != nil {
// return nil, err
// }
// msg.Text = make([]byte, msg.Length)
// if err := binary.Read(c, binary.BigEndian, &msg.Text); err != nil {
// return nil, err
// }
// return &msg, nil
// }
// func (msg *ServerCutText) Write(c common.Conn) error {
// if err := binary.Write(c, binary.BigEndian, msg.Type()); err != nil {
// return err
// }
// var pad [1]byte
// if err := binary.Write(c, binary.BigEndian, pad); err != nil {
// return err
// }
// if msg.Length < uint32(len(msg.Text)) {
// msg.Length = uint32(len(msg.Text))
// }
// if err := binary.Write(c, binary.BigEndian, msg.Length); err != nil {
// return err
// }
// if err := binary.Write(c, binary.BigEndian, msg.Text); err != nil {
// return err
// }
// return nil
// }
// type Bell struct{}
// func (*Bell) Type() ServerMessageType {
// return BellMsgType
// }
// func (*Bell) Read(c common.Conn) (common.ServerMessage, error) {
// return &Bell{}, nil
// }
// func (msg *Bell) Write(c common.Conn) error {
// return binary.Write(c, binary.BigEndian, msg.Type())
// }
// type SetColorMapEntries struct {
// _ [1]byte
// FirstColor uint16
// ColorsNum uint16
// Colors []common.Color
// }
// func (*SetColorMapEntries) Type() ServerMessageType {
// return SetColorMapEntriesMsgType
// }
// func (*SetColorMapEntries) Read(c common.Conn) (common.ServerMessage, error) {
// msg := SetColorMapEntries{}
// var pad [1]byte
// if err := binary.Read(c, binary.BigEndian, &pad); err != nil {
// return nil, err
// }
// if err := binary.Read(c, binary.BigEndian, &msg.FirstColor); err != nil {
// return nil, err
// }
// if err := binary.Read(c, binary.BigEndian, &msg.ColorsNum); err != nil {
// return nil, err
// }
// msg.Colors = make([]common.Color, msg.ColorsNum)
// colorMap := c.ColorMap()
// for i := uint16(0); i < msg.ColorsNum; i++ {
// color := &msg.Colors[i]
// if err := binary.Read(c, binary.BigEndian, &color); err != nil {
// return nil, err
// }
// colorMap[msg.FirstColor+i] = *color
// }
// c.SetColorMap(colorMap)
// return &msg, nil
// }
// func (msg *SetColorMapEntries) Write(c common.Conn) error {
// if err := binary.Write(c, binary.BigEndian, msg.Type()); err != nil {
// return err
// }
// var pad [1]byte
// if err := binary.Write(c, binary.BigEndian, &pad); err != nil {
// return err
// }
// if err := binary.Write(c, binary.BigEndian, msg.FirstColor); err != nil {
// return err
// }
// if msg.ColorsNum < uint16(len(msg.Colors)) {
// msg.ColorsNum = uint16(len(msg.Colors))
// }
// if err := binary.Write(c, binary.BigEndian, msg.ColorsNum); err != nil {
// return err
// }
// for i := 0; i < len(msg.Colors); i++ {
// color := msg.Colors[i]
// if err := binary.Write(c, binary.BigEndian, color); err != nil {
// return err
// }
// }
// return nil
// }
// func (*FramebufferUpdate) Read(cliInfo common.IClientConn, c *common.RfbReadHelper) (common.ServerMessage, error) {
// msg := FramebufferUpdate{}
// var pad [1]byte
// if err := binary.Read(c, binary.BigEndian, &pad); err != nil {
// return nil, err
// }
// if err := binary.Read(c, binary.BigEndian, &msg.NumRect); err != nil {
// return nil, err
// }
// for i := uint16(0); i < msg.NumRect; i++ {
// rect := &common.Rectangle{}
// if err := rect.Read(c); err != nil {
// return nil, err
// }
// msg.Rects = append(msg.Rects, rect)
// }
// return &msg, nil
// }
// func (msg *FramebufferUpdate) Write(c common.Conn) error {
// if err := binary.Write(c, binary.BigEndian, msg.Type()); err != nil {
// return err
// }
// var pad [1]byte
// if err := binary.Write(c, binary.BigEndian, pad); err != nil {
// return err
// }
// if err := binary.Write(c, binary.BigEndian, msg.NumRect); err != nil {
// return err
// }
// for _, rect := range msg.Rects {
// if err := rect.Write(c); err != nil {
// return err
// }
// }
// return c.Flush()
// }

View File

@ -3,24 +3,19 @@ package server
import ( import (
"context" "context"
"log" "log"
"net"
"testing" "testing"
"vncproxy/common" "vncproxy/common"
"vncproxy/encodings" "vncproxy/encodings"
) )
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
ln, err := net.Listen("tcp", ":5903")
if err != nil {
log.Fatalf("Error listen. %v", err)
}
chServer := make(chan common.ClientMessage) chServer := make(chan common.ClientMessage)
chClient := make(chan common.ServerMessage) chClient := make(chan common.ServerMessage)
cfg := &ServerConfig{ cfg := &ServerConfig{
//SecurityHandlers: []SecurityHandler{&ServerAuthNone{}, &ServerAuthVNC{}}, //SecurityHandlers: []SecurityHandler{&ServerAuthNone{}, &ServerAuthVNC{}},
SecurityHandlers: []SecurityHandler{&ServerAuthVNC{}}, SecurityHandlers: []SecurityHandler{&ServerAuthVNC{"Ch_#!T@8"}},
Encodings: []common.Encoding{&encodings.RawEncoding{}, &encodings.TightEncoding{}, &encodings.CopyRectEncoding{}}, Encodings: []common.Encoding{&encodings.RawEncoding{}, &encodings.TightEncoding{}, &encodings.CopyRectEncoding{}},
PixelFormat: common.NewPixelFormat(32), PixelFormat: common.NewPixelFormat(32),
ClientMessageCh: chServer, ClientMessageCh: chServer,
@ -29,10 +24,10 @@ func TestServer(t *testing.T) {
DesktopName: []byte("workDesk"), DesktopName: []byte("workDesk"),
Height: uint16(768), Height: uint16(768),
Width: uint16(1024), Width: uint16(1024),
} }
go Serve(context.Background(), ln, cfg) url := "http://localhost:8091/"
go WsServe(url, context.Background(), cfg)
go TcpServe(":5903", context.Background(), cfg)
// Process messages coming in on the ClientMessage channel. // Process messages coming in on the ClientMessage channel.
for { for {
msg := <-chClient msg := <-chClient

43
server/ws-server-go.go Normal file
View File

@ -0,0 +1,43 @@
package server
import (
"fmt"
"io"
"net/http"
"net/url"
"golang.org/x/net/websocket"
)
type WsServer struct {
cfg *ServerConfig
}
type WsHandler func(io.ReadWriter, *ServerConfig)
// This example demonstrates a trivial echo server.
func (wsServer *WsServer) Listen(urlStr string, handlerFunc WsHandler) {
//http.Handle("/", websocket.Handler(EchoHandler))
if urlStr == "" {
urlStr = "/"
}
url, err := url.Parse(urlStr)
if err != nil {
fmt.Println("error while parsing url: ", err)
}
http.Handle(url.Path, websocket.Handler(func(ws *websocket.Conn) {
// header := ws.Request().Header
// url := ws.Request().URL
// //stam := header.Get("Origin")
// fmt.Printf("header: %v\nurl: %v\n", header, url)
// io.Copy(ws, ws)
ws.PayloadType = websocket.BinaryFrame
handlerFunc(ws, wsServer.cfg)
}))
err = http.ListenAndServe(url.Host, nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}

104
server/ws-server-gorilla.go Normal file
View File

@ -0,0 +1,104 @@
package server
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"bytes"
"github.com/gorilla/websocket"
)
type WsServer1 struct {
cfg *ServerConfig
}
type WsHandler1 func(io.ReadWriter, *ServerConfig)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
}}
type WsConnection struct {
Reader WsReader
Writer WsWriter
}
func NewWsConnection(c *websocket.Conn) *WsConnection {
return &WsConnection{
WsReader{},
WsWriter{c},
}
}
type WsWriter struct {
conn *websocket.Conn
}
type WsReader struct {
Buff bytes.Buffer
}
func (wr WsReader) Read(p []byte) (n int, err error) {
return wr.Buff.Read(p)
}
func (wr WsWriter) Write(p []byte) (int, error) {
err := wr.conn.WriteMessage(websocket.BinaryMessage, p)
return len(p), err
}
func handleConnection(w http.ResponseWriter, r *http.Request) {
log.Print("got connection:", r.URL)
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
myConn := NewWsConnection(c)
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
if mt == websocket.BinaryMessage {
myConn.Reader.Buff.Write(message)
}
log.Printf("recv: %s", message)
// err = c.WriteMessage(mt, message)
// if err != nil {
// log.Println("write:", err)
// break
// }
}
}
// This example demonstrates a trivial echo server.
func (wsServer *WsServer1) Listen(urlStr string, handlerFunc WsHandler) {
//http.Handle("/", websocket.Handler(EchoHandler))
if urlStr == "" {
urlStr = "/"
}
url, err := url.Parse(urlStr)
if err != nil {
fmt.Println("error while parsing url: ", err)
}
http.HandleFunc(url.Path, handleConnection)
err = http.ListenAndServe(url.Host, nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}

33
server/ws_test.go Normal file
View File

@ -0,0 +1,33 @@
package server
// import (
// "fmt"
// "io"
// "net/http"
// "testing"
// "golang.org/x/net/websocket"
// )
// func TestWsServer(t *testing.T) {
// server := WsServer{}
// server.Listen(":8090")
// }
// // Echo the data received on the WebSocket.
// func EchoHandler(ws *websocket.Conn) {
// header := ws.Request().Header
// url := ws.Request().URL
// //stam := header.Get("Origin")
// fmt.Printf("header: %v\nurl: %v\n", header, url)
// io.Copy(ws, ws)
// }
// // This example demonstrates a trivial echo server.
// func TestGoWsServer(t *testing.T) {
// http.Handle("/", websocket.Handler(EchoHandler))
// err := http.ListenAndServe(":11111", nil)
// if err != nil {
// panic("ListenAndServe: " + err.Error())
// }
// }

10
vncproxy.iml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="GOPATH &lt;vncproxy&gt;" level="project" />
</component>
</module>