summaryrefslogtreecommitdiff
path: root/contrib/cgi/cgi.go
blob: e43f1ef27bfe99e5cf9dbd40ef971856086c4312 (plain)
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package cgi

import (
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io/fs"
	"net"
	"os"
	"os/exec"
	"strings"

	"tildegit.org/tjp/gus/gemini"
)

// CGIDirectory runs any executable files relative to a root directory on the file system.
//
// It will also find and run any executables _part way_ through the path, so for example
// a request for /foo/bar/baz can also run an executable found at /foo or  /foo/bar. In
// such a case the PATH_INFO environment variable will include the remaining portion of
// the URI path.
func CGIDirectory(pathRoot, fsRoot string) gemini.Handler {
	fsRoot = strings.TrimRight(fsRoot, "/")

	return func(ctx context.Context, req *gemini.Request) *gemini.Response {
		if !strings.HasPrefix(req.Path, pathRoot) {
			return gemini.NotFound("Resource does not exist.")
		}

		path := req.Path[len(pathRoot):]
		segments := strings.Split(strings.TrimLeft(path, "/"), "/")
		for i := range append(segments, "") {
			path := strings.Join(append([]string{fsRoot}, segments[:i]...), "/")
			path = strings.TrimRight(path, "/")
			isDir, isExecutable, err := executableFile(path)
			if err != nil {
				return gemini.Failure(err)
			}

			if isExecutable {
				pathInfo := "/"
				if len(segments) > i+1 {
					pathInfo = strings.Join(segments[i:], "/")
				}
				return RunCGI(ctx, req, path, pathInfo)
			}

			if !isDir {
				break
			}
		}

		return gemini.NotFound("Resource does not exist.")
	}
}

func executableFile(path string) (bool, bool, error) {
	file, err := os.Open(path)
	if isNotExistError(err) {
		return false, false, nil
	}
	if err != nil {
		return false, false, err
	}
	defer file.Close()

	info, err := file.Stat()
	if err != nil {
		return false, false, err
	}

	if info.IsDir() {
		return true, false, nil
	}

	// readable + executable by anyone
	return false, info.Mode()&0005 == 0005, nil
}

func isNotExistError(err error) bool {
	if err != nil {
		var pathErr *fs.PathError
		if errors.As(err, &pathErr) {
			e := pathErr.Err
			if errors.Is(e, fs.ErrInvalid) || errors.Is(e, fs.ErrNotExist) {
				return true
			}
		}
	}

	return false
}

// RunCGI runs a specific program as a CGI script.
func RunCGI(
	ctx context.Context,
	req *gemini.Request,
	executable string,
	pathInfo string,
) *gemini.Response {
	pathSegments := strings.Split(executable, "/")

	dirPath := "."
	if len(pathSegments) > 1 {
		dirPath = strings.Join(pathSegments[:len(pathSegments)-1], "/")
	}
	basename := pathSegments[len(pathSegments)-1]

	scriptName := req.Path[:len(req.Path)-len(pathInfo)]
	if strings.HasSuffix(scriptName, "/") {
		scriptName = scriptName[:len(scriptName)-1]
	}

	cmd := exec.CommandContext(ctx, "./"+basename)
	cmd.Env = prepareCGIEnv(ctx, req, scriptName, pathInfo)
	cmd.Dir = dirPath

	responseBuffer := &bytes.Buffer{}
	cmd.Stdout = responseBuffer

	if err := cmd.Run(); err != nil {
		var exErr *exec.ExitError
		if errors.As(err, &exErr) {
			errMsg := fmt.Sprintf("CGI returned exit code %d", exErr.ExitCode())
			return gemini.CGIError(errMsg)
		}
		return gemini.Failure(err)
	}

	response, err := gemini.ParseResponse(responseBuffer)
	if err != nil {
		return gemini.Failure(err)
	}
	return response
}

func prepareCGIEnv(
	ctx context.Context,
	req *gemini.Request,
	scriptName string,
	pathInfo string,
) []string {
	var authType string
	if len(req.TLSState.PeerCertificates) > 0 {
		authType = "Certificate"
	}
	environ := []string{
		"AUTH_TYPE=" + authType,
		"CONTENT_LENGTH=",
		"CONTENT_TYPE=",
		"GATEWAY_INTERFACE=CGI/1.1",
		"PATH_INFO=" + pathInfo,
		"PATH_TRANSLATED=",
		"QUERY_STRING=" + req.RawQuery,
	}

	host, _, _ := net.SplitHostPort(req.RemoteAddr.String())
	environ = append(environ, "REMOTE_ADDR="+host)

	environ = append(
		environ,
		"REMOTE_HOST=",
		"REMOTE_IDENT=",
		"SCRIPT_NAME="+scriptName,
		"SERVER_NAME="+req.Server.Hostname(),
		"SERVER_PORT="+req.Server.Port(),
		"SERVER_PROTOCOL=GEMINI",
		"SERVER_SOFTWARE=GUS",
	)

	if len(req.TLSState.PeerCertificates) > 0 {
		cert := req.TLSState.PeerCertificates[0]
		environ = append(
			environ,
			"TLS_CLIENT_HASH="+fingerprint(cert.Raw),
			"TLS_CLIENT_ISSUER="+cert.Issuer.String(),
			"TLS_CLIENT_ISSUER_CN="+cert.Issuer.CommonName,
			"TLS_CLIENT_SUBJECT="+cert.Subject.String(),
			"TLS_CLIENT_SUBJECT_CN="+cert.Subject.CommonName,
		)
	}

	return environ
}

func fingerprint(raw []byte) string {
	hash := sha256.Sum256(raw)
	return hex.EncodeToString(hash[:])
}