├── hijack.go ├── README.md ├── LICENSE └── dcgi.go /hijack.go: -------------------------------------------------------------------------------- 1 | package dcgi 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "log" 7 | 8 | "github.com/docker/docker/pkg/stdcopy" 9 | "github.com/docker/engine-api/types" 10 | ) 11 | 12 | // holdHijackedConnection handles copying input to and output from streams to 13 | // the connection. Copied from github.com/docker/docker/api/client. 14 | func holdHijackedConnection(inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp types.HijackedResponse) error { 15 | var err error 16 | 17 | receiveStdout := make(chan error, 1) 18 | if outputStream != nil || errorStream != nil { 19 | go func() { 20 | _, err = stdcopy.StdCopy(outputStream, errorStream, resp.Reader) 21 | // log.Printf("[hijack] End of stdout") 22 | receiveStdout <- err 23 | }() 24 | } 25 | 26 | stdinDone := make(chan struct{}) 27 | go func() { 28 | if inputStream != nil { 29 | io.Copy(resp.Conn, inputStream) 30 | // log.Printf("[hijack] End of stdin") 31 | } 32 | 33 | if err := resp.CloseWrite(); err != nil { 34 | log.Printf("cgi: couldn't send EOF: %s", err) 35 | } 36 | close(stdinDone) 37 | }() 38 | 39 | select { 40 | case err := <-receiveStdout: 41 | if err != nil { 42 | return fmt.Errorf("Error receiveStdout: %s", err) 43 | } 44 | case <-stdinDone: 45 | if outputStream != nil || errorStream != nil { 46 | err := <-receiveStdout 47 | if err != nil { 48 | return fmt.Errorf("Error receiveStdout: %s", err) 49 | } 50 | } 51 | } 52 | 53 | return nil 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-dcgi 2 | 3 | DCGI is a technique for serving web pages dynamically with Docker. As you may know, World Wide Web servers can only serve static files off disk. A DCGI server allows you to *execute code in real-time*, so the Web page can contain *dynamic* information. 4 | 5 | For each HTTP request that a DGCI server receives, a Docker container is spun up to serve the HTTP request. Inside the Docker container is a [CGI](https://en.wikipedia.org/wiki/Common_Gateway_Interface) executable which handles the request. That executable could do anything – and could be written in any language or framework. 6 | 7 | Wow! No longer do we have to build Web sites which just serve static content. For example, you could "hook up" your Unix database to the World Wide Web so people all over the world could query it. Or, you could create HTML forms to allow people to transmit information into your database engine. The possibilities are limitless. 8 | 9 | So, what's this library for? go-dcgi is a library for writing DGCI servers. It includes a Go HTTP handler, `dcgi.Handler`, which serves an HTTP request by running a Docker container. 10 | 11 | ## Usage 12 | 13 | Say you've got a really simple CGI script, `script.pl`: 14 | 15 | ```perl 16 | print "Content-Type: text/html\n\n"; 17 | print "

Hello World!

\n"; 18 | ``` 19 | 20 | And a `Dockerfile` to put it inside a container: 21 | 22 | ``` 23 | FROM perl 24 | ADD script.pl /code/script.pl 25 | ENTRYPOINT ["perl", "/code/script.pl"] 26 | ``` 27 | 28 | Build this into a container: 29 | 30 | ```bash 31 | $ docker build -t bfirsh/example-dcgi-app . 32 | ``` 33 | 34 | You can serve this container over HTTP with go-dcgi: 35 | 36 | ```go 37 | package main 38 | 39 | import ( 40 | "net/http" 41 | dcgi "github.com/bfirsh/go-dcgi" 42 | "github.com/docker/engine-api/client" 43 | ) 44 | 45 | func main() { 46 | cli, err := client.NewClient("unix:///var/run/docker.sock", "v1.23", nil, nil) 47 | if err != nil { 48 | panic(err) 49 | } 50 | 51 | http.Handle("/", &dcgi.Handler{ 52 | Image: "bfirsh/example-dcgi-app", 53 | Client: cli, 54 | }) 55 | http.ListenAndServe(":80", nil) 56 | } 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | https://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | Copyright 2016 Ben Firshman 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | https://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /dcgi.go: -------------------------------------------------------------------------------- 1 | // Package dcgi implements CGI (Common Gateway Interface), but 2 | // running inside Docker containers. 3 | // 4 | // Based off https://golang.org/pkg/net/http/cgi/ 5 | // Copyright 2011 The Go Authors. All rights reserved. 6 | // https://github.com/golang/go/blob/master/LICENSE 7 | package dcgi 8 | 9 | import ( 10 | "bufio" 11 | "fmt" 12 | "io" 13 | "log" 14 | "net" 15 | "net/http" 16 | "os" 17 | "regexp" 18 | "runtime" 19 | "strconv" 20 | "strings" 21 | 22 | "github.com/docker/engine-api/client" 23 | "github.com/docker/engine-api/types" 24 | "github.com/docker/engine-api/types/container" 25 | "golang.org/x/net/context" 26 | ) 27 | 28 | var trailingPort = regexp.MustCompile(`:([0-9]+)$`) 29 | 30 | var osDefaultInheritEnv = map[string][]string{ 31 | "darwin": {"DYLD_LIBRARY_PATH"}, 32 | "freebsd": {"LD_LIBRARY_PATH"}, 33 | "hpux": {"LD_LIBRARY_PATH", "SHLIB_PATH"}, 34 | "irix": {"LD_LIBRARY_PATH", "LD_LIBRARYN32_PATH", "LD_LIBRARY64_PATH"}, 35 | "linux": {"LD_LIBRARY_PATH"}, 36 | "openbsd": {"LD_LIBRARY_PATH"}, 37 | "solaris": {"LD_LIBRARY_PATH", "LD_LIBRARY_PATH_32", "LD_LIBRARY_PATH_64"}, 38 | "windows": {"SystemRoot", "COMSPEC", "PATHEXT", "WINDIR"}, 39 | } 40 | 41 | // Handler runs an executable in a subprocess with a CGI environment. 42 | type Handler struct { 43 | Client *client.Client // Docker client to use 44 | Image string // Docker image to run 45 | HostConfig *container.HostConfig 46 | Root string // root URI prefix of handler or empty for "/" 47 | 48 | Env []string // extra environment variables to set, if any, as "key=value" 49 | InheritEnv []string // environment variables to inherit from host, as "key" 50 | Logger *log.Logger // optional log for errors or nil to use log.Print 51 | Args []string // optional arguments to pass to child process 52 | 53 | // PathLocationHandler specifies the root http Handler that 54 | // should handle internal redirects when the CGI process 55 | // returns a Location header value starting with a "/", as 56 | // specified in RFC 3875 § 6.3.2. This will likely be 57 | // http.DefaultServeMux. 58 | // 59 | // If nil, a CGI response with a local URI path is instead sent 60 | // back to the client and not redirected internally. 61 | PathLocationHandler http.Handler 62 | } 63 | 64 | // removeLeadingDuplicates remove leading duplicate in environments. 65 | // It's possible to override environment like following. 66 | // cgi.Handler{ 67 | // ... 68 | // Env: []string{"SCRIPT_FILENAME=foo.php"}, 69 | // } 70 | func removeLeadingDuplicates(env []string) (ret []string) { 71 | for i, e := range env { 72 | found := false 73 | if eq := strings.IndexByte(e, '='); eq != -1 { 74 | keq := e[:eq+1] // "key=" 75 | for _, e2 := range env[i+1:] { 76 | if strings.HasPrefix(e2, keq) { 77 | found = true 78 | break 79 | } 80 | } 81 | } 82 | if !found { 83 | ret = append(ret, e) 84 | } 85 | } 86 | return 87 | } 88 | 89 | func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { 90 | root := h.Root 91 | if root == "" { 92 | root = "/" 93 | } 94 | 95 | if len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked" { 96 | rw.WriteHeader(http.StatusBadRequest) 97 | rw.Write([]byte("Chunked request bodies are not supported by CGI.")) 98 | return 99 | } 100 | 101 | pathInfo := req.URL.Path 102 | if root != "/" && strings.HasPrefix(pathInfo, root) { 103 | pathInfo = pathInfo[len(root):] 104 | } 105 | 106 | port := "80" 107 | if matches := trailingPort.FindStringSubmatch(req.Host); len(matches) != 0 { 108 | port = matches[1] 109 | } 110 | 111 | env := []string{ 112 | "SERVER_SOFTWARE=go", 113 | "SERVER_NAME=" + req.Host, 114 | "SERVER_PROTOCOL=HTTP/1.1", 115 | "HTTP_HOST=" + req.Host, 116 | "GATEWAY_INTERFACE=CGI/1.1", 117 | "REQUEST_METHOD=" + req.Method, 118 | "QUERY_STRING=" + req.URL.RawQuery, 119 | "REQUEST_URI=" + req.URL.RequestURI(), 120 | "PATH_INFO=" + pathInfo, 121 | "SCRIPT_NAME=" + root, 122 | "SCRIPT_FILENAME=", 123 | "SERVER_PORT=" + port, 124 | } 125 | 126 | if remoteIP, remotePort, err := net.SplitHostPort(req.RemoteAddr); err == nil { 127 | env = append(env, "REMOTE_ADDR="+remoteIP, "REMOTE_HOST="+remoteIP, "REMOTE_PORT="+remotePort) 128 | } else { 129 | // could not parse ip:port, let's use whole RemoteAddr and leave REMOTE_PORT undefined 130 | env = append(env, "REMOTE_ADDR="+req.RemoteAddr, "REMOTE_HOST="+req.RemoteAddr) 131 | } 132 | 133 | if req.TLS != nil { 134 | env = append(env, "HTTPS=on") 135 | } 136 | 137 | for k, v := range req.Header { 138 | k = strings.Map(upperCaseAndUnderscore, k) 139 | joinStr := ", " 140 | if k == "COOKIE" { 141 | joinStr = "; " 142 | } 143 | env = append(env, "HTTP_"+k+"="+strings.Join(v, joinStr)) 144 | } 145 | 146 | if req.ContentLength > 0 { 147 | env = append(env, fmt.Sprintf("CONTENT_LENGTH=%d", req.ContentLength)) 148 | } 149 | if ctype := req.Header.Get("Content-Type"); ctype != "" { 150 | env = append(env, "CONTENT_TYPE="+ctype) 151 | } 152 | 153 | for _, e := range h.InheritEnv { 154 | if v := os.Getenv(e); v != "" { 155 | env = append(env, e+"="+v) 156 | } 157 | } 158 | 159 | for _, e := range osDefaultInheritEnv[runtime.GOOS] { 160 | if v := os.Getenv(e); v != "" { 161 | env = append(env, e+"="+v) 162 | } 163 | } 164 | 165 | if h.Env != nil { 166 | env = append(env, h.Env...) 167 | } 168 | 169 | env = removeLeadingDuplicates(env) 170 | 171 | internalError := func(err error) { 172 | rw.WriteHeader(http.StatusInternalServerError) 173 | h.printf("CGI error: %v", err) 174 | } 175 | 176 | containerConfig := &container.Config{ 177 | Image: h.Image, 178 | Cmd: h.Args, 179 | Env: env, 180 | AttachStdout: true, 181 | AttachStderr: true, 182 | AttachStdin: true, 183 | Tty: false, 184 | OpenStdin: true, 185 | StdinOnce: true, 186 | } 187 | 188 | ctx := context.Background() 189 | resp, err := h.Client.ContainerCreate(ctx, containerConfig, h.HostConfig, nil, "") 190 | if err != nil { 191 | internalError(err) 192 | return 193 | } 194 | containerID := resp.ID 195 | defer func() { 196 | status, err := h.Client.ContainerWait(ctx, containerID) 197 | if err != nil { 198 | h.printf("cgi: error getting container status: %s", err) 199 | } 200 | if status == 0 { 201 | options := types.ContainerRemoveOptions{ 202 | RemoveVolumes: true, 203 | Force: true, 204 | } 205 | if err := h.Client.ContainerRemove(ctx, containerID, options); err != nil { 206 | h.printf("cgi: error removing container: %s", err) 207 | } 208 | } 209 | }() 210 | 211 | attachOptions := types.ContainerAttachOptions{ 212 | Stdout: true, 213 | Stderr: true, 214 | Stdin: true, 215 | Stream: true, 216 | } 217 | attachResp, err := h.Client.ContainerAttach(ctx, containerID, attachOptions) 218 | if err != nil { 219 | internalError(err) 220 | return 221 | } 222 | 223 | containerStartOptions := types.ContainerStartOptions{} 224 | if err := h.Client.ContainerStart(ctx, containerID, containerStartOptions); err != nil { 225 | internalError(err) 226 | return 227 | } 228 | 229 | stdoutRead, stdoutWrite := io.Pipe() 230 | 231 | // just write errors to stderr for now 232 | stderrWrite := os.Stderr 233 | 234 | go func() { 235 | var stdinRead io.ReadCloser 236 | if req.ContentLength == 0 { 237 | stdinRead = nil 238 | } else { 239 | stdinRead = req.Body 240 | } 241 | 242 | if err := holdHijackedConnection(stdinRead, stdoutWrite, stderrWrite, attachResp); err != nil { 243 | h.printf("cgi: error in HoldHijackedConnection: %v", err) 244 | } 245 | stdoutWrite.Close() 246 | // stdoutWrite.Close() 247 | }() 248 | 249 | linebody := bufio.NewReaderSize(stdoutRead, 1024) 250 | headers := make(http.Header) 251 | statusCode := 0 252 | headerLines := 0 253 | sawBlankLine := false 254 | for { 255 | line, isPrefix, err := linebody.ReadLine() 256 | // fmt.Printf("readLine: %s\n", line) 257 | if isPrefix { 258 | rw.WriteHeader(http.StatusInternalServerError) 259 | h.printf("cgi: long header line from subprocess.") 260 | return 261 | } 262 | if err == io.EOF { 263 | break 264 | } 265 | if err != nil { 266 | rw.WriteHeader(http.StatusInternalServerError) 267 | h.printf("cgi: error reading headers: %v", err) 268 | return 269 | } 270 | if len(line) == 0 { 271 | sawBlankLine = true 272 | break 273 | } 274 | headerLines++ 275 | parts := strings.SplitN(string(line), ":", 2) 276 | if len(parts) < 2 { 277 | h.printf("cgi: bogus header line: %s", string(line)) 278 | continue 279 | } 280 | header, val := parts[0], parts[1] 281 | header = strings.TrimSpace(header) 282 | val = strings.TrimSpace(val) 283 | switch { 284 | case header == "Status": 285 | if len(val) < 3 { 286 | h.printf("cgi: bogus status (short): %q", val) 287 | return 288 | } 289 | code, err := strconv.Atoi(val[0:3]) 290 | if err != nil { 291 | h.printf("cgi: bogus status: %q", val) 292 | h.printf("cgi: line was %q", line) 293 | return 294 | } 295 | statusCode = code 296 | default: 297 | headers.Add(header, val) 298 | } 299 | } 300 | if headerLines == 0 || !sawBlankLine { 301 | rw.WriteHeader(http.StatusInternalServerError) 302 | h.printf("cgi: no headers") 303 | return 304 | } 305 | 306 | if loc := headers.Get("Location"); loc != "" { 307 | if strings.HasPrefix(loc, "/") && h.PathLocationHandler != nil { 308 | h.handleInternalRedirect(rw, req, loc) 309 | return 310 | } 311 | if statusCode == 0 { 312 | statusCode = http.StatusFound 313 | } 314 | } 315 | 316 | if statusCode == 0 && headers.Get("Content-Type") == "" { 317 | rw.WriteHeader(http.StatusInternalServerError) 318 | h.printf("cgi: missing required Content-Type in headers") 319 | return 320 | } 321 | 322 | if statusCode == 0 { 323 | statusCode = http.StatusOK 324 | } 325 | 326 | // Copy headers to rw's headers, after we've decided not to 327 | // go into handleInternalRedirect, which won't want its rw 328 | // headers to have been touched. 329 | for k, vv := range headers { 330 | for _, v := range vv { 331 | rw.Header().Add(k, v) 332 | } 333 | } 334 | 335 | rw.WriteHeader(statusCode) 336 | 337 | _, err = io.Copy(rw, linebody) 338 | if err != nil { 339 | h.printf("cgi: copy error: %v", err) 340 | // And kill the child CGI process so we don't hang on 341 | // the deferred cmd.Wait above if the error was just 342 | // the client (rw) going away. If it was a read error 343 | // (because the child died itself), then the extra 344 | // kill of an already-dead process is harmless (the PID 345 | // won't be reused until the Wait above). 346 | h.Client.ContainerKill(ctx, containerID, "KILL") 347 | } 348 | } 349 | 350 | func (h *Handler) printf(format string, v ...interface{}) { 351 | if h.Logger != nil { 352 | h.Logger.Printf(format, v...) 353 | } else { 354 | log.Printf(format, v...) 355 | } 356 | } 357 | 358 | func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) { 359 | url, err := req.URL.Parse(path) 360 | if err != nil { 361 | rw.WriteHeader(http.StatusInternalServerError) 362 | h.printf("cgi: error resolving local URI path %q: %v", path, err) 363 | return 364 | } 365 | // TODO: RFC 3875 isn't clear if only GET is supported, but it 366 | // suggests so: "Note that any message-body attached to the 367 | // request (such as for a POST request) may not be available 368 | // to the resource that is the target of the redirect." We 369 | // should do some tests against Apache to see how it handles 370 | // POST, HEAD, etc. Does the internal redirect get the same 371 | // method or just GET? What about incoming headers? 372 | // (e.g. Cookies) Which headers, if any, are copied into the 373 | // second request? 374 | newReq := &http.Request{ 375 | Method: "GET", 376 | URL: url, 377 | Proto: "HTTP/1.1", 378 | ProtoMajor: 1, 379 | ProtoMinor: 1, 380 | Header: make(http.Header), 381 | Host: url.Host, 382 | RemoteAddr: req.RemoteAddr, 383 | TLS: req.TLS, 384 | } 385 | h.PathLocationHandler.ServeHTTP(rw, newReq) 386 | } 387 | 388 | func upperCaseAndUnderscore(r rune) rune { 389 | switch { 390 | case r >= 'a' && r <= 'z': 391 | return r - ('a' - 'A') 392 | case r == '-': 393 | return '_' 394 | case r == '=': 395 | // Maybe not part of the CGI 'spec' but would mess up 396 | // the environment in any case, as Go represents the 397 | // environment as a slice of "key=value" strings. 398 | return '_' 399 | } 400 | // TODO: other transformations in spec or practice? 401 | return r 402 | } 403 | 404 | var testHookStartProcess func(*os.Process) // nil except for some tests 405 | --------------------------------------------------------------------------------