-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgofcgisrv.go
334 lines (303 loc) · 7.7 KB
/
gofcgisrv.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
/*
Package gofcgisrv implements the webserver side of the CGI, FastCGI, and SCGI protocols.
CGI: http://tools.ietf.org/html/rfc3875
FastCGI: http://www.fastcgi.com/drupal/node/6?q=node/22
SCGI: http://python.ca/scgi/protocol.txt protocols.
*/
package gofcgisrv
import (
"bytes"
"io"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
var logger *log.Logger = log.New(os.Stderr, "", 0)
// Requester is the interface for any CGI-like protocol server.
type Requester interface {
Request(env []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error
}
// Wrapper for functions
type RequesterFunc func(env []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error
func (f RequesterFunc) Request(env []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
return f(env, stdin, stdout, stderr)
}
// Server is the external interface. It manages connections to a single FastCGI application.
// A server may maintain many connections, each of which may multiplex many requests.
type FCGIRequester struct {
dialer Dialer
connections []*conn
reqLock sync.Mutex
reqCond *sync.Cond
initialized bool
// Parameters of the application
CanMultiplex bool
MaxConns int
MaxRequests int
}
// NewServer creates a server that will attempt to connect to the application at the given address over TCP.
func NewFCGI(applicationAddr string) *FCGIRequester {
s := &FCGIRequester{}
s.dialer = TCPDialer{addr: applicationAddr}
s.MaxConns = 1
s.MaxRequests = 1
s.reqCond = sync.NewCond(&s.reqLock)
return s
}
// NewFCGIStdin creates a server that runs the app and connects over stdin.
func NewFCGIStdin(app string, args ...string) *FCGIRequester {
s := &FCGIRequester{}
s.dialer = &StdinDialer{app: app, args: args}
s.MaxConns = 1
s.MaxRequests = 1
s.reqCond = sync.NewCond(&s.reqLock)
return s
}
func (s *FCGIRequester) processGetValuesResult(rec record) (int, error) {
nproc := 0
switch rec.Type {
case fcgiGetValuesResult:
reader := bytes.NewReader(rec.Content)
for {
name, value, err := readNameValue(reader)
if err != nil {
return nproc, err
}
val, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return nproc, err
}
nproc++
switch name {
case fcgiMaxConns:
s.MaxConns = int(val)
case fcgiMaxReqs:
s.MaxRequests = int(val)
case fcgiMpxsConns:
s.CanMultiplex = (val != 0)
}
}
}
return nproc, nil
}
// PHP barfs on FCGI_GET_VALUES. I don't know why. Maybe it expects a different connection.
// For now don't do it unless asked.
func (s *FCGIRequester) GetValues() error {
c, err := s.dialer.Dial()
time.AfterFunc(time.Second, func() { c.Close() })
if err != nil {
return err
}
// time.AfterFunc(time.Second, func() { c.Close()})
writeGetValues(c, fcgiMpxsConns, fcgiMaxReqs, fcgiMaxConns)
n := 0
for n < 3 {
rec, err := readRecord(c)
if err != nil {
return nil
}
np, _ := s.processGetValuesResult(rec)
n += np
}
c.Close()
return nil
}
// Request executes a request using env and stdin as inputs and stdout and stderr as outputs.
// env should be a slice of name=value pairs. It blocks until the application has finished.
func (s *FCGIRequester) Request(env []string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
// Get a request. We may have to wait for one to free up.
r, err := s.newRequest()
if err != nil {
return err
}
// Send BeginRequest.
writeBeginRequest(r.conn.netconn, r.id, fcgiResponder, 0)
// Send the environment.
params := newStreamWriter(r.conn.netconn, fcgiParams, r.id)
for _, envstring := range env {
splits := strings.SplitN(envstring, "=", 2)
if len(splits) == 2 {
writeNameValue(params, splits[0], splits[1])
}
}
params.Close()
r.Stdout = stdout
r.Stderr = stderr
// Send stdin.
reqStdin := newStreamWriter(r.conn.netconn, fcgiStdin, r.id)
io.Copy(reqStdin, stdin)
reqStdin.Close()
// Wait for end request.
<-r.done
return nil
}
// ServeHTTP serves an HTTP request.
func (s *FCGIRequester) ServeHTTP(w http.ResponseWriter, r *http.Request) {
env := HTTPEnv(nil, r)
buffer := bytes.NewBuffer(nil)
s.Request(env, r.Body, buffer, os.Stderr)
// Add any headers produced by the application, and skip to the response.
ProcessResponse(buffer, w, r)
}
// Should only be called if reqLock is held.
func (s *FCGIRequester) numRequests() int {
var n = 0
for _, c := range s.connections {
n += c.numRequests()
}
return n
}
func (s *FCGIRequester) newRequest() (*request, error) {
// We may have to wait for one to become available
s.reqLock.Lock()
defer s.reqLock.Unlock()
for s.numRequests() >= s.MaxRequests {
s.reqCond.Wait()
}
// We will always need to create a new connection, for now.
netconn, err := s.dialer.Dial()
if err != nil {
return nil, err
}
conn := newConn(s, netconn)
go conn.Run()
return conn.newRequest(), nil
}
func (s *FCGIRequester) releaseRequest(r *request) {
s.reqLock.Lock()
defer s.reqLock.Unlock()
r.conn.removeRequest(r)
// For now, we're telling apps to close connections, so we're done with it.
// But we're not trusting apps to do it, because not all of them do, the bastards.
r.conn.netconn.Close()
for i, c := range s.connections {
if c == r.conn {
s.connections = append(s.connections[:i], s.connections[i+1:]...)
break
}
}
if r.done != nil {
close(r.done)
}
s.reqCond.Signal()
}
// Conn wraps a net.Conn. It may multiplex many requests.
type conn struct {
server *FCGIRequester
netconn net.Conn
requests []*request
numReq int
reqLock sync.RWMutex
}
func newConn(s *FCGIRequester, netconn net.Conn) *conn {
return &conn{server: s, netconn: netconn}
}
func (c *conn) newRequest() *request {
// For now, there shouldn't be anything there.
// But pretend.
c.reqLock.Lock()
defer c.reqLock.Unlock()
r := &request{conn: c}
r.done = make(chan bool)
c.numReq++
for i, r := range c.requests {
if r == nil {
r.id = requestId(i + 1)
c.requests[i] = r
return r
}
}
r.id = requestId(len(c.requests) + 1)
c.requests = append(c.requests, r)
return r
}
func (c *conn) removeRequest(r *request) {
c.reqLock.Lock()
defer c.reqLock.Unlock()
idx := int(r.id) - 1
if c.requests[idx] == r {
c.requests[idx] = nil
c.numReq--
}
}
func (c *conn) releaseAllRequests() {
c.reqLock.Lock()
var reqs []*request
reqs = append(reqs, c.requests...)
c.reqLock.Unlock()
for _, r := range reqs {
if r != nil {
c.server.releaseRequest(r)
}
}
}
func (c *conn) numRequests() int {
c.reqLock.Lock()
defer c.reqLock.Unlock()
return c.numReq
}
func (c *conn) findRequest(id requestId) *request {
c.reqLock.Lock()
defer c.reqLock.Unlock()
idx := int(id) - 1
if int(idx) >= len(c.requests) {
return nil
}
return c.requests[idx]
}
func (c *conn) Run() error {
// Sit in a loop reading records.
for {
rec, err := readRecord(c.netconn)
if err != nil {
// We're done?
c.releaseAllRequests()
return err
}
// If it's a management record
if rec.Id == 0 {
switch rec.Type {
case fcgiGetValuesResult:
c.server.processGetValuesResult(rec)
}
} else {
// Get the request.
req := c.findRequest(rec.Id)
// If there isn't one, ignore it.
if req == nil {
continue
}
switch rec.Type {
case fcgiEndRequest:
// We're done!
c.server.releaseRequest(req)
case fcgiStdout:
// Write the data to the stdout stream
if len(rec.Content) > 0 {
if _, err := req.Stdout.Write(rec.Content); err != nil {
}
}
case fcgiStderr:
// Write the data to the stderr stream
if len(rec.Content) > 0 {
if _, err := req.Stderr.Write(rec.Content); err != nil {
}
}
}
}
}
return nil
}
// Request is a single request.
type request struct {
id requestId
conn *conn
done chan bool
Stdout io.Writer
Stderr io.Writer
}