2015-01-30 01:48:35 -05:00
|
|
|
// Package fastcgi has middleware that acts as a FastCGI client. Requests
|
|
|
|
// that get forwarded to FastCGI stop the middleware execution chain.
|
2015-04-11 18:15:17 -05:00
|
|
|
// The most common use for this package is to serve PHP websites via php-fpm.
|
2015-01-30 00:03:14 -05:00
|
|
|
package fastcgi
|
2015-01-21 19:51:47 -05:00
|
|
|
|
|
|
|
import (
|
2016-02-24 13:35:21 -05:00
|
|
|
"bytes"
|
2015-10-30 20:24:37 -05:00
|
|
|
"errors"
|
2015-01-21 19:51:47 -05:00
|
|
|
"io"
|
|
|
|
"net/http"
|
2015-04-20 18:40:54 -05:00
|
|
|
"os"
|
2015-01-21 19:51:47 -05:00
|
|
|
"path/filepath"
|
2015-04-20 18:40:54 -05:00
|
|
|
"strconv"
|
2015-01-21 19:51:47 -05:00
|
|
|
"strings"
|
|
|
|
|
2015-01-30 00:03:14 -05:00
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-21 19:51:47 -05:00
|
|
|
)
|
|
|
|
|
2015-04-11 18:15:17 -05:00
|
|
|
// Handler is a middleware type that can handle requests as a FastCGI client.
|
|
|
|
type Handler struct {
|
2015-05-05 16:50:42 -05:00
|
|
|
Next middleware.Handler
|
|
|
|
Rules []Rule
|
|
|
|
Root string
|
|
|
|
AbsRoot string // same as root, but absolute path
|
|
|
|
FileSys http.FileSystem
|
2015-04-11 18:15:17 -05:00
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// These are sent to CGI scripts in env variables
|
|
|
|
SoftwareName string
|
|
|
|
SoftwareVersion string
|
|
|
|
ServerName string
|
|
|
|
ServerPort string
|
2015-04-20 18:40:54 -05:00
|
|
|
}
|
|
|
|
|
2015-04-11 18:15:17 -05:00
|
|
|
// ServeHTTP satisfies the middleware.Handler interface.
|
|
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
|
|
|
for _, rule := range h.Rules {
|
2015-05-05 16:50:42 -05:00
|
|
|
|
|
|
|
// First requirement: Base path must match
|
|
|
|
if !middleware.Path(r.URL.Path).Matches(rule.Path) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// In addition to matching the path, a request must meet some
|
|
|
|
// other criteria before being proxied as FastCGI. For example,
|
|
|
|
// we probably want to exclude static assets (CSS, JS, images...)
|
|
|
|
// but we also want to be flexible for the script we proxy to.
|
2015-04-11 18:15:17 -05:00
|
|
|
|
2015-05-05 16:50:42 -05:00
|
|
|
fpath := r.URL.Path
|
|
|
|
if idx, ok := middleware.IndexFile(h.FileSys, fpath, rule.IndexFiles); ok {
|
|
|
|
fpath = idx
|
2015-10-30 20:24:37 -05:00
|
|
|
// Index file present.
|
|
|
|
// If request path cannot be split, return error.
|
|
|
|
if !h.canSplit(fpath, rule) {
|
|
|
|
return http.StatusInternalServerError, ErrIndexMissingSplit
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// No index file present.
|
|
|
|
// If request path cannot be split, ignore request.
|
|
|
|
if !h.canSplit(fpath, rule) {
|
|
|
|
continue
|
|
|
|
}
|
2015-05-05 16:50:42 -05:00
|
|
|
}
|
2015-04-28 14:15:14 -05:00
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// These criteria work well in this order for PHP sites
|
2015-10-30 20:24:37 -05:00
|
|
|
if !h.exists(fpath) || fpath[len(fpath)-1] == '/' || strings.HasSuffix(fpath, rule.Ext) {
|
2015-01-21 19:51:47 -05:00
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// Create environment for CGI script
|
2015-05-05 16:50:42 -05:00
|
|
|
env, err := h.buildEnv(r, rule, fpath)
|
2015-04-11 18:15:17 -05:00
|
|
|
if err != nil {
|
|
|
|
return http.StatusInternalServerError, err
|
2015-01-21 19:51:47 -05:00
|
|
|
}
|
2015-03-28 17:52:43 -05:00
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// Connect to FastCGI gateway
|
2016-01-27 19:00:08 -05:00
|
|
|
network, address := rule.parseAddress()
|
2016-02-24 18:41:45 -05:00
|
|
|
fcgiBackend, err := Dial(network, address)
|
2015-04-11 18:15:17 -05:00
|
|
|
if err != nil {
|
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
|
|
|
|
2015-04-20 18:40:54 -05:00
|
|
|
var resp *http.Response
|
2015-05-03 06:12:18 -05:00
|
|
|
contentLength, _ := strconv.Atoi(r.Header.Get("Content-Length"))
|
2015-04-25 22:56:14 -05:00
|
|
|
switch r.Method {
|
2015-05-03 06:12:18 -05:00
|
|
|
case "HEAD":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Head(env)
|
2015-04-25 22:56:14 -05:00
|
|
|
case "GET":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Get(env)
|
2015-05-06 12:14:02 -05:00
|
|
|
case "OPTIONS":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Options(env)
|
2015-04-25 22:56:14 -05:00
|
|
|
case "POST":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Post(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
2015-05-03 06:12:18 -05:00
|
|
|
case "PUT":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Put(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
2015-05-03 06:12:18 -05:00
|
|
|
case "PATCH":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Patch(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
2015-05-03 06:12:18 -05:00
|
|
|
case "DELETE":
|
2016-02-24 18:41:45 -05:00
|
|
|
resp, err = fcgiBackend.Delete(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
2015-04-25 22:56:14 -05:00
|
|
|
default:
|
|
|
|
return http.StatusMethodNotAllowed, nil
|
2015-04-20 18:40:54 -05:00
|
|
|
}
|
2015-05-22 21:39:23 -05:00
|
|
|
|
|
|
|
if resp.Body != nil {
|
|
|
|
defer resp.Body.Close()
|
|
|
|
}
|
2015-04-11 18:15:17 -05:00
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
if err != nil && err != io.EOF {
|
2015-04-11 18:15:17 -05:00
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
|
|
|
|
2016-02-24 18:41:45 -05:00
|
|
|
var responseBody io.Reader = resp.Body
|
2016-02-24 21:50:46 -05:00
|
|
|
if resp.Header.Get("Content-Length") == "" {
|
2016-02-24 18:41:45 -05:00
|
|
|
// If the upstream app didn't set a Content-Length (shame on them),
|
|
|
|
// we need to do it to prevent error messages being appended to
|
|
|
|
// an already-written response, and other problematic behavior.
|
|
|
|
// So we copy it to a buffer and read its size before flushing
|
|
|
|
// the response out to the client. See issues #567 and #614.
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
_, err := io.Copy(buf, resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
2016-02-24 13:35:21 -05:00
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
|
2016-02-24 18:41:45 -05:00
|
|
|
responseBody = buf
|
2016-02-24 13:35:21 -05:00
|
|
|
}
|
2016-02-24 18:41:45 -05:00
|
|
|
|
|
|
|
// Write the status code and header fields
|
2015-10-09 17:35:34 -05:00
|
|
|
writeHeader(w, resp)
|
2015-04-11 18:15:17 -05:00
|
|
|
|
2015-04-26 23:01:20 -05:00
|
|
|
// Write the response body
|
2016-02-24 18:41:45 -05:00
|
|
|
_, err = io.Copy(w, responseBody)
|
2015-04-26 23:01:20 -05:00
|
|
|
if err != nil {
|
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
2015-04-20 18:40:54 -05:00
|
|
|
|
2015-12-12 08:04:48 -05:00
|
|
|
// FastCGI stderr outputs
|
2016-02-24 18:41:45 -05:00
|
|
|
if fcgiBackend.stderr.Len() != 0 {
|
2015-12-13 06:58:21 -05:00
|
|
|
// Remove trailing newline, error logger already does this.
|
2016-02-24 18:41:45 -05:00
|
|
|
err = LogError(strings.TrimSuffix(fcgiBackend.stderr.String(), "\n"))
|
2015-12-12 08:04:48 -05:00
|
|
|
}
|
|
|
|
|
2016-02-24 21:50:46 -05:00
|
|
|
// Normally we should only return a status >= 400 if no response
|
|
|
|
// body is written yet, however, upstream apps don't know about
|
|
|
|
// this contract and we still want the correct code logged, so error
|
|
|
|
// handling code in our stack needs to check Content-Length before
|
|
|
|
// writing an error message... oh well.
|
2015-12-13 06:58:21 -05:00
|
|
|
return resp.StatusCode, err
|
2015-04-11 18:15:17 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
return h.Next.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
2016-01-27 19:00:08 -05:00
|
|
|
// parseAddress returns the network and address of r.
|
|
|
|
// The first string is the network, "tcp" or "unix", implied from the scheme and address.
|
|
|
|
// The second string is r.Address, with scheme prefixes removed.
|
|
|
|
// The two returned strings can be used as parameters to the Dial() function.
|
|
|
|
func (r Rule) parseAddress() (string, string) {
|
|
|
|
// check if address has tcp scheme explicitly set
|
|
|
|
if strings.HasPrefix(r.Address, "tcp://") {
|
|
|
|
return "tcp", r.Address[len("tcp://"):]
|
|
|
|
}
|
2016-02-14 02:10:57 -05:00
|
|
|
// check if address has fastcgi scheme explicitly set
|
2016-01-27 19:00:08 -05:00
|
|
|
if strings.HasPrefix(r.Address, "fastcgi://") {
|
|
|
|
return "tcp", r.Address[len("fastcgi://"):]
|
|
|
|
}
|
|
|
|
// check if unix socket
|
2015-10-09 17:35:34 -05:00
|
|
|
if trim := strings.HasPrefix(r.Address, "unix"); strings.HasPrefix(r.Address, "/") || trim {
|
|
|
|
if trim {
|
2016-01-27 19:00:08 -05:00
|
|
|
return "unix", r.Address[len("unix:"):]
|
2015-10-09 17:35:34 -05:00
|
|
|
}
|
2016-01-27 19:00:08 -05:00
|
|
|
return "unix", r.Address
|
2015-10-09 17:35:34 -05:00
|
|
|
}
|
2016-01-27 19:00:08 -05:00
|
|
|
// default case, a plain tcp address with no scheme
|
|
|
|
return "tcp", r.Address
|
2015-10-09 17:35:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func writeHeader(w http.ResponseWriter, r *http.Response) {
|
|
|
|
for key, vals := range r.Header {
|
|
|
|
for _, val := range vals {
|
|
|
|
w.Header().Add(key, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
w.WriteHeader(r.StatusCode)
|
|
|
|
}
|
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
func (h Handler) exists(path string) bool {
|
|
|
|
if _, err := os.Stat(h.Root + path); err == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-10-30 20:24:37 -05:00
|
|
|
func (h Handler) canSplit(path string, rule Rule) bool {
|
|
|
|
return strings.Contains(path, rule.SplitPath)
|
|
|
|
}
|
|
|
|
|
2015-05-05 16:50:42 -05:00
|
|
|
// buildEnv returns a set of CGI environment variables for the request.
|
|
|
|
func (h Handler) buildEnv(r *http.Request, rule Rule, fpath string) (map[string]string, error) {
|
2015-04-25 22:56:14 -05:00
|
|
|
var env map[string]string
|
|
|
|
|
|
|
|
// Get absolute path of requested resource
|
2015-05-05 16:50:42 -05:00
|
|
|
absPath := filepath.Join(h.AbsRoot, fpath)
|
2015-04-25 22:56:14 -05:00
|
|
|
|
|
|
|
// Separate remote IP and port; more lenient than net.SplitHostPort
|
|
|
|
var ip, port string
|
2016-01-28 09:26:33 -05:00
|
|
|
if idx := strings.LastIndex(r.RemoteAddr, ":"); idx > -1 {
|
2015-04-25 22:56:14 -05:00
|
|
|
ip = r.RemoteAddr[:idx]
|
|
|
|
port = r.RemoteAddr[idx+1:]
|
|
|
|
} else {
|
|
|
|
ip = r.RemoteAddr
|
2015-04-11 18:15:17 -05:00
|
|
|
}
|
|
|
|
|
2015-10-30 20:24:37 -05:00
|
|
|
// Split path in preparation for env variables.
|
|
|
|
// Previous h.canSplit checks ensure this can never be -1.
|
2015-05-05 16:50:42 -05:00
|
|
|
splitPos := strings.Index(fpath, rule.SplitPath)
|
2015-10-30 20:24:37 -05:00
|
|
|
|
|
|
|
// Request has the extension; path was split successfully
|
|
|
|
docURI := fpath[:splitPos+len(rule.SplitPath)]
|
|
|
|
pathInfo := fpath[splitPos+len(rule.SplitPath):]
|
|
|
|
scriptName := fpath
|
|
|
|
scriptFilename := absPath
|
2015-04-25 22:56:14 -05:00
|
|
|
|
2015-09-16 13:25:40 -05:00
|
|
|
// Strip PATH_INFO from SCRIPT_NAME
|
2015-09-28 15:11:05 -05:00
|
|
|
scriptName = strings.TrimSuffix(scriptName, pathInfo)
|
|
|
|
|
2015-09-27 19:27:45 -05:00
|
|
|
// Get the request URI. The request URI might be as it came in over the wire,
|
|
|
|
// or it might have been rewritten internally by the rewrite middleware (see issue #256).
|
|
|
|
// If it was rewritten, there will be a header indicating the original URL,
|
|
|
|
// which is needed to get the correct RequestURI value for PHP apps.
|
|
|
|
const internalRewriteFieldName = "Caddy-Rewrite-Original-URI"
|
|
|
|
reqURI := r.URL.RequestURI()
|
|
|
|
if origURI := r.Header.Get(internalRewriteFieldName); origURI != "" {
|
|
|
|
reqURI = origURI
|
|
|
|
r.Header.Del(internalRewriteFieldName)
|
2015-09-16 13:25:40 -05:00
|
|
|
}
|
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// Some variables are unused but cleared explicitly to prevent
|
|
|
|
// the parent environment from interfering.
|
|
|
|
env = map[string]string{
|
|
|
|
|
|
|
|
// Variables defined in CGI 1.1 spec
|
|
|
|
"AUTH_TYPE": "", // Not used
|
|
|
|
"CONTENT_LENGTH": r.Header.Get("Content-Length"),
|
|
|
|
"CONTENT_TYPE": r.Header.Get("Content-Type"),
|
|
|
|
"GATEWAY_INTERFACE": "CGI/1.1",
|
|
|
|
"PATH_INFO": pathInfo,
|
|
|
|
"QUERY_STRING": r.URL.RawQuery,
|
|
|
|
"REMOTE_ADDR": ip,
|
|
|
|
"REMOTE_HOST": ip, // For speed, remote host lookups disabled
|
|
|
|
"REMOTE_PORT": port,
|
|
|
|
"REMOTE_IDENT": "", // Not used
|
|
|
|
"REMOTE_USER": "", // Not used
|
|
|
|
"REQUEST_METHOD": r.Method,
|
|
|
|
"SERVER_NAME": h.ServerName,
|
|
|
|
"SERVER_PORT": h.ServerPort,
|
|
|
|
"SERVER_PROTOCOL": r.Proto,
|
|
|
|
"SERVER_SOFTWARE": h.SoftwareName + "/" + h.SoftwareVersion,
|
|
|
|
|
|
|
|
// Other variables
|
2015-05-05 16:50:42 -05:00
|
|
|
"DOCUMENT_ROOT": h.AbsRoot,
|
2015-04-25 22:56:14 -05:00
|
|
|
"DOCUMENT_URI": docURI,
|
|
|
|
"HTTP_HOST": r.Host, // added here, since not always part of headers
|
2015-09-27 19:27:45 -05:00
|
|
|
"REQUEST_URI": reqURI,
|
2015-04-25 22:56:14 -05:00
|
|
|
"SCRIPT_FILENAME": scriptFilename,
|
|
|
|
"SCRIPT_NAME": scriptName,
|
|
|
|
}
|
|
|
|
|
2015-06-30 05:54:50 -05:00
|
|
|
// compliance with the CGI specification that PATH_TRANSLATED
|
|
|
|
// should only exist if PATH_INFO is defined.
|
|
|
|
// Info: https://www.ietf.org/rfc/rfc3875 Page 14
|
|
|
|
if env["PATH_INFO"] != "" {
|
|
|
|
env["PATH_TRANSLATED"] = filepath.Join(h.AbsRoot, pathInfo) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
|
|
|
|
}
|
|
|
|
|
2015-08-03 18:16:24 -05:00
|
|
|
// Some web apps rely on knowing HTTPS or not
|
|
|
|
if r.TLS != nil {
|
|
|
|
env["HTTPS"] = "on"
|
|
|
|
}
|
|
|
|
|
2015-05-01 13:55:47 -05:00
|
|
|
// Add env variables from config
|
|
|
|
for _, envVar := range rule.EnvVars {
|
|
|
|
env[envVar[0]] = envVar[1]
|
|
|
|
}
|
|
|
|
|
2015-04-25 22:56:14 -05:00
|
|
|
// Add all HTTP headers to env variables
|
|
|
|
for field, val := range r.Header {
|
|
|
|
header := strings.ToUpper(field)
|
|
|
|
header = headerNameReplacer.Replace(header)
|
2015-04-26 23:01:20 -05:00
|
|
|
env["HTTP_"+header] = strings.Join(val, ", ")
|
2015-04-25 22:56:14 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return env, nil
|
2015-04-11 18:15:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Rule represents a FastCGI handling rule.
|
|
|
|
type Rule struct {
|
2015-04-25 22:56:14 -05:00
|
|
|
// The base path to match. Required.
|
|
|
|
Path string
|
|
|
|
|
|
|
|
// The address of the FastCGI server. Required.
|
|
|
|
Address string
|
|
|
|
|
|
|
|
// Always process files with this extension with fastcgi.
|
|
|
|
Ext string
|
|
|
|
|
|
|
|
// The path in the URL will be split into two, with the first piece ending
|
|
|
|
// with the value of SplitPath. The first piece will be assumed as the
|
|
|
|
// actual resource (CGI script) name, and the second piece will be set to
|
|
|
|
// PATH_INFO for the CGI script to use.
|
|
|
|
SplitPath string
|
|
|
|
|
2015-05-05 16:50:42 -05:00
|
|
|
// If the URL ends with '/' (which indicates a directory), these index
|
|
|
|
// files will be tried instead.
|
|
|
|
IndexFiles []string
|
2015-05-01 13:55:47 -05:00
|
|
|
|
|
|
|
// Environment Variables
|
|
|
|
EnvVars [][2]string
|
2015-01-21 19:51:47 -05:00
|
|
|
}
|
2015-04-25 22:56:14 -05:00
|
|
|
|
2015-10-30 20:24:37 -05:00
|
|
|
var (
|
|
|
|
headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
|
2015-11-02 14:28:50 -05:00
|
|
|
// ErrIndexMissingSplit describes an index configuration error.
|
2015-10-30 20:24:37 -05:00
|
|
|
ErrIndexMissingSplit = errors.New("configured index file(s) must include split value")
|
|
|
|
)
|
2015-12-12 08:04:48 -05:00
|
|
|
|
|
|
|
// LogError is a non fatal error that allows requests to go through.
|
|
|
|
type LogError string
|
|
|
|
|
|
|
|
// Error satisfies error interface.
|
|
|
|
func (l LogError) Error() string {
|
|
|
|
return string(l)
|
|
|
|
}
|