forked from philippseith/signalr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpmux.go
280 lines (260 loc) · 8.05 KB
/
httpmux.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package signalr
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/teivah/onecontext"
"nhooyr.io/websocket"
)
type httpMux struct {
mx sync.RWMutex
connectionMap map[string]Connection
server Server
}
func newHTTPMux(server Server) *httpMux {
return &httpMux{
connectionMap: make(map[string]Connection),
server: server,
}
}
func (h *httpMux) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
switch request.Method {
case "POST":
h.handlePost(writer, request)
case "GET":
h.handleGet(writer, request)
default:
writer.WriteHeader(http.StatusBadRequest)
}
}
func (h *httpMux) handlePost(writer http.ResponseWriter, request *http.Request) {
connectionID := request.URL.Query().Get("id")
if connectionID == "" {
writer.WriteHeader(http.StatusBadRequest)
return
}
info, _ := h.server.prefixLoggers("")
for {
h.mx.RLock()
c, ok := h.connectionMap[connectionID]
h.mx.RUnlock()
if ok {
// Connection is initiated
switch conn := c.(type) {
case *serverSSEConnection:
writer.WriteHeader(conn.consumeRequest(request))
return
case *negotiateConnection:
// connection start initiated but not completed
default:
// ConnectionID already used for WebSocket(?)
writer.WriteHeader(http.StatusConflict)
return
}
} else {
writer.WriteHeader(http.StatusNotFound)
return
}
<-time.After(10 * time.Millisecond)
_ = info.Log("event", "handlePost for SSE connection repeated")
}
}
func (h *httpMux) handleGet(writer http.ResponseWriter, request *http.Request) {
upgrade := false
for _, connHead := range strings.Split(request.Header.Get("Connection"), ",") {
if strings.ToLower(strings.TrimSpace(connHead)) == "upgrade" {
upgrade = true
break
}
}
if upgrade &&
strings.ToLower(request.Header.Get("Upgrade")) == "websocket" {
h.handleWebsocket(writer, request)
} else if strings.ToLower(request.Header.Get("Accept")) == "text/event-stream" {
h.handleServerSentEvent(writer, request)
} else {
writer.WriteHeader(http.StatusBadRequest)
}
}
func (h *httpMux) handleServerSentEvent(writer http.ResponseWriter, request *http.Request) {
connectionID := request.URL.Query().Get("id")
if connectionID == "" {
writer.WriteHeader(http.StatusBadRequest)
return
}
h.mx.RLock()
c, ok := h.connectionMap[connectionID]
h.mx.RUnlock()
if ok {
if _, ok := c.(*negotiateConnection); ok {
ctx, _ := onecontext.Merge(h.server.context(), request.Context())
sseConn, jobChan, jobResultChan, err := newServerSSEConnection(ctx, c.ConnectionID())
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
return
}
flusher, ok := writer.(http.Flusher)
if !ok {
writer.WriteHeader(http.StatusInternalServerError)
return
}
// Connection is negotiated but not initiated
// We compose http and send it over sse
writer.Header().Set("Content-Type", "text/event-stream")
writer.Header().Set("Connection", "keep-alive")
writer.Header().Set("Cache-Control", "no-cache")
writer.WriteHeader(http.StatusOK)
// End this Server Sent Event (yes, your response now is one and the client will wait for this initial event to end)
_, _ = fmt.Fprint(writer, ":\r\n\r\n")
writer.(http.Flusher).Flush()
go func() {
// We can't WriteHeader 500 if we get an error as we already wrote the header, so ignore it.
_ = h.serveConnection(sseConn)
}()
// Loop for write jobs from the sseServerConnection
for buf := range jobChan {
n, err := writer.Write(buf)
if err == nil {
flusher.Flush()
}
jobResultChan <- RWJobResult{n: n, err: err}
}
close(jobResultChan)
} else {
// connectionID in use
writer.WriteHeader(http.StatusConflict)
}
} else {
writer.WriteHeader(http.StatusNotFound)
}
}
func (h *httpMux) handleWebsocket(writer http.ResponseWriter, request *http.Request) {
accOptions := &websocket.AcceptOptions{
CompressionMode: websocket.CompressionContextTakeover,
InsecureSkipVerify: h.server.insecureSkipVerify(),
OriginPatterns: h.server.originPatterns(),
}
websocketConn, err := websocket.Accept(writer, request, accOptions)
if err != nil {
_, debug := h.server.loggers()
_ = debug.Log(evt, "handleWebsocket", msg, "error accepting websockets", "error", err)
// don't need to write an error header here as websocket.Accept has already used http.Error
return
}
websocketConn.SetReadLimit(int64(h.server.maximumReceiveMessageSize()))
connectionMapKey := request.URL.Query().Get("id")
if connectionMapKey == "" {
// Support websocket connection without negotiate
connectionMapKey = newConnectionID()
h.mx.Lock()
h.connectionMap[connectionMapKey] = &negotiateConnection{
ConnectionBase{connectionID: connectionMapKey},
}
h.mx.Unlock()
}
h.mx.RLock()
c, ok := h.connectionMap[connectionMapKey]
h.mx.RUnlock()
if ok {
if _, ok := c.(*negotiateConnection); ok {
// Connection is negotiated but not initiated
ctx, _ := onecontext.Merge(h.server.context(), request.Context())
err = h.serveConnection(newWebSocketConnection(ctx, c.ConnectionID(), websocketConn))
if err != nil {
_ = websocketConn.Close(1005, err.Error())
}
} else {
// Already initiated
_ = websocketConn.Close(1002, "Bad request")
}
} else {
// Not negotiated
_ = websocketConn.Close(1002, "Not found")
}
}
func (h *httpMux) negotiate(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
w.WriteHeader(http.StatusBadRequest)
} else {
connectionID := newConnectionID()
connectionMapKey := connectionID
// Check the header for negotiateVersion
headerNegotiateVersion, err := strconv.Atoi(req.Header.Get("negotiateVersion"))
if err != nil {
headerNegotiateVersion = 0
}
// Check the query parameter for negotiateVersion
queryNegotiateVersion, err := strconv.Atoi(req.URL.Query().Get("negotiateVersion"))
if err != nil {
queryNegotiateVersion = 0
}
// Use the negotiateVersion from query if present, otherwise use the one from the header parameter
negotiateVersion := queryNegotiateVersion
if headerNegotiateVersion != 0 {
negotiateVersion = headerNegotiateVersion
}
connectionToken := ""
if negotiateVersion == 1 {
connectionToken = newConnectionID()
connectionMapKey = connectionToken
}
h.mx.Lock()
h.connectionMap[connectionMapKey] = &negotiateConnection{
ConnectionBase{connectionID: connectionID},
}
h.mx.Unlock()
var availableTransports []availableTransport
for _, transport := range h.server.availableTransports() {
switch transport {
case TransportServerSentEvents:
availableTransports = append(availableTransports,
availableTransport{
Transport: string(TransportServerSentEvents),
TransferFormats: []string{string(TransferFormatText)},
})
case TransportWebSockets:
availableTransports = append(availableTransports,
availableTransport{
Transport: string(TransportWebSockets),
TransferFormats: []string{string(TransferFormatText), string(TransferFormatBinary)},
})
}
}
response := negotiateResponse{
ConnectionToken: connectionToken,
ConnectionID: connectionID,
NegotiateVersion: negotiateVersion,
AvailableTransports: availableTransports,
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(response) // Can't imagine an error when encoding
}
}
func (h *httpMux) serveConnection(c Connection) error {
h.mx.Lock()
h.connectionMap[c.ConnectionID()] = c
h.mx.Unlock()
return h.server.Serve(c)
}
func newConnectionID() string {
bytes := make([]byte, 16)
// rand.Read only fails when the systems random number generator fails. Rare case, ignore
_, _ = rand.Read(bytes)
// Important: Use URLEncoding. StdEncoding contains "/" which will be randomly part of the connectionID and cause parsing problems
return base64.URLEncoding.EncodeToString(bytes)
}
type negotiateConnection struct {
ConnectionBase
}
func (n *negotiateConnection) Read([]byte) (int, error) {
return 0, nil
}
func (n *negotiateConnection) Write([]byte) (int, error) {
return 0, nil
}