aboutsummaryrefslogtreecommitdiff
path: root/cgit.go
blob: e2687d3413c243404058e97d90fb716807330509 (plain) (blame)
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main

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

// Cgit is the browser. One config per repository, because under scan-path any
// request reaching cgit's index lists every repository. The configs are
// derived state in a temporary directory.
type Cgit struct {
	binary  string
	css     []byte // cgit's own stylesheet, read from beside the binary
	logo    []byte // and its logo, which is the default one
	favicon []byte
	dir     string
	store   *Store
}

// cgitBinary is the CGI in Alpine's cgit package; the override is for running
// outside that image.
func cgitBinary() string {
	if path := os.Getenv("GIT_FORGE_CGIT"); path != "" {
		return path
	}
	return "/usr/share/webapps/cgit/cgit.cgi"
}

func newCgit(store *Store, forgeCSS []byte) (*Cgit, error) {
	dir, err := os.MkdirTemp("", "git-forge-cgit")
	if err != nil {
		return nil, err
	}
	c := &Cgit{binary: cgitBinary(), dir: dir, store: store}
	if _, err := os.Stat(c.binary); err != nil {
		log.Printf("cgit: %v, so browsing will not work", err)
	}
	// cgit's own, read beside the CGI: its licence, and it changes with the
	// package.
	beside := filepath.Dir(c.binary)
	if c.css, err = os.ReadFile(filepath.Join(beside, "cgit.css")); err != nil {
		log.Printf("cgit: %v, so pages will be unstyled", err)
	}
	// One file at the path cgit links to, or the injected bar is unstyled.
	c.css = append(c.css, forgeCSS...)
	// The defaults, linked to when no logo is configured.
	if c.logo, err = os.ReadFile(filepath.Join(beside, "cgit.png")); err != nil {
		log.Printf("cgit: %v, so /cgit.png answers 404", err)
	}
	if c.favicon, err = os.ReadFile(filepath.Join(beside, "favicon.ico")); err != nil {
		log.Printf("cgit: %v, so /favicon.ico answers 404", err)
	}
	log.Printf("cgit configs in %s, written on demand and never backed up", dir)
	return c, c.writeFilters()
}

func (c *Cgit) close() { os.RemoveAll(c.dir) }

// writeFilters generates the two filter shims: an exec filter is not split on
// spaces, so "git-forge md" cannot be named directly.
func (c *Cgit) writeFilters() error {
	exe, err := os.Executable()
	if err != nil {
		return err
	}
	// Quoted: an unquoted path with a space in it execs its first word.
	quoted := "'" + strings.ReplaceAll(exe, "'", `'\''`) + "'"
	for _, sub := range []string{"md", "highlight"} {
		shim := fmt.Sprintf("#!/bin/sh\nexec %s %s \"$@\"\n", quoted, sub)
		if err := writeFile(filepath.Join(c.dir, sub), []byte(shim), 0700); err != nil {
			return err
		}
	}
	return nil
}

// config writes one repository's cgitrc if it is not there. The content
// depends on the path alone.
func (c *Cgit) config(path, kind string) (string, error) {
	name := c.configPath(path, kind)
	if _, err := os.Stat(name); err == nil {
		return name, nil
	}
	return c.write(path, kind)
}

func (c *Cgit) configPath(path, kind string) string {
	// A path holds at most one slash and no colon, so this is unambiguous.
	return filepath.Join(c.dir, strings.ReplaceAll(urlPath(path, kind), "/", ":")+".rc")
}

func (c *Cgit) repoDir(path, kind string) string {
	return filepath.Join(c.store.reposDir, path+gitSuffix(kind))
}

// virtual-root is unset: with SCRIPT_NAME empty, cgit emits links of the form
// /infra/dns/log/, the forge's own routes. No repo.desc: the description is in
// repos.json.
func (c *Cgit) write(path, kind string) (string, error) {
	url := urlPath(path, kind)
	var b strings.Builder
	// css stays /cgit.css; the injected bar carries the name.
	fmt.Fprintf(&b, "logo=\n")
	fmt.Fprintf(&b, "noheader=1\n")
	fmt.Fprintf(&b, "enable-blame=1\n")
	fmt.Fprintf(&b, "enable-http-clone=0\n")
	fmt.Fprintf(&b, "enable-log-filecount=1\n")
	fmt.Fprintf(&b, "enable-log-linecount=1\n")
	fmt.Fprintf(&b, "snapshots=tar.gz\n")
	// Both spellings, since a repository may carry either.
	fmt.Fprintf(&b, "readme=:README.md\n")
	fmt.Fprintf(&b, "readme=:README\n")
	// highlight is fed arbitrary blobs, so capped. In kilobytes.
	fmt.Fprintf(&b, "max-blob-size=512\n")
	// No mimetype mapping, so every blob comes back as text, not run on this
	// origin.
	fmt.Fprintf(&b, "mimetype-file=\n")
	fmt.Fprintf(&b, "about-filter=%s\n", filepath.Join(c.dir, "md"))
	fmt.Fprintf(&b, "source-filter=%s\n", filepath.Join(c.dir, "highlight"))
	fmt.Fprintf(&b, "clone-url=%s/%s.git\n", c.store.cfg.BaseURL, url)
	fmt.Fprintf(&b, "repo.url=%s\n", url)
	fmt.Fprintf(&b, "repo.path=%s\n", c.repoDir(path, kind))

	name := c.configPath(path, kind)
	return name, writeFile(name, []byte(b.String()), 0600)
}

// urlPath is how a repository and its siblings appear in a URL: infra/dns,
// infra/dns.issues, infra/dns.wiki.
func urlPath(path, kind string) string {
	if kind == "" {
		return path
	}
	return path + "." + kind
}

// browsing bounds the cgit children in flight. Its own budget: a page must not
// queue behind a clone.
var browsing = make(chan struct{}, 8)

// Authorisation has already happened: cgit is only ever told about a
// repository the viewer may read.
func (f *Forge) handleCgit(w http.ResponseWriter, r *http.Request, path, kind, rest string, repo Repo) {
	config, err := f.cgit.config(path, kind)
	if err != nil {
		f.problem(w, r, http.StatusInternalServerError, err)
		return
	}
	// The neutral configuration gitEnv gives: cgit reads repositories with
	// git's library.
	env := []string{
		"CGIT_CONFIG=" + config,
		"PATH_INFO=/" + urlPath(path, kind) + "/" + rest,
		"SCRIPT_NAME=",
		"GIT_CONFIG_NOSYSTEM=1",
		"GIT_CONFIG_GLOBAL=/dev/null",
	}
	nav := &injector{ResponseWriter: w, nav: f.navPart(r, "header", path, kind, repo)}
	// The forge's tabs go inside cgit's row; a sibling's history has none.
	if kind == "" {
		nav.tabs = f.navPart(r, "tabs", path, kind, repo)
	}
	if strings.HasPrefix(rest, "about") {
		nav.summary = "/" + urlPath(path, kind) + "/"
	}
	release, ok := childSlot(browsing, r)
	if !ok {
		return
	}
	defer release()
	(&cgi.Handler{Path: f.cgit.binary, Env: env, Stderr: os.Stdout}).ServeHTTP(nav, r)
	nav.flush()
}

// navPart renders one of nav.html's partials for injection into a cgit page:
// injected, so it follows the knobs and names the account.
func (f *Forge) navPart(r *http.Request, part, path, kind string, repo Repo) []byte {
	d := f.page(r)
	d.Repo = f.repoBar(r, path, kind, "", repo)
	var buf bytes.Buffer
	if err := f.nav.ExecuteTemplate(&buf, part, d); err != nil {
		log.Printf("nav %s: %v", part, err)
		return nil
	}
	return buf.Bytes()
}

// injector puts the header inside cgit's div and the tabs inside its tab row.
// Only text/html is buffered, and only until both are placed or the window
// runs out.
type injector struct {
	http.ResponseWriter
	nav      []byte
	tabs     []byte
	summary  string // where to send an about page cgit declined to answer
	html     bool
	wrote    bool
	injected bool
	buf      bytes.Buffer
}

// cgitTabs is where cgit's own tab cell ends; the forge's go in before it.
var cgitTabs = []byte("</td><td class='form'>")

// cgitDiv is the element cgit puts its whole page in.
var cgitDiv = []byte("<div id='cgit'>")

// maxInject bounds the wait for markup that may never come.
const maxInject = 64 << 10

func (w *injector) WriteHeader(status int) {
	if w.wrote {
		return
	}
	w.wrote = true
	// Without a readme cgit redirects the about page to a path that is not a
	// route.
	if w.summary != "" && status >= 300 && status < 400 {
		if strings.Contains(w.Header().Get("Location"), "..") {
			w.Header().Set("Location", w.summary)
		}
	}
	if strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") {
		w.html = true
		// The bar changes the length.
		w.Header().Del("Content-Length")
	}
	w.ResponseWriter.WriteHeader(status)
}

func (w *injector) Write(p []byte) (int, error) {
	if !w.wrote {
		w.WriteHeader(http.StatusOK)
	}
	if !w.html || w.injected {
		return w.ResponseWriter.Write(p)
	}
	w.buf.Write(p)
	// Both go in the first kilobyte of a cgit page.
	done := w.placed()
	if done || w.buf.Len() > maxInject {
		if !done {
			cgitMoved()
		}
		w.injected = true
		if err := w.drain(); err != nil {
			return 0, err
		}
	}
	return len(p), nil
}

// cgitMoved is a cgit whose markup no longer carries what the bar goes on: a
// package upgrade.
func cgitMoved() {
	log.Printf("cgit: the bar was not placed, so cgit's markup has moved")
}

// placed reports whether anything is left to wait for. The tabs go in first:
// the header carries a cell of its own.
func (w *injector) placed() bool {
	tabs := insertNear(&w.buf, cgitTabs, w.tabs, false)
	return insertNear(&w.buf, cgitDiv, w.nav, true) && tabs
}

// insertNear reports whether what went in. Nothing to insert, or something
// already inserted, counts as done.
func insertNear(buf *bytes.Buffer, needle, what []byte, after bool) bool {
	if len(what) == 0 || bytes.Contains(buf.Bytes(), what) {
		return true
	}
	at := bytes.Index(buf.Bytes(), needle)
	if at < 0 {
		return false
	}
	if after {
		at += len(needle)
	}
	rest := append([]byte(nil), buf.Bytes()[at:]...)
	buf.Truncate(at)
	buf.Write(what)
	buf.Write(rest)
	return true
}

func (w *injector) flush() {
	if w.buf.Len() > 0 {
		cgitMoved()
		w.drain()
	}
}

func (w *injector) drain() error {
	out := w.buf.Bytes()
	w.buf.Reset()
	_, err := w.ResponseWriter.Write(out)
	return err
}