1
0
mirror of https://github.com/golang/go synced 2024-11-20 04:34:41 -07:00

fcgi: fix server capability discovery

The wrong length was being sent, and two parameters
were also transposed. Made the record type be a type
and made the constants typed, to prevent that sort
of bug in the future.

Fixes #2469

R=golang-dev, edsrzf
CC=golang-dev
https://golang.org/cl/5394046
This commit is contained in:
Brad Fitzpatrick 2011-11-16 10:11:39 -08:00
parent f5db4d05f2
commit 881f2076fb
3 changed files with 146 additions and 93 deletions

View File

@ -7,6 +7,7 @@ package fcgi
// This file implements FastCGI from the perspective of a child process. // This file implements FastCGI from the perspective of a child process.
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net" "net"
@ -125,49 +126,61 @@ func (r *response) Close() error {
type child struct { type child struct {
conn *conn conn *conn
handler http.Handler handler http.Handler
requests map[uint16]*request // keyed by request ID
} }
func newChild(rwc net.Conn, handler http.Handler) *child { func newChild(rwc io.ReadWriteCloser, handler http.Handler) *child {
return &child{newConn(rwc), handler} return &child{
conn: newConn(rwc),
handler: handler,
requests: make(map[uint16]*request),
}
} }
func (c *child) serve() { func (c *child) serve() {
requests := map[uint16]*request{}
defer c.conn.Close() defer c.conn.Close()
var rec record var rec record
var br beginRequest
for { for {
if err := rec.read(c.conn.rwc); err != nil { if err := rec.read(c.conn.rwc); err != nil {
return return
} }
if err := c.handleRecord(&rec); err != nil {
return
}
}
}
req, ok := requests[rec.h.Id] var errCloseConn = errors.New("fcgi: connection should be closed")
func (c *child) handleRecord(rec *record) error {
req, ok := c.requests[rec.h.Id]
if !ok && rec.h.Type != typeBeginRequest && rec.h.Type != typeGetValues { if !ok && rec.h.Type != typeBeginRequest && rec.h.Type != typeGetValues {
// The spec says to ignore unknown request IDs. // The spec says to ignore unknown request IDs.
continue return nil
} }
if ok && rec.h.Type == typeBeginRequest { if ok && rec.h.Type == typeBeginRequest {
// The server is trying to begin a request with the same ID // The server is trying to begin a request with the same ID
// as an in-progress request. This is an error. // as an in-progress request. This is an error.
return return errors.New("fcgi: received ID that is already in-flight")
} }
switch rec.h.Type { switch rec.h.Type {
case typeBeginRequest: case typeBeginRequest:
var br beginRequest
if err := br.read(rec.content()); err != nil { if err := br.read(rec.content()); err != nil {
return return err
} }
if br.role != roleResponder { if br.role != roleResponder {
c.conn.writeEndRequest(rec.h.Id, 0, statusUnknownRole) c.conn.writeEndRequest(rec.h.Id, 0, statusUnknownRole)
break return nil
} }
requests[rec.h.Id] = newRequest(rec.h.Id, br.flags) c.requests[rec.h.Id] = newRequest(rec.h.Id, br.flags)
case typeParams: case typeParams:
// NOTE(eds): Technically a key-value pair can straddle the boundary // NOTE(eds): Technically a key-value pair can straddle the boundary
// between two packets. We buffer until we've received all parameters. // between two packets. We buffer until we've received all parameters.
if len(rec.content()) > 0 { if len(rec.content()) > 0 {
req.rawParams = append(req.rawParams, rec.content()...) req.rawParams = append(req.rawParams, rec.content()...)
break return nil
} }
req.parseParams() req.parseParams()
case typeStdin: case typeStdin:
@ -190,22 +203,22 @@ func (c *child) serve() {
} }
case typeGetValues: case typeGetValues:
values := map[string]string{"FCGI_MPXS_CONNS": "1"} values := map[string]string{"FCGI_MPXS_CONNS": "1"}
c.conn.writePairs(0, typeGetValuesResult, values) c.conn.writePairs(typeGetValuesResult, 0, values)
case typeData: case typeData:
// If the filter role is implemented, read the data stream here. // If the filter role is implemented, read the data stream here.
case typeAbortRequest: case typeAbortRequest:
delete(requests, rec.h.Id) delete(c.requests, rec.h.Id)
c.conn.writeEndRequest(rec.h.Id, 0, statusRequestComplete) c.conn.writeEndRequest(rec.h.Id, 0, statusRequestComplete)
if !req.keepConn { if !req.keepConn {
// connection will close upon return // connection will close upon return
return return errCloseConn
} }
default: default:
b := make([]byte, 8) b := make([]byte, 8)
b[0] = rec.h.Type b[0] = byte(rec.h.Type)
c.conn.writeRecord(typeUnknownType, 0, b) c.conn.writeRecord(typeUnknownType, 0, b)
} }
} return nil
} }
func (c *child) serveRequest(req *request, body io.ReadCloser) { func (c *child) serveRequest(req *request, body io.ReadCloser) {

View File

@ -19,19 +19,22 @@ import (
"sync" "sync"
) )
// recType is a record type, as defined by
// http://www.fastcgi.com/devkit/doc/fcgi-spec.html#S8
type recType uint8
const ( const (
// Packet Types typeBeginRequest recType = 1
typeBeginRequest = iota + 1 typeAbortRequest recType = 2
typeAbortRequest typeEndRequest recType = 3
typeEndRequest typeParams recType = 4
typeParams typeStdin recType = 5
typeStdin typeStdout recType = 6
typeStdout typeStderr recType = 7
typeStderr typeData recType = 8
typeData typeGetValues recType = 9
typeGetValues typeGetValuesResult recType = 10
typeGetValuesResult typeUnknownType recType = 11
typeUnknownType
) )
// keep the connection between web-server and responder open after request // keep the connection between web-server and responder open after request
@ -59,7 +62,7 @@ const headerLen = 8
type header struct { type header struct {
Version uint8 Version uint8
Type uint8 Type recType
Id uint16 Id uint16
ContentLength uint16 ContentLength uint16
PaddingLength uint8 PaddingLength uint8
@ -85,7 +88,7 @@ func (br *beginRequest) read(content []byte) error {
// not synchronized because we don't care what the contents are // not synchronized because we don't care what the contents are
var pad [maxPad]byte var pad [maxPad]byte
func (h *header) init(recType uint8, reqId uint16, contentLength int) { func (h *header) init(recType recType, reqId uint16, contentLength int) {
h.Version = 1 h.Version = 1
h.Type = recType h.Type = recType
h.Id = reqId h.Id = reqId
@ -137,7 +140,7 @@ func (r *record) content() []byte {
} }
// writeRecord writes and sends a single record. // writeRecord writes and sends a single record.
func (c *conn) writeRecord(recType uint8, reqId uint16, b []byte) error { func (c *conn) writeRecord(recType recType, reqId uint16, b []byte) error {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() defer c.mutex.Unlock()
c.buf.Reset() c.buf.Reset()
@ -167,12 +170,12 @@ func (c *conn) writeEndRequest(reqId uint16, appStatus int, protocolStatus uint8
return c.writeRecord(typeEndRequest, reqId, b) return c.writeRecord(typeEndRequest, reqId, b)
} }
func (c *conn) writePairs(recType uint8, reqId uint16, pairs map[string]string) error { func (c *conn) writePairs(recType recType, reqId uint16, pairs map[string]string) error {
w := newWriter(c, recType, reqId) w := newWriter(c, recType, reqId)
b := make([]byte, 8) b := make([]byte, 8)
for k, v := range pairs { for k, v := range pairs {
n := encodeSize(b, uint32(len(k))) n := encodeSize(b, uint32(len(k)))
n += encodeSize(b[n:], uint32(len(k))) n += encodeSize(b[n:], uint32(len(v)))
if _, err := w.Write(b[:n]); err != nil { if _, err := w.Write(b[:n]); err != nil {
return err return err
} }
@ -235,7 +238,7 @@ func (w *bufWriter) Close() error {
return w.closer.Close() return w.closer.Close()
} }
func newWriter(c *conn, recType uint8, reqId uint16) *bufWriter { func newWriter(c *conn, recType recType, reqId uint16) *bufWriter {
s := &streamWriter{c: c, recType: recType, reqId: reqId} s := &streamWriter{c: c, recType: recType, reqId: reqId}
w, _ := bufio.NewWriterSize(s, maxWrite) w, _ := bufio.NewWriterSize(s, maxWrite)
return &bufWriter{s, w} return &bufWriter{s, w}
@ -245,7 +248,7 @@ func newWriter(c *conn, recType uint8, reqId uint16) *bufWriter {
// It only writes maxWrite bytes at a time. // It only writes maxWrite bytes at a time.
type streamWriter struct { type streamWriter struct {
c *conn c *conn
recType uint8 recType recType
reqId uint16 reqId uint16
} }

View File

@ -6,6 +6,7 @@ package fcgi
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"testing" "testing"
) )
@ -40,25 +41,25 @@ func TestSize(t *testing.T) {
var streamTests = []struct { var streamTests = []struct {
desc string desc string
recType uint8 recType recType
reqId uint16 reqId uint16
content []byte content []byte
raw []byte raw []byte
}{ }{
{"single record", typeStdout, 1, nil, {"single record", typeStdout, 1, nil,
[]byte{1, typeStdout, 0, 1, 0, 0, 0, 0}, []byte{1, byte(typeStdout), 0, 1, 0, 0, 0, 0},
}, },
// this data will have to be split into two records // this data will have to be split into two records
{"two records", typeStdin, 300, make([]byte, 66000), {"two records", typeStdin, 300, make([]byte, 66000),
bytes.Join([][]byte{ bytes.Join([][]byte{
// header for the first record // header for the first record
{1, typeStdin, 0x01, 0x2C, 0xFF, 0xFF, 1, 0}, {1, byte(typeStdin), 0x01, 0x2C, 0xFF, 0xFF, 1, 0},
make([]byte, 65536), make([]byte, 65536),
// header for the second // header for the second
{1, typeStdin, 0x01, 0x2C, 0x01, 0xD1, 7, 0}, {1, byte(typeStdin), 0x01, 0x2C, 0x01, 0xD1, 7, 0},
make([]byte, 472), make([]byte, 472),
// header for the empty record // header for the empty record
{1, typeStdin, 0x01, 0x2C, 0, 0, 0, 0}, {1, byte(typeStdin), 0x01, 0x2C, 0, 0, 0, 0},
}, },
nil), nil),
}, },
@ -111,3 +112,39 @@ outer:
} }
} }
} }
type writeOnlyConn struct {
buf []byte
}
func (c *writeOnlyConn) Write(p []byte) (int, error) {
c.buf = append(c.buf, p...)
return len(p), nil
}
func (c *writeOnlyConn) Read(p []byte) (int, error) {
return 0, errors.New("conn is write-only")
}
func (c *writeOnlyConn) Close() error {
return nil
}
func TestGetValues(t *testing.T) {
var rec record
rec.h.Type = typeGetValues
wc := new(writeOnlyConn)
c := newChild(wc, nil)
err := c.handleRecord(&rec)
if err != nil {
t.Fatalf("handleRecord: %v", err)
}
const want = "\x01\n\x00\x00\x00\x12\x06\x00" +
"\x0f\x01FCGI_MPXS_CONNS1" +
"\x00\x00\x00\x00\x00\x00\x01\n\x00\x00\x00\x00\x00\x00"
if got := string(wc.buf); got != want {
t.Errorf(" got: %q\nwant: %q\n", got, want)
}
}