1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// godoc: Go Documentation Server
6
7// Web server tree:
8//
9//	http://godoc/		redirect to /pkg/
10//	http://godoc/src/	serve files from $GOROOT/src; .go gets pretty-printed
11//	http://godoc/cmd/	serve documentation about commands
12//	http://godoc/pkg/	serve documentation about packages
13//				(idea is if you say import "compress/zlib", you go to
14//				http://godoc/pkg/compress/zlib)
15//
16
17package main
18
19import (
20	"archive/zip"
21	"bytes"
22	"context"
23	"encoding/json"
24	_ "expvar" // to serve /debug/vars
25	"flag"
26	"fmt"
27	"go/build"
28	"io"
29	"log"
30	"net/http"
31	_ "net/http/pprof" // to serve /debug/pprof/*
32	"net/url"
33	"os"
34	"os/exec"
35	"path"
36	"path/filepath"
37	"regexp"
38	"runtime"
39	"strings"
40
41	"golang.org/x/tools/godoc"
42	"golang.org/x/tools/godoc/analysis"
43	"golang.org/x/tools/godoc/static"
44	"golang.org/x/tools/godoc/vfs"
45	"golang.org/x/tools/godoc/vfs/gatefs"
46	"golang.org/x/tools/godoc/vfs/mapfs"
47	"golang.org/x/tools/godoc/vfs/zipfs"
48	"golang.org/x/tools/internal/gocommand"
49	"golang.org/x/xerrors"
50)
51
52const defaultAddr = "localhost:6060" // default webserver address
53
54var (
55	// file system to serve
56	// (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico)
57	zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty")
58
59	// file-based index
60	writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files")
61
62	analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform when in GOPATH mode (supported: type, pointer). See https://golang.org/lib/godoc/analysis/help.html`)
63
64	// network
65	httpAddr = flag.String("http", defaultAddr, "HTTP service address")
66
67	// layout control
68	urlFlag = flag.String("url", "", "print HTML for named URL")
69
70	verbose = flag.Bool("v", false, "verbose mode")
71
72	// file system roots
73	// TODO(gri) consider the invariant that goroot always end in '/'
74	goroot = flag.String("goroot", findGOROOT(), "Go root directory")
75
76	// layout control
77	showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings")
78	templateDir    = flag.String("templates", "", "load templates/JS/CSS from disk in this directory")
79	showPlayground = flag.Bool("play", false, "enable playground")
80	declLinks      = flag.Bool("links", true, "link identifiers to their declarations")
81
82	// search index
83	indexEnabled  = flag.Bool("index", false, "enable search index")
84	indexFiles    = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order")
85	indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup")
86	maxResults    = flag.Int("maxresults", 10000, "maximum number of full text search results shown")
87	indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle")
88
89	// source code notes
90	notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show")
91)
92
93// An httpResponseRecorder is an http.ResponseWriter
94type httpResponseRecorder struct {
95	body   *bytes.Buffer
96	header http.Header
97	code   int
98}
99
100func (w *httpResponseRecorder) Header() http.Header         { return w.header }
101func (w *httpResponseRecorder) Write(b []byte) (int, error) { return w.body.Write(b) }
102func (w *httpResponseRecorder) WriteHeader(code int)        { w.code = code }
103
104func usage() {
105	fmt.Fprintf(os.Stderr, "usage: godoc -http="+defaultAddr+"\n")
106	flag.PrintDefaults()
107	os.Exit(2)
108}
109
110func loggingHandler(h http.Handler) http.Handler {
111	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
112		log.Printf("%s\t%s", req.RemoteAddr, req.URL)
113		h.ServeHTTP(w, req)
114	})
115}
116
117func handleURLFlag() {
118	// Try up to 10 fetches, following redirects.
119	urlstr := *urlFlag
120	for i := 0; i < 10; i++ {
121		// Prepare request.
122		u, err := url.Parse(urlstr)
123		if err != nil {
124			log.Fatal(err)
125		}
126		req := &http.Request{
127			URL: u,
128		}
129
130		// Invoke default HTTP handler to serve request
131		// to our buffering httpWriter.
132		w := &httpResponseRecorder{code: 200, header: make(http.Header), body: new(bytes.Buffer)}
133		http.DefaultServeMux.ServeHTTP(w, req)
134
135		// Return data, error, or follow redirect.
136		switch w.code {
137		case 200: // ok
138			os.Stdout.Write(w.body.Bytes())
139			return
140		case 301, 302, 303, 307: // redirect
141			redirect := w.header.Get("Location")
142			if redirect == "" {
143				log.Fatalf("HTTP %d without Location header", w.code)
144			}
145			urlstr = redirect
146		default:
147			log.Fatalf("HTTP error %d", w.code)
148		}
149	}
150	log.Fatalf("too many redirects")
151}
152
153func initCorpus(corpus *godoc.Corpus) {
154	err := corpus.Init()
155	if err != nil {
156		log.Fatal(err)
157	}
158}
159
160func main() {
161	flag.Usage = usage
162	flag.Parse()
163
164	// Check usage.
165	if flag.NArg() > 0 {
166		fmt.Fprintln(os.Stderr, `Unexpected arguments. Use "go doc" for command-line help output instead. For example, "go doc fmt.Printf".`)
167		usage()
168	}
169	if *httpAddr == "" && *urlFlag == "" && !*writeIndex {
170		fmt.Fprintln(os.Stderr, "At least one of -http, -url, or -write_index must be set to a non-zero value.")
171		usage()
172	}
173
174	// Set the resolved goroot.
175	vfs.GOROOT = *goroot
176
177	fsGate := make(chan bool, 20)
178
179	// Determine file system to use.
180	if *zipfile == "" {
181		// use file system of underlying OS
182		rootfs := gatefs.New(vfs.OS(*goroot), fsGate)
183		fs.Bind("/", rootfs, "/", vfs.BindReplace)
184	} else {
185		// use file system specified via .zip file (path separator must be '/')
186		rc, err := zip.OpenReader(*zipfile)
187		if err != nil {
188			log.Fatalf("%s: %s\n", *zipfile, err)
189		}
190		defer rc.Close() // be nice (e.g., -writeIndex mode)
191		fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace)
192	}
193	if *templateDir != "" {
194		fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore)
195	} else {
196		fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace)
197	}
198
199	// Get the GOMOD value, use it to determine if godoc is being invoked in module mode.
200	goModFile, err := goMod()
201	if err != nil {
202		fmt.Fprintf(os.Stderr, "failed to determine go env GOMOD value: %v", err)
203		goModFile = "" // Fall back to GOPATH mode.
204	}
205
206	if goModFile != "" {
207		fmt.Printf("using module mode; GOMOD=%s\n", goModFile)
208
209		if *analysisFlag != "" {
210			fmt.Fprintln(os.Stderr, "The -analysis flag is supported only in GOPATH mode at this time.")
211			fmt.Fprintln(os.Stderr, "See https://golang.org/issue/34473.")
212			usage()
213		}
214
215		// Detect whether to use vendor mode or not.
216		mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.Background(), gocommand.Invocation{}, &gocommand.Runner{})
217		if err != nil {
218			fmt.Fprintf(os.Stderr, "failed to determine if vendoring is enabled: %v", err)
219			os.Exit(1)
220		}
221		if vendorEnabled {
222			// Bind the root directory of the main module.
223			fs.Bind(path.Join("/src", mainMod.Path), gatefs.New(vfs.OS(mainMod.Dir), fsGate), "/", vfs.BindAfter)
224
225			// Bind the vendor directory.
226			//
227			// Note that in module mode, vendor directories in locations
228			// other than the main module's root directory are ignored.
229			// See https://golang.org/ref/mod#vendoring.
230			vendorDir := filepath.Join(mainMod.Dir, "vendor")
231			fs.Bind("/src", gatefs.New(vfs.OS(vendorDir), fsGate), "/", vfs.BindAfter)
232
233		} else {
234			// Try to download dependencies that are not in the module cache in order to
235			// to show their documentation.
236			// This may fail if module downloading is disallowed (GOPROXY=off) or due to
237			// limited connectivity, in which case we print errors to stderr and show
238			// documentation only for packages that are available.
239			fillModuleCache(os.Stderr, goModFile)
240
241			// Determine modules in the build list.
242			mods, err := buildList(goModFile)
243			if err != nil {
244				fmt.Fprintf(os.Stderr, "failed to determine the build list of the main module: %v", err)
245				os.Exit(1)
246			}
247
248			// Bind module trees into Go root.
249			for _, m := range mods {
250				if m.Dir == "" {
251					// Module is not available in the module cache, skip it.
252					continue
253				}
254				dst := path.Join("/src", m.Path)
255				fs.Bind(dst, gatefs.New(vfs.OS(m.Dir), fsGate), "/", vfs.BindAfter)
256			}
257		}
258	} else {
259		fmt.Println("using GOPATH mode")
260
261		// Bind $GOPATH trees into Go root.
262		for _, p := range filepath.SplitList(build.Default.GOPATH) {
263			fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter)
264		}
265	}
266
267	var typeAnalysis, pointerAnalysis bool
268	if *analysisFlag != "" {
269		for _, a := range strings.Split(*analysisFlag, ",") {
270			switch a {
271			case "type":
272				typeAnalysis = true
273			case "pointer":
274				pointerAnalysis = true
275			default:
276				log.Fatalf("unknown analysis: %s", a)
277			}
278		}
279	}
280
281	var corpus *godoc.Corpus
282	if goModFile != "" {
283		corpus = godoc.NewCorpus(moduleFS{fs})
284	} else {
285		corpus = godoc.NewCorpus(fs)
286	}
287	corpus.Verbose = *verbose
288	corpus.MaxResults = *maxResults
289	corpus.IndexEnabled = *indexEnabled
290	if *maxResults == 0 {
291		corpus.IndexFullText = false
292	}
293	corpus.IndexFiles = *indexFiles
294	corpus.IndexDirectory = func(dir string) bool {
295		return dir != "/pkg" && !strings.HasPrefix(dir, "/pkg/")
296	}
297	corpus.IndexThrottle = *indexThrottle
298	corpus.IndexInterval = *indexInterval
299	if *writeIndex || *urlFlag != "" {
300		corpus.IndexThrottle = 1.0
301		corpus.IndexEnabled = true
302		initCorpus(corpus)
303	} else {
304		go initCorpus(corpus)
305	}
306
307	// Initialize the version info before readTemplates, which saves
308	// the map value in a method value.
309	corpus.InitVersionInfo()
310
311	pres = godoc.NewPresentation(corpus)
312	pres.ShowTimestamps = *showTimestamps
313	pres.ShowPlayground = *showPlayground
314	pres.DeclLinks = *declLinks
315	if *notesRx != "" {
316		pres.NotesRx = regexp.MustCompile(*notesRx)
317	}
318
319	readTemplates(pres)
320	registerHandlers(pres)
321
322	if *writeIndex {
323		// Write search index and exit.
324		if *indexFiles == "" {
325			log.Fatal("no index file specified")
326		}
327
328		log.Println("initialize file systems")
329		*verbose = true // want to see what happens
330
331		corpus.UpdateIndex()
332
333		log.Println("writing index file", *indexFiles)
334		f, err := os.Create(*indexFiles)
335		if err != nil {
336			log.Fatal(err)
337		}
338		index, _ := corpus.CurrentIndex()
339		_, err = index.WriteTo(f)
340		if err != nil {
341			log.Fatal(err)
342		}
343
344		log.Println("done")
345		return
346	}
347
348	// Print content that would be served at the URL *urlFlag.
349	if *urlFlag != "" {
350		handleURLFlag()
351		return
352	}
353
354	var handler http.Handler = http.DefaultServeMux
355	if *verbose {
356		log.Printf("Go Documentation Server")
357		log.Printf("version = %s", runtime.Version())
358		log.Printf("address = %s", *httpAddr)
359		log.Printf("goroot = %s", *goroot)
360		switch {
361		case !*indexEnabled:
362			log.Print("search index disabled")
363		case *maxResults > 0:
364			log.Printf("full text index enabled (maxresults = %d)", *maxResults)
365		default:
366			log.Print("identifier search index enabled")
367		}
368		fs.Fprint(os.Stderr)
369		handler = loggingHandler(handler)
370	}
371
372	// Initialize search index.
373	if *indexEnabled {
374		go corpus.RunIndexer()
375	}
376
377	// Start type/pointer analysis.
378	if typeAnalysis || pointerAnalysis {
379		go analysis.Run(pointerAnalysis, &corpus.Analysis)
380	}
381
382	// Start http server.
383	if *verbose {
384		log.Println("starting HTTP server")
385	}
386	if err := http.ListenAndServe(*httpAddr, handler); err != nil {
387		log.Fatalf("ListenAndServe %s: %v", *httpAddr, err)
388	}
389}
390
391// goMod returns the go env GOMOD value in the current directory
392// by invoking the go command.
393//
394// GOMOD is documented at https://golang.org/cmd/go/#hdr-Environment_variables:
395//
396// 	The absolute path to the go.mod of the main module,
397// 	or the empty string if not using modules.
398//
399func goMod() (string, error) {
400	out, err := exec.Command("go", "env", "-json", "GOMOD").Output()
401	if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) {
402		return "", fmt.Errorf("go command exited unsuccessfully: %v\n%s", ee.ProcessState.String(), ee.Stderr)
403	} else if err != nil {
404		return "", err
405	}
406	var env struct {
407		GoMod string
408	}
409	err = json.Unmarshal(out, &env)
410	if err != nil {
411		return "", err
412	}
413	return env.GoMod, nil
414}
415
416// fillModuleCache does a best-effort attempt to fill the module cache
417// with all dependencies of the main module in the current directory
418// by invoking the go command. Module download logs are streamed to w.
419// If there are any problems encountered, they are also written to w.
420// It should only be used in module mode, when vendor mode isn't on.
421//
422// See https://golang.org/cmd/go/#hdr-Download_modules_to_local_cache.
423func fillModuleCache(w io.Writer, goMod string) {
424	if goMod == os.DevNull {
425		// No module requirements, nothing to do.
426		return
427	}
428
429	cmd := exec.Command("go", "mod", "download", "-json")
430	var out bytes.Buffer
431	cmd.Stdout = &out
432	cmd.Stderr = w
433	err := cmd.Run()
434	if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) && ee.ExitCode() == 1 {
435		// Exit code 1 from this command means there were some
436		// non-empty Error values in the output. Print them to w.
437		fmt.Fprintf(w, "documentation for some packages is not shown:\n")
438		for dec := json.NewDecoder(&out); ; {
439			var m struct {
440				Path    string // Module path.
441				Version string // Module version.
442				Error   string // Error loading module.
443			}
444			err := dec.Decode(&m)
445			if err == io.EOF {
446				break
447			} else if err != nil {
448				fmt.Fprintf(w, "error decoding JSON object from go mod download -json: %v\n", err)
449				continue
450			}
451			if m.Error == "" {
452				continue
453			}
454			fmt.Fprintf(w, "\tmodule %s@%s is not in the module cache and there was a problem downloading it: %s\n", m.Path, m.Version, m.Error)
455		}
456	} else if err != nil {
457		fmt.Fprintf(w, "there was a problem filling module cache: %v\n", err)
458	}
459}
460
461type mod struct {
462	Path string // Module path.
463	Dir  string // Directory holding files for this module, if any.
464}
465
466// buildList determines the build list in the current directory
467// by invoking the go command. It should only be used in module mode,
468// when vendor mode isn't on.
469//
470// See https://golang.org/cmd/go/#hdr-The_main_module_and_the_build_list.
471func buildList(goMod string) ([]mod, error) {
472	if goMod == os.DevNull {
473		// Empty build list.
474		return nil, nil
475	}
476
477	out, err := exec.Command("go", "list", "-m", "-json", "all").Output()
478	if ee := (*exec.ExitError)(nil); xerrors.As(err, &ee) {
479		return nil, fmt.Errorf("go command exited unsuccessfully: %v\n%s", ee.ProcessState.String(), ee.Stderr)
480	} else if err != nil {
481		return nil, err
482	}
483	var mods []mod
484	for dec := json.NewDecoder(bytes.NewReader(out)); ; {
485		var m mod
486		err := dec.Decode(&m)
487		if err == io.EOF {
488			break
489		} else if err != nil {
490			return nil, err
491		}
492		mods = append(mods, m)
493	}
494	return mods, nil
495}
496
497// moduleFS is a vfs.FileSystem wrapper used when godoc is running
498// in module mode. It's needed so that packages inside modules are
499// considered to be third party.
500//
501// It overrides the RootType method of the underlying filesystem
502// and implements it using a heuristic based on the import path.
503// If the first element of the import path does not contain a dot,
504// that package is considered to be inside GOROOT. If it contains
505// a dot, then that package is considered to be third party.
506//
507// TODO(dmitshur): The RootType abstraction works well when GOPATH
508// workspaces are bound at their roots, but scales poorly in the
509// general case. It should be replaced by a more direct solution
510// for determining whether a package is third party or not.
511//
512type moduleFS struct{ vfs.FileSystem }
513
514func (moduleFS) RootType(path string) vfs.RootType {
515	if !strings.HasPrefix(path, "/src/") {
516		return ""
517	}
518	domain := path[len("/src/"):]
519	if i := strings.Index(domain, "/"); i >= 0 {
520		domain = domain[:i]
521	}
522	if !strings.Contains(domain, ".") {
523		// No dot in the first element of import path
524		// suggests this is a package in GOROOT.
525		return vfs.RootTypeGoRoot
526	} else {
527		// A dot in the first element of import path
528		// suggests this is a third party package.
529		return vfs.RootTypeGoPath
530	}
531}
532func (fs moduleFS) String() string { return "module(" + fs.FileSystem.String() + ")" }
533