package runnerdist
import (
_ "embed"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
//go:embed install.sh
var installScript string
// cliName is a client build's served name; each is the same bytes as the
// quarry-runner build for that platform.
var cliName = regexp.MustCompile(`^quarry-(linux|darwin|windows)-(amd64|arm64)(\.exe)?$`)
// CLIFile is the name the client for this platform is served as.
func (p Platform) CLIFile() string {
name := "quarry-" + p.OS + "-" + p.Arch
if p.OS == "windows" {
name += ".exe"
}
return name
}
// CLIHandler serves the client download from dir (the same directory as
// the runner builds): GET /cli/{file} for quarry-OS-ARCH, the runner's
// own name, and SHA256SUMS; and GET /install.sh, the installer made for
// origin, the public address of this forge. A forge with no https origin
// has no installer to give.
func CLIHandler(dir, origin string) http.Handler {
origin = strings.TrimSuffix(origin, "/")
mux := http.NewServeMux()
mux.HandleFunc("GET /cli/{file}", func(w http.ResponseWriter, req *http.Request) {
name := req.PathValue("file")
switch {
case name == SumsFile:
serveSums(w, req, dir)
case cliName.MatchString(name):
serveBuild(w, req, filepath.Join(dir, "quarry-runner-"+strings.TrimPrefix(name, "quarry-")), name)
case fileName.MatchString(name):
serveBuild(w, req, filepath.Join(dir, name), name)
default:
http.NotFound(w, req)
}
})
mux.HandleFunc("GET /install.sh", func(w http.ResponseWriter, req *http.Request) {
u, err := url.Parse(origin)
if err != nil || u.Scheme != "https" || u.Host == "" || u.Path != "" || !safeHost.MatchString(u.Host) {
http.Error(w, "this forge has no public https address set, so it has no installer to give", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/x-shellscript; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-cache")
w.Write([]byte(strings.ReplaceAll(installScript, "@ORIGIN@", origin)))
})
return mux
}
// safeHost is a host and port and nothing a shell would read as more.
var safeHost = regexp.MustCompile(`^[A-Za-z0-9.-]+(:[0-9]+)?$`)
func serveBuild(w http.ResponseWriter, req *http.Request, path, name string) {
f, err := os.Open(path)
if err != nil {
http.Error(w, "this forge carries no "+name+" build", http.StatusNotFound)
return
}
defer f.Close()
st, err := f.Stat()
if err != nil || st.IsDir() {
http.NotFound(w, req)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-cache")
http.ServeContent(w, req, name, st.ModTime(), f)
}
// sumLines is the checksum list as /cli/SHA256SUMS serves it: each
// quarry-runner line, then the same bytes under the quarry name.
func sumLines(dir string) ([][2]string, error) {
raw, err := os.ReadFile(filepath.Join(dir, SumsFile))
if err != nil {
return nil, err
}
var out [][2]string
for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
hash, name, ok := strings.Cut(line, " ")
name = strings.TrimPrefix(name, "*")
if !ok || !fileName.MatchString(name) {
continue
}
out = append(out, [2]string{hash, name}, [2]string{hash, "quarry-" + strings.TrimPrefix(name, "quarry-runner-")})
}
return out, nil
}
// serveSums answers with the runner's checksum list, each quarry-runner
// line given again under the quarry name of the same bytes.
func serveSums(w http.ResponseWriter, req *http.Request, dir string) {
lines, err := sumLines(dir)
if err != nil {
http.Error(w, "this forge carries no "+SumsFile, http.StatusNotFound)
return
}
var out strings.Builder
for _, l := range lines {
out.WriteString(l[0] + " " + l[1] + "\n")
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-cache")
w.Write([]byte(out.String()))
}
// Build is one file under /cli/ that SHA256SUMS lists and the forge holds.
type Build struct {
Name string
Size int64
SHA256 string
}
// Builds is every build /cli/SHA256SUMS lists whose file is present in
// dir, in the list's order; empty when the forge carries none.
func Builds(dir string) []Build {
lines, _ := sumLines(dir)
var out []Build
for _, l := range lines {
file := l[1]
if cliName.MatchString(file) {
file = "quarry-runner-" + strings.TrimPrefix(file, "quarry-")
}
st, err := os.Stat(filepath.Join(dir, file))
if err != nil || st.IsDir() {
continue
}
out = append(out, Build{Name: l[1], Size: st.Size(), SHA256: l[0]})
}
return out
}