2015-01-30 14:48:35 +08:00
|
|
|
// Package fastcgi has middleware that acts as a FastCGI client. Requests
|
|
|
|
// that get forwarded to FastCGI stop the middleware execution chain.
|
2015-04-12 07:15:17 +08:00
|
|
|
// The most common use for this package is to serve PHP websites via php-fpm.
|
2015-01-30 13:03:14 +08:00
|
|
|
package fastcgi
|
2015-01-22 08:51:47 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2015-04-21 07:40:54 +08:00
|
|
|
"os"
|
2015-01-22 08:51:47 +08:00
|
|
|
"path/filepath"
|
2015-04-21 07:40:54 +08:00
|
|
|
"strconv"
|
2015-01-22 08:51:47 +08:00
|
|
|
"strings"
|
|
|
|
|
2015-01-30 13:03:14 +08:00
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-22 08:51:47 +08:00
|
|
|
)
|
|
|
|
|
2015-04-12 07:15:17 +08:00
|
|
|
// Handler is a middleware type that can handle requests as a FastCGI client.
|
|
|
|
type Handler struct {
|
2015-05-06 05:50:42 +08:00
|
|
|
Next middleware.Handler
|
|
|
|
Rules []Rule
|
|
|
|
Root string
|
|
|
|
AbsRoot string // same as root, but absolute path
|
|
|
|
FileSys http.FileSystem
|
2015-04-12 07:15:17 +08:00
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// These are sent to CGI scripts in env variables
|
|
|
|
SoftwareName string
|
|
|
|
SoftwareVersion string
|
|
|
|
ServerName string
|
|
|
|
ServerPort string
|
2015-04-21 07:40:54 +08:00
|
|
|
}
|
|
|
|
|
2015-04-12 07:15:17 +08: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-06 05:50:42 +08:00
|
|
|
|
|
|
|
// First requirement: Base path must match
|
|
|
|
if !middleware.Path(r.URL.Path).Matches(rule.Path) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2015-04-26 11:56:14 +08: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-12 07:15:17 +08:00
|
|
|
|
2015-05-06 05:50:42 +08:00
|
|
|
fpath := r.URL.Path
|
|
|
|
if idx, ok := middleware.IndexFile(h.FileSys, fpath, rule.IndexFiles); ok {
|
|
|
|
fpath = idx
|
|
|
|
}
|
2015-04-29 03:15:14 +08:00
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// These criteria work well in this order for PHP sites
|
2015-05-06 05:50:42 +08:00
|
|
|
if fpath[len(fpath)-1] == '/' || strings.HasSuffix(fpath, rule.Ext) || !h.exists(fpath) {
|
2015-01-22 08:51:47 +08:00
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// Create environment for CGI script
|
2015-05-06 05:50:42 +08:00
|
|
|
env, err := h.buildEnv(r, rule, fpath)
|
2015-04-12 07:15:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return http.StatusInternalServerError, err
|
2015-01-22 08:51:47 +08:00
|
|
|
}
|
2015-03-29 06:52:43 +08:00
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// Connect to FastCGI gateway
|
2015-04-12 07:15:17 +08:00
|
|
|
fcgi, err := Dial("tcp", rule.Address)
|
|
|
|
if err != nil {
|
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
|
|
|
|
2015-04-21 07:40:54 +08:00
|
|
|
var resp *http.Response
|
2015-05-03 19:12:18 +08:00
|
|
|
contentLength, _ := strconv.Atoi(r.Header.Get("Content-Length"))
|
2015-04-26 11:56:14 +08:00
|
|
|
switch r.Method {
|
2015-05-03 19:12:18 +08:00
|
|
|
case "HEAD":
|
|
|
|
resp, err = fcgi.Head(env)
|
2015-04-26 11:56:14 +08:00
|
|
|
case "GET":
|
2015-04-21 07:40:54 +08:00
|
|
|
resp, err = fcgi.Get(env)
|
2015-05-07 01:14:02 +08:00
|
|
|
case "OPTIONS":
|
|
|
|
resp, err = fcgi.Options(env)
|
2015-04-26 11:56:14 +08:00
|
|
|
case "POST":
|
2015-05-03 19:12:18 +08:00
|
|
|
resp, err = fcgi.Post(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
|
|
|
case "PUT":
|
|
|
|
resp, err = fcgi.Put(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
|
|
|
case "PATCH":
|
|
|
|
resp, err = fcgi.Patch(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
|
|
|
case "DELETE":
|
|
|
|
resp, err = fcgi.Delete(env, r.Header.Get("Content-Type"), r.Body, contentLength)
|
2015-04-26 11:56:14 +08:00
|
|
|
default:
|
|
|
|
return http.StatusMethodNotAllowed, nil
|
2015-04-21 07:40:54 +08:00
|
|
|
}
|
2015-04-26 11:56:14 +08:00
|
|
|
defer resp.Body.Close()
|
2015-04-12 07:15:17 +08:00
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
if err != nil && err != io.EOF {
|
2015-04-12 07:15:17 +08:00
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// Write the response header
|
2015-04-12 07:15:17 +08:00
|
|
|
for key, vals := range resp.Header {
|
|
|
|
for _, val := range vals {
|
|
|
|
w.Header().Add(key, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
w.WriteHeader(resp.StatusCode)
|
|
|
|
|
2015-04-27 12:01:20 +08:00
|
|
|
// Write the response body
|
2015-04-30 21:50:07 +08:00
|
|
|
// TODO: If this has an error, the response will already be
|
|
|
|
// partly written. We should copy out of resp.Body into a buffer
|
|
|
|
// first, then write it to the response...
|
2015-04-27 12:01:20 +08:00
|
|
|
_, err = io.Copy(w, resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return http.StatusBadGateway, err
|
|
|
|
}
|
2015-04-21 07:40:54 +08:00
|
|
|
|
2015-04-30 21:50:07 +08:00
|
|
|
return 0, nil
|
2015-04-12 07:15:17 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
return h.Next.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h Handler) exists(path string) bool {
|
|
|
|
if _, err := os.Stat(h.Root + path); err == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2015-05-06 05:50:42 +08: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-26 11:56:14 +08:00
|
|
|
var env map[string]string
|
|
|
|
|
|
|
|
// Get absolute path of requested resource
|
2015-05-06 05:50:42 +08:00
|
|
|
absPath := filepath.Join(h.AbsRoot, fpath)
|
2015-04-26 11:56:14 +08:00
|
|
|
|
|
|
|
// Separate remote IP and port; more lenient than net.SplitHostPort
|
|
|
|
var ip, port string
|
|
|
|
if idx := strings.Index(r.RemoteAddr, ":"); idx > -1 {
|
|
|
|
ip = r.RemoteAddr[:idx]
|
|
|
|
port = r.RemoteAddr[idx+1:]
|
|
|
|
} else {
|
|
|
|
ip = r.RemoteAddr
|
2015-04-12 07:15:17 +08:00
|
|
|
}
|
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// Split path in preparation for env variables
|
2015-05-06 05:50:42 +08:00
|
|
|
splitPos := strings.Index(fpath, rule.SplitPath)
|
2015-04-26 11:56:14 +08:00
|
|
|
var docURI, scriptName, scriptFilename, pathInfo string
|
|
|
|
if splitPos == -1 {
|
2015-04-29 03:15:14 +08:00
|
|
|
// Request doesn't have the extension, so assume index file in root
|
2015-05-06 05:50:42 +08:00
|
|
|
docURI = "/" + rule.IndexFiles[0]
|
|
|
|
scriptName = "/" + rule.IndexFiles[0]
|
|
|
|
scriptFilename = filepath.Join(h.AbsRoot, rule.IndexFiles[0])
|
|
|
|
pathInfo = fpath
|
2015-04-26 11:56:14 +08:00
|
|
|
} else {
|
|
|
|
// Request has the extension; path was split successfully
|
2015-05-06 05:50:42 +08:00
|
|
|
docURI = fpath[:splitPos+len(rule.SplitPath)]
|
|
|
|
pathInfo = fpath[splitPos+len(rule.SplitPath):]
|
|
|
|
scriptName = fpath
|
2015-04-26 11:56:14 +08:00
|
|
|
scriptFilename = absPath
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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,
|
2015-05-06 05:50:42 +08:00
|
|
|
"PATH_TRANSLATED": filepath.Join(h.AbsRoot, pathInfo), // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
|
2015-04-26 11:56:14 +08:00
|
|
|
"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-06 05:50:42 +08:00
|
|
|
"DOCUMENT_ROOT": h.AbsRoot,
|
2015-04-26 11:56:14 +08:00
|
|
|
"DOCUMENT_URI": docURI,
|
|
|
|
"HTTP_HOST": r.Host, // added here, since not always part of headers
|
|
|
|
"REQUEST_URI": r.URL.RequestURI(),
|
|
|
|
"SCRIPT_FILENAME": scriptFilename,
|
|
|
|
"SCRIPT_NAME": scriptName,
|
|
|
|
}
|
|
|
|
|
2015-05-02 02:55:47 +08:00
|
|
|
// Add env variables from config
|
|
|
|
for _, envVar := range rule.EnvVars {
|
|
|
|
env[envVar[0]] = envVar[1]
|
|
|
|
}
|
|
|
|
|
2015-04-26 11:56:14 +08:00
|
|
|
// Add all HTTP headers to env variables
|
|
|
|
for field, val := range r.Header {
|
|
|
|
header := strings.ToUpper(field)
|
|
|
|
header = headerNameReplacer.Replace(header)
|
2015-04-27 12:01:20 +08:00
|
|
|
env["HTTP_"+header] = strings.Join(val, ", ")
|
2015-04-26 11:56:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return env, nil
|
2015-04-12 07:15:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Rule represents a FastCGI handling rule.
|
|
|
|
type Rule struct {
|
2015-04-26 11:56:14 +08: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-06 05:50:42 +08:00
|
|
|
// If the URL ends with '/' (which indicates a directory), these index
|
|
|
|
// files will be tried instead.
|
|
|
|
IndexFiles []string
|
2015-05-02 02:55:47 +08:00
|
|
|
|
|
|
|
// Environment Variables
|
|
|
|
EnvVars [][2]string
|
2015-01-22 08:51:47 +08:00
|
|
|
}
|
2015-04-26 11:56:14 +08:00
|
|
|
|
|
|
|
var headerNameReplacer = strings.NewReplacer(" ", "_", "-", "_")
|