Debian Codegraph @

main.go

raw symbols SCIP
1 package main
2
3 import (
4 "archive/tar"
5 "bufio"
6 "bytes"
7 "crypto"
8 "crypto/sha256"
9 "encoding/hex"
10 "errors"
11 "fmt"
12 "io"
13 "io/fs"
14 "net/http"
15 "net/url"
16 "os"
17 "regexp"
18 "runtime/debug"
19 "strconv"
20 "strings"
21 "time"
22
23 "github.com/google/uuid"
24 "github.com/klauspost/compress/zstd"
25 "github.com/spf13/pflag"
26 )
27
28 // By default the version information is retrieved from VCS. If not available during build,
29 // override this variable using linker flags to change the displayed version.
30 // Example: `-ldflags "-X main.versionOverride=v1.2.3"`
31 var versionOverride = ""
32
33 func versionInfo() string {
34 version := "(unknown)"
35 if versionOverride != "" {
36 version = versionOverride
37 } else if buildInfo, ok := debug.ReadBuildInfo(); ok {
38 version = buildInfo.Main.Version
39 }
40 return fmt.Sprintf("git-pages-cli %s", version)
41 }
42
43 var passwordFlag = pflag.String("password", "", "use `<password>` for DNS challenge authorization")
44 var passwordFileFlag = pflag.String("password-file", "", "read `<filename>` for DNS challenge authorization")
45 var tokenFlag = pflag.String("token", "", "use `<token>` for forge authorization")
46 var challengeFlag = pflag.Bool("challenge", false, "compute DNS challenge entry from password (output zone file record)")
47 var challengeBareFlag = pflag.Bool("challenge-bare", false, "compute DNS challenge entry from password (output bare TXT value)")
48 var uploadGitFlag = pflag.String("upload-git", "", "replace site with contents of git `<repository>`")
49 var uploadDirFlag = pflag.String("upload-dir", "", "replace whole site or a path with contents of `<directory>`")
50 var deleteFlag = pflag.Bool("delete", false, "delete whole site or a path")
51 var debugManifestFlag = pflag.Bool("debug-manifest", false, "retrieve site manifest as ProtoJSON, for debugging")
52 var serverFlag = pflag.String("server", "", "hostname of server to connect to")
53 var pathFlag = pflag.String("path", "", "upload contents to `<path>` without modifying the rest")
54 var parentsFlag = pflag.Bool("parents", false, "create parent directories of --path")
55 var atomicFlag = pflag.Bool("atomic", false, "require partial updates to be atomic")
56 var incrementalFlag = pflag.Bool("incremental", true, "make --upload-dir only upload changed files")
57 var expiresFlag = pflag.Uint("expires", 0, "schedule site to be expired after `<lifetime>` days")
58 var dryRunFlag = pflag.BoolP("dry-run", "n", false, "only check authorization, don't update")
59 var verboseFlag = pflag.BoolP("verbose", "v", false, "display more information for debugging")
60 var versionFlag = pflag.BoolP("version", "V", false, "display version information")
61
62 func singleOperation() bool {
63 operations := 0
64 if *challengeFlag {
65 operations++
66 }
67 if *challengeBareFlag {
68 operations++
69 }
70 if *uploadDirFlag != "" {
71 operations++
72 }
73 if *uploadGitFlag != "" {
74 operations++
75 }
76 if *deleteFlag {
77 operations++
78 }
79 if *debugManifestFlag {
80 operations++
81 }
82 if *versionFlag {
83 operations++
84 }
85 return operations == 1
86 }
87
88 func gitBlobSHA256(data []byte) string {
89 h := crypto.SHA256.New()
90 h.Write([]byte("blob "))
91 h.Write([]byte(strconv.FormatInt(int64(len(data)), 10)))
92 h.Write([]byte{0})
93 h.Write(data)
94 return hex.EncodeToString(h.Sum(nil))
95 }
96
97 func displayFS(root fs.FS, prefix string) error {
98 return fs.WalkDir(root, ".", func(name string, entry fs.DirEntry, err error) error {
99 if err != nil {
100 return err
101 }
102 switch {
103 case entry.Type().IsDir():
104 fmt.Fprintf(os.Stderr, "dir %s%s\n", prefix, name)
105 case entry.Type().IsRegular():
106 fmt.Fprintf(os.Stderr, "file %s%s\n", prefix, name)
107 case entry.Type() == fs.ModeSymlink:
108 fmt.Fprintf(os.Stderr, "symlink %s%s\n", prefix, name)
109 default:
110 fmt.Fprintf(os.Stderr, "other %s%s\n", prefix, name)
111 }
112 return nil
113 })
114 }
115
116 // It doesn't make sense to use incremental updates for very small files since the cost of
117 // repeating a request to fill in a missing blob is likely to be higher than any savings gained.
118 const incrementalSizeThreshold = 256
119
120 func archiveFS(writer io.Writer, root fs.FS, prefix string, needBlobs []string) (err error) {
121 requestedSet := make(map[string]struct{})
122 for _, hash := range needBlobs {
123 requestedSet[hash] = struct{}{}
124 }
125 zstdWriter, _ := zstd.NewWriter(writer)
126 tarWriter := tar.NewWriter(zstdWriter)
127 if err = fs.WalkDir(root, ".", func(name string, entry fs.DirEntry, err error) error {
128 if err != nil {
129 return err
130 }
131 header := &tar.Header{}
132 data := []byte{}
133 if prefix == "" && name == "." {
134 return nil
135 } else if name == "." {
136 header.Name = prefix
137 } else {
138 header.Name = prefix + name
139 }
140 switch {
141 case entry.Type().IsDir():
142 header.Typeflag = tar.TypeDir
143 header.Name += "/"
144 case entry.Type().IsRegular():
145 header.Typeflag = tar.TypeReg
146 if data, err = fs.ReadFile(root, name); err != nil {
147 return err
148 }
149 if *incrementalFlag && len(data) > incrementalSizeThreshold {
150 hash := gitBlobSHA256(data)
151 if _, requested := requestedSet[hash]; !requested {
152 header.Typeflag = tar.TypeSymlink
153 header.Linkname = "/git/blobs/" + hash
154 data = nil
155 }
156 }
157 case entry.Type() == fs.ModeSymlink:
158 header.Typeflag = tar.TypeSymlink
159 if header.Linkname, err = fs.ReadLink(root, name); err != nil {
160 return err
161 }
162 default:
163 return errors.New("tar: cannot add non-regular file")
164 }
165 header.Size = int64(len(data))
166 if err = tarWriter.WriteHeader(header); err != nil {
167 return err
168 }
169 if _, err = tarWriter.Write(data); err != nil {
170 return err
171 }
172 return err
173 }); err != nil {
174 return
175 }
176 if err = tarWriter.Close(); err != nil {
177 return
178 }
179 if err = zstdWriter.Close(); err != nil {
180 return
181 }
182 return
183 }
184
185 // Stream archive data without ever loading the entire working set into RAM.
186 func streamArchiveFS(root fs.FS, prefix string, needBlobs []string) io.ReadCloser {
187 reader, writer := io.Pipe()
188 go func() {
189 err := archiveFS(writer, root, prefix, needBlobs)
190 if err != nil {
191 writer.CloseWithError(err)
192 } else {
193 writer.Close()
194 }
195 }()
196 return reader
197 }
198
199 func makeWhiteout(path string) (reader io.Reader) {
200 buffer := &bytes.Buffer{}
201 tarWriter := tar.NewWriter(buffer)
202 tarWriter.WriteHeader(&tar.Header{
203 Typeflag: tar.TypeChar,
204 Name: path,
205 })
206 tarWriter.Flush()
207 return buffer
208 }
209
210 const usageExitCode = 125
211
212 func usage() {
213 fmt.Fprintf(os.Stderr,
214 "Usage: %s <site-url> {--challenge|--upload-git url|--upload-dir path|--delete} [options...]\n",
215 os.Args[0],
216 )
217 pflag.PrintDefaults()
218 }
219
220 func main() {
221 pflag.Usage = usage
222 pflag.Parse()
223 if !singleOperation() || (!*versionFlag && len(pflag.Args()) != 1) {
224 pflag.Usage()
225 os.Exit(usageExitCode)
226 }
227
228 if *versionFlag {
229 fmt.Fprintln(os.Stdout, versionInfo())
230 os.Exit(0)
231 }
232
233 if *passwordFlag == "" {
234 *passwordFlag = os.Getenv("GIT_PAGES_PASSWORD")
235 }
236
237 if *tokenFlag == "" {
238 *tokenFlag = os.Getenv("GIT_PAGES_TOKEN")
239 }
240
241 if *passwordFileFlag != "" && *passwordFlag != "" {
242 fmt.Fprintf(os.Stderr, "error: --password-file and --password/$GIT_PAGES_PASSWORD are mutually exclusive\n")
243 os.Exit(usageExitCode)
244 }
245
246 if *passwordFlag != "" && *tokenFlag != "" {
247 fmt.Fprintf(os.Stderr, "error: --password-file/--password/$GIT_PAGES_PASSWORD and --token/$GIT_PAGES_TOKEN are mutually exclusive\n")
248 os.Exit(usageExitCode)
249 }
250
251 if *passwordFileFlag != "" {
252 contents, err := os.ReadFile(*passwordFileFlag)
253 if err != nil {
254 fmt.Fprintf(os.Stderr, "error: invalid password file: %s\n", err)
255 os.Exit(1)
256 }
257 // Trim all trailing newlines; there's no legitimate reason to have one in a password.
258 *passwordFlag = strings.TrimRight(string(contents), "\n")
259 }
260
261 var pathPrefix string
262 if *pathFlag != "" {
263 if *uploadDirFlag == "" && !*deleteFlag {
264 fmt.Fprintf(os.Stderr, "error: --path requires --upload-dir or --delete\n")
265 os.Exit(usageExitCode)
266 } else {
267 pathPrefix = strings.Trim(*pathFlag, "/") + "/"
268 }
269 }
270
271 var expiresAt time.Time
272 if *expiresFlag != 0 {
273 if *uploadDirFlag == "" {
274 fmt.Fprintf(os.Stderr, "error: --expires requires --upload-dir\n")
275 os.Exit(usageExitCode)
276 } else {
277 expiresAt = time.Now().AddDate(0, 0, int(*expiresFlag))
278 }
279 }
280
281 var err error
282 siteURL, err := url.Parse(pflag.Args()[0])
283 if err != nil {
284 fmt.Fprintf(os.Stderr, "error: invalid site URL: %s\n", err)
285 os.Exit(1)
286 }
287
288 var request *http.Request
289 var uploadDir *os.Root
290 switch {
291 case *challengeFlag || *challengeBareFlag:
292 if *passwordFlag == "" {
293 *passwordFlag = uuid.NewString()
294 fmt.Fprintf(os.Stderr, "password: %s\n", *passwordFlag)
295 }
296
297 challenge := sha256.Sum256(fmt.Appendf(nil, "%s %s", siteURL.Hostname(), *passwordFlag))
298 if *challengeBareFlag {
299 fmt.Fprintf(os.Stdout, "%x\n", challenge)
300 } else {
301 fmt.Fprintf(os.Stdout, "_git-pages-challenge.%s. 3600 IN TXT \"%x\"\n", siteURL.Hostname(), challenge)
302 }
303 os.Exit(0)
304
305 case *uploadGitFlag != "":
306 uploadGitUrl, err := url.Parse(*uploadGitFlag)
307 if err != nil {
308 fmt.Fprintf(os.Stderr, "error: invalid repository URL: %s\n", err)
309 os.Exit(1)
310 }
311
312 requestBody := []byte(uploadGitUrl.String())
313 request, err = http.NewRequest("PUT", siteURL.String(), bytes.NewReader(requestBody))
314 if err != nil {
315 fmt.Fprintf(os.Stderr, "error: %s\n", err)
316 os.Exit(1)
317 }
318 request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
319 if !expiresAt.IsZero() {
320 request.Header.Add("Expires", expiresAt.Format(http.TimeFormat))
321 }
322
323 case *uploadDirFlag != "":
324 uploadDir, err = os.OpenRoot(*uploadDirFlag)
325 if err != nil {
326 fmt.Fprintf(os.Stderr, "error: invalid directory: %s\n", err)
327 os.Exit(1)
328 }
329
330 if *verboseFlag {
331 err := displayFS(uploadDir.FS(), pathPrefix)
332 if err != nil {
333 fmt.Fprintf(os.Stderr, "error: %s\n", err)
334 os.Exit(1)
335 }
336 }
337
338 if *pathFlag == "" {
339 request, err = http.NewRequest("PUT", siteURL.String(), nil)
340 } else {
341 request, err = http.NewRequest("PATCH", siteURL.String(), nil)
342 }
343 if err != nil {
344 fmt.Fprintf(os.Stderr, "error: %s\n", err)
345 os.Exit(1)
346 }
347 if *pathFlag != "" {
348 if *parentsFlag {
349 request.Header.Add("Create-Parents", "yes")
350 } else {
351 request.Header.Add("Create-Parents", "no")
352 }
353 }
354 if !expiresAt.IsZero() {
355 request.Header.Add("Expires", expiresAt.Format(http.TimeFormat))
356 }
357 request.GetBody = func() (io.ReadCloser, error) {
358 return streamArchiveFS(uploadDir.FS(), pathPrefix, []string{}), nil
359 }
360 request.Body, _ = request.GetBody()
361 request.ContentLength = -1
362 request.Header.Add("Content-Type", "application/x-tar+zstd")
363 request.Header.Add("Accept", "application/vnd.git-pages.unresolved;q=1.0, text/plain;q=0.9")
364
365 case *deleteFlag:
366 if *pathFlag == "" {
367 request, err = http.NewRequest("DELETE", siteURL.String(), nil)
368 if err != nil {
369 fmt.Fprintf(os.Stderr, "error: %s\n", err)
370 os.Exit(1)
371 }
372 } else {
373 request, err = http.NewRequest("PATCH", siteURL.String(), makeWhiteout(pathPrefix))
374 if err != nil {
375 fmt.Fprintf(os.Stderr, "error: %s\n", err)
376 os.Exit(1)
377 }
378 request.Header.Add("Content-Type", "application/x-tar")
379 }
380
381 case *debugManifestFlag:
382 manifestURL := siteURL.JoinPath(".git-pages/manifest.json")
383 request, err = http.NewRequest("GET", manifestURL.String(), nil)
384 if err != nil {
385 fmt.Fprintf(os.Stderr, "error: %s\n", err)
386 os.Exit(1)
387 }
388
389 default:
390 panic("no operation chosen")
391 }
392 request.Header.Add("User-Agent", versionInfo())
393 if request.Method == "PATCH" {
394 if *atomicFlag {
395 request.Header.Add("Atomic", "yes")
396 } else {
397 request.Header.Add("Atomic", "no")
398 }
399 }
400 makeAuthorization := func(headerName string, kind string, value string) {
401 if strings.ContainsAny(value, "\r\n") {
402 fmt.Fprintf(os.Stderr, "error: invalid characters in %s header value: %q\n",
403 headerName, value)
404 os.Exit(1)
405 }
406 request.Header.Add(headerName, fmt.Sprintf("%s %s", kind, value))
407 }
408 switch {
409 case *passwordFlag != "":
410 makeAuthorization("Authorization", "Pages", *passwordFlag)
411 case *tokenFlag != "":
412 makeAuthorization("Forge-Authorization", "token", *tokenFlag)
413 }
414 if *dryRunFlag {
415 request.Header.Add("Dry-Run", "yes")
416 }
417 if *serverFlag != "" {
418 // Send the request to `--server` host, but set the `Host:` header to the site host.
419 // This allows first-time publishing to proceed without the git-pages server yet having
420 // a TLS certificate for the site host (which has a circular dependency on completion of
421 // first-time publishing).
422 newURL := *request.URL
423 newURL.Host = *serverFlag
424 request.URL = &newURL
425 request.Header.Set("Host", siteURL.Host)
426 }
427
428 // HTTP-to-HTTPS redirects are often implemented with 301 or 302 response codes which instruct
429 // the Go HTTP client to disregard the original request method and use GET instead. To prevent
430 // confusion, detect such redirects and preserve the original request method and body.
431 http.DefaultClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
432 last := via[len(via)-1]
433 newURL := req.URL.JoinPath()
434 lastURL := last.URL.JoinPath()
435 if lastURL.Scheme == "http" && newURL.Scheme == "https" {
436 lastURL.Scheme = newURL.Scheme
437 if lastURL.String() == newURL.String() {
438 req.Method = last.Method
439 req.Body, _ = last.GetBody()
440 req.Header.Set("Content-Type", last.Header.Get("Content-Type"))
441 return nil
442 }
443 }
444 if req.Method != last.Method {
445 return fmt.Errorf("unexpected redirect")
446 }
447 return nil
448 }
449
450 displayServer := *verboseFlag
451 for {
452 response, err := http.DefaultClient.Do(request)
453 if err != nil {
454 if response != nil && (response.StatusCode == 301 || response.StatusCode == 302) {
455 if innerErr := errors.Unwrap(err); innerErr != nil {
456 // If the error is due to a redirect, that means it wasn't followed, but the
457 // original url.Error confusingly reports the new URL anyway.
458 err = innerErr
459 }
460 }
461 fmt.Fprintf(os.Stderr, "error: %s\n", err)
462 os.Exit(1)
463 }
464 serverValues := response.Header.Values("Server")
465 // Cloudflare &co love to insert themselves into the `Server:` header without a way to
466 // override it. They shouldn't, but this is a losing battle, so provide a workaround for
467 // people stuck behind it.
468 serverValues = append(serverValues, response.Header.Values("X-Server")...)
469 serverIdent := strings.Join(serverValues, ", ")
470 //lint:ignore SA6000 This isn't a hot loop.
471 if matched, err := regexp.MatchString(`\bgit-pages\b`, serverIdent); err != nil {
472 panic(err)
473 } else if !matched {
474 message := fmt.Sprintf(
475 "the tool only works with git-pages, but the URL points to a %q server",
476 serverIdent)
477 if request.Method != "GET" {
478 fmt.Fprintf(os.Stderr, "error: %s\n", message)
479 os.Exit(1)
480 }
481 fmt.Fprintf(os.Stderr, "warning: %s\n", message)
482 }
483 if displayServer {
484 fmt.Fprintf(os.Stderr, "server: %s\n", serverIdent)
485 displayServer = false
486 }
487 if *debugManifestFlag {
488 if response.StatusCode == http.StatusOK {
489 io.Copy(os.Stdout, response.Body)
490 fmt.Fprintf(os.Stdout, "\n")
491 } else {
492 io.Copy(os.Stderr, response.Body)
493 os.Exit(1)
494 }
495 } else { // an update operation
496 if *verboseFlag {
497 fmt.Fprintf(os.Stderr, "response: %d %s\n",
498 response.StatusCode, response.Header.Get("Content-Type"))
499 }
500 if response.StatusCode == http.StatusUnprocessableEntity &&
501 response.Header.Get("Content-Type") == "application/vnd.git-pages.unresolved" {
502 needBlobs := []string{}
503 scanner := bufio.NewScanner(response.Body)
504 for scanner.Scan() {
505 needBlobs = append(needBlobs, scanner.Text())
506 }
507 response.Body.Close()
508 if *verboseFlag {
509 fmt.Fprintf(os.Stderr, "incremental: need %d blobs\n", len(needBlobs))
510 }
511 request.GetBody = func() (io.ReadCloser, error) {
512 return streamArchiveFS(uploadDir.FS(), pathPrefix, needBlobs), nil
513 }
514 request.Body, _ = request.GetBody()
515 continue // resubmit
516 } else if response.StatusCode == http.StatusOK {
517 fmt.Fprintf(os.Stdout, "result: %s\n", response.Header.Get("Update-Result"))
518 io.Copy(os.Stdout, response.Body)
519 } else {
520 fmt.Fprintf(os.Stderr, "result: error\n")
521 io.Copy(os.Stderr, response.Body)
522 os.Exit(1)
523 }
524 }
525 break
526 }
527 }