├── .gitignore ├── LICENSE ├── README.md ├── client.go ├── encode.go ├── go.mod ├── upgrader.go ├── vncproxy ├── README.md └── handler.go └── websocket.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | 26 | # Intellij IDE 27 | .idea/ 28 | *.iml 29 | 30 | # test 31 | test_* 32 | 33 | # log 34 | *.log 35 | 36 | # VS Code 37 | .vscode/ 38 | 39 | # Unix hidden files 40 | .* 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # websocket [![GoDoc](https://pkg.go.dev/badge/github.com/xgfone/go-websocket)](https://pkg.go.dev/github.com/xgfone/go-websocket) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](https://raw.githubusercontent.com/xgfone/go-websocket/master/LICENSE) 2 | 3 | This is a websocket implementation supporting `Go1.7+`, which is inspired by [websockify](https://github.com/novnc/websockify) and [websocket](https://github.com/gorilla/websocket). 4 | 5 | #### Difference from `gorilla/websocket` 6 | - `gorilla/websocket` only has a goroutine to read from websocket and a goroutine to write to websocket, that's, read or write can be done concurrently. 7 | - Though this library cannot read from websocket concurrently, it's able to write to websocket concurrently. Moreover, it will be enhanced to read concurrently. 8 | 9 | ## Install 10 | 11 | ```shell 12 | $ go get -u github.com/xgfone/go-websocket 13 | ``` 14 | 15 | ## VNC Proxy on WebSocket 16 | 17 | The sub-package [vncproxy](https://github.com/xgfone/go-websocket/tree/master/vncproxy) provides a HTTP handler about VNC Proxy on Websocket. 18 | 19 | ## Example 20 | 21 | ### Websocket Server Example 22 | ```go 23 | package main 24 | 25 | import ( 26 | "log" 27 | "net/http" 28 | "time" 29 | 30 | "github.com/xgfone/go-websocket" 31 | ) 32 | 33 | var upgrader = websocket.Upgrader{ 34 | MaxMsgSize: 1024, 35 | Timeout: time.Second * 30, 36 | CheckOrigin: func(r *http.Request) bool { return true }, 37 | } 38 | 39 | func websocketHandler(rw http.ResponseWriter, r *http.Request) { 40 | ws, err := upgrader.Upgrade(rw, r, nil) 41 | if err != nil { 42 | log.Printf("failed to upgrade to websocket: %s\n", err) 43 | return 44 | } 45 | 46 | ws.Run(func(msgType int, message []byte) { 47 | switch msgType { 48 | case websocket.MsgTypeBinary: 49 | ws.SendBinaryMsg(message) 50 | case websocket.MsgTypeText: 51 | ws.SendTextMsg(message) 52 | } 53 | }) 54 | } 55 | 56 | func main() { 57 | http.ListenAndServe(":80", http.HandlerFunc(websocketHandler)) 58 | } 59 | ``` 60 | 61 | ### Websocket Client Example 62 | ```go 63 | package main 64 | 65 | import ( 66 | "fmt" 67 | "time" 68 | 69 | "github.com/xgfone/go-websocket" 70 | ) 71 | 72 | func main() { 73 | ws, err := websocket.NewClientWebsocket("ws://127.0.0.1/") 74 | if err == nil { 75 | go func() { 76 | tick := time.NewTicker(time.Second * 10) 77 | defer tick.Stop() 78 | for { 79 | select { 80 | case now := <-tick.C: 81 | if err := ws.SendTextMsg([]byte(now.String())); err != nil { 82 | fmt.Println(err) 83 | return 84 | } 85 | } 86 | } 87 | }() 88 | 89 | err = ws.Run(func(msgType int, msg []byte) { 90 | fmt.Printf("Receive: %s\n", string(msg)) 91 | }) 92 | } 93 | fmt.Println(err) 94 | } 95 | ``` 96 | 97 | The client will output like this: 98 | ``` 99 | Receive: 2019-07-13 18:33:47.951688 +0800 CST m=+10.007139340 100 | Receive: 2019-07-13 18:33:57.951479 +0800 CST m=+20.006605995 101 | Receive: 2019-07-13 18:34:07.948628 +0800 CST m=+30.003442484 102 | Receive: 2019-07-13 18:34:17.949763 +0800 CST m=+40.004270178 103 | Receive: 2019-07-13 18:34:27.947877 +0800 CST m=+50.002081112 104 | Receive: 2019-07-13 18:34:37.949986 +0800 CST m=+60.003888082 105 | ... 106 | ``` 107 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package websocket 16 | 17 | import ( 18 | "bufio" 19 | "bytes" 20 | "crypto/tls" 21 | "encoding/base64" 22 | "fmt" 23 | "io" 24 | "math/rand" 25 | "net" 26 | "net/http" 27 | "net/url" 28 | "strings" 29 | "time" 30 | ) 31 | 32 | // ClientOption is used to configure the client websocket. 33 | // 34 | // Notice: all the options are optional. 35 | type ClientOption struct { 36 | // MaxLine represents the number of the characters of the longest line 37 | // which is 1024 by default. 38 | MaxLine int 39 | 40 | // Origin is used to set the Origin header. 41 | Origin string 42 | 43 | // Protocal is used to set the Sec-Websocket-Protocol header. 44 | Protocol []string 45 | 46 | // Header is the additional header to do websocket handshake. 47 | Header http.Header 48 | 49 | // Config is used by the default DialTLS to open a TCP/TLS connection. 50 | Config *tls.Config 51 | 52 | // Dial is used to open a TCP connection to addr, which is by default 53 | // net.Dial("tcp", addr) 54 | Dial func(addr string) (net.Conn, error) 55 | 56 | // DialTLS is used to open a TCP/TLS connection to addr, which is by default 57 | // tls.Dial("tcp", addr, ClientOption.Config) 58 | DialTLS func(addr string) (net.Conn, error) 59 | 60 | // GenerateHandshakeChallenge is used to generate a challenge 61 | // for websocket handshake. 62 | // 63 | // If missing, it will use the default implementation. 64 | GenerateHandshakeChallenge func() []byte 65 | } 66 | 67 | func defaultDial(addr string) (net.Conn, error) { 68 | return net.Dial("tcp", addr) 69 | } 70 | 71 | func defaultGenerateHandshakeChallenge() []byte { 72 | var bs [16]byte 73 | for i := range bs { 74 | bs[i] = byte(rand.Intn(256)) 75 | } 76 | return bs[:] 77 | } 78 | 79 | func init() { 80 | rand.Seed(time.Now().UnixNano()) 81 | } 82 | 83 | func getHost(hostport, defaultPort string) string { 84 | _, _, err := net.SplitHostPort(hostport) 85 | if err != nil && strings.Contains(err.Error(), "missing port") { 86 | return net.JoinHostPort(hostport, defaultPort) 87 | } 88 | return hostport 89 | } 90 | 91 | // NewClientWebsocket returns a new client websocket to connect to wsurl. 92 | func NewClientWebsocket(wsurl string, option ...ClientOption) (ws *Websocket, err error) { 93 | u, err := url.Parse(wsurl) 94 | if err != nil { 95 | return nil, err 96 | } 97 | 98 | var opt ClientOption 99 | if len(option) > 0 { 100 | opt = option[0] 101 | } 102 | if opt.MaxLine < 1 { 103 | opt.MaxLine = 1024 104 | } 105 | 106 | var conn net.Conn 107 | switch u.Scheme { 108 | case "ws": 109 | if opt.Dial != nil { 110 | conn, err = opt.Dial(getHost(u.Host, "80")) 111 | } else { 112 | conn, err = defaultDial(getHost(u.Host, "80")) 113 | } 114 | case "wss": 115 | if opt.DialTLS != nil { 116 | conn, err = opt.DialTLS(u.Host) 117 | } else if opt.Config != nil { 118 | conn, err = tls.Dial("tcp", getHost(u.Host, "443"), opt.Config) 119 | } else { 120 | conn, err = tls.Dial("tcp", getHost(u.Host, "443"), &tls.Config{}) 121 | } 122 | default: 123 | return nil, fmt.Errorf("the websocket scheme must be ws or wss") 124 | } 125 | if err != nil { 126 | return nil, err 127 | } 128 | 129 | defer func() { 130 | if err != nil && conn != nil { 131 | conn.Close() 132 | } 133 | }() 134 | 135 | switch u.Path { 136 | case "": 137 | u.Path = "/" 138 | case "//": 139 | u.Path = u.Path[1:] 140 | } 141 | 142 | genkey := opt.GenerateHandshakeChallenge 143 | if genkey == nil { 144 | genkey = defaultGenerateHandshakeChallenge 145 | } 146 | 147 | // Send the websocket handshake. 148 | buf := bytes.NewBuffer(nil) 149 | buf.Grow(512) 150 | 151 | // Write the request line 152 | buf.WriteString("GET ") 153 | if u.Path == "" { 154 | buf.WriteByte('/') 155 | } else { 156 | buf.WriteString(u.Path) 157 | } 158 | if u.RawQuery != "" { 159 | buf.WriteByte('?') 160 | buf.WriteString(u.RawQuery) 161 | } 162 | buf.WriteString(" HTTP/1.1\r\n") 163 | 164 | // Write the request header 165 | challenge := base64.StdEncoding.EncodeToString(genkey()) 166 | fmt.Fprintf(buf, "Host: %s\r\n", u.Host) 167 | buf.WriteString("Connection: Upgrade\r\n") 168 | buf.WriteString("Upgrade: websocket\r\n") 169 | fmt.Fprintf(buf, "Sec-WebSocket-Version: 13\r\n") 170 | fmt.Fprintf(buf, "Sec-WebSocket-Key: %s\r\n", challenge) 171 | if len(opt.Protocol) > 0 { 172 | fmt.Fprintf(buf, "Sec-Websocket-Protocol: %s\r\n", strings.Join(opt.Protocol, ", ")) 173 | } 174 | if opt.Origin != "" { 175 | fmt.Fprintf(buf, "Origin: %s\r\n", opt.Origin) 176 | } 177 | for key, value := range opt.Header { 178 | fmt.Fprintf(buf, "%s: %s\r\n", key, strings.Join(value, ", ")) 179 | } 180 | 181 | // Write the header end 182 | buf.WriteString("\r\n") 183 | 184 | // Send the websocket handshake request 185 | if n, err := conn.Write(buf.Bytes()); err != nil { 186 | return nil, err 187 | } else if n != buf.Len() { 188 | return nil, fmt.Errorf("failed to send the websocket handshake request") 189 | } 190 | 191 | // Handle the websocket handshake response 192 | reader := bufio.NewReaderSize(conn, opt.MaxLine) 193 | resp, err := http.ReadResponse(reader, nil) 194 | if err != nil { 195 | return nil, err 196 | } 197 | defer resp.Body.Close() 198 | 199 | var body []byte 200 | if resp.ContentLength > 0 { 201 | buf := bytes.NewBuffer(nil) 202 | if resp.ContentLength < 1024 { 203 | buf.Grow(1024) 204 | } else { 205 | buf.Grow(8192) 206 | } 207 | 208 | if m, err := io.Copy(buf, io.LimitReader(resp.Body, resp.ContentLength)); err != nil { 209 | return nil, err 210 | } else if m < resp.ContentLength { 211 | return nil, fmt.Errorf("the websocket handshake response is too few") 212 | } 213 | } 214 | 215 | if resp.StatusCode != 101 { 216 | if len(body) == 0 { 217 | return nil, fmt.Errorf("code=%d", resp.StatusCode) 218 | } 219 | return nil, fmt.Errorf("code=%d: %s", resp.StatusCode, string(body)) 220 | } else if strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { 221 | return nil, fmt.Errorf("the Connection header is not upgrade") 222 | } else if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" { 223 | return nil, fmt.Errorf("the Upgrade header is not websocket") 224 | } else if accept := resp.Header.Get("Sec-WebSocket-Accept"); accept == "" { 225 | return nil, fmt.Errorf("missing Sec-WebSocket-Accept header") 226 | } else if accept != computeAcceptKey(challenge) { 227 | return nil, fmt.Errorf("invalid websocket challenge: %s", accept) 228 | } 229 | 230 | protocol := resp.Header.Get("Sec-WebSocket-Protocol") 231 | return NewWebsocket(conn).SetProtocol(protocol).SetClient(), nil 232 | } 233 | -------------------------------------------------------------------------------- /encode.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package websocket 16 | 17 | import ( 18 | "encoding/binary" 19 | "fmt" 20 | ) 21 | 22 | // maskFrame masks a frame. 23 | func maskFrame(frame, mask []byte) []byte { 24 | return unmaskFrame(frame, mask) 25 | } 26 | 27 | // unmaskFrame unmasks a frame. 28 | func unmaskFrame(frame, mask []byte) []byte { 29 | if len(mask) != 4 { 30 | panic(fmt.Errorf("the length of frame mask is not 4")) 31 | } 32 | for i := range frame { 33 | frame[i] ^= mask[i%4] 34 | } 35 | return frame 36 | } 37 | 38 | // encodeHybi encodes a HyBi style WebSocket frame. 39 | // 40 | // Optional opcode: 41 | // 42 | // 0x0 - continuation 43 | // 0x1 - text frame 44 | // 0x2 - binary frame 45 | // 0x8 - connection close 46 | // 0x9 - ping 47 | // 0xA - pong 48 | func encodeHyBi(opcode int, buf, mask []byte, fin bool) []byte { 49 | b1 := opcode & 0x0f 50 | if fin { 51 | b1 |= 0x80 52 | } 53 | 54 | maskBit := 0 55 | if len(mask) > 0 { 56 | maskBit = 0x80 57 | maskFrame(buf, mask) 58 | } 59 | 60 | var header [16]byte 61 | var headerLen int 62 | payloadLen := len(buf) 63 | if payloadLen <= 125 { 64 | headerLen = 2 65 | header[0] = byte(b1) 66 | header[1] = byte(payloadLen | maskBit) 67 | } else if payloadLen < 65536 { 68 | headerLen = 4 69 | header[0] = byte(b1) 70 | header[1] = byte(126 | maskBit) 71 | binary.BigEndian.PutUint16(header[2:], uint16(payloadLen)) 72 | } else { 73 | headerLen = 10 74 | header[0] = byte(b1) 75 | header[1] = byte(127 | maskBit) 76 | binary.BigEndian.PutUint64(header[2:], uint64(payloadLen)) 77 | } 78 | headers := header[:headerLen] 79 | 80 | bs := make([]byte, 0, len(headers)+len(mask)+len(buf)) 81 | bs = append(bs, headers...) 82 | bs = append(bs, mask...) 83 | bs = append(bs, buf...) 84 | return bs 85 | } 86 | 87 | // decodeHyBi decodes HyBi style WebSocket packets. 88 | func decodeHyBi(frame *frame, buf []byte) bool { 89 | blen := len(buf) 90 | hlen := 2 91 | if blen < hlen { 92 | return false 93 | } 94 | 95 | b1 := int(buf[0]) 96 | b2 := int(buf[1]) 97 | 98 | frame.opcode = b1 & 0x0f 99 | frame.fin = b1&0x80 > 0 100 | frame.masked = b2&0x80 > 0 101 | 102 | if frame.masked { 103 | hlen += 4 104 | if blen < hlen { 105 | return false 106 | } 107 | } 108 | 109 | length := b2 & 0x7f 110 | if length == 126 { 111 | hlen += 2 112 | if blen < hlen { 113 | return false 114 | } 115 | length = int(binary.BigEndian.Uint16(buf[2:4])) 116 | } else if length == 127 { 117 | hlen += 8 118 | if blen < hlen { 119 | return false 120 | } 121 | length = int(binary.BigEndian.Uint64(buf[2:10])) 122 | } 123 | frame.length = hlen + length 124 | 125 | if blen < frame.length { 126 | return false 127 | } 128 | 129 | if frame.masked { 130 | // unmask payload 131 | frame.payload = unmaskFrame(buf[hlen:frame.length], buf[hlen-4:hlen]) 132 | } else { 133 | frame.payload = buf[hlen:frame.length] 134 | } 135 | return true 136 | } 137 | 138 | type frame struct { 139 | opcode int 140 | length int 141 | payload []byte 142 | masked bool 143 | fin bool 144 | } 145 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/xgfone/go-websocket 2 | 3 | go 1.11 4 | -------------------------------------------------------------------------------- /upgrader.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 xgfone 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package websocket 16 | 17 | import ( 18 | "crypto/sha1" 19 | "encoding/base64" 20 | "errors" 21 | "fmt" 22 | "net/http" 23 | "net/url" 24 | "strings" 25 | "time" 26 | "unicode/utf8" 27 | ) 28 | 29 | func headerContainValue(header http.Header, key string, value string) bool { 30 | for _, v := range header[key] { 31 | for _, s := range strings.Split(v, ",") { 32 | if strings.ToLower(strings.TrimSpace(s)) == value { 33 | return true 34 | } 35 | } 36 | } 37 | return false 38 | } 39 | 40 | // equalASCIIFold returns true if s is equal to t with ASCII case folding as 41 | // defined in RFC 4790. 42 | func equalASCIIFold(s, t string) bool { 43 | for s != "" && t != "" { 44 | sr, size := utf8.DecodeRuneInString(s) 45 | s = s[size:] 46 | tr, size := utf8.DecodeRuneInString(t) 47 | t = t[size:] 48 | if sr == tr { 49 | continue 50 | } 51 | if 'A' <= sr && sr <= 'Z' { 52 | sr = sr + 'a' - 'A' 53 | } 54 | if 'A' <= tr && tr <= 'Z' { 55 | tr = tr + 'a' - 'A' 56 | } 57 | if sr != tr { 58 | return false 59 | } 60 | } 61 | return s == t 62 | } 63 | 64 | func computeAcceptKey(challengeKey string) string { 65 | h := sha1.New() 66 | h.Write([]byte(challengeKey)) 67 | h.Write([]byte(GUID)) 68 | return base64.StdEncoding.EncodeToString(h.Sum(nil)) 69 | } 70 | 71 | // Upgrader is used to upgrade HTTP connection to websocket. 72 | type Upgrader struct { 73 | BufferSize int // The default is 2048KB. 74 | MaxMsgSize int // The default is no limit. 75 | Subprotocols []string 76 | Timeout time.Duration // The default is no timeout. 77 | 78 | CheckOrigin func(*http.Request) bool 79 | Authenticate func(*http.Request) bool 80 | } 81 | 82 | func (u Upgrader) handleError(w http.ResponseWriter, r *http.Request, code int, 83 | reason string) (*Websocket, error) { 84 | w.WriteHeader(code) 85 | fmt.Fprint(w, reason) 86 | return nil, errors.New(reason) 87 | } 88 | 89 | // subprotocols returns the subprotocols requested by the client in the 90 | // Sec-Websocket-Protocol header. 91 | func (u Upgrader) subprotocols(r *http.Request) []string { 92 | h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) 93 | if h == "" { 94 | return nil 95 | } 96 | protocols := strings.Split(h, ",") 97 | for i := range protocols { 98 | protocols[i] = strings.TrimSpace(protocols[i]) 99 | } 100 | return protocols 101 | } 102 | 103 | func (u Upgrader) selectSubprotocol(protocols []string) string { 104 | for _, serverProtocol := range u.Subprotocols { 105 | for _, clientProtocol := range protocols { 106 | if clientProtocol == serverProtocol { 107 | return clientProtocol 108 | } 109 | } 110 | } 111 | return "" 112 | } 113 | 114 | func (u Upgrader) checkSameOrigin(r *http.Request) bool { 115 | origin := r.Header["Origin"] 116 | if len(origin) == 0 { 117 | return true 118 | } 119 | _u, err := url.Parse(origin[0]) 120 | if err != nil { 121 | return false 122 | } 123 | return equalASCIIFold(_u.Host, r.Host) 124 | } 125 | 126 | // Upgrade upgrades the HTTP connection to websocket. 127 | func (u Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, 128 | responseHeader http.Header) (*Websocket, error) { 129 | 130 | if r.Method != "GET" { 131 | return u.handleError(w, r, http.StatusMethodNotAllowed, 132 | "websocket: request method is not GET") 133 | } 134 | 135 | if !headerContainValue(r.Header, "Connection", "upgrade") { 136 | return u.handleError(w, r, http.StatusBadRequest, 137 | "websocket: missing or incorrect Connection header") 138 | } 139 | 140 | if !headerContainValue(r.Header, "Upgrade", "websocket") { 141 | return u.handleError(w, r, http.StatusBadRequest, 142 | "websocket: missing or incorrect Upgrader header") 143 | } 144 | 145 | if !headerContainValue(r.Header, "Sec-Websocket-Version", "13") { 146 | w.Header().Set("Sec-Websocket-Version", "13") 147 | return u.handleError(w, r, http.StatusUpgradeRequired, 148 | "websocket: only support protocol version 13") 149 | } 150 | 151 | // if len(r.Header.Get("Sec-WebSocket-Extensions")) > 0 { 152 | // return u.handleError(w, r, http.StatusBadRequest, 153 | // "websocket: not support extensions") 154 | // } 155 | 156 | if u.Authenticate != nil && !u.Authenticate(r) { 157 | return u.handleError(w, r, http.StatusUnauthorized, 158 | "websocket: authenticate failed") 159 | } 160 | 161 | challengeKey := r.Header.Get("Sec-Websocket-Key") 162 | if challengeKey == "" { 163 | return u.handleError(w, r, http.StatusBadRequest, 164 | "websocket: missing Sec-Websocket-Key header") 165 | } 166 | challengeKey = computeAcceptKey(challengeKey) 167 | 168 | var subprotocol string 169 | protocols := u.subprotocols(r) 170 | if len(protocols) > 0 { 171 | if subprotocol = u.selectSubprotocol(protocols); subprotocol == "" { 172 | return u.handleError(w, r, http.StatusBadRequest, 173 | "websocket: invalid protocol") 174 | } 175 | } 176 | 177 | checkOrigin := u.CheckOrigin 178 | if checkOrigin == nil { 179 | checkOrigin = u.checkSameOrigin 180 | } 181 | if !checkOrigin(r) { 182 | return u.handleError(w, r, http.StatusForbidden, 183 | "websocket: request origin not allowed") 184 | } 185 | 186 | h, ok := w.(http.Hijacker) 187 | if !ok { 188 | return u.handleError(w, r, http.StatusInternalServerError, 189 | "websocket: response does not implement http.Hijacker") 190 | } 191 | conn, brw, err := h.Hijack() 192 | if err != nil { 193 | return u.handleError(w, r, http.StatusInternalServerError, err.Error()) 194 | } 195 | if brw.Reader.Buffered() > 0 { 196 | conn.Close() 197 | return nil, errors.New("websocket: client sent data before handshake is complete") 198 | } 199 | 200 | var cache [512]byte 201 | buf := cache[:0] 202 | buf = append(buf, "HTTP/1.1 101 Switching Protocols\r\n"...) 203 | buf = append(buf, "Upgrade: websocket\r\n"...) 204 | buf = append(buf, "Connection: Upgrade\r\n"...) 205 | buf = append(buf, "Sec-WebSocket-Accept: "...) 206 | buf = append(buf, challengeKey...) 207 | buf = append(buf, "\r\n"...) 208 | if subprotocol != "" { 209 | buf = append(buf, "Sec-WebSocket-Protocol: "...) 210 | buf = append(buf, subprotocol...) 211 | buf = append(buf, "\r\n"...) 212 | } 213 | for k, vs := range responseHeader { 214 | if k == "Sec-Websocket-Protocol" { 215 | continue 216 | } 217 | for _, v := range vs { 218 | buf = append(buf, k...) 219 | buf = append(buf, ": "...) 220 | for i := 0; i < len(v); i++ { 221 | b := v[i] 222 | if b <= 31 { 223 | // prevent response splitting. 224 | b = ' ' 225 | } 226 | buf = append(buf, b) 227 | } 228 | buf = append(buf, "\r\n"...) 229 | } 230 | } 231 | buf = append(buf, "\r\n"...) 232 | 233 | // Clear deadlines set by HTTP server. 234 | if u.Timeout > 0 { 235 | conn.SetDeadline(time.Now().Add(u.Timeout)) 236 | } else { 237 | conn.SetDeadline(time.Time{}) 238 | } 239 | if _, err = conn.Write(buf); err != nil { 240 | conn.Close() 241 | return nil, err 242 | } 243 | 244 | maxMsgSize := u.MaxMsgSize 245 | if maxMsgSize < 0 { 246 | maxMsgSize = 0 247 | } 248 | bufSize := u.BufferSize 249 | if bufSize < 1024 { 250 | bufSize = 2048 251 | } 252 | 253 | ws := NewWebsocket(conn) 254 | ws.SetBufferSize(bufSize).SetMaxMsgSize(maxMsgSize).SetTimeout(u.Timeout). 255 | SetProtocol(subprotocol).SetDeadlineByDuration(u.Timeout) 256 | return ws, nil 257 | } 258 | -------------------------------------------------------------------------------- /vncproxy/README.md: -------------------------------------------------------------------------------- 1 | # vncproxy 2 | 3 | It provides a HTTP Handler to implement the VNC proxy over websocket. 4 | 5 | you can use it easily as following: 6 | 7 | ```go 8 | tokens := map[string]string { 9 | "token1": "host1:port1", 10 | "token2": "host2:port2", 11 | // ... 12 | } 13 | wsconf := vncproxy.ProxyConfig{ 14 | GetBackend: func(r *http.Request) (string, error) { 15 | if vs := r.URL.Query()["token"]; len(vs) > 0 { 16 | return tokens[vs[0]], nil 17 | } 18 | return "", nil 19 | }, 20 | CheckOrigin: func(r *http.Request) bool { 21 | return true 22 | }, 23 | } 24 | handler := vncproxy.NewWebsocketVncProxyHandler(wsconf) 25 | http.Handle("/websockify", handler) 26 | http.ListenAndServe(":5900", nil) 27 | ``` 28 | 29 | Then, you can use [noVNC](https://github.com/novnc/noVNC) by the url `http://127.0.0.1:5900/websockify?token=token1` to connect to "host1:port1" over websocket. 30 | 31 | Here is a complete example program. 32 | ```go 33 | // main.go 34 | package main 35 | 36 | import ( 37 | "context" 38 | "flag" 39 | "fmt" 40 | "log" 41 | "net/http" 42 | "sync" 43 | "time" 44 | 45 | "github.com/redis/go-redis/v9" 46 | "github.com/xgfone/go-websocket/vncproxy" 47 | ) 48 | 49 | var ( 50 | listenAddr string 51 | managerAddr string 52 | keyFile string 53 | certFile string 54 | redisURL string 55 | expired time.Duration 56 | ) 57 | 58 | func init() { 59 | flag.StringVar(&listenAddr, "listenaddr", ":5900", "The address that VNC proxy listens to.") 60 | flag.StringVar(&managerAddr, "manageraddr", "", "The address that the manager listens to. It is disabled by default.") 61 | flag.StringVar(&keyFile, "keyfile", "", "The path of the key file.") 62 | flag.StringVar(&certFile, "certfile", "", "The path of cert file.") 63 | flag.StringVar(&redisURL, "redisurl", "redis://localhost:6379/0", "The url to connect to redis.") 64 | flag.DurationVar(&expired, "expired", 0, "The expiration time of the token.") 65 | } 66 | 67 | func main() { 68 | flag.Parse() 69 | 70 | redisOpt, err := redis.ParseURL(redisURL) 71 | if err != nil { 72 | log.Fatalf("can't parse redis URL '%s': %s", redisURL, err) 73 | } 74 | redisClient := redis.NewClient(redisOpt) 75 | defer redisClient.Close() 76 | 77 | // Create the HTTP handler of the VNC proxy. 78 | handler := vncproxy.NewWebsocketVncProxyHandler(vncproxy.ProxyConfig{ 79 | CheckOrigin: func(r *http.Request) bool { return true }, 80 | GetBackend: func(r *http.Request) (string, error) { 81 | if vs := r.URL.Query()["token"]; len(vs) > 0 { 82 | token, err := redisClient.Get(context.TODO(), vs[0]).Result() 83 | if err != nil && err != redis.Nil { 84 | log.Printf("redis GET error: %s", err) 85 | } 86 | return token, nil 87 | } 88 | return "", nil 89 | }, 90 | }) 91 | 92 | wg := new(sync.WaitGroup) 93 | wg.Add(2) 94 | 95 | go func() { 96 | defer wg.Done() 97 | mux := http.NewServeMux() 98 | mux.Handle("/vnc", handler) 99 | if keyFile != "" && certFile != "" { 100 | http.ListenAndServeTLS(listenAddr, certFile, keyFile, mux) 101 | } 102 | }() 103 | 104 | go func() { 105 | defer wg.Done() 106 | if managerAddr == "" { 107 | return 108 | } 109 | 110 | mux := http.NewServeMux() 111 | mux.HandleFunc("/connections", func(w http.ResponseWriter, r *http.Request) { 112 | fmt.Fprint(w, handler.Connections()) 113 | }) 114 | mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { 115 | query := r.URL.Query() 116 | token := query.Get("token") 117 | addr := query.Get("addr") 118 | if token == "" || addr == "" { 119 | w.WriteHeader(400) 120 | fmt.Fprint(w, "missing token or addr") 121 | return 122 | } 123 | 124 | err := redisClient.Set(context.TODO(), token, addr, expired).Err() 125 | if err != nil { 126 | w.WriteHeader(500) 127 | fmt.Fprint(w, err.Error()) 128 | } 129 | }) 130 | http.ListenAndServe(managerAddr, mux) 131 | }() 132 | 133 | wg.Wait() 134 | } 135 | ``` 136 | 137 | ```shell 138 | $ cat > go.mod < 0, indicating that 161 | // some of the data was successfully written. 162 | // A zero value for t means Write will not time out. 163 | func (ws *Websocket) SetWriteDeadline(t time.Time) error { 164 | return ws.conn.SetWriteDeadline(t) 165 | } 166 | 167 | // SetDeadlineByDuration is equal to SetDeadline(time.Now().Add(d)) if d > 0. 168 | func (ws *Websocket) SetDeadlineByDuration(d time.Duration) error { 169 | if d == 0 { 170 | return nil 171 | } 172 | return ws.SetDeadline(time.Now().Add(d)) 173 | } 174 | 175 | // SetReadDeadlineByDuration is equal to SetReadDeadline(time.Now().Add(d)) if d > 0. 176 | func (ws *Websocket) SetReadDeadlineByDuration(d time.Duration) error { 177 | if d == 0 { 178 | return nil 179 | } 180 | return ws.SetReadDeadline(time.Now().Add(d)) 181 | } 182 | 183 | // SetWriteDeadlineByDuration is equal to SetWriteDeadline(time.Now().Add(d)) if d > 0. 184 | func (ws *Websocket) SetWriteDeadlineByDuration(d time.Duration) error { 185 | if d == 0 { 186 | return nil 187 | } 188 | return ws.SetWriteDeadline(time.Now().Add(d)) 189 | } 190 | 191 | // SetPingHander sets the ping handler. 192 | func (ws *Websocket) SetPingHander(h func(ws *Websocket, data []byte)) *Websocket { 193 | if h != nil { 194 | ws.handlePing = h 195 | } 196 | return ws 197 | } 198 | 199 | // SetPongHander sets the pong handler. 200 | func (ws *Websocket) SetPongHander(h func(ws *Websocket, data []byte)) *Websocket { 201 | if h != nil { 202 | ws.handlePong = h 203 | } 204 | return ws 205 | } 206 | 207 | // SetCloseNotice sets the notice function that the connection is closed, 208 | // that's, the callback cb will be called when the connection is closed. 209 | func (ws *Websocket) SetCloseNotice(cb func()) *Websocket { 210 | ws.closeNotice = cb 211 | return ws 212 | } 213 | 214 | // SetClient sets the websocket is a client. 215 | func (ws *Websocket) SetClient() *Websocket { 216 | ws.isClient = true 217 | return ws 218 | } 219 | 220 | // SetTimeout sets the timeout to receive and send the websocket message. 221 | func (ws *Websocket) SetTimeout(timeout time.Duration) *Websocket { 222 | ws.timeout = timeout 223 | return ws 224 | } 225 | 226 | // SetMaxMsgSize sets the max message size of websocket. 227 | // 228 | // The default(0) is no limit. 229 | func (ws *Websocket) SetMaxMsgSize(size int) *Websocket { 230 | if size >= 0 { 231 | ws.maxMsgSize = size 232 | } 233 | return ws 234 | } 235 | 236 | // SetBufferSize sets the buffer size of websocket. 237 | // 238 | // The default is 2048. 239 | func (ws *Websocket) SetBufferSize(size int) *Websocket { 240 | if size > 0 { 241 | size += 16 242 | ws.bufferSize = size 243 | ws.recvBuffer = bytes.NewBuffer(nil) 244 | ws.recvBuffer.Grow(size) 245 | ws.msgBuffer = bytes.NewBuffer(nil) 246 | ws.msgBuffer.Grow(size) 247 | } 248 | return ws 249 | } 250 | 251 | // SetProtocol sets the selected protocol of websocket. 252 | func (ws *Websocket) SetProtocol(protocol string) *Websocket { 253 | ws.subprotocol = protocol 254 | return ws 255 | } 256 | 257 | // Subprotocol returns the selected protocol. 258 | func (ws *Websocket) Subprotocol() string { 259 | return ws.subprotocol 260 | } 261 | 262 | ///////////////////////////////////////////////////////////////////////////// 263 | 264 | // SendPing sends a ping control message. 265 | func (ws *Websocket) SendPing(data []byte) error { 266 | if data == nil { 267 | data = pingPayload 268 | } 269 | err := ws.sendMsg(MsgTypePing, data) 270 | ws.SetReadDeadlineByDuration(ws.timeout) 271 | return err 272 | } 273 | 274 | // SendPong sends a pong control message. 275 | func (ws *Websocket) SendPong(data []byte) error { 276 | if data == nil { 277 | data = pongPayload 278 | } 279 | return ws.sendMsg(MsgTypePong, data) 280 | } 281 | 282 | // SendClose termiates the websocket connection gracefully, which will send 283 | // a close frame to the peer then close the underlying connection. 284 | func (ws *Websocket) SendClose(code int, reason string) error { 285 | msg := make([]byte, len(reason)+2) 286 | binary.BigEndian.PutUint16(msg, uint16(code)) 287 | if reason != "" { 288 | copy(msg[2:], reason) 289 | } 290 | 291 | err := ws.sendMsg(MsgTypeClose, msg) 292 | ws.close() 293 | return err 294 | } 295 | 296 | // SendTextMsg sends a text message. 297 | // 298 | // If fin is false, the message will be fragmented. 299 | // 300 | // Notice: when sending fragmented message, you should not send another message 301 | // until this fragmented message is sent totally. 302 | func (ws *Websocket) SendTextMsg(message []byte, fin ...bool) error { 303 | return ws.sendMsg(MsgTypeText, message, fin...) 304 | } 305 | 306 | // SendBinaryMsg sends a binary message. 307 | // 308 | // If fin is false, the message will be fragmented. 309 | // 310 | // Notice: when sending fragmented message, you should not send another message 311 | // until this fragmented message is sent totally. 312 | func (ws *Websocket) SendBinaryMsg(message []byte, fin ...bool) error { 313 | return ws.sendMsg(MsgTypeBinary, message, fin...) 314 | } 315 | 316 | // SendMsg sends the message with the message type. 317 | // 318 | // If the message is empty, it will be ignored. 319 | // 320 | // If fin is false, the message will be fragmented. 321 | // 322 | // Notice: when sending fragmented message, you should not send another message 323 | // until this fragmented message is sent totally. 324 | func (ws *Websocket) sendMsg(msgType int, message []byte, _fin ...bool) (err error) { 325 | if ws.IsClosed() { 326 | return errors.New("the connection has been closed") 327 | } 328 | 329 | fin := true 330 | if len(_fin) > 0 { 331 | fin = _fin[0] 332 | } 333 | 334 | if msgType > 0x7 { 335 | // RCF 6455 Section 5.4 336 | if !fin { 337 | panic(fmt.Errorf("the control frame message cannot be fragmented")) 338 | } 339 | 340 | // RCF 6455 Section 5.5 341 | if len(message) > 125 { 342 | panic(fmt.Errorf("the control frame message too big")) 343 | } 344 | } 345 | 346 | // Sends a standard data message 347 | var frame []byte 348 | if ws.isClient { 349 | var mask [4]byte 350 | mask[0] = byte(rand.Intn(256)) 351 | mask[1] = byte(rand.Intn(256)) 352 | mask[2] = byte(rand.Intn(256)) 353 | mask[3] = byte(rand.Intn(256)) 354 | frame = encodeHyBi(msgType, message, mask[:], fin) 355 | } else { 356 | frame = encodeHyBi(msgType, message, nil, fin) 357 | } 358 | 359 | n, _len := 0, len(frame) 360 | for { 361 | ws.SetWriteDeadlineByDuration(ws.timeout) 362 | if n, err = ws.conn.Write(frame); err != nil { 363 | ws.setClosed() 364 | return err 365 | } else if n < _len { 366 | _len -= n 367 | frame = frame[:n] 368 | } else { 369 | return nil 370 | } 371 | } 372 | } 373 | 374 | // Run runs forever until the connection is closed and returned the error. 375 | // 376 | // When receiving a websocket message, it will handle it by calling handle(). 377 | // 378 | // Notice: 379 | // 1. msgType be only MsgTypeText or MsgTypeBinary. 380 | // 2. The message data must not be cached, such as putting it into channel. 381 | func (ws *Websocket) Run(handle func(msgType int, message []byte)) error { 382 | for { 383 | messages, err := ws.RecvMsg() 384 | if err != nil { 385 | return err 386 | } 387 | for _, msg := range messages { 388 | handle(msg.Type, msg.Data) 389 | } 390 | } 391 | } 392 | 393 | func (ws *Websocket) errClose(code int, reason string) error { 394 | ws.SendClose(code, reason) 395 | return fmt.Errorf("[%d]%s", code, reason) 396 | } 397 | 398 | // RecvMsg receives and returns the websocket message. 399 | // 400 | // Notice: 401 | // 1. If it returns an error, the underlying connection has been closed. 402 | // 2. It only returns the text or binary message, not the control message. 403 | // So the message type be only MsgTypeText or MsgTypeBinary. 404 | // 3. The message data must not be cached, such as putting it into channel. 405 | func (ws *Websocket) RecvMsg() (messages []Message, err error) { 406 | frames, err := ws.recvFrames() 407 | if err != nil { 408 | return 409 | } 410 | 411 | for _, frame := range frames { 412 | // RFC 6455 Section 5.1: The server Must close the connection 413 | // upon receiving a frame that is not masked. 414 | if !ws.isClient && !frame.masked { 415 | return nil, ws.errClose(CloseProtocolError, "Protocol error: Frame not masked") 416 | } 417 | 418 | // RFC 6455 Section 5.1: A client MUST close a connection 419 | // if it detects a masked frame. 420 | if ws.isClient && frame.masked { 421 | return nil, ws.errClose(CloseProtocolError, "Protocol error: Frame masked") 422 | } 423 | 424 | if frame.opcode > 0x7 && len(frame.payload) > 125 { 425 | return nil, ws.errClose(CloseMessageTooBig, "The control frame message too big") 426 | } 427 | 428 | switch frame.opcode { 429 | case 0x0: 430 | if ws.msgBuffer.Len() == 0 || ws.opcode == 0 { 431 | return nil, ws.errClose(CloseProtocolError, "Protocol error: Unexpected continuation frame") 432 | } 433 | 434 | ws.msgBuffer.Write(frame.payload) 435 | if ws.maxMsgSize > 0 && ws.msgBuffer.Len() > ws.maxMsgSize { 436 | return nil, ws.errClose(CloseMessageTooBig, "The message is too big") 437 | } 438 | 439 | if frame.fin { 440 | messages = append(messages, Message{Type: ws.opcode, Data: ws.msgBuffer.Bytes()}) 441 | ws.opcode = 0 442 | ws.msgBuffer.Reset() 443 | } 444 | case MsgTypeBinary, MsgTypeText: 445 | if ws.msgBuffer.Len() > 0 { 446 | return nil, ws.errClose(CloseProtocolError, "Protocol error: Unexpected new frame") 447 | } 448 | 449 | if frame.fin { 450 | messages = append(messages, Message{Type: frame.opcode, Data: frame.payload}) 451 | continue 452 | } 453 | 454 | if ws.opcode > 0 { 455 | return nil, ws.errClose(CloseProtocolError, "Protocol error: more new fragmented") 456 | } 457 | ws.opcode = frame.opcode 458 | ws.msgBuffer.Write(frame.payload) 459 | case MsgTypeClose: 460 | if !frame.fin { 461 | return nil, ws.errClose(CloseUnsupportedData, "Unsupported: Fragmented close") 462 | } 463 | 464 | var code int 465 | var reason string 466 | if len(frame.payload) >= 2 { 467 | code = int(binary.BigEndian.Uint16(frame.payload[:2])) 468 | 469 | // RFC 6455 Section 8.1 470 | if len(frame.payload) > 2 { 471 | bs := frame.payload[2:] 472 | if !utf8.Valid(bs) { 473 | return nil, ws.errClose(CloseProtocolError, "Protocol error: Invalid UTF-8 in close") 474 | } 475 | reason = string(bs) 476 | } 477 | } 478 | 479 | if code == 0 { 480 | return nil, ws.errClose(CloseNoStatusReceived, "No close status code specified by peer") 481 | } 482 | return nil, ws.errClose(code, reason) 483 | case MsgTypePing: 484 | if !frame.fin { 485 | return nil, ws.errClose(CloseUnsupportedData, "Unsupported: Fragmented ping") 486 | } 487 | ws.handlePing(ws, frame.payload) 488 | case MsgTypePong: 489 | if !frame.fin { 490 | return nil, ws.errClose(CloseUnsupportedData, "Unsupported: Fragmented pong") 491 | } 492 | ws.handlePong(ws, frame.payload) 493 | default: 494 | return nil, ws.errClose(CloseUnsupportedData, 495 | fmt.Sprintf("Unsupported: Unknown opcode 0x%02x", frame.opcode)) 496 | } 497 | } 498 | 499 | return 500 | } 501 | 502 | // recvFrames fetches more data from the socket to the buffer then decodes it. 503 | func (ws *Websocket) recvFrames() (frames []frame, err error) { 504 | var n int 505 | for { 506 | if ws.IsClosed() { 507 | return nil, errors.New("the connection has been closed") 508 | } 509 | 510 | // Read the message. 511 | recvbuf := make([]byte, ws.bufferSize) 512 | ws.SetReadDeadlineByDuration(ws.timeout) 513 | if n, err = ws.conn.Read(recvbuf); err != nil { 514 | ws.close() 515 | return nil, err 516 | } 517 | ws.recvBuffer.Write(recvbuf[:n]) 518 | 519 | // Check the message is too big. 520 | if _len := ws.recvBuffer.Len(); ws.maxMsgSize > 0 && _len > ws.maxMsgSize { 521 | ws.close() 522 | return nil, fmt.Errorf("the received message is too big: %d", _len) 523 | } 524 | 525 | // Decode the frame 526 | buffer := ws.recvBuffer.Bytes() 527 | for len(buffer) > 0 { 528 | var frame frame 529 | if decodeHyBi(&frame, buffer) { 530 | frames = append(frames, frame) 531 | buffer = buffer[frame.length:] 532 | } else { 533 | break 534 | } 535 | } 536 | 537 | if len(frames) > 0 { 538 | // Copy the frame data, don't use the buffer cache 539 | for i := range frames { 540 | data := make([]byte, len(frames[i].payload)) 541 | copy(data, frames[i].payload) 542 | frames[i].payload = data 543 | } 544 | 545 | ws.recvBuffer.Reset() 546 | if len(buffer) > 0 { 547 | ws.recvBuffer.Write(buffer) 548 | } 549 | 550 | return 551 | } 552 | } 553 | } 554 | 555 | // IsClosed reports whether the underlying connection has been closed. 556 | func (ws *Websocket) IsClosed() bool { 557 | return atomic.LoadInt32(&ws.closed) == 1 558 | } 559 | 560 | func (ws *Websocket) setClosed() { 561 | atomic.StoreInt32(&ws.closed, 1) 562 | if ws.closeNotice != nil { 563 | ws.closeNotice() 564 | } 565 | } 566 | 567 | // close closes the underlying socket. 568 | func (ws *Websocket) close() { 569 | if !ws.IsClosed() { 570 | ws.setClosed() 571 | ws.conn.Close() 572 | } 573 | } 574 | --------------------------------------------------------------------------------