├── .gitignore ├── README ├── rfb ├── rfb_test.go └── rfb.go ├── demo.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | rfbgo 3 | *.[68] 4 | *.prof 5 | \#* 6 | \.\#* 7 | _test* 8 | [568a].out 9 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | This is a toy RFB (VNC) server. 2 | 3 | I just wanted to learn the protocol. (conclusion: nice & simple) 4 | 5 | I'm not sure what I'm going to do with this now. Some stupid hacks come to mind. 6 | 7 | -------------------------------------------------------------------------------- /rfb/rfb_test.go: -------------------------------------------------------------------------------- 1 | package rfb_test 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func BenchmarkAppend(b *testing.B) { 8 | var buf []uint16 9 | for i := 0; i < b.N; i++ { 10 | buf = buf[:0] 11 | for v := uint16(0); v < 65535; v++ { 12 | buf = append(buf, v) 13 | } 14 | } 15 | } 16 | 17 | func BenchmarkArray(b *testing.B) { 18 | var buf []uint16 = make([]uint16, 65536) 19 | for i := 0; i < b.N; i++ { 20 | for v := uint16(0); v < 65535; v++ { 21 | buf[v] = v 22 | } 23 | } 24 | } 25 | 26 | func BenchmarkMod4(b *testing.B) { 27 | for i := 0; i < b.N; i++ { 28 | switch i % 4 { 29 | case 0: 30 | _ = i 31 | case 1: 32 | _ = i 33 | case 2: 34 | _ = i 35 | case 3: 36 | _ = i 37 | } 38 | } 39 | } 40 | 41 | func BenchmarkMask3(b *testing.B) { 42 | for i := 0; i < b.N; i++ { 43 | switch i & 3 { 44 | case 0: 45 | _ = i 46 | case 1: 47 | _ = i 48 | case 2: 49 | _ = i 50 | case 3: 51 | _ = i 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /demo.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011 Google Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // Example of using the rfb package. 18 | // 19 | // Author: Brad Fitzpatrick 20 | 21 | package main 22 | 23 | import ( 24 | "flag" 25 | "image" 26 | "log" 27 | "math" 28 | "net" 29 | "os" 30 | "runtime/pprof" 31 | "time" 32 | 33 | "github.com/bradfitz/rfbgo/rfb" 34 | ) 35 | 36 | var ( 37 | listen = flag.String("listen", ":5900", "listen on [ip]:port") 38 | profile = flag.Bool("profile", false, "write a cpu.prof file when client disconnects") 39 | ) 40 | 41 | const ( 42 | width = 1280 43 | height = 720 44 | ) 45 | 46 | func main() { 47 | flag.Parse() 48 | 49 | ln, err := net.Listen("tcp", *listen) 50 | if err != nil { 51 | log.Fatal(err) 52 | } 53 | 54 | s := rfb.NewServer(width, height) 55 | go func() { 56 | err = s.Serve(ln) 57 | log.Fatalf("rfb server ended with: %v", err) 58 | }() 59 | for c := range s.Conns { 60 | handleConn(c) 61 | } 62 | } 63 | 64 | func handleConn(c *rfb.Conn) { 65 | if *profile { 66 | f, err := os.Create("cpu.prof") 67 | if err != nil { 68 | log.Fatal(err) 69 | } 70 | err = pprof.StartCPUProfile(f) 71 | if err != nil { 72 | log.Fatal(err) 73 | } 74 | log.Printf("profiling CPU") 75 | defer pprof.StopCPUProfile() 76 | defer log.Printf("stopping profiling CPU") 77 | } 78 | 79 | im := image.NewRGBA(image.Rect(0, 0, width, height)) 80 | li := &rfb.LockableImage{Img: im} 81 | 82 | closec := make(chan bool) 83 | go func() { 84 | slide := 0 85 | tick := time.NewTicker(time.Second / 30) 86 | defer tick.Stop() 87 | haveNewFrame := false 88 | for { 89 | feed := c.Feed 90 | if !haveNewFrame { 91 | feed = nil 92 | } 93 | _ = feed 94 | select { 95 | case feed <- li: 96 | haveNewFrame = false 97 | case <-closec: 98 | return 99 | case <-tick.C: 100 | slide++ 101 | li.Lock() 102 | drawImage(im, slide) 103 | li.Unlock() 104 | haveNewFrame = true 105 | } 106 | } 107 | }() 108 | 109 | for e := range c.Event { 110 | log.Printf("got event: %#v", e) 111 | } 112 | close(closec) 113 | log.Printf("Client disconnected") 114 | } 115 | 116 | func drawImage(im *image.RGBA, anim int) { 117 | pos := 0 118 | const border = 50 119 | for y := 0; y < height; y++ { 120 | for x := 0; x < width; x++ { 121 | var r, g, b uint8 122 | switch { 123 | case x < border*2.5 && x < int((1.1+math.Sin(float64(y+anim*2)/40))*border): 124 | r = 255 125 | case x > width-border*2.5 && x > width-int((1.1+math.Sin(math.Pi+float64(y+anim*2)/40))*border): 126 | g = 255 127 | case y < border*2.5 && y < int((1.1+math.Sin(float64(x+anim*2)/40))*border): 128 | r, g = 255, 255 129 | case y > height-border*2.5 && y > height-int((1.1+math.Sin(math.Pi+float64(x+anim*2)/40))*border): 130 | b = 255 131 | default: 132 | r, g, b = uint8(x+anim), uint8(y+anim), uint8(x+y+anim*3) 133 | } 134 | im.Pix[pos] = r 135 | im.Pix[pos+1] = g 136 | im.Pix[pos+2] = b 137 | pos += 4 // skipping alpha 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /rfb/rfb.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011 Google Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | // toy VNC (RFB) server in Go, just learning the protocol. 18 | // 19 | // Protocol docs: 20 | // http://www.realvnc.com/docs/rfbproto.pdf 21 | // 22 | // Author: Brad Fitzpatrick 23 | 24 | package rfb 25 | 26 | import ( 27 | "bufio" 28 | "encoding/binary" 29 | "fmt" 30 | "image" 31 | "log" 32 | "net" 33 | "strconv" 34 | "sync" 35 | ) 36 | 37 | const ( 38 | v3 = "RFB 003.003\n" 39 | v7 = "RFB 003.007\n" 40 | v8 = "RFB 003.008\n" 41 | 42 | authNone = 1 43 | 44 | statusOK = 0 45 | statusFailed = 1 46 | 47 | encodingRaw = 0 48 | encodingCopyRect = 1 49 | 50 | // Client -> Server 51 | cmdSetPixelFormat = 0 52 | cmdSetEncodings = 2 53 | cmdFramebufferUpdateRequest = 3 54 | cmdKeyEvent = 4 55 | cmdPointerEvent = 5 56 | cmdClientCutText = 6 57 | 58 | // Server -> Client 59 | cmdFramebufferUpdate = 0 60 | ) 61 | 62 | func NewServer(width, height int) *Server { 63 | if width < 1 { 64 | width = 1 65 | } 66 | if height < 1 { 67 | height = 1 68 | } 69 | conns := make(chan *Conn, 16) 70 | return &Server{ 71 | width: width, 72 | height: height, 73 | Conns: conns, 74 | conns: conns, 75 | } 76 | } 77 | 78 | type Server struct { 79 | width, height int 80 | conns chan *Conn // read/write version of Conns 81 | 82 | // Conns is a channel of incoming connections. 83 | Conns <-chan *Conn 84 | } 85 | 86 | func (s *Server) Serve(ln net.Listener) error { 87 | for { 88 | c, err := ln.Accept() 89 | if err != nil { 90 | return err 91 | } 92 | conn := s.newConn(c) 93 | select { 94 | case s.conns <- conn: 95 | default: 96 | // client is behind; doesn't get this updated. 97 | } 98 | go conn.serve() 99 | } 100 | panic("unreachable") 101 | } 102 | 103 | func (s *Server) newConn(c net.Conn) *Conn { 104 | feed := make(chan *LockableImage, 16) 105 | event := make(chan interface{}, 16) 106 | conn := &Conn{ 107 | s: s, 108 | c: c, 109 | br: bufio.NewReader(c), 110 | bw: bufio.NewWriter(c), 111 | fbupc: make(chan FrameBufferUpdateRequest, 128), 112 | closec: make(chan bool), 113 | feed: feed, 114 | Feed: feed, // the send-only version 115 | event: event, 116 | Event: event, // the recieve-only version 117 | } 118 | return conn 119 | } 120 | 121 | type LockableImage struct { 122 | sync.RWMutex 123 | Img image.Image 124 | } 125 | 126 | type Conn struct { 127 | s *Server 128 | c net.Conn 129 | br *bufio.Reader 130 | bw *bufio.Writer 131 | fbupc chan FrameBufferUpdateRequest 132 | closec chan bool // never sent; just closed 133 | 134 | // should only be mutated once during handshake, but then 135 | // only read. 136 | format PixelFormat 137 | 138 | feed chan *LockableImage 139 | mu sync.RWMutex // guards last (but not its pixels, just the variable) 140 | last *LockableImage 141 | 142 | buf8 []uint8 // temporary buffer to avoid generating garbage 143 | 144 | // Feed is the channel to send new frames. 145 | Feed chan<- *LockableImage 146 | 147 | // Event is a readable channel of events from the client. 148 | // The value will be either a KeyEvent or PointerEvent. The 149 | // channel is closed when the client disconnects. 150 | Event <-chan interface{} 151 | 152 | event chan interface{} // internal version of Event 153 | 154 | gotFirstFrame bool 155 | } 156 | 157 | func (c *Conn) dimensions() (w, h int) { 158 | return c.s.width, c.s.height 159 | } 160 | 161 | func (c *Conn) readByte(what string) byte { 162 | b, err := c.br.ReadByte() 163 | if err != nil { 164 | c.failf("reading client byte for %q: %v", what, err) 165 | } 166 | return b 167 | } 168 | 169 | func (c *Conn) readPadding(what string, size int) { 170 | for i := 0; i < size; i++ { 171 | c.readByte(what) 172 | } 173 | } 174 | 175 | func (c *Conn) read(what string, v interface{}) { 176 | err := binary.Read(c.br, binary.BigEndian, v) 177 | if err != nil { 178 | c.failf("reading from client into %T for %q: %v", v, what, err) 179 | } 180 | } 181 | 182 | func (c *Conn) w(v interface{}) { 183 | binary.Write(c.bw, binary.BigEndian, v) 184 | } 185 | 186 | func (c *Conn) flush() { 187 | c.bw.Flush() 188 | } 189 | 190 | func (c *Conn) failf(format string, args ...interface{}) { 191 | panic(fmt.Sprintf(format, args...)) 192 | } 193 | 194 | func (c *Conn) serve() { 195 | defer c.c.Close() 196 | defer close(c.fbupc) 197 | defer close(c.closec) 198 | defer close(c.event) 199 | defer func() { 200 | e := recover() 201 | if e != nil { 202 | log.Printf("Client disconnect: %v", e) 203 | } 204 | }() 205 | 206 | c.bw.WriteString("RFB 003.008\n") 207 | c.flush() 208 | sl, err := c.br.ReadSlice('\n') 209 | if err != nil { 210 | c.failf("reading client protocol version: %v", err) 211 | } 212 | ver := string(sl) 213 | log.Printf("client wants: %q", ver) 214 | switch ver { 215 | case v3, v7, v8: // cool. 216 | default: 217 | c.failf("bogus client-requested security type %q", ver) 218 | } 219 | 220 | // Auth 221 | if ver >= v7 { 222 | // Just 1 auth type supported: 1 (no auth) 223 | c.bw.WriteString("\x01\x01") 224 | c.flush() 225 | wanted := c.readByte("6.1.2:client requested security-type") 226 | if wanted != authNone { 227 | c.failf("client wanted auth type %d, not None", int(wanted)) 228 | } 229 | } else { 230 | // Old way. Just tell client we're doing no auth. 231 | c.w(uint32(authNone)) 232 | c.flush() 233 | } 234 | 235 | if ver >= v8 { 236 | // 6.1.3. SecurityResult 237 | c.w(uint32(statusOK)) 238 | c.flush() 239 | } 240 | 241 | log.Printf("reading client init") 242 | 243 | // ClientInit 244 | wantShared := c.readByte("shared-flag") != 0 245 | _ = wantShared 246 | 247 | c.format = PixelFormat{ 248 | BPP: 16, 249 | Depth: 16, 250 | BigEndian: 0, 251 | TrueColour: 1, 252 | RedMax: 0x1f, 253 | GreenMax: 0x1f, 254 | BlueMax: 0x1f, 255 | RedShift: 0xa, 256 | GreenShift: 0x5, 257 | BlueShift: 0, 258 | } 259 | 260 | // 6.3.2. ServerInit 261 | width, height := c.dimensions() 262 | c.w(uint16(width)) 263 | c.w(uint16(height)) 264 | c.w(c.format.BPP) 265 | c.w(c.format.Depth) 266 | c.w(c.format.BigEndian) 267 | c.w(c.format.TrueColour) 268 | c.w(c.format.RedMax) 269 | c.w(c.format.GreenMax) 270 | c.w(c.format.BlueMax) 271 | c.w(c.format.RedShift) 272 | c.w(c.format.GreenShift) 273 | c.w(c.format.BlueShift) 274 | c.w(uint8(0)) // pad1 275 | c.w(uint8(0)) // pad2 276 | c.w(uint8(0)) // pad3 277 | serverName := "rfb-go" 278 | c.w(int32(len(serverName))) 279 | c.bw.WriteString(serverName) 280 | c.flush() 281 | 282 | for { 283 | //log.Printf("awaiting command byte from client...") 284 | cmd := c.readByte("6.4:client-server-packet-type") 285 | //log.Printf("got command type %d from client", int(cmd)) 286 | switch cmd { 287 | case cmdSetPixelFormat: 288 | c.handleSetPixelFormat() 289 | case cmdSetEncodings: 290 | c.handleSetEncodings() 291 | case cmdFramebufferUpdateRequest: 292 | c.handleUpdateRequest() 293 | case cmdPointerEvent: 294 | c.handlePointerEvent() 295 | case cmdKeyEvent: 296 | c.handleKeyEvent() 297 | default: 298 | c.failf("unsupported command type %d from client", int(cmd)) 299 | } 300 | } 301 | } 302 | 303 | func (c *Conn) pushFramesLoop() { 304 | for { 305 | select { 306 | case ur, ok := <-c.fbupc: 307 | if !ok { 308 | // Client disconnected. 309 | return 310 | } 311 | c.pushFrame(ur) 312 | case li := <-c.feed: 313 | c.mu.Lock() 314 | c.last = li 315 | c.mu.Unlock() 316 | c.pushImage(li) 317 | } 318 | } 319 | } 320 | 321 | func (c *Conn) pushFrame(ur FrameBufferUpdateRequest) { 322 | c.mu.RLock() 323 | defer c.mu.RUnlock() 324 | li := c.last 325 | if li == nil { 326 | return 327 | } 328 | 329 | if ur.incremental() { 330 | li.Lock() 331 | defer li.Unlock() 332 | im := li.Img 333 | b := im.Bounds() 334 | width, height := b.Dx(), b.Dy() 335 | 336 | //log.Printf("Client wants incremental update, sending none. %#v", ur) 337 | c.w(uint8(cmdFramebufferUpdate)) 338 | c.w(uint8(0)) // padding byte 339 | c.w(uint16(1)) // no rectangles 340 | c.w(uint16(0)) // x 341 | c.w(uint16(0)) // y 342 | c.w(uint16(width)) // x 343 | c.w(uint16(height)) 344 | c.w(int32(encodingCopyRect)) 345 | c.w(uint16(0)) // src-x 346 | c.w(uint16(0)) // src-y 347 | c.flush() 348 | return 349 | } 350 | c.pushImage(li) 351 | } 352 | 353 | func (c *Conn) pushImage(li *LockableImage) { 354 | li.Lock() 355 | defer li.Unlock() 356 | 357 | im := li.Img 358 | b := im.Bounds() 359 | if b.Min.X != 0 || b.Min.Y != 0 { 360 | panic("this code is lazy and assumes images with Min bounds at 0,0") 361 | } 362 | width, height := b.Dx(), b.Dy() 363 | 364 | c.w(uint8(cmdFramebufferUpdate)) 365 | c.w(uint8(0)) // padding byte 366 | c.w(uint16(1)) // 1 rectangle 367 | 368 | //log.Printf("sending %d x %d pixels", width, height) 369 | 370 | if c.format.TrueColour == 0 { 371 | c.failf("only true-colour supported") 372 | } 373 | 374 | // Send that rectangle: 375 | c.w(uint16(0)) // x 376 | c.w(uint16(0)) // y 377 | c.w(uint16(width)) // x 378 | c.w(uint16(height)) 379 | c.w(int32(encodingRaw)) 380 | 381 | rgba, isRGBA := im.(*image.RGBA) 382 | if isRGBA && c.format.isScreensThousands() { 383 | // Fast path. 384 | c.pushRGBAScreensThousandsLocked(rgba) 385 | } else { 386 | c.pushGenericLocked(im) 387 | } 388 | c.flush() 389 | } 390 | 391 | func (c *Conn) pushRGBAScreensThousandsLocked(im *image.RGBA) { 392 | var u16 uint16 393 | pixels := len(im.Pix) / 4 394 | if len(c.buf8) < pixels*2 { 395 | c.buf8 = make([]byte, pixels*2) 396 | } 397 | out := c.buf8[:] 398 | isBigEndian := c.format.BigEndian != 0 399 | for i, v8 := range im.Pix { 400 | switch i % 4 { 401 | case 0: // red 402 | u16 = uint16(v8&248) << 7 // 3 masked bits + 7 shifted == redshift of 10 403 | case 1: // green 404 | u16 |= uint16(v8&248) << 2 // redshift of 5 405 | case 2: // blue 406 | u16 |= uint16(v8 >> 3) 407 | case 3: // alpha, unused. use this to just move the dest 408 | hb, lb := uint8(u16>>8), uint8(u16) 409 | if isBigEndian { 410 | out[0] = hb 411 | out[1] = lb 412 | } else { 413 | out[0] = lb 414 | out[1] = hb 415 | } 416 | out = out[2:] 417 | } 418 | } 419 | c.bw.Write(c.buf8[:pixels*2]) 420 | } 421 | 422 | // pushGenericLocked is the slow path generic implementation that works on 423 | // any image.Image concrete type and any client-requested pixel format. 424 | // If you're lucky, you never end in this path. 425 | func (c *Conn) pushGenericLocked(im image.Image) { 426 | b := im.Bounds() 427 | width, height := b.Dx(), b.Dy() 428 | for y := 0; y < height; y++ { 429 | for x := 0; x < width; x++ { 430 | col := im.At(x, y) 431 | r16, g16, b16, _ := col.RGBA() 432 | r16 = inRange(r16, c.format.RedMax) 433 | g16 = inRange(g16, c.format.GreenMax) 434 | b16 = inRange(b16, c.format.BlueMax) 435 | var u32 uint32 = (r16 << c.format.RedShift) | 436 | (g16 << c.format.GreenShift) | 437 | (b16 << c.format.BlueShift) 438 | var v interface{} 439 | switch c.format.BPP { 440 | case 32: 441 | v = u32 442 | case 16: 443 | v = uint16(u32) 444 | case 8: 445 | v = uint8(u32) 446 | default: 447 | c.failf("TODO: BPP of %d", c.format.BPP) 448 | } 449 | if c.format.BigEndian != 0 { 450 | binary.Write(c.bw, binary.BigEndian, v) 451 | } else { 452 | binary.Write(c.bw, binary.LittleEndian, v) 453 | } 454 | } 455 | } 456 | } 457 | 458 | type PixelFormat struct { 459 | BPP, Depth uint8 460 | BigEndian, TrueColour uint8 // flags; 0 or non-zero 461 | RedMax, GreenMax, BlueMax uint16 462 | RedShift, GreenShift, BlueShift uint8 463 | } 464 | 465 | // Is the format requested by the OS X "Screens" app's "Thousands" mode. 466 | func (f *PixelFormat) isScreensThousands() bool { 467 | // Note: Screens asks for Depth 16; RealVNC asks for Depth 15 (which is more accurate) 468 | // Accept either. Same format. 469 | return f.BPP == 16 && (f.Depth == 16 || f.Depth == 15) && f.TrueColour != 0 && 470 | f.RedMax == 0x1f && f.GreenMax == 0x1f && f.BlueMax == 0x1f && 471 | f.RedShift == 10 && f.GreenShift == 5 && f.BlueShift == 0 472 | } 473 | 474 | // 6.4.1 475 | func (c *Conn) handleSetPixelFormat() { 476 | log.Printf("handling setpixel format") 477 | c.readPadding("SetPixelFormat padding", 3) 478 | var pf PixelFormat 479 | c.read("pixelformat.bpp", &pf.BPP) 480 | c.read("pixelformat.depth", &pf.Depth) 481 | c.read("pixelformat.beflag", &pf.BigEndian) 482 | c.read("pixelformat.truecolour", &pf.TrueColour) 483 | c.read("pixelformat.redmax", &pf.RedMax) 484 | c.read("pixelformat.greenmax", &pf.GreenMax) 485 | c.read("pixelformat.bluemax", &pf.BlueMax) 486 | c.read("pixelformat.redshift", &pf.RedShift) 487 | c.read("pixelformat.greenshift", &pf.GreenShift) 488 | c.read("pixelformat.blueshift", &pf.BlueShift) 489 | c.readPadding("SetPixelFormat pixel format padding", 3) 490 | log.Printf("Client wants pixel format: %#v", pf) 491 | c.format = pf 492 | 493 | // TODO: send PixelFormat event? would clients care? 494 | } 495 | 496 | // 6.4.2 497 | func (c *Conn) handleSetEncodings() { 498 | c.readPadding("SetEncodings padding", 1) 499 | 500 | var numEncodings uint16 501 | c.read("6.4.2:number-of-encodings", &numEncodings) 502 | var encType []int32 503 | for i := 0; i < int(numEncodings); i++ { 504 | var t int32 505 | c.read("encoding-type", &t) 506 | encType = append(encType, t) 507 | } 508 | log.Printf("Client encodings: %#v", encType) 509 | 510 | } 511 | 512 | // 6.4.3 513 | type FrameBufferUpdateRequest struct { 514 | IncrementalFlag uint8 515 | X, Y, Width, Height uint16 516 | } 517 | 518 | func (r *FrameBufferUpdateRequest) incremental() bool { return r.IncrementalFlag != 0 } 519 | 520 | // 6.4.3 521 | func (c *Conn) handleUpdateRequest() { 522 | if !c.gotFirstFrame { 523 | li := <-c.feed 524 | c.mu.Lock() 525 | c.last = li 526 | c.mu.Unlock() 527 | c.gotFirstFrame = true 528 | go c.pushFramesLoop() 529 | } 530 | 531 | var req FrameBufferUpdateRequest 532 | c.read("framebuffer-update.incremental", &req.IncrementalFlag) 533 | c.read("framebuffer-update.x", &req.X) 534 | c.read("framebuffer-update.y", &req.Y) 535 | c.read("framebuffer-update.width", &req.Width) 536 | c.read("framebuffer-update.height", &req.Height) 537 | c.fbupc <- req 538 | } 539 | 540 | // 6.4.4 541 | type KeyEvent struct { 542 | DownFlag uint8 543 | Key uint32 544 | } 545 | 546 | // 6.4.4 547 | func (c *Conn) handleKeyEvent() { 548 | var req KeyEvent 549 | c.read("key-event.downflag", &req.DownFlag) 550 | c.readPadding("key-event.padding", 2) 551 | c.read("key-event.key", &req.Key) 552 | select { 553 | case c.event <- req: 554 | default: 555 | // Client's too slow. 556 | } 557 | } 558 | 559 | // 6.4.5 560 | type PointerEvent struct { 561 | ButtonMask uint8 562 | X, Y uint16 563 | } 564 | 565 | // 6.4.5 566 | func (c *Conn) handlePointerEvent() { 567 | var req PointerEvent 568 | c.read("pointer-event.mask", &req.ButtonMask) 569 | c.read("pointer-event.x", &req.X) 570 | c.read("pointer-event.y", &req.Y) 571 | select { 572 | case c.event <- req: 573 | default: 574 | // Client's too slow. 575 | } 576 | } 577 | 578 | func inRange(v uint32, max uint16) uint32 { 579 | switch max { 580 | case 0x1f: // 5 bits 581 | return v >> (16 - 5) 582 | } 583 | panic("todo; max value = " + strconv.Itoa(int(max))) 584 | } 585 | --------------------------------------------------------------------------------