forked from edsrzf/mongrel2-go
/
mongrel2.go
203 lines (177 loc) · 4.45 KB
/
mongrel2.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
package mongrel2
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/edsrzf/zegomq"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"time"
)
func Serve(identity, pullAddr, pubAddr string, handler http.Handler) error {
c := zmq.NewContext()
pull, err := c.NewSocket(zmq.SOCK_PULL, "")
if err != nil {
return err
}
if err = pull.Connect(pullAddr); err != nil {
return err
}
pub, err := c.NewSocket(zmq.SOCK_PUB, identity)
if err != nil {
return err
}
if err = pub.Connect(pubAddr); err != nil {
return err
}
for {
msg, err := pull.RecvMsg()
if err != nil {
panic(err.Error())
}
b, err := ioutil.ReadAll(msg)
if err != nil {
panic(err.Error())
}
msg.Close()
split := bytes.SplitN(b, []byte{' '}, 4)
if len(split) < 4 {
panic("bad parse")
}
uuid, id := split[0], split[1]
headerJson, n := parseNetstring(split[3])
var header map[string]string
if err = json.Unmarshal(headerJson, &header); err != nil {
panic(err.Error())
}
body, _ := parseNetstring(split[3][n:])
req, err := makeRequest(header)
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
resp := response{buf: bytes.NewBuffer(nil), header: http.Header{}}
handler.ServeHTTP(&resp, req)
_, err = fmt.Fprintf(pub, "%s %s, %s", uuid, netstring(id), resp.buf.Bytes())
if err != nil {
panic(err.Error())
}
}
panic("unreachable")
}
var skipHeader = map[string]bool{
"PATH": true,
"METHOD": true,
"VERSION": true,
"URI": true,
"PATTERN": true,
"Host": true,
"Referer": true,
"User-Agent": true,
"Content-Length": true,
}
func makeRequest(params map[string]string) (*http.Request, error) {
r := new(http.Request)
r.Method = params["METHOD"]
if r.Method == "" {
return nil, errors.New("mongrel2: no METHOD")
}
r.Proto = params["VERSION"]
var ok bool
r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
if !ok {
return nil, errors.New("mongrel2: invalid protocol version")
}
r.Trailer = http.Header{}
r.Header = http.Header{}
r.Host = params["Host"]
r.Header.Set("Referer", params["Referer"])
r.Header.Set("User-Agent", params["User-Agent"])
if lenstr := params["Content-Length"]; lenstr != "" {
clen, err := strconv.ParseInt(lenstr, 10, 64)
if err != nil {
return nil, errors.New("mongrel2: bad Content-Length")
}
r.ContentLength = clen
}
for k, v := range params {
if !skipHeader[k] {
r.Header.Add(k, v)
}
}
// TODO: cookies
if r.Host != "" {
url_, err := url.Parse("http://" + r.Host + params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse host and URI into a URL")
}
r.URL = url_
}
if r.URL == nil {
url_, err := url.Parse(params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse URI into a URL")
}
r.URL = url_
}
// TODO: how do we know if we're using HTTPS?
// TODO: fill in r.RemoteAddr
return r, nil
}
type response struct {
buf *bytes.Buffer
wroteHeader bool
header http.Header
}
// get header
func (r response) Header() http.Header {
return r.header
}
// write headers and body
func (r response) Write(b []byte) (int, error) {
r.header.Set("Content-Length", strconv.Itoa(len(b)))
r.WriteHeader(http.StatusOK) // does nothing if headers have been set before
r.header.Write(r.buf) // write headers
r.buf.WriteString("\r\n") // delimiter between headers and body
return r.buf.Write(b) // write body
}
// set headers, except content-length. does not write the headers.
func (r *response) WriteHeader(status int) {
if r.wroteHeader {
return
}
r.wroteHeader = true
if r.header.Get("Content-Type") == "" {
r.header.Set("Content-Type", "text/html; charset=utf-8")
}
if r.header.Get("Date") == "" {
r.header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
fmt.Fprintf(r.buf, "HTTP/1.1 %d %s\r\n", status, http.StatusText(status))
}
func parseNetstring(nstr []byte) ([]byte, int) {
i := bytes.IndexByte(nstr, ':')
if i < 0 {
panic("not a netstring?")
}
n, err := strconv.Atoi(string(nstr[:i]))
if err != nil {
panic("invalid number before colon")
}
if n > len(nstr[i+1:]) {
panic("netstring length too long")
}
count := i + 1 + n
if nstr[count] != ',' {
panic("netstring doesn't end with a comma")
}
return nstr[i+1 : count], count + 1
}
func netstring(str []byte) []byte {
l := strconv.Itoa(len(str))
b := make([]byte, len(l)+1+len(str))
i := copy(b, l)
b[i] = ':'
copy(b[i+1:], str)
return b
}