summaryrefslogtreecommitdiff
path: root/contrib/cgi/gopher.go
blob: bb3e73eca55c943d04eab57aea8588e32c9a85fe (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
package cgi

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	sr "tildegit.org/tjp/sliderule"
	"tildegit.org/tjp/sliderule/gopher"
	"tildegit.org/tjp/sliderule/gopher/gophermap"
	"tildegit.org/tjp/sliderule/logging"
)

// GopherCGIDirectory 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 GopherCGIDirectory(fsroot, urlroot string, settings *gophermap.FileSystemSettings) sr.Handler {
	if settings == nil || !settings.Exec {
		return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response { return nil })
	}
	fsroot = strings.TrimRight(fsroot, "/")

	return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
		if !strings.HasPrefix(request.Path, urlroot) {
			return nil
		}
		requestpath := strings.Trim(strings.TrimPrefix(request.Path, urlroot), "/")

		fullpath, pathinfo, err := resolveGopherCGI(fsroot, requestpath)
		if err != nil {
			return gopher.Error(err).Response()
		}
		if fullpath == "" {
			return nil
		}

		return runGopherCGI(ctx, request, fullpath, pathinfo, *settings)
	})
}

// ExecGopherMaps runs any gophermaps
func ExecGopherMaps(fsroot, urlroot string, settings *gophermap.FileSystemSettings) sr.Handler {
	if settings == nil || !settings.Exec {
		return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response { return nil })
	}
	fsroot = strings.TrimRight(fsroot, "/")

	return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
		if !strings.HasPrefix(request.Path, urlroot) {
			return nil
		}
		requestpath := strings.Trim(strings.TrimPrefix(request.Path, urlroot), "/")

		fullpath := filepath.Join(fsroot, requestpath)
		info, err := os.Stat(fullpath)
		if isNotExistError(err) {
			return nil
		}
		if err != nil {
			return gopher.Error(err).Response()
		}

		if info.IsDir() {
			for _, fname := range settings.DirMaps {
				fpath := filepath.Join(fullpath, fname)
				finfo, err := os.Stat(fpath)
				if isNotExistError(err) {
					continue
				}
				if err != nil {
					return gopher.Error(err).Response()
				}

				m := finfo.Mode()
				if m.IsDir() {
					continue
				}
				if !m.IsRegular() || m&5 != 5 {
					continue
				}
				return runGopherCGI(ctx, request, fpath, "/", *settings)
			}

			return nil
		}

		m := info.Mode()
		if !m.IsRegular() || m&5 != 5 {
			return nil
		}

		return runGopherCGI(ctx, request, fullpath, "/", *settings)
	})
}

func runGopherCGI(
	ctx context.Context,
	request *sr.Request,
	fullpath string,
	pathinfo string,
	settings gophermap.FileSystemSettings,
) *sr.Response {
	stderr := &bytes.Buffer{}
	stdout, exitCode, err := RunCGI(ctx, request, fullpath, pathinfo, stderr)
	if err != nil {
		return gopher.Error(err).Response()
	}
	if exitCode != 0 {
		ctx.Value("warnlog").(logging.Logger).Log(
			"msg", "cgi exited with non-zero exit code",
			"code", exitCode,
			"stderr", stderr.String(),
		)
		return gopher.Error(
			fmt.Errorf("CGI process exited with status %d", exitCode),
		).Response()
	}

	if settings.ParseExtended {
		edoc, err := gophermap.ParseExtended(stdout, request.URL)
		if err != nil {
			return gopher.Error(err).Response()
		}

		doc, _, err := edoc.Compatible(filepath.Dir(fullpath), settings)
		if err != nil {
			return gopher.Error(err).Response()
		}
		return doc.Response()
	}

	return gopher.File(gopher.MenuType, stdout)
}

func resolveGopherCGI(fsRoot string, reqPath string) (string, string, error) {
	segments := append([]string{""}, strings.Split(reqPath, "/")...)
	fullpath := fsRoot
	for i, segment := range segments {
		fullpath = filepath.Join(fullpath, segment)

		info, err := os.Stat(fullpath)
		if isNotExistError(err) {
			return "", "", nil
		}
		if err != nil {
			return "", "", err
		}

		if !info.IsDir() {
			if info.Mode()&5 == 5 {
				pathinfo := "/"
				if len(segments) > i+1 {
					pathinfo = path.Join(segments[i:]...)
				}
				return fullpath, pathinfo, nil
			}
			break
		}
	}

	return "", "", nil
}