Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/http/cgi/integration_test.go

Documentation: net/http/cgi

     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  // Tests a Go CGI program running under a Go CGI host process.
     6  // Further, the two programs are the same binary, just checking
     7  // their environment to figure out what mode to run in.
     8  
     9  package cgi
    10  
    11  import (
    12  	"bytes"
    13  	"errors"
    14  	"fmt"
    15  	"internal/testenv"
    16  	"io"
    17  	"net/http"
    18  	"net/http/httptest"
    19  	"net/url"
    20  	"os"
    21  	"strings"
    22  	"testing"
    23  	"time"
    24  )
    25  
    26  // This test is a CGI host (testing host.go) that runs its own binary
    27  // as a child process testing the other half of CGI (child.go).
    28  func TestHostingOurselves(t *testing.T) {
    29  	testenv.MustHaveExec(t)
    30  
    31  	h := &Handler{
    32  		Path: os.Args[0],
    33  		Root: "/test.go",
    34  		Args: []string{"-test.run=TestBeChildCGIProcess"},
    35  	}
    36  	expectedMap := map[string]string{
    37  		"test":                  "Hello CGI-in-CGI",
    38  		"param-a":               "b",
    39  		"param-foo":             "bar",
    40  		"env-GATEWAY_INTERFACE": "CGI/1.1",
    41  		"env-HTTP_HOST":         "example.com",
    42  		"env-PATH_INFO":         "",
    43  		"env-QUERY_STRING":      "foo=bar&a=b",
    44  		"env-REMOTE_ADDR":       "1.2.3.4",
    45  		"env-REMOTE_HOST":       "1.2.3.4",
    46  		"env-REMOTE_PORT":       "1234",
    47  		"env-REQUEST_METHOD":    "GET",
    48  		"env-REQUEST_URI":       "/test.go?foo=bar&a=b",
    49  		"env-SCRIPT_FILENAME":   os.Args[0],
    50  		"env-SCRIPT_NAME":       "/test.go",
    51  		"env-SERVER_NAME":       "example.com",
    52  		"env-SERVER_PORT":       "80",
    53  		"env-SERVER_SOFTWARE":   "go",
    54  	}
    55  	replay := runCgiTest(t, h, "GET /test.go?foo=bar&a=b HTTP/1.0\nHost: example.com\n\n", expectedMap)
    56  
    57  	if expected, got := "text/plain; charset=utf-8", replay.Header().Get("Content-Type"); got != expected {
    58  		t.Errorf("got a Content-Type of %q; expected %q", got, expected)
    59  	}
    60  	if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
    61  		t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
    62  	}
    63  }
    64  
    65  type customWriterRecorder struct {
    66  	w io.Writer
    67  	*httptest.ResponseRecorder
    68  }
    69  
    70  func (r *customWriterRecorder) Write(p []byte) (n int, err error) {
    71  	return r.w.Write(p)
    72  }
    73  
    74  type limitWriter struct {
    75  	w io.Writer
    76  	n int
    77  }
    78  
    79  func (w *limitWriter) Write(p []byte) (n int, err error) {
    80  	if len(p) > w.n {
    81  		p = p[:w.n]
    82  	}
    83  	if len(p) > 0 {
    84  		n, err = w.w.Write(p)
    85  		w.n -= n
    86  	}
    87  	if w.n == 0 {
    88  		err = errors.New("past write limit")
    89  	}
    90  	return
    91  }
    92  
    93  // If there's an error copying the child's output to the parent, test
    94  // that we kill the child.
    95  func TestKillChildAfterCopyError(t *testing.T) {
    96  	testenv.MustHaveExec(t)
    97  
    98  	defer func() { testHookStartProcess = nil }()
    99  	proc := make(chan *os.Process, 1)
   100  	testHookStartProcess = func(p *os.Process) {
   101  		proc <- p
   102  	}
   103  
   104  	h := &Handler{
   105  		Path: os.Args[0],
   106  		Root: "/test.go",
   107  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   108  	}
   109  	req, _ := http.NewRequest("GET", "http://example.com/test.cgi?write-forever=1", nil)
   110  	rec := httptest.NewRecorder()
   111  	var out bytes.Buffer
   112  	const writeLen = 50 << 10
   113  	rw := &customWriterRecorder{&limitWriter{&out, writeLen}, rec}
   114  
   115  	donec := make(chan bool, 1)
   116  	go func() {
   117  		h.ServeHTTP(rw, req)
   118  		donec <- true
   119  	}()
   120  
   121  	select {
   122  	case <-donec:
   123  		if out.Len() != writeLen || out.Bytes()[0] != 'a' {
   124  			t.Errorf("unexpected output: %q", out.Bytes())
   125  		}
   126  	case <-time.After(5 * time.Second):
   127  		t.Errorf("timeout. ServeHTTP hung and didn't kill the child process?")
   128  		select {
   129  		case p := <-proc:
   130  			p.Kill()
   131  			t.Logf("killed process")
   132  		default:
   133  			t.Logf("didn't kill process")
   134  		}
   135  	}
   136  }
   137  
   138  // Test that a child handler writing only headers works.
   139  // golang.org/issue/7196
   140  func TestChildOnlyHeaders(t *testing.T) {
   141  	testenv.MustHaveExec(t)
   142  
   143  	h := &Handler{
   144  		Path: os.Args[0],
   145  		Root: "/test.go",
   146  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   147  	}
   148  	expectedMap := map[string]string{
   149  		"_body": "",
   150  	}
   151  	replay := runCgiTest(t, h, "GET /test.go?no-body=1 HTTP/1.0\nHost: example.com\n\n", expectedMap)
   152  	if expected, got := "X-Test-Value", replay.Header().Get("X-Test-Header"); got != expected {
   153  		t.Errorf("got a X-Test-Header of %q; expected %q", got, expected)
   154  	}
   155  }
   156  
   157  func TestChildContentType(t *testing.T) {
   158  	testenv.MustHaveExec(t)
   159  
   160  	h := &Handler{
   161  		Path: os.Args[0],
   162  		Root: "/test.go",
   163  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   164  	}
   165  	var tests = []struct {
   166  		name   string
   167  		body   string
   168  		wantCT string
   169  	}{
   170  		{
   171  			name:   "no body",
   172  			wantCT: "text/plain; charset=utf-8",
   173  		},
   174  		{
   175  			name:   "html",
   176  			body:   "<html><head><title>test page</title></head><body>This is a body</body></html>",
   177  			wantCT: "text/html; charset=utf-8",
   178  		},
   179  		{
   180  			name:   "text",
   181  			body:   strings.Repeat("gopher", 86),
   182  			wantCT: "text/plain; charset=utf-8",
   183  		},
   184  		{
   185  			name:   "jpg",
   186  			body:   "\xFF\xD8\xFF" + strings.Repeat("B", 1024),
   187  			wantCT: "image/jpeg",
   188  		},
   189  	}
   190  	for _, tt := range tests {
   191  		t.Run(tt.name, func(t *testing.T) {
   192  			expectedMap := map[string]string{"_body": tt.body}
   193  			req := fmt.Sprintf("GET /test.go?exact-body=%s HTTP/1.0\nHost: example.com\n\n", url.QueryEscape(tt.body))
   194  			replay := runCgiTest(t, h, req, expectedMap)
   195  			if got := replay.Header().Get("Content-Type"); got != tt.wantCT {
   196  				t.Errorf("got a Content-Type of %q; expected it to start with %q", got, tt.wantCT)
   197  			}
   198  		})
   199  	}
   200  }
   201  
   202  // golang.org/issue/7198
   203  func Test500WithNoHeaders(t *testing.T)     { want500Test(t, "/immediate-disconnect") }
   204  func Test500WithNoContentType(t *testing.T) { want500Test(t, "/no-content-type") }
   205  func Test500WithEmptyHeaders(t *testing.T)  { want500Test(t, "/empty-headers") }
   206  
   207  func want500Test(t *testing.T, path string) {
   208  	h := &Handler{
   209  		Path: os.Args[0],
   210  		Root: "/test.go",
   211  		Args: []string{"-test.run=TestBeChildCGIProcess"},
   212  	}
   213  	expectedMap := map[string]string{
   214  		"_body": "",
   215  	}
   216  	replay := runCgiTest(t, h, "GET "+path+" HTTP/1.0\nHost: example.com\n\n", expectedMap)
   217  	if replay.Code != 500 {
   218  		t.Errorf("Got code %d; want 500", replay.Code)
   219  	}
   220  }
   221  
   222  type neverEnding byte
   223  
   224  func (b neverEnding) Read(p []byte) (n int, err error) {
   225  	for i := range p {
   226  		p[i] = byte(b)
   227  	}
   228  	return len(p), nil
   229  }
   230  
   231  // Note: not actually a test.
   232  func TestBeChildCGIProcess(t *testing.T) {
   233  	if os.Getenv("REQUEST_METHOD") == "" {
   234  		// Not in a CGI environment; skipping test.
   235  		return
   236  	}
   237  	switch os.Getenv("REQUEST_URI") {
   238  	case "/immediate-disconnect":
   239  		os.Exit(0)
   240  	case "/no-content-type":
   241  		fmt.Printf("Content-Length: 6\n\nHello\n")
   242  		os.Exit(0)
   243  	case "/empty-headers":
   244  		fmt.Printf("\nHello")
   245  		os.Exit(0)
   246  	}
   247  	Serve(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
   248  		rw.Header().Set("X-Test-Header", "X-Test-Value")
   249  		req.ParseForm()
   250  		if req.FormValue("no-body") == "1" {
   251  			return
   252  		}
   253  		if eb, ok := req.Form["exact-body"]; ok {
   254  			io.WriteString(rw, eb[0])
   255  			return
   256  		}
   257  		if req.FormValue("write-forever") == "1" {
   258  			io.Copy(rw, neverEnding('a'))
   259  			for {
   260  				time.Sleep(5 * time.Second) // hang forever, until killed
   261  			}
   262  		}
   263  		fmt.Fprintf(rw, "test=Hello CGI-in-CGI\n")
   264  		for k, vv := range req.Form {
   265  			for _, v := range vv {
   266  				fmt.Fprintf(rw, "param-%s=%s\n", k, v)
   267  			}
   268  		}
   269  		for _, kv := range os.Environ() {
   270  			fmt.Fprintf(rw, "env-%s\n", kv)
   271  		}
   272  	}))
   273  	os.Exit(0)
   274  }
   275  

View as plain text