forked from improbable-eng/grpc-web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebsocket_wrapper.go
216 lines (182 loc) · 6.24 KB
/
websocket_wrapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package grpcweb
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"io"
"net/http"
"net/textproto"
"strings"
"github.com/gorilla/websocket"
"golang.org/x/net/http2"
)
type webSocketResponseWriter struct {
writtenHeaders bool
wsConn *websocket.Conn
headers http.Header
flushedHeaders http.Header
closeNotifyChan chan bool
}
func newWebSocketResponseWriter(wsConn *websocket.Conn) *webSocketResponseWriter {
return &webSocketResponseWriter{
writtenHeaders: false,
headers: make(http.Header),
flushedHeaders: make(http.Header),
wsConn: wsConn,
closeNotifyChan: make(chan bool),
}
}
func (w *webSocketResponseWriter) Header() http.Header {
return w.headers
}
func (w *webSocketResponseWriter) Write(b []byte) (int, error) {
if !w.writtenHeaders {
w.WriteHeader(http.StatusOK)
}
return len(b), w.wsConn.WriteMessage(websocket.BinaryMessage, b)
}
func (w *webSocketResponseWriter) writeHeaderFrame(headers http.Header) {
headerBuffer := new(bytes.Buffer)
headers.Write(headerBuffer)
headerGrpcDataHeader := []byte{1 << 7, 0, 0, 0, 0} // MSB=1 indicates this is a header data frame.
binary.BigEndian.PutUint32(headerGrpcDataHeader[1:5], uint32(headerBuffer.Len()))
w.wsConn.WriteMessage(websocket.BinaryMessage, headerGrpcDataHeader)
w.wsConn.WriteMessage(websocket.BinaryMessage, headerBuffer.Bytes())
}
func (w *webSocketResponseWriter) copyFlushedHeaders() {
for k, vv := range w.headers {
// Skip the pre-annoucement of Trailer headers. Don't add them to the response headers.
if strings.ToLower(k) == "trailer" {
continue
}
for _, v := range vv {
w.flushedHeaders.Add(k, v)
}
}
}
func (w *webSocketResponseWriter) WriteHeader(code int) {
w.copyFlushedHeaders()
w.writtenHeaders = true
w.writeHeaderFrame(w.headers)
return
}
func (w *webSocketResponseWriter) extractTrailerHeaders() http.Header {
trailerHeaders := make(http.Header)
for k, vv := range w.headers {
// Skip the pre-annoucement of Trailer headers. Don't add them to the response headers.
if strings.ToLower(k) == "trailer" {
continue
}
// Skip existing headers that were already sent.
if _, exists := w.flushedHeaders[k]; exists {
continue
}
// Skip the Trailer prefix
if strings.HasPrefix(k, http2.TrailerPrefix) {
k = k[len(http2.TrailerPrefix):]
}
for _, v := range vv {
trailerHeaders.Add(k, v)
}
}
return trailerHeaders
}
func (w *webSocketResponseWriter) FlushTrailers() {
w.writeHeaderFrame(w.extractTrailerHeaders())
}
func (w *webSocketResponseWriter) Flush() {
// no-op
}
func (w *webSocketResponseWriter) CloseNotify() <-chan bool {
return w.closeNotifyChan
}
type webSocketWrappedReader struct {
wsConn *websocket.Conn
respWriter *webSocketResponseWriter
remainingBuffer []byte
remainingError error
}
func (w *webSocketWrappedReader) Close() error {
w.respWriter.FlushTrailers()
return w.wsConn.Close()
}
// First byte of a binary WebSocket frame is used for control flow:
// 0 = Data
// 1 = End of client send
func (w *webSocketWrappedReader) Read(p []byte) (int, error) {
// If a buffer remains from a previous WebSocket frame read then continue reading it
if w.remainingBuffer != nil {
// If the remaining buffer fits completely inside the argument slice then read all of it and return any error
// that was retained from the original call
if len(w.remainingBuffer) <= len(p) {
copy(p, w.remainingBuffer)
remainingLength := len(w.remainingBuffer)
err := w.remainingError
// Clear the remaining buffer and error so that the next read will be a read from the websocket frame,
// unless the error terminates the stream
w.remainingBuffer = nil
w.remainingError = nil
return remainingLength, err
}
// The remaining buffer doesn't fit inside the argument slice, so copy the bytes that will fit and retain the
// bytes that don't fit - don't return the remainingError as there are still bytes to be read from the frame
copy(p, w.remainingBuffer[:len(p)])
w.remainingBuffer = w.remainingBuffer[len(p):]
// Return the length of the argument slice as that was the length of the written bytes
return len(p), nil
}
// Read a whole frame from the WebSocket connection
messageType, framePayload, err := w.wsConn.ReadMessage()
if err == io.EOF || messageType == -1 {
// The client has closed the connection. Indicate to the response writer that it should close
w.respWriter.closeNotifyChan <- true
return 0, io.EOF
}
// Only Binary frames are valid
if messageType != websocket.BinaryMessage {
return 0, errors.New("websocket frame was not a binary frame")
}
// If the frame consists of only a single byte of value 1 then this indicates the client has finished sending
if len(framePayload) == 1 && framePayload[0] == 1 {
return 0, io.EOF
}
// If the frame is somehow empty then just return the error
if len(framePayload) == 0 {
return 0, err
}
// The first byte is used for control flow, so the data starts from the second byte
dataPayload := framePayload[1:]
// If the remaining buffer fits completely inside the argument slice then read all of it and return the error
if len(dataPayload) <= len(p) {
copy(p, dataPayload)
return len(dataPayload), err
}
// The data read from the frame doesn't fit inside the argument slice, so copy the bytes that fit into the argument
// slice
copy(p, dataPayload[:len(p)])
// Retain the bytes that do not fit in the argument slice
w.remainingBuffer = dataPayload[len(p):]
// Retain the error instead of returning it so that the retained bytes will be read
w.remainingError = err
// Return the length of the argument slice as that is the length of the written bytes
return len(p), nil
}
func newWebsocketWrappedReader(wsConn *websocket.Conn, respWriter *webSocketResponseWriter) *webSocketWrappedReader {
return &webSocketWrappedReader{
wsConn: wsConn,
respWriter: respWriter,
remainingBuffer: nil,
remainingError: nil,
}
}
func parseHeaders(headerString string) (http.Header, error) {
reader := bufio.NewReader(strings.NewReader(headerString + "\r\n"))
tp := textproto.NewReader(reader)
mimeHeader, err := tp.ReadMIMEHeader()
if err != nil {
return nil, err
}
// http.Header and textproto.MIMEHeader are both just a map[string][]string
return http.Header(mimeHeader), nil
}