This repository has been archived by the owner on Mar 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
cgi.go
167 lines (157 loc) · 4.87 KB
/
cgi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
* Copyright (c) 2017 Kurt Jung (Gmail: kurt.w.jung)
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package cgi
import (
"bytes"
"errors"
"net/http"
"net/http/cgi"
"os"
"path"
"path/filepath"
"strings"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
)
// match returns true if the request string (reqStr) matches the pattern string
// (patternStr), false otherwise. If true is returned, it is followed by the
// prefix that matches the pattern and the unmatched portion to its right.
// patternStr uses glob notation; see path/Match for matching details. If the
// pattern is invalid (for example, contains an unpaired "["), false is
// returned.
func match(requestStr string, patterns []string) (ok bool, prefixStr, suffixStr string) {
var str, last string
var err error
ln := len(patterns)
for j := 0; j < ln && !ok; j++ {
pattern := patterns[j]
str = requestStr
last = ""
for last != str && !ok && err == nil {
ok, err = path.Match(pattern, str)
if err == nil {
if ok {
prefixStr = str
suffixStr = requestStr[len(str):]
} else {
last = str
str = filepath.Dir(str)
}
}
}
}
return
}
// excluded returns true if the request string (reqStr) matches any of the
// pattern strings (patterns), false otherwise. patterns use glob notation; see
// path/Match for matching details. If the pattern is invalid (for example,
// contains an unpaired "["), false is returned.
func excluded(reqStr string, patterns []string) (ok bool) {
var err error
var match bool
ln := len(patterns)
for j := 0; j < ln && !ok; j++ {
match, err = path.Match(patterns[j], reqStr)
if err == nil {
if match {
ok = true
// fmt.Printf("[%s] is excluded by rule [%s]\n", reqStr, patterns[j])
}
}
}
return
}
// currentDir returns the current working directory
func currentDir() (wdStr string) {
wdStr, _ = filepath.Abs(".")
return
}
// passAll returns a slice of strings made up of each environment key
func passAll() (list []string) {
envList := os.Environ() // ["HOME=/home/foo", "LVL=2", ...]
for _, str := range envList {
pos := strings.Index(str, "=")
if pos > 0 {
list = append(list, str[:pos])
}
}
return
}
// setupCall instantiates a CGI handler based on the incoming request and the
// configuration rule that it matches.
func setupCall(h handlerType, rule ruleType, lfStr, rtStr string,
rep httpserver.Replacer, hdr http.Header, username string) (cgiHnd cgi.Handler) {
cgiHnd.Root = "/"
cgiHnd.Dir = h.root
rep.Set("root", h.root)
rep.Set("match", lfStr)
rep.Set(".", currentDir())
cgiHnd.Path = rep.Replace(rule.exe)
if rule.dir != "" {
cgiHnd.Dir = rule.dir
}
cgiHnd.Env = append(cgiHnd.Env, "REMOTE_USER="+username)
envAdd := func(key, val string) {
val = rep.Replace(val)
cgiHnd.Env = append(cgiHnd.Env, key+"="+val)
}
for _, env := range rule.envs {
envAdd(env[0], env[1])
}
for _, env := range rule.emptyEnvs {
cgiHnd.Env = append(cgiHnd.Env, env+"=")
}
envAdd("PATH_INFO", rtStr)
envAdd("SCRIPT_FILENAME", cgiHnd.Path)
envAdd("SCRIPT_NAME", lfStr)
if rule.passAll {
cgiHnd.InheritEnv = passAll()
} else {
cgiHnd.InheritEnv = append(cgiHnd.InheritEnv, rule.passEnvs...)
}
for _, str := range rule.args {
cgiHnd.Args = append(cgiHnd.Args, rep.Replace(str))
}
envAdd("SCRIPT_EXEC", trim(sprintf("%s %s", cgiHnd.Path, join(cgiHnd.Args, " "))))
return
}
// ServeHTTP satisfies the httpserver.Handler interface.
func (h handlerType) ServeHTTP(w http.ResponseWriter, r *http.Request) (code int, err error) {
rep := httpserver.NewReplacer(r, nil, "")
for _, rule := range h.rules {
ok, lfStr, rtStr := match(r.URL.Path, rule.matches)
if ok {
ok = !excluded(r.URL.Path, rule.exceptions)
if ok {
var buf bytes.Buffer
// Retrieve name of remote user that was set by some downstream middleware,
// possibly basicauth.
remoteUser, _ := r.Context().Value(httpserver.RemoteUserCtxKey).(string) // Blank if not set
cgiHnd := setupCall(h, rule, lfStr, rtStr, rep, r.Header, remoteUser)
cgiHnd.Stderr = &buf
if rule.inspect {
inspect(cgiHnd, w, r, rep)
} else {
cgiHnd.ServeHTTP(w, r)
}
if buf.Len() > 0 {
err = errors.New(trim(buf.String()))
}
return
}
}
}
return h.next.ServeHTTP(w, r)
}