vnc

package module
v0.0.0-...-4a1a6b8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2019 License: MIT Imports: 22 Imported by: 0

README

VNC Library for Go

go-vnc is a VNC client library for Go.

This library implements RFC 6143 -- The Remote Framebuffer Protocol -- the protocol used by VNC.

  • Build Status: Build Status
  • Documentation: GoDoc

Setup

  1. Download software and supporting packages.

    $ go get github.com/18121861183/go-vnc
    $ go get golang.org/x/net
    

Usage

Sample code usage is available in the GoDoc.

The source code is laid out such that the files match the document sections:

  • [7.1] handshake.go
  • [7.2] security.go
  • [7.3] initialization.go
  • [7.4] pixel_format.go
  • [7.5] client.go
  • [7.6] server.go
  • [7.7] encodings.go

There are two additional files that provide everything else:

  • vncclient.go -- code for instantiating a VNC client
  • common.go -- common stuff not related to the RFB protocol

Example

nc, err := net.Dial("tcp", "192.168.9.93:5900")
if err != nil {
   log.Fatalf("Error connecting to VNC host. %v", err)
}

// Negotiate connection with the server.
vcc := vnc.NewClientConfig("11111111")
vc, version, err := vnc.Connect(context.Background(), nc, vcc)

print(version)
if err != nil {
   log.Fatalf("Error negotiating connection to VNC host. %v", err)
}
fmt.Println(vc.DesktopName())

Documentation

Overview

Package vnc provides VNC client implementation.

This package implements The Remote Framebuffer Protocol as documented in [RFC 6143](http://tools.ietf.org/html/rfc6143).

A basic VNC client can be created like this. Replace the IP on the net.Dial line with something more appropriate for your setup.

package main

import (
  "context"
  "log"
  "net"
  "time"

  "github.com/18121861183/go-vnc"
  "github.com/18121861183/go-vnc/messages"
  "github.com/18121861183/go-vnc/rfbflags"
)

func main() {
  // Establish TCP connection to VNC server.
  nc, err := net.Dial("tcp", "127.0.0.1:5900")
  if err != nil {
    log.Fatalf("Error connecting to VNC host. %v", err)
  }

  // Negotiate connection with the server.
  vcc := vnc.NewClientConfig("some_password")
  vc, err := vnc.Connect(context.Background(), nc, vcc)
  if err != nil {
    log.Fatalf("Error negotiating connection to VNC host. %v", err)
  }

  // Periodically request framebuffer updates.
  go func() {
    w, h := vc.FramebufferWidth(), vc.FramebufferHeight()
    for {
      if err := vc.FramebufferUpdateRequest(rfbflags.RFBTrue, 0, 0, w, h); err != nil {
        log.Printf("error requesting framebuffer update: %v", err)
      }
      time.Sleep(1 * time.Second)
    }
  }()

  // Listen and handle server messages.
  go vc.ListenAndHandle()

  // Process messages coming in on the ServerMessage channel.
  for {
    msg := <-vcc.ServerMessageCh
    switch msg.Type() {
    case messages.FramebufferUpdate:
      log.Println("Received FramebufferUpdate message.")
    default:
      log.Printf("Received message type:%v msg:%v\n", msg.Type(), msg)
    }
  }
}

This example will connect to a VNC server running on the localhost. It will periodically request updates from the server, and listen for and handle incoming FramebufferUpdate messages coming from the server.

Implementation of RFC 6143 §7.7 Encodings. https://tools.ietf.org/html/rfc6143#section-7.7

Implementation of RFC 6143 §7.6 Server-to-Client Messages. https://tools.ietf.org/html/rfc6143#section-7.6

Index

Examples

Constants

View Source
const (
	PressKey   = true
	ReleaseKey = false
)
View Source
const (
	// Client ProtocolVersions.
	PROTO_VERS_UNSUP = "UNSUPPORTED"
	PROTO_VERS_3_3   = "RFB 003.003\n"
	PROTO_VERS_3_8   = "RFB 003.008\n"
)

Variables

This section is empty.

Functions

func Errorf

func Errorf(format string, a ...interface{}) error

func NewVNCError

func NewVNCError(desc string) error

NewVNCError returns a custom VNCError error.

func SetSettle

func SetSettle(s time.Duration)

SetSettle changes the UI settle duration.

func Settle

func Settle() time.Duration

Settle returns the UI settle duration.

Types

type Bell

type Bell struct{}

Bell represents the wire format message, sans message-type.

func (*Bell) Read

func (*Bell) Read(c *ClientConn) (ServerMessage, error)

Read implements the ServerMessage interface.

func (*Bell) Type

func (*Bell) Type() messages.ServerMessage

Type implements the ServerMessage interface.

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

func NewBuffer

func NewBuffer(b []byte) *Buffer

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

func (*Buffer) Read

func (b *Buffer) Read(data interface{}) error

func (*Buffer) Write

func (b *Buffer) Write(data interface{}) error

func (*Buffer) WriteByte

func (b *Buffer) WriteByte(c byte) error

type ClientAuth

type ClientAuth interface {
	// SecurityType returns the byte identifier sent by the server to
	// identify this authentication scheme.
	SecurityType() uint8

	// Handshake is called when the authentication handshake should be
	// performed, as part of the general RFB handshake. (see 7.2.1)
	Handshake(*ClientConn) error
}

ClientAuth implements a method of authenticating with a remote server.

type ClientAuthNone

type ClientAuthNone struct{}

ClientAuthNone is the "none" authentication. See 7.2.1.

func (*ClientAuthNone) Handshake

func (*ClientAuthNone) Handshake(conn *ClientConn) error

func (*ClientAuthNone) SecurityType

func (*ClientAuthNone) SecurityType() uint8

type ClientAuthVNC

type ClientAuthVNC struct {
	Password string
}

ClientAuthVNC is the standard password authentication. See 7.2.2.

func (*ClientAuthVNC) Handshake

func (auth *ClientAuthVNC) Handshake(conn *ClientConn) error

func (*ClientAuthVNC) SecurityType

func (*ClientAuthVNC) SecurityType() uint8

type ClientConfig

type ClientConfig struct {

	// A slice of ClientAuth methods. Only the first instance that is
	// suitable by the server will be used to authenticate.
	Auth []ClientAuth

	// Password for servers that require authentication.
	Password string

	// Exclusive determines whether the connection is shared with other
	// clients. If true, then all other clients connected will be
	// disconnected when a connection is established to the VNC server.
	Exclusive bool

	// The channel that all messages received from the server will be
	// sent on. If the channel blocks, then the goroutine reading data
	// from the VNC server may block indefinitely. It is up to the user
	// of the library to ensure that this channel is properly read.
	// If this is not set, then all messages will be discarded.
	ServerMessageCh chan ServerMessage

	// A slice of supported messages that can be read from the server.
	// This only needs to contain NEW server messages, and doesn't
	// need to explicitly contain the RFC-required messages.
	ServerMessages []ServerMessage
	// contains filtered or unexported fields
}

A ClientConfig structure is used to configure a ClientConn. After one has been passed to initialize a connection, it must not be modified.

func NewClientConfig

func NewClientConfig(p string) *ClientConfig

NewClientConfig returns a populated ClientConfig.

type ClientConn

type ClientConn struct {
	// contains filtered or unexported fields
}

The ClientConn type holds client connection information.

func Connect

func Connect(ctx context.Context, c net.Conn, cfg *ClientConfig) (*ClientConn, string, error)

Connect negotiates a connection to a VNC server.

func NewClientConn

func NewClientConn(c net.Conn, cfg *ClientConfig) *ClientConn

func (*ClientConn) ClientCutText

func (c *ClientConn) ClientCutText(text string) error

ClientCutText tells the server that the client has new text in its cut buffer. The text string MUST only contain Latin-1 characters. This encoding is compatible with Go's native string format, but can only use up to unicode.MaxLatin1 values.

See RFC 6143 Section 7.5.6

func (*ClientConn) Close

func (c *ClientConn) Close() error

Close a connection to a VNC server.

func (*ClientConn) DebugMetrics

func (c *ClientConn) DebugMetrics()

func (*ClientConn) DesktopName

func (c *ClientConn) DesktopName() string

DesktopName returns the server provided desktop name.

func (*ClientConn) Encodable

func (c *ClientConn) Encodable(enc encodings.Encoding) (Encoding, bool)

Encodable returns the Encoding that can be used to encode a Rectangle, or false if the encoding isn't recognized.

func (*ClientConn) Encodings

func (c *ClientConn) Encodings() Encodings

Encodings returns the server provided encodings.

func (*ClientConn) FramebufferHeight

func (c *ClientConn) FramebufferHeight() uint16

FramebufferHeight returns the server provided framebuffer height.

func (*ClientConn) FramebufferUpdateRequest

func (c *ClientConn) FramebufferUpdateRequest(inc rfbflags.RFBFlag, x, y, w, h uint16) error

Requests a framebuffer update from the server. There may be an indefinite time between the request and the actual framebuffer update being received.

See RFC 6143 Section 7.5.3

func (*ClientConn) FramebufferWidth

func (c *ClientConn) FramebufferWidth() uint16

FramebufferWidth returns the server provided framebuffer width.

func (*ClientConn) KeyEvent

func (c *ClientConn) KeyEvent(key keys.Key, down bool) error

KeyEvent indicates a key press or release and sends it to the server. The key is indicated using the X Window System "keysym" value. Constants are provided in `keys/keys.go`. To simulate a key press, you must send a key with both a true and false down event.

See RFC 6143 Section 7.5.4.

Example
// Establish TCP connection.
nc, err := net.DialTimeout("tcp", "127.0.0.1:5900", 10*time.Second)
if err != nil {
	panic(fmt.Sprintf("Error connecting to host: %v\n", err))
}

// Negotiate VNC connection.
vc, err := Connect(context.Background(), nc, NewClientConfig("somepass"))
if err != nil {
	panic(fmt.Sprintf("Could not negotiate a VNC connection: %v\n", err))
}

// Press and release the return key.
vc.KeyEvent(keys.Return, true)
vc.KeyEvent(keys.Return, false)

// Close VNC connection.
vc.Close()
Output:

func (*ClientConn) ListenAndHandle

func (c *ClientConn) ListenAndHandle() error

ListenAndHandle listens to a VNC server and handles server messages.

func (*ClientConn) PointerEvent

func (c *ClientConn) PointerEvent(button buttons.Button, x, y uint16) error

PointerEvent indicates that pointer movement or a pointer button press or release.

The `button` is a bitwise mask of various Button values. When a button is set, it is pressed, when it is unset, it is released.

See RFC 6143 Section 7.5.5

Example
// Establish TCP connection.
nc, err := net.DialTimeout("tcp", "127.0.0.1:5900", 10*time.Second)
if err != nil {
	panic(fmt.Sprintf("Error connecting to host: %v\n", err))
}

// Negotiate VNC connection.
vc, err := Connect(context.Background(), nc, NewClientConfig("somepass"))
if err != nil {
	panic(fmt.Sprintf("Could not negotiate a VNC connection: %v\n", err))
}

// Move mouse to x=100, y=200.
x, y := uint16(100), uint16(200)
vc.PointerEvent(buttons.None, x, y)

// Click and release the left mouse button.
vc.PointerEvent(buttons.Left, x, y)
vc.PointerEvent(buttons.None, x, y)

// Close connection.
vc.Close()
Output:

func (*ClientConn) SetEncodings

func (c *ClientConn) SetEncodings(encs Encodings) error

SetEncodings sets the encoding types in which the pixel data can be sent from the server. After calling this method, the encs slice given should not be modified.

TODO(18121861183:20170306) Fix bad practice of mixing of protocol and internal state here.

See RFC 6143 Section 7.5.2

func (*ClientConn) SetPixelFormat

func (c *ClientConn) SetPixelFormat(pf PixelFormat) error

SetPixelFormat sets the format in which pixel values should be sent in FramebufferUpdate messages from the server.

See RFC 6143 Section 7.5.1

type ClientCutTextMessage

type ClientCutTextMessage struct {
	Msg messages.ClientMessage // message-type

	Length uint32 // length
	// contains filtered or unexported fields
}

ClientCutTextMessage holds the wire format message, sans the text field.

type Color

type Color struct {
	R, G, B uint16
	// contains filtered or unexported fields
}

Color represents a single color in a color map.

func NewColor

func NewColor(pf *PixelFormat, cm *ColorMap) *Color

NewColor returns a new Color object.

func (*Color) Marshal

func (c *Color) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

func (*Color) Unmarshal

func (c *Color) Unmarshal(data []byte) error

Unmarshal implements the Unmarshaler interface.

type ColorMap

type ColorMap [256]Color

ColorMap represents a translation map of colors.

type DesktopSizePseudoEncoding

type DesktopSizePseudoEncoding struct{}

DesktopSizePseudoEncoding represents a desktop size message from the server.

func (*DesktopSizePseudoEncoding) Marshal

func (e *DesktopSizePseudoEncoding) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

func (*DesktopSizePseudoEncoding) Read

Read implements the Encoding interface.

func (*DesktopSizePseudoEncoding) String

func (e *DesktopSizePseudoEncoding) String() string

String implements the fmt.Stringer interface.

func (*DesktopSizePseudoEncoding) Type

Type implements the Encoding interface.

type EncodableFunc

type EncodableFunc func(enc encodings.Encoding) (Encoding, bool)

EncodableFunc describes the function for encoding a Rectangle.

type Encoding

type Encoding interface {
	fmt.Stringer
	Marshaler

	// Read the contents of the encoded pixel data from the reader.
	// This should return a new Encoding implementation that contains
	// the proper data.
	Read(*ClientConn, *Rectangle) (Encoding, error)

	// The number that uniquely identifies this encoding type.
	Type() encodings.Encoding
}

An Encoding implements a method for encoding pixel data that is sent by the server to the client.

type Encodings

type Encodings []Encoding

Encodings describes a slice of Encoding.

func (Encodings) Marshal

func (e Encodings) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

type FramebufferUpdate

type FramebufferUpdate struct {
	NumRect uint16      // number-of-rectangles
	Rects   []Rectangle // rectangles
}

FramebufferUpdate holds a FramebufferUpdate wire format message.

func (*FramebufferUpdate) Marshal

func (m *FramebufferUpdate) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

func (*FramebufferUpdate) Read

Read implements the ServerMessage interface.

func (*FramebufferUpdate) Type

Type implements the ServerMessage interface.

func (*FramebufferUpdate) Unmarshal

func (m *FramebufferUpdate) Unmarshal(_ []byte) error

Unmarshal implements the Unmarshaler interface.

type FramebufferUpdateRequestMessage

type FramebufferUpdateRequestMessage struct {
	Msg           messages.ClientMessage // message-type
	Inc           rfbflags.RFBFlag       // incremental
	X, Y          uint16                 // x-, y-position
	Width, Height uint16                 // width, height
}

FramebufferUpdateRequestMessage holds the wire format message.

type KeyEventMessage

type KeyEventMessage struct {
	Msg      messages.ClientMessage // message-type
	DownFlag rfbflags.RFBFlag       // down-flag

	Key keys.Key // key
	// contains filtered or unexported fields
}

KeyEventMessage holds the wire format message.

type Marshaler

type Marshaler interface {
	// Marshal returns the wire encoding of a message.
	Marshal() ([]byte, error)
}

Marshaler is the interface satisfied for marshaling messages.

type MarshalerUnmarshaler

type MarshalerUnmarshaler interface {
	Marshaler
	Unmarshaler
}

MarshalerUnmarshaler satisfies both the Marshaler and Unmarshaler interfaces.

type PixelFormat

type PixelFormat struct {
	BPP                             uint8            // bits-per-pixel
	Depth                           uint8            // depth
	BigEndian                       rfbflags.RFBFlag // big-endian-flag
	TrueColor                       rfbflags.RFBFlag // true-color-flag
	RedMax, GreenMax, BlueMax       uint16           // red-, green-, blue-max (2^BPP-1)
	RedShift, GreenShift, BlueShift uint8            // red-, green-, blue-shift
	// contains filtered or unexported fields
}

PixelFormat describes the way a pixel is formatted for a VNC connection.

var (
	PixelFormat8bit  PixelFormat = NewPixelFormat(8)
	PixelFormat16bit PixelFormat = NewPixelFormat(16)
	PixelFormat32bit PixelFormat = NewPixelFormat(32)
)

func NewPixelFormat

func NewPixelFormat(bpp uint8) PixelFormat

NewPixelFormat returns a populated PixelFormat structure.

func (PixelFormat) Marshal

func (pf PixelFormat) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

func (*PixelFormat) Read

func (pf *PixelFormat) Read(r io.Reader) error

Read reads from an io.Reader, and populates the PixelFormat.

func (PixelFormat) String

func (pf PixelFormat) String() string

String implements the fmt.Stringer interface.

func (*PixelFormat) Unmarshal

func (pf *PixelFormat) Unmarshal(data []byte) error

Unmarshal implements the Unmarshaler interface.

type PointerEventMessage

type PointerEventMessage struct {
	Msg  messages.ClientMessage // message-type
	Mask uint8                  // button-mask
	X, Y uint16                 // x-, y-position
}

PointerEventMessage holds the wire format message.

type RawEncoding

type RawEncoding struct {
	Colors []Color
}

RawEncoding holds raw encoded rectangle data.

func (*RawEncoding) Marshal

func (e *RawEncoding) Marshal() ([]byte, error)

Marshal implements the Encoding interface.

func (*RawEncoding) Read

func (*RawEncoding) Read(c *ClientConn, rect *Rectangle) (Encoding, error)

Read implements the Encoding interface.

func (*RawEncoding) String

func (*RawEncoding) String() string

String implements the fmt.Stringer interface.

func (*RawEncoding) Type

func (*RawEncoding) Type() encodings.Encoding

Type implements the Encoding interface.

type Rectangle

type Rectangle struct {
	X, Y          uint16
	Width, Height uint16
	Enc           Encoding
	// contains filtered or unexported fields
}

Rectangle represents a rectangle of pixel data.

func NewRectangle

func NewRectangle(fn EncodableFunc) *Rectangle

NewRectangle returns a new Rectangle object.

func (*Rectangle) Area

func (r *Rectangle) Area() int

Area returns the total area in pixels of the Rectangle.

func (*Rectangle) Marshal

func (r *Rectangle) Marshal() ([]byte, error)

Marshal implements the Marshaler interface.

func (*Rectangle) Read

func (r *Rectangle) Read(c *ClientConn) error

Read a rectangle message from ClientConn c.

func (*Rectangle) String

func (r *Rectangle) String() string

String implements the fmt.Stringer interface.

func (*Rectangle) Unmarshal

func (r *Rectangle) Unmarshal(data []byte) error

Unmarshal implements the Unmarshaler interface.

type ServerCutText

type ServerCutText struct {
	Text string
}

ServerCutText represents the wire format message, sans message-type and padding.

func (*ServerCutText) Read

Read implements the ServerMessage interface.

func (*ServerCutText) Type

Type implements the ServerMessage interface.

type ServerInit

type ServerInit struct {
	FBWidth, FBHeight uint16
	PixelFormat       PixelFormat
	NameLength        uint32
}

ServerInit message sent after server receives a ClientInit message. https://tools.ietf.org/html/rfc6143#section-7.3.2

func (*ServerInit) Read

func (m *ServerInit) Read(r io.Reader) error

Read implements

func (*ServerInit) Unmarshal

func (m *ServerInit) Unmarshal(data []byte) error

type ServerMessage

type ServerMessage interface {
	// The type of the message that is sent down on the wire.
	Type() messages.ServerMessage

	// Read reads the contents of the message from the reader. At the point
	// this is called, the message type has already been read from the reader.
	// This should return a new ServerMessage that is the appropriate type.
	Read(*ClientConn) (ServerMessage, error)
}

ServerMessage is the interface satisfied by server messages.

type SetColorMapEntries

type SetColorMapEntries struct {
	FirstColor uint16
	Colors     []Color
}

SetColorMapEntries holds a SetColorMapEntries wire format message, sans message-type and padding.

func (*SetColorMapEntries) Read

Read implements the ServerMessage interface.

func (*SetColorMapEntries) Type

Type implements the ServerMessage interface.

type SetEncodingsMessage

type SetEncodingsMessage struct {
	Msg messages.ClientMessage // message-type

	NumEncs uint16 // number-of-encodings
	// contains filtered or unexported fields
}

SetEncodingsMessage holds the wire format message, sans encoding-type field.

type SetPixelFormatMessage

type SetPixelFormatMessage struct {
	Msg messages.ClientMessage // message-type

	PF PixelFormat // pixel-format
	// contains filtered or unexported fields
}

SetPixelFormatMessage holds the wire format message.

type Unmarshaler

type Unmarshaler interface {
	// Unmarshal parses a wire format message into a message.
	Unmarshal(data []byte) error
}

Unarshaler is the interface satisfied for unmarshaling messages.

type VNCError

type VNCError struct {
	// contains filtered or unexported fields
}

VNCError implements error interface.

func (VNCError) Error

func (e VNCError) Error() string

Error returns an VNCError as a string.

Directories

Path Synopsis
Package buttons describes the supported button masks.
Package buttons describes the supported button masks.
Package encodings provides constants for the known VNC encoding types.
Package encodings provides constants for the known VNC encoding types.
go
metrics
The metrics package provides support for tracking various metrics.
The metrics package provides support for tracking various metrics.
Package keys provides constants for all the keyboard inputs.
Package keys provides constants for all the keyboard inputs.
Package logging provides common logging functionality.
Package logging provides common logging functionality.
Package messages provides constants for the client and server messages.
Package messages provides constants for the client and server messages.
Package rfbflags provides constants for the RFB flag values.
Package rfbflags provides constants for the RFB flag values.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL