github.com/ck00004/CobaltStrikeParser-Go@v1.0.14/lib/http/fcgi/child.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fcgi
     6  
     7  // This file implements FastCGI from the perspective of a child process.
     8  
     9  import (
    10  	"context"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"net"
    15  	"os"
    16  	"strings"
    17  	"time"
    18  
    19  	"github.com/ck00004/CobaltStrikeParser-Go/lib/http/cgi"
    20  
    21  	"github.com/ck00004/CobaltStrikeParser-Go/lib/http"
    22  )
    23  
    24  // request holds the state for an in-progress request. As soon as it's complete,
    25  // it's converted to an http.Request.
    26  type request struct {
    27  	pw        *io.PipeWriter
    28  	reqId     uint16
    29  	params    map[string]string
    30  	buf       [1024]byte
    31  	rawParams []byte
    32  	keepConn  bool
    33  }
    34  
    35  // envVarsContextKey uniquely identifies a mapping of CGI
    36  // environment variables to their values in a request context
    37  type envVarsContextKey struct{}
    38  
    39  func newRequest(reqId uint16, flags uint8) *request {
    40  	r := &request{
    41  		reqId:    reqId,
    42  		params:   map[string]string{},
    43  		keepConn: flags&flagKeepConn != 0,
    44  	}
    45  	r.rawParams = r.buf[:0]
    46  	return r
    47  }
    48  
    49  // parseParams reads an encoded []byte into Params.
    50  func (r *request) parseParams() {
    51  	text := r.rawParams
    52  	r.rawParams = nil
    53  	for len(text) > 0 {
    54  		keyLen, n := readSize(text)
    55  		if n == 0 {
    56  			return
    57  		}
    58  		text = text[n:]
    59  		valLen, n := readSize(text)
    60  		if n == 0 {
    61  			return
    62  		}
    63  		text = text[n:]
    64  		if int(keyLen)+int(valLen) > len(text) {
    65  			return
    66  		}
    67  		key := readString(text, keyLen)
    68  		text = text[keyLen:]
    69  		val := readString(text, valLen)
    70  		text = text[valLen:]
    71  		r.params[key] = val
    72  	}
    73  }
    74  
    75  // response implements http.ResponseWriter.
    76  type response struct {
    77  	req            *request
    78  	header         http.Header
    79  	code           int
    80  	wroteHeader    bool
    81  	wroteCGIHeader bool
    82  	w              *bufWriter
    83  }
    84  
    85  func newResponse(c *child, req *request) *response {
    86  	return &response{
    87  		req:    req,
    88  		header: http.Header{},
    89  		w:      newWriter(c.conn, typeStdout, req.reqId),
    90  	}
    91  }
    92  
    93  func (r *response) Header() http.Header {
    94  	return r.header
    95  }
    96  
    97  func (r *response) Write(p []byte) (n int, err error) {
    98  	if !r.wroteHeader {
    99  		r.WriteHeader(http.StatusOK)
   100  	}
   101  	if !r.wroteCGIHeader {
   102  		r.writeCGIHeader(p)
   103  	}
   104  	return r.w.Write(p)
   105  }
   106  
   107  func (r *response) WriteHeader(code int) {
   108  	if r.wroteHeader {
   109  		return
   110  	}
   111  	r.wroteHeader = true
   112  	r.code = code
   113  	if code == http.StatusNotModified {
   114  		// Must not have body.
   115  		r.header.Del("Content-Type")
   116  		r.header.Del("Content-Length")
   117  		r.header.Del("Transfer-Encoding")
   118  	}
   119  	if r.header.Get("Date") == "" {
   120  		r.header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
   121  	}
   122  }
   123  
   124  // writeCGIHeader finalizes the header sent to the client and writes it to the output.
   125  // p is not written by writeHeader, but is the first chunk of the body
   126  // that will be written. It is sniffed for a Content-Type if none is
   127  // set explicitly.
   128  func (r *response) writeCGIHeader(p []byte) {
   129  	if r.wroteCGIHeader {
   130  		return
   131  	}
   132  	r.wroteCGIHeader = true
   133  	fmt.Fprintf(r.w, "Status: %d %s\r\n", r.code, http.StatusText(r.code))
   134  	if _, hasType := r.header["Content-Type"]; r.code != http.StatusNotModified && !hasType {
   135  		r.header.Set("Content-Type", http.DetectContentType(p))
   136  	}
   137  	r.header.Write(r.w)
   138  	r.w.WriteString("\r\n")
   139  	r.w.Flush()
   140  }
   141  
   142  func (r *response) Flush() {
   143  	if !r.wroteHeader {
   144  		r.WriteHeader(http.StatusOK)
   145  	}
   146  	r.w.Flush()
   147  }
   148  
   149  func (r *response) Close() error {
   150  	r.Flush()
   151  	return r.w.Close()
   152  }
   153  
   154  type child struct {
   155  	conn    *conn
   156  	handler http.Handler
   157  
   158  	requests map[uint16]*request // keyed by request ID
   159  }
   160  
   161  func newChild(rwc io.ReadWriteCloser, handler http.Handler) *child {
   162  	return &child{
   163  		conn:     newConn(rwc),
   164  		handler:  handler,
   165  		requests: make(map[uint16]*request),
   166  	}
   167  }
   168  
   169  func (c *child) serve() {
   170  	defer c.conn.Close()
   171  	defer c.cleanUp()
   172  	var rec record
   173  	for {
   174  		if err := rec.read(c.conn.rwc); err != nil {
   175  			return
   176  		}
   177  		if err := c.handleRecord(&rec); err != nil {
   178  			return
   179  		}
   180  	}
   181  }
   182  
   183  var errCloseConn = errors.New("fcgi: connection should be closed")
   184  
   185  var emptyBody = io.NopCloser(strings.NewReader(""))
   186  
   187  // ErrRequestAborted is returned by Read when a handler attempts to read the
   188  // body of a request that has been aborted by the web server.
   189  var ErrRequestAborted = errors.New("fcgi: request aborted by web server")
   190  
   191  // ErrConnClosed is returned by Read when a handler attempts to read the body of
   192  // a request after the connection to the web server has been closed.
   193  var ErrConnClosed = errors.New("fcgi: connection to web server closed")
   194  
   195  func (c *child) handleRecord(rec *record) error {
   196  	req, ok := c.requests[rec.h.Id]
   197  	if !ok && rec.h.Type != typeBeginRequest && rec.h.Type != typeGetValues {
   198  		// The spec says to ignore unknown request IDs.
   199  		return nil
   200  	}
   201  
   202  	switch rec.h.Type {
   203  	case typeBeginRequest:
   204  		if req != nil {
   205  			// The server is trying to begin a request with the same ID
   206  			// as an in-progress request. This is an error.
   207  			return errors.New("fcgi: received ID that is already in-flight")
   208  		}
   209  
   210  		var br beginRequest
   211  		if err := br.read(rec.content()); err != nil {
   212  			return err
   213  		}
   214  		if br.role != roleResponder {
   215  			c.conn.writeEndRequest(rec.h.Id, 0, statusUnknownRole)
   216  			return nil
   217  		}
   218  		req = newRequest(rec.h.Id, br.flags)
   219  		c.requests[rec.h.Id] = req
   220  		return nil
   221  	case typeParams:
   222  		// NOTE(eds): Technically a key-value pair can straddle the boundary
   223  		// between two packets. We buffer until we've received all parameters.
   224  		if len(rec.content()) > 0 {
   225  			req.rawParams = append(req.rawParams, rec.content()...)
   226  			return nil
   227  		}
   228  		req.parseParams()
   229  		return nil
   230  	case typeStdin:
   231  		content := rec.content()
   232  		if req.pw == nil {
   233  			var body io.ReadCloser
   234  			if len(content) > 0 {
   235  				// body could be an io.LimitReader, but it shouldn't matter
   236  				// as long as both sides are behaving.
   237  				body, req.pw = io.Pipe()
   238  			} else {
   239  				body = emptyBody
   240  			}
   241  			go c.serveRequest(req, body)
   242  		}
   243  		if len(content) > 0 {
   244  			// TODO(eds): This blocks until the handler reads from the pipe.
   245  			// If the handler takes a long time, it might be a problem.
   246  			req.pw.Write(content)
   247  		} else {
   248  			delete(c.requests, req.reqId)
   249  			if req.pw != nil {
   250  				req.pw.Close()
   251  			}
   252  		}
   253  		return nil
   254  	case typeGetValues:
   255  		values := map[string]string{"FCGI_MPXS_CONNS": "1"}
   256  		c.conn.writePairs(typeGetValuesResult, 0, values)
   257  		return nil
   258  	case typeData:
   259  		// If the filter role is implemented, read the data stream here.
   260  		return nil
   261  	case typeAbortRequest:
   262  		delete(c.requests, rec.h.Id)
   263  		c.conn.writeEndRequest(rec.h.Id, 0, statusRequestComplete)
   264  		if req.pw != nil {
   265  			req.pw.CloseWithError(ErrRequestAborted)
   266  		}
   267  		if !req.keepConn {
   268  			// connection will close upon return
   269  			return errCloseConn
   270  		}
   271  		return nil
   272  	default:
   273  		b := make([]byte, 8)
   274  		b[0] = byte(rec.h.Type)
   275  		c.conn.writeRecord(typeUnknownType, 0, b)
   276  		return nil
   277  	}
   278  }
   279  
   280  // filterOutUsedEnvVars returns a new map of env vars without the
   281  // variables in the given envVars map that are read for creating each http.Request
   282  func filterOutUsedEnvVars(envVars map[string]string) map[string]string {
   283  	withoutUsedEnvVars := make(map[string]string)
   284  	for k, v := range envVars {
   285  		if addFastCGIEnvToContext(k) {
   286  			withoutUsedEnvVars[k] = v
   287  		}
   288  	}
   289  	return withoutUsedEnvVars
   290  }
   291  
   292  func (c *child) serveRequest(req *request, body io.ReadCloser) {
   293  	r := newResponse(c, req)
   294  	httpReq, err := cgi.RequestFromMap(req.params)
   295  	if err != nil {
   296  		// there was an error reading the request
   297  		r.WriteHeader(http.StatusInternalServerError)
   298  		c.conn.writeRecord(typeStderr, req.reqId, []byte(err.Error()))
   299  	} else {
   300  		httpReq.Body = body
   301  		withoutUsedEnvVars := filterOutUsedEnvVars(req.params)
   302  		envVarCtx := context.WithValue(httpReq.Context(), envVarsContextKey{}, withoutUsedEnvVars)
   303  		httpReq = httpReq.WithContext(envVarCtx)
   304  		c.handler.ServeHTTP(r, httpReq)
   305  	}
   306  	// Make sure we serve something even if nothing was written to r
   307  	r.Write(nil)
   308  	r.Close()
   309  	c.conn.writeEndRequest(req.reqId, 0, statusRequestComplete)
   310  
   311  	// Consume the entire body, so the host isn't still writing to
   312  	// us when we close the socket below in the !keepConn case,
   313  	// otherwise we'd send a RST. (golang.org/issue/4183)
   314  	// TODO(bradfitz): also bound this copy in time. Or send
   315  	// some sort of abort request to the host, so the host
   316  	// can properly cut off the client sending all the data.
   317  	// For now just bound it a little and
   318  	io.CopyN(io.Discard, body, 100<<20)
   319  	body.Close()
   320  
   321  	if !req.keepConn {
   322  		c.conn.Close()
   323  	}
   324  }
   325  
   326  func (c *child) cleanUp() {
   327  	for _, req := range c.requests {
   328  		if req.pw != nil {
   329  			// race with call to Close in c.serveRequest doesn't matter because
   330  			// Pipe(Reader|Writer).Close are idempotent
   331  			req.pw.CloseWithError(ErrConnClosed)
   332  		}
   333  	}
   334  }
   335  
   336  // Serve accepts incoming FastCGI connections on the listener l, creating a new
   337  // goroutine for each. The goroutine reads requests and then calls handler
   338  // to reply to them.
   339  // If l is nil, Serve accepts connections from os.Stdin.
   340  // If handler is nil, http.DefaultServeMux is used.
   341  func Serve(l net.Listener, handler http.Handler) error {
   342  	if l == nil {
   343  		var err error
   344  		l, err = net.FileListener(os.Stdin)
   345  		if err != nil {
   346  			return err
   347  		}
   348  		defer l.Close()
   349  	}
   350  	if handler == nil {
   351  		handler = http.DefaultServeMux
   352  	}
   353  	for {
   354  		rw, err := l.Accept()
   355  		if err != nil {
   356  			return err
   357  		}
   358  		c := newChild(rw, handler)
   359  		go c.serve()
   360  	}
   361  }
   362  
   363  // ProcessEnv returns FastCGI environment variables associated with the request r
   364  // for which no effort was made to be included in the request itself - the data
   365  // is hidden in the request's context. As an example, if REMOTE_USER is set for a
   366  // request, it will not be found anywhere in r, but it will be included in
   367  // ProcessEnv's response (via r's context).
   368  func ProcessEnv(r *http.Request) map[string]string {
   369  	env, _ := r.Context().Value(envVarsContextKey{}).(map[string]string)
   370  	return env
   371  }
   372  
   373  // addFastCGIEnvToContext reports whether to include the FastCGI environment variable s
   374  // in the http.Request.Context, accessible via ProcessEnv.
   375  func addFastCGIEnvToContext(s string) bool {
   376  	// Exclude things supported by net/http natively:
   377  	switch s {
   378  	case "CONTENT_LENGTH", "CONTENT_TYPE", "HTTPS",
   379  		"PATH_INFO", "QUERY_STRING", "REMOTE_ADDR",
   380  		"REMOTE_HOST", "REMOTE_PORT", "REQUEST_METHOD",
   381  		"REQUEST_URI", "SCRIPT_NAME", "SERVER_PROTOCOL":
   382  		return false
   383  	}
   384  	if strings.HasPrefix(s, "HTTP_") {
   385  		return false
   386  	}
   387  	// Explicitly include FastCGI-specific things.
   388  	// This list is redundant with the default "return true" below.
   389  	// Consider this documentation of the sorts of things we expect
   390  	// to maybe see.
   391  	switch s {
   392  	case "REMOTE_USER":
   393  		return true
   394  	}
   395  	// Unknown, so include it to be safe.
   396  	return true
   397  }