-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
uwsgi.go
350 lines (302 loc) · 7.65 KB
/
uwsgi.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
This file implements the uWSGI protocol.
This implements run as net.Listener:
l, err = net.Listen("unix", "/path/to/socket")
http.Serve(&UwsgiListener{l}, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Length", 11)
w.Write([]byte("hello world"))
})
*/
package uwsgi
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"time"
)
// Listener behave as net.Listener
type Listener struct {
net.Listener
}
// Conn is connection for uWSGI
type Conn struct {
net.Conn
env map[string][]string
reader io.Reader
hdrdone bool
ready bool
readych chan bool
err error
}
func (c *Conn) Read(b []byte) (n int, e error) {
// Wait until headers have been processed
if !c.ready && c.err == nil {
<-c.readych
c.ready = true
}
if c.err != nil {
return 0, c.err
}
// After headers have been read by HTTP server, transfer
// socket over to the underlying connection for direct read.
if !c.hdrdone {
n, e = c.reader.Read(b)
if n == 0 || e != nil {
c.hdrdone = true
}
}
if c.hdrdone {
n, e = c.Conn.Read(b)
c.err = e
}
return n, e
}
// Writer behave as same as net.Listener
func (c *Conn) Write(b []byte) (int, error) {
if c.err != nil {
return 0, c.err
}
return c.Conn.Write(b)
}
// SetDeadline behave as same as net.Listener
func (c *Conn) SetDeadline(t time.Time) error {
if c.err != nil {
return c.err
}
return c.Conn.SetDeadline(t)
}
// SetReadDeadline behave as same as net.Listener
func (c *Conn) SetReadDeadline(t time.Time) error {
if c.err != nil {
return c.err
}
return c.Conn.SetReadDeadline(t)
}
// SetWriteDeadline behave as same as net.Listener
func (c *Conn) SetWriteDeadline(t time.Time) error {
if c.err != nil {
return c.err
}
return c.Conn.SetWriteDeadline(t)
}
var headerMappings = map[string]string{
"HTTP_HOST": "Host",
"CONTENT_TYPE": "Content-Type",
"HTTP_ACCEPT": "Accept",
"HTTP_ACCEPT_ENCODING": "Accept-Encoding",
"HTTP_ACCEPT_LANGUAGE": "Accept-Language",
"HTTP_ACCEPT_CHARSET": "Accept-Charset",
"HTTP_CONTENT_TYPE": "Content-Type",
"HTTP_COOKIE": "Cookie",
"HTTP_IF_MATCH": "If-Match",
"HTTP_IF_MODIFIED_SINCE": "If-Modified-Since",
"HTTP_IF_NONE_MATCH": "If-None-Match",
"HTTP_IF_RANGE": "If-Range",
"HTTP_RANGE": "Range",
"HTTP_REFERER": "Referer",
"HTTP_USER_AGENT": "User-Agent",
"HTTP_X_REQUESTED_WITH": "Requested-With",
}
// Accept conduct as net.Listener. uWSGI protocol is working good for CGI.
// This function parse headers and pass to the Server.
func (l *Listener) Accept() (net.Conn, error) {
fd, err := l.Listener.Accept()
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
c := &Conn{fd, make(map[string][]string), buf, false, false, make(chan bool, 1), nil}
go func() {
/*
* uwsgi header:
* struct {
* uint8 modifier1;
* uint16 datasize;
* uint8 modifier2;
* }
* -- for HTTP, mod1 and mod2 = 0
*/
var head [4]byte
fd.Read(head[:])
b := []byte{head[1], head[2]}
envsize := binary.LittleEndian.Uint16(b)
envbuf := make([]byte, envsize)
if _, err := io.ReadFull(fd, envbuf); err != nil {
fd.Close()
c.err = err
return
}
/*
* uwsgi vars are linear lists of the form:
* struct {
* uint16 key_size;
* uint8 key[key_size];
* uint16 val_size;
* uint8 val[val_size];
* }
*/
i := uint16(0)
var reqMethod string
var reqURI string
var reqProtocol string
for {
// Ensure no corrupted payload; shouldn't happen but it has...
if i+1 >= uint16(len(envbuf)) {
break
}
b := []byte{envbuf[i], envbuf[i+1]}
kl := binary.LittleEndian.Uint16(b)
i += 2
if i+kl > uint16(len(envbuf)) {
fd.Close()
c.err = errors.New("Invalid uwsgi request; uwsgi vars index out of range")
return
}
k := string(envbuf[i : i+kl])
i += kl
if i+1 >= uint16(len(envbuf)) {
fd.Close()
c.err = errors.New("Invalid uwsgi request; uwsgi vars index out of range")
return
}
b = []byte{envbuf[i], envbuf[i+1]}
vl := binary.LittleEndian.Uint16(b)
i += 2
if i+vl > uint16(len(envbuf)) {
fd.Close()
c.err = errors.New("Invalid uwsgi request; uwsgi vars index out of range")
return
}
v := string(envbuf[i : i+vl])
i += vl
if k == "REQUEST_METHOD" {
reqMethod = v
} else if k == "REQUEST_URI" {
reqURI = v
} else if k == "SERVER_PROTOCOL" {
v = "HTTP/1.0"
reqProtocol = v
}
val, ok := c.env[k]
if !ok {
val = make([]string, 0, 2)
}
val = append(val, v)
c.env[k] = val
if i >= envsize {
break
}
}
if reqProtocol == "" {
// Invalid protocol
fd.Close()
c.err = errors.New("Invalid uwsgi request; no protocol specified")
return
}
fmt.Fprintf(buf, "%s %s %s\r\n", reqMethod, reqURI, reqProtocol)
var cl int64
for i := range c.env {
switch i {
case "CONTENT_LENGTH":
cl, _ = strconv.ParseInt(c.env[i][0], 10, 64)
if cl > 0 {
fmt.Fprintf(buf, "Content-Length: %d\r\n", cl)
}
default:
hname, ok := headerMappings[i]
if !ok {
// To avoid double Host headers in some cases, only parse HTTP_HOST as a correct Host.
if i == "Host" {
continue
}
hname = i
}
for v := range c.env[i] {
fmt.Fprintf(buf, "%s: %s\r\n", hname, c.env[i][v])
}
}
}
buf.Write([]byte("\r\n"))
// Signal to indicate header processing is complete and remaining
// payload can be read from the socket itself.
c.readych <- true
}()
return c, nil
}
// Passenger works as uWSGI transport
type Passenger struct {
Net string
Addr string
}
var trailingPort = regexp.MustCompile(`:([0-9]+)$`)
func (p Passenger) ServeHTTP(w http.ResponseWriter, req *http.Request) {
conn, err := net.Dial(p.Net, p.Addr)
if err != nil {
panic(err.Error())
}
defer conn.Close()
port := "80"
if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 {
port = matches[1]
}
header := make(map[string][]string)
header["REQUEST_METHOD"] = []string{req.Method}
header["REQUEST_URI"] = []string{req.RequestURI}
header["CONTENT_LENGTH"] = []string{strconv.Itoa(int(req.ContentLength))}
header["SERVER_PROTOCOL"] = []string{req.Proto}
header["SERVER_NAME"] = []string{req.Host}
header["SERVER_ADDR"] = []string{req.RemoteAddr}
header["SERVER_PORT"] = []string{port}
header["REMOTE_HOST"] = []string{req.RemoteAddr}
header["REMOTE_ADDR"] = []string{req.RemoteAddr}
header["SCRIPT_NAME"] = []string{req.URL.Path}
header["PATH_INFO"] = []string{req.URL.Path}
header["QUERY_STRING"] = []string{req.URL.RawQuery}
if ctype := req.Header.Get("Content-Type"); ctype != "" {
header["CONTENT_TYPE"] = []string{ctype}
}
for k, v := range req.Header {
if _, ok := header[k]; ok == false {
k = "HTTP_" + strings.ToUpper(strings.Replace(k, "-", "_", -1))
header[k] = v
}
}
var size uint16
for k, v := range header {
for _, vv := range v {
size += uint16(len(([]byte)(k))) + 2
size += uint16(len(([]byte)(vv))) + 2
}
}
hsize := make([]byte, 4)
binary.LittleEndian.PutUint16(hsize[1:3], size)
conn.Write(hsize)
for k, v := range header {
for _, vv := range v {
binary.Write(conn, binary.LittleEndian, uint16(len(([]byte)(k))))
conn.Write([]byte(k))
binary.Write(conn, binary.LittleEndian, uint16(len(([]byte)(vv))))
conn.Write([]byte(vv))
}
}
io.Copy(conn, req.Body)
res, err := http.ReadResponse(bufio.NewReader(conn), req)
if err != nil {
panic(err.Error())
}
for k, v := range res.Header {
w.Header().Del(k)
for _, vv := range v {
w.Header().Add(k, vv)
}
}
io.Copy(w, res.Body)
}