senary.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
168
169
170
171
172
173
174
175
176
177
178
179
package main

import (
	"bytes"
	"fmt"
	"log"
	"net/http"
	"net/http/cgi"
	"net/http/httputil"
	"path"
	"path/filepath"
	"strings"

	"os"
	"senary/auth"
	"senary/common"
	"senary/gen"
	"senary/repo"
)

const SOFTWARE_NAME = "senary"

func Regen(config *common.Config, repo string) {
	err := gen.GenerateRepoPages(config, repo)
	if err != nil {
		fmt.Printf("[error] %v\n", err)
	}
}

func printHelp() {
	fmt.Printf("usage: %v [serve|build]\n", SOFTWARE_NAME)
}

func printBuildHelp() {
	fmt.Printf("usage: %v build <repo>\n", SOFTWARE_NAME)
}

var (
	git_http_backend_bin = "/usr/lib/git-core/git-http-backend"
	git_repos            = "/srv/repos/"
)

func gitBackend(w http.ResponseWriter, r *http.Request) {

	// defense in depth, blackhole receive-pack requests
	// we expect the bare repo to also be configured to reject http(s) push requests
	// but this should prevent any access to it from the web interface at all..
	if strings.Contains(r.URL.String(), "receive-pack") {
		http.Error(w, "forbidden", http.StatusForbidden)
		return
	}

	env := []string{
		fmt.Sprintf("GIT_PROJECT_ROOT=%s", git_repos),
		"GIT_HTTP_EXPORT_ALL=",
		"REMOTE_USER=githttp",
	}

	// debug git request
	requestDump, err := httputil.DumpRequest(r, true)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(string(requestDump))

	var stdErr bytes.Buffer
	handler := &cgi.Handler{
		Path:   git_http_backend_bin,
		Root:   "/repos/",
		Env:    env,
		Stderr: &stdErr,
	}
	handler.ServeHTTP(w, r)

	if stdErr.Len() > 0 {
		log.Println("[backend]", stdErr.String())
	}
}

func main() {

	numArgs := len(os.Args)

	if numArgs == 1 {
		printHelp()
		os.Exit(1)
	}

	config, err := common.LoadConfig("senary.json")
	if err != nil {
		fmt.Printf("[error] %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Maintainer Domains:%v\n", config.MaintainerDomains)

	switch os.Args[1] {
	case "serve":

		authClient := auth.NewAuthClient(config)

		fs := http.FileServer(http.Dir(config.BaseDir))
		http.Handle("/", fs)

		http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
			config.Templates.ExecuteTemplate(w, "index.tpl.html", gen.StaticDirListing{StaticBase: gen.StaticBase{User: authClient.GetAuthInfo(config, r)}})
		})

		http.HandleFunc("GET /repos/{$}", func(w http.ResponseWriter, r *http.Request) {
			entries := []gen.FileEntry{}

			dirEntries, _ := os.ReadDir(config.RepoDir)

			for _, e := range dirEntries {
				if e.IsDir() {
					entries = append(entries, gen.FileEntry{Dir: true, Name: e.Name(), Path: e.Name()})
				}
			}
			config.Templates.ExecuteTemplate(w, "repos.tpl.html", gen.StaticDirListing{StaticBase: gen.StaticBase{User: authClient.GetAuthInfo(config, r)}, Path: "Repositories", DirName: "Repositories", Contents: entries})
		})

		http.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) {
			config.Templates.ExecuteTemplate(w, "login.tpl.html", gen.StaticDirListing{StaticBase: gen.StaticBase{User: authClient.GetAuthInfo(config, r)}})
		})
		http.HandleFunc("POST /login", authClient.LoginHandler)
		http.HandleFunc("GET /callback", authClient.CallbackHandler)

		dirEntries, _ := os.ReadDir(config.RepoDir)

		for _, e := range dirEntries {
			if e.IsDir() {

				repos := repo.NewRepository(config, e.Name(), authClient)

				repopath := path.Join("/repos/", e.Name(), "/{$}")
				http.HandleFunc("GET "+repopath, repos.ServeTree)
				treepath := path.Join("/repos/", e.Name(), "tree") + "/"
				http.HandleFunc("GET "+treepath, repos.ServeTree)
				commitpath := path.Join("/repos/", e.Name(), "commits") + "/"
				http.HandleFunc("GET "+commitpath, repos.ServeTree)

				// make a request handler for the repo
				rm := repo.NewRequestManager(config, e.Name(), authClient)
				http.HandleFunc(path.Join("/repos/", e.Name(), "requests")+"/", rm.Serve)
				http.HandleFunc("POST "+path.Join("/repos/", e.Name(), "requests")+"/new", rm.Submit)
				http.HandleFunc("POST "+path.Join("/repos/", e.Name(), "requests")+"/approve", rm.Submit)
				http.HandleFunc("POST "+path.Join("/repos/", e.Name(), "requests")+"/tombstone", rm.Submit)

				// allow downloading patches and applying them...
				http.HandleFunc("GET "+path.Join("/repos/", e.Name(), "patch/{id}/{patch}")+"/{$}", rm.ServePatch)
				http.HandleFunc("POST "+path.Join("/repos/", e.Name(), "apply/{id}/{patch}")+"/{$}", rm.ApplyPatch)
				// allow https cloning by redirecting to git https backend
				http.HandleFunc(path.Join("/repos/", e.Name()+".git")+"/", gitBackend)
			}
		}

		log.Print("Listening on :3000...")
		err := http.ListenAndServe("localhost:3000", nil)
		if err != nil {
			log.Fatal(err)
		}
	case "build":
		if numArgs == 2 {
			for _, base := range config.RepoBases {

				dirEntries, _ := os.ReadDir(base)

				for _, e := range dirEntries {
					if e.IsDir() {
						Regen(config, filepath.Join(base, e.Name()))
					}
				}
			}
		} else {
			printBuildHelp()
		}

	}
}