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

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

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

func cgiDirectory(protocol sr.ServerProtocol, fsroot, urlroot, cmd string) sr.Handler {
	fsroot = strings.TrimRight(fsroot, "/")

	return sr.HandlerFunc(func(ctx context.Context, request *sr.Request) *sr.Response {
		if !strings.HasPrefix(request.Path, urlroot) {
			return nil
		}

		rpath := strings.TrimPrefix(request.Path, urlroot)
		rpath = strings.Trim(rpath, "/")
		execpath, pathinfo, err := ResolveCGI(rpath, fsroot)
		if err != nil {
			return protocol.TemporaryServerError(err)
		}
		if execpath == "" {
			return nil
		}
		workdir := filepath.Dir(execpath)

		if cmd != "" {
			execpath = cmd
		}

		stderr := &bytes.Buffer{}
		stdout, exitCode, err := RunCGI(ctx, request, execpath, pathinfo, workdir, stderr)
		if err != nil {
			return protocol.TemporaryServerError(err)
		}
		if exitCode != 0 {
			_ = ctx.Value("warnlog").(logging.Logger).Log(
				"msg", "cgi exited with non-zero exit code",
				"code", exitCode,
				"stderr", stderr.String(),
			)
			return protocol.CGIFailure(fmt.Errorf("CGI process exited with status %d", exitCode))
		}

		response, err := protocol.ParseResponse(stdout)
		if err != nil {
			return protocol.TemporaryServerError(err)
		}
		return response
	})
}