Debian Codegraph @

gopls/internal/server/server.go

raw symbols SCIP
1 // Copyright 2018 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 // Package server defines gopls' implementation of the LSP server
6 // interface, [protocol.Server]. Call [New] to create an instance.
7 package server
8
9 import (
10 "context"
11 "crypto/rand"
12 "embed"
13 "encoding/base64"
14 "fmt"
15 "io"
16 "io/fs"
17 "log"
18 "net"
19 "net/http"
20 "net/url"
21 "os"
22 paths "path"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27
28 "golang.org/x/tools/gopls/internal/cache"
29 "golang.org/x/tools/gopls/internal/cache/metadata"
30 "golang.org/x/tools/gopls/internal/filewatcher"
31 "golang.org/x/tools/gopls/internal/golang"
32 "golang.org/x/tools/gopls/internal/golang/splitpkg"
33 "golang.org/x/tools/gopls/internal/progress"
34 "golang.org/x/tools/gopls/internal/protocol"
35 "golang.org/x/tools/gopls/internal/settings"
36 "golang.org/x/tools/gopls/internal/util/bug"
37 "golang.org/x/tools/internal/event"
38 )
39
40 // New creates an LSP server and binds it to handle incoming client
41 // messages on the supplied stream.
42 func New(session *cache.Session, client protocol.ClientCloser, options *settings.Options) protocol.Server {
43 const concurrentAnalyses = 1
44 // If this assignment fails to compile after a protocol
45 // upgrade, it means that one or more new methods need new
46 // stub declarations in unimplemented.go.
47 return &server{
48 diagnostics: make(map[protocol.DocumentURI]*fileDiagnostics),
49 watchedGlobPatterns: nil, // empty
50 changedFiles: make(map[protocol.DocumentURI]unit),
51 session: session,
52 client: client,
53 diagnosticsSema: make(chan unit, concurrentAnalyses),
54 progress: progress.NewTracker(client),
55 options: options,
56 viewsToDiagnose: make(map[*cache.View]uint64),
57 }
58 }
59
60 type serverState int
61
62 const (
63 serverCreated = serverState(iota)
64 serverInitializing // set once the server has received "initialize" request
65 serverInitialized // set once the server has received "initialized" request
66 serverShutDown
67 )
68
69 func (s serverState) String() string {
70 switch s {
71 case serverCreated:
72 return "created"
73 case serverInitializing:
74 return "initializing"
75 case serverInitialized:
76 return "initialized"
77 case serverShutDown:
78 return "shutDown"
79 }
80 return fmt.Sprintf("(unknown state: %d)", int(s))
81 }
82
83 // server implements the [protocol.Server] interface.
84 //
85 // A server holds the server-side state of a single client/server
86 // session or connection; it conceptually corresponds to a single call
87 // to accept(2), not to listen(2) as the name "server" might suggest.
88 type server struct {
89 client protocol.ClientCloser
90
91 stateMu sync.Mutex
92 state serverState
93 // notifications generated before serverInitialized
94 notifications []*protocol.ShowMessageParams
95
96 session *cache.Session
97
98 // changedFiles tracks files for which there has been a textDocument/didChange.
99 changedFilesMu sync.Mutex
100 changedFiles map[protocol.DocumentURI]unit
101
102 // folders is only valid between initialize and initialized, and holds the
103 // set of folders to build views for when we are ready.
104 // Only the valid, non-empty 'file'-scheme URIs will be added.
105 pendingFolders []protocol.WorkspaceFolder
106
107 // watchedGlobPatterns is the set of glob patterns that we have requested
108 // the client watch on disk. It will be updated as the set of directories
109 // that the server should watch changes.
110 // The map field may be reassigned but the map is immutable.
111 watchedGlobPatternsMu sync.Mutex
112 watchedGlobPatterns map[protocol.RelativePattern]unit
113 watchRegistrationCount int
114
115 fileWatcherMu sync.Mutex
116 fileWatcher filewatcher.Watcher
117
118 diagnosticsMu sync.Mutex // guards map and its values
119 diagnostics map[protocol.DocumentURI]*fileDiagnostics
120
121 // diagnosticsSema limits the concurrency of diagnostics runs, which can be
122 // expensive.
123 diagnosticsSema chan unit
124
125 progress *progress.Tracker
126
127 // When the workspace fails to load, we show its status through a progress
128 // report with an error message.
129 criticalErrorStatusMu sync.Mutex
130 criticalErrorStatus *progress.WorkDone
131
132 // Track an ongoing CPU profile created with the StartProfile command and
133 // terminated with the StopProfile command.
134 ongoingProfileMu sync.Mutex
135 ongoingProfile *os.File // if non-nil, an ongoing profile is writing to this file
136
137 // Track most recently requested options.
138 optionsMu sync.Mutex
139 options *settings.Options
140
141 // Track the most recent completion results, for measuring completion efficacy
142 efficacyMu sync.Mutex
143 efficacyURI protocol.DocumentURI
144 efficacyVersion int32
145 efficacyItems []protocol.CompletionItem
146 efficacyPos protocol.Position
147
148 // Web server (for package documentation, etc) associated with this
149 // LSP server. Opened on demand, and closed during LSP Shutdown.
150 webOnce sync.Once
151 web *web
152 webErr error
153
154 // # Modification tracking and diagnostics
155 //
156 // For the purpose of tracking diagnostics, we need a monotonically
157 // increasing clock. Each time a change occurs on the server, this clock is
158 // incremented and the previous diagnostics pass is cancelled. When the
159 // changed is processed, the Session (via DidModifyFiles) determines which
160 // Views are affected by the change and these views are added to the
161 // viewsToDiagnose set. Then the server calls diagnoseChangedViews
162 // in a separate goroutine. Any Views that successfully complete their
163 // diagnostics are removed from the viewsToDiagnose set, provided they haven't
164 // been subsequently marked for re-diagnosis (as determined by the latest
165 // modificationID referenced by viewsToDiagnose).
166 //
167 // In this way, we enforce eventual completeness of the diagnostic set: any
168 // views requiring diagnosis are diagnosed, though possibly at a later point
169 // in time. Notably, the logic in Session.DidModifyFiles to determines if a
170 // view needs diagnosis considers whether any packages in the view were
171 // invalidated. Consider the following sequence of snapshots for a given view
172 // V:
173 //
174 // C1 C2
175 // S1 -> S2 -> S3
176 //
177 // In this case, suppose that S1 was fully type checked, and then two changes
178 // C1 and C2 occur in rapid succession, to a file in their package graph but
179 // perhaps not enclosed by V's root. In this case, the logic of
180 // DidModifyFiles will detect that V needs to be reloaded following C1. In
181 // order for our eventual consistency to be sound, we need to avoid the race
182 // where S2 is being diagnosed, C2 arrives, and S3 is not detected as needing
183 // diagnosis because the relevant package has not yet been computed in S2. To
184 // achieve this, we only remove V from viewsToDiagnose if the diagnosis of S2
185 // completes before C2 is processed, which we can confirm by checking
186 // S2.BackgroundContext().
187 modificationMu sync.Mutex
188 cancelPrevDiagnostics func()
189 viewsToDiagnose map[*cache.View]uint64 // View -> modification at which it last required diagnosis
190 lastModificationID uint64 // incrementing clock
191
192 runGovulncheckInProgress atomic.Bool
193 }
194
195 func (s *server) WorkDoneProgressCancel(ctx context.Context, params *protocol.WorkDoneProgressCancelParams) error {
196 ctx, done := event.Start(ctx, "server.WorkDoneProgressCancel")
197 defer done()
198
199 return s.progress.Cancel(params.Token)
200 }
201
202 // web encapsulates the web server associated with an LSP server.
203 // It is used for package documentation and other queries
204 // where HTML makes more sense than a client editor UI.
205 //
206 // Example URL:
207 //
208 // http://127.0.0.1:PORT/gopls/SECRET/...
209 //
210 // where
211 // - PORT is the random port number;
212 // - "gopls" helps the reader guess which program is the server;
213 // - SECRET is the 64-bit token; and
214 // - ... is the material part of the endpoint.
215 //
216 // Valid endpoints:
217 //
218 // open?file=%s&line=%d&col=%d - open a file
219 // pkg/PKGPATH?view=%s - show doc for package in a given view
220 // assembly?pkg=%s&view=%s&symbol=%s - show assembly of specified func symbol
221 // freesymbols?file=%s&range=%d:%d:%d:%d:&view=%s - show report of free symbols
222 // splitpkg?pkg=%s&view=%s - show "split package" HTML for given package/view
223 // splitpkg-json?pkg=%s&view=%s - query component dependency graph for given package/view
224 // splitpkg-components?pkg=%s&view=%s - update component definitions for given package/view
225 type web struct {
226 server *http.Server
227 addr url.URL // "http://127.0.0.1:PORT/gopls/SECRET"
228 mux *http.ServeMux
229 }
230
231 // getWeb returns the web server associated with this
232 // LSP server, creating it on first request.
233 func (s *server) getWeb() (*web, error) {
234 s.webOnce.Do(func() {
235 s.web, s.webErr = s.initWeb()
236 })
237 return s.web, s.webErr
238 }
239
240 // initWeb starts the local web server through which gopls
241 // serves package documentation and suchlike.
242 //
243 // Clients should use [getWeb].
244 func (s *server) initWeb() (*web, error) {
245 // Use 64 random bits as the base of the URL namespace.
246 // This ensures that URLs are unguessable to any local
247 // processes that connect to the server, preventing
248 // exfiltration of source code.
249 //
250 // (Note: depending on the LSP client, URLs that are passed to
251 // it via showDocument and that result in the opening of a
252 // browser tab may be transiently published through the argv
253 // array of the open(1) or xdg-open(1) command.)
254 token := make([]byte, 8)
255 if _, err := rand.Read(token); err != nil {
256 return nil, fmt.Errorf("generating secret token: %v", err)
257 }
258
259 // Pick any free port.
260 listener, err := net.Listen("tcp", "127.0.0.1:0")
261 if err != nil {
262 return nil, err
263 }
264
265 // -- There should be no early returns after this point. --
266
267 // The root mux is not authenticated.
268 rootMux := http.NewServeMux()
269 rootMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
270 http.Error(w, "request URI lacks authentication segment", http.StatusUnauthorized)
271 })
272 rootMux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, req *http.Request) {
273 http.Redirect(w, req, "/assets/favicon.ico", http.StatusMovedPermanently)
274 })
275 rootMux.HandleFunc("/hang", func(w http.ResponseWriter, req *http.Request) {
276 // This endpoint hangs until cancelled.
277 // It is used by JS to detect server disconnect.
278 <-req.Context().Done()
279 })
280
281 // Serve assets (JS, PNG, etc) from embedded data,
282 // except during local development.
283 fs := fs.FS(assets)
284 // fs = os.DirFS("/Users/adonovan/w/xtools/gopls/internal/server") // uncomment during development
285 rootMux.Handle("/assets/", http.FileServer(http.FS(fs)))
286
287 secret := "/gopls/" + base64.RawURLEncoding.EncodeToString(token)
288 webMux := http.NewServeMux()
289 rootMux.Handle(secret+"/", withPanicHandler(http.StripPrefix(secret, webMux)))
290
291 webServer := &http.Server{Addr: listener.Addr().String(), Handler: rootMux}
292 go func() {
293 // This should run until LSP Shutdown, at which point
294 // it will return ErrServerClosed. Any other error
295 // means it failed to start.
296 if err := webServer.Serve(listener); err != nil {
297 if err != http.ErrServerClosed {
298 log.Print(err)
299 }
300 }
301 }()
302
303 web := &web{
304 server: webServer,
305 addr: url.URL{Scheme: "http", Host: webServer.Addr, Path: secret},
306 mux: webMux,
307 }
308
309 // The /src handler allows the browser to request that the
310 // LSP client editor open a file; see web.SrcURL.
311 webMux.HandleFunc("/src", func(w http.ResponseWriter, req *http.Request) {
312 if err := req.ParseForm(); err != nil {
313 http.Error(w, err.Error(), http.StatusBadRequest)
314 return
315 }
316 uri := protocol.URIFromPath(req.Form.Get("file"))
317 line, _ := strconv.Atoi(req.Form.Get("line")) // 1-based
318 col, _ := strconv.Atoi(req.Form.Get("col")) // 1-based UTF-8
319 posn := protocol.Position{
320 Line: uint32(line - 1),
321 Character: uint32(col - 1), // TODO(adonovan): map to UTF-16
322 }
323 openClientEditor(req.Context(), s.client, protocol.Location{
324 URI: uri,
325 Range: protocol.Range{Start: posn, End: posn},
326 }, s.Options())
327 })
328
329 // getSnapshot returns the snapshot for the view=... request parameter.
330 // On success, the caller must call the snapshot's release function;
331 // callers may assume that req.ParseForm succeeded.
332 // On failure, it reports an HTTP error.
333 getSnapshot := func(w http.ResponseWriter, req *http.Request) (*cache.Snapshot, func(), bool) {
334 if err := req.ParseForm(); err != nil {
335 http.Error(w, err.Error(), http.StatusBadRequest)
336 return nil, nil, false
337 }
338 viewID := req.Form.Get("view")
339 if viewID == "" {
340 http.Error(w, "no view=... parameter", http.StatusBadRequest)
341 return nil, nil, false
342 }
343 view, err := s.session.View(viewID)
344 if err != nil {
345 http.Error(w, err.Error(), http.StatusNotFound)
346 return nil, nil, false
347 }
348 snapshot, release, err := view.Snapshot()
349 if err != nil {
350 http.Error(w, err.Error(), http.StatusInternalServerError)
351 return nil, nil, false
352 }
353 return snapshot, release, true
354 }
355
356 // The /pkg/PATH&view=... handler shows package documentation for PATH.
357 webMux.Handle("/pkg/", http.StripPrefix("/pkg/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
358 snapshot, release, ok := getSnapshot(w, req)
359 if !ok {
360 return
361 }
362 defer release()
363
364 // Find package by path.
365 pkgPath := metadata.PackagePath(req.URL.Path)
366 mps := snapshot.MetadataGraph().ForPackagePath[pkgPath]
367 if len(mps) == 0 {
368 // TODO(adonovan): what should we do for external test packages?
369 http.Error(w, "package not found", http.StatusNotFound)
370 return
371 }
372 found := mps[0]
373
374 // Type-check the package and render its documentation.
375 pkgs, err := snapshot.TypeCheck(req.Context(), found.ID)
376 if err != nil {
377 http.Error(w, err.Error(), http.StatusInternalServerError)
378 return
379 }
380 content, err := golang.PackageDocHTML(snapshot.View().ID(), pkgs[0], web)
381 if err != nil {
382 http.Error(w, err.Error(), http.StatusInternalServerError)
383 return
384 }
385 w.Write(content)
386 })))
387
388 // The /freesymbols?file=...&range=...&view=... handler shows
389 // free symbols referenced by the selection.
390 webMux.HandleFunc("/freesymbols", func(w http.ResponseWriter, req *http.Request) {
391 snapshot, release, ok := getSnapshot(w, req)
392 if !ok {
393 return
394 }
395 defer release()
396
397 // Get selection range and type-check.
398 loc := protocol.Location{
399 URI: protocol.DocumentURI(req.Form.Get("file")),
400 }
401 if _, err := fmt.Sscanf(req.Form.Get("range"), "%d:%d:%d:%d",
402 &loc.Range.Start.Line,
403 &loc.Range.Start.Character,
404 &loc.Range.End.Line,
405 &loc.Range.End.Character,
406 ); err != nil {
407 http.Error(w, "invalid range", http.StatusInternalServerError)
408 return
409 }
410 pkg, pgf, err := golang.NarrowestPackageForFile(req.Context(), snapshot, loc.URI)
411 if err != nil {
412 http.Error(w, err.Error(), http.StatusInternalServerError)
413 return
414 }
415 start, end, err := pgf.RangePos(loc.Range)
416 if err != nil {
417 http.Error(w, err.Error(), http.StatusInternalServerError)
418 return
419 }
420
421 // Produce report.
422 html := golang.FreeSymbolsHTML(snapshot.View().ID(), pkg, pgf, start, end, web)
423 w.Write(html)
424 })
425
426 // The /assembly?pkg=...&view=...&symbol=... handler shows
427 // the assembly of the current function.
428 webMux.HandleFunc("/assembly", func(w http.ResponseWriter, req *http.Request) {
429 snapshot, release, ok := getSnapshot(w, req)
430 if !ok {
431 return
432 }
433 defer release()
434
435 // Get other parameters.
436 var (
437 pkgID = metadata.PackageID(req.Form.Get("pkg"))
438 symbol = req.Form.Get("symbol")
439 )
440 if pkgID == "" || symbol == "" {
441 http.Error(w, "/assembly requires pkg, symbol", http.StatusBadRequest)
442 return
443 }
444
445 ctx := req.Context()
446 pkgs, err := snapshot.TypeCheck(ctx, pkgID)
447 if err != nil {
448 http.Error(w, err.Error(), http.StatusInternalServerError)
449 return
450 }
451 pkg := pkgs[0]
452
453 // Produce report.
454 golang.AssemblyHTML(ctx, snapshot, w, pkg, symbol, web)
455 })
456
457 // The /splitpkg?pkg=...&view=... handler shows
458 // the "split package" tool (HTML) for the specified package/view.
459 webMux.HandleFunc("/splitpkg", func(w http.ResponseWriter, req *http.Request) {
460 snapshot, release, ok := getSnapshot(w, req)
461 if !ok {
462 return
463 }
464 defer release()
465
466 // Get metadata for pkg.
467 pkgID := metadata.PackageID(req.Form.Get("pkg"))
468 if pkgID == "" {
469 http.Error(w, "/splitpkg requires pkg", http.StatusBadRequest)
470 return
471 }
472 mp := snapshot.Metadata(pkgID)
473 if mp == nil {
474 http.Error(w, "no such package: "+string(pkgID), http.StatusInternalServerError)
475 return
476 }
477
478 w.Write(splitpkg.HTML(mp.PkgPath))
479 })
480
481 // The /splitpkg-json?pkg=...&view=... handler returns the symbol reference graph.
482 webMux.HandleFunc("/splitpkg-json", func(w http.ResponseWriter, req *http.Request) {
483 snapshot, release, ok := getSnapshot(w, req)
484 if !ok {
485 return
486 }
487 defer release()
488
489 // Get type information for pkg.
490 pkgID := metadata.PackageID(req.Form.Get("pkg"))
491 if pkgID == "" {
492 http.Error(w, "/splitpkg-json requires pkg", http.StatusBadRequest)
493 return
494 }
495 pkgs, err := snapshot.TypeCheck(req.Context(), pkgID)
496 if err != nil {
497 http.Error(w, err.Error(), http.StatusInternalServerError)
498 return
499 }
500 pkg := pkgs[0]
501
502 data, err := splitpkg.JSON(pkg, web)
503 if err != nil {
504 http.Error(w, err.Error(), http.StatusInternalServerError)
505 return
506 }
507 w.Write(data)
508 })
509
510 // The /splitpkg-components?pkg=...&view=... handler updates the components mapping.
511 // for the specified package, causing it to be saved persistently, and
512 // returned by future /splitpkg-json queries.
513 webMux.HandleFunc("/splitpkg-components", func(w http.ResponseWriter, req *http.Request) {
514 snapshot, release, ok := getSnapshot(w, req)
515 if !ok {
516 return
517 }
518 defer release()
519
520 // Get metadata for pkg.
521 pkgID := metadata.PackageID(req.Form.Get("pkg"))
522 if pkgID == "" {
523 http.Error(w, "/splitpkg-components requires pkg", http.StatusBadRequest)
524 return
525 }
526 mp := snapshot.Metadata(pkgID)
527 if mp == nil {
528 http.Error(w, "no such package: "+string(pkgID), http.StatusInternalServerError)
529 return
530 }
531
532 data, err := io.ReadAll(req.Body)
533 if err != nil {
534 msg := fmt.Sprintf("reading request body: %v", err)
535 http.Error(w, msg, http.StatusBadRequest)
536 return
537 }
538
539 if err := splitpkg.UpdateComponentsJSON(pkgID, data); err != nil {
540 http.Error(w, err.Error(), http.StatusBadRequest)
541 return
542 }
543 })
544
545 return web, nil
546 }
547
548 // assets holds our static web server content.
549 //
550 //go:embed assets/*
551 var assets embed.FS
552
553 // SrcURL returns a /src URL that, when visited, causes the client
554 // editor to open the specified file/line/column (in 1-based UTF-8
555 // coordinates).
556 //
557 // (Rendering may generate hundreds of positions across files of many
558 // packages, so don't convert to LSP coordinates yet: wait until the
559 // URL is opened.)
560 func (w *web) SrcURL(filename string, line, col8 int) protocol.URI {
561 query := fmt.Sprintf("file=%s&line=%d&col=%d",
562 url.QueryEscape(filename),
563 line,
564 col8)
565 return w.url("src", query, "")
566 }
567
568 // PkgURL returns a /pkg URL for the documentation of the specified package.
569 // The optional fragment must be of the form "Println" or "Buffer.WriteString".
570 func (w *web) PkgURL(viewID string, path golang.PackagePath, fragment string) protocol.URI {
571 query := "view=" + url.QueryEscape(viewID)
572 return w.url("pkg/"+string(path), query, fragment)
573 }
574
575 // freesymbolsURL returns a /freesymbols URL for a report
576 // on the free symbols referenced within the selection span (loc).
577 func (w *web) freesymbolsURL(viewID string, loc protocol.Location) protocol.URI {
578 query := fmt.Sprintf("file=%s&range=%d:%d:%d:%d&view=%s",
579 url.QueryEscape(string(loc.URI)),
580 loc.Range.Start.Line,
581 loc.Range.Start.Character,
582 loc.Range.End.Line,
583 loc.Range.End.Character,
584 url.QueryEscape(viewID))
585 return w.url("freesymbols", query, "")
586 }
587
588 // assemblyURL returns the URL of an assembly listing of the specified function symbol.
589 func (w *web) assemblyURL(viewID, packageID, symbol string) protocol.URI {
590 query := fmt.Sprintf("view=%s&pkg=%s&symbol=%s",
591 url.QueryEscape(viewID),
592 url.QueryEscape(packageID),
593 url.QueryEscape(symbol))
594 return w.url("assembly", query, "")
595 }
596
597 // splitpkgURL returns the URL of the "split package" HTML page for the specified package.
598 func (w *web) splitpkgURL(viewID, packageID string) protocol.URI {
599 query := fmt.Sprintf("view=%s&pkg=%s",
600 url.QueryEscape(viewID),
601 url.QueryEscape(packageID))
602 return w.url("splitpkg", query, "")
603 }
604
605 // url returns a URL by joining a relative path, an (encoded) query,
606 // and an (unencoded) fragment onto the authenticated base URL of the
607 // web server.
608 func (w *web) url(path, query, fragment string) protocol.URI {
609 url2 := w.addr
610 url2.Path = paths.Join(url2.Path, strings.TrimPrefix(path, "/"))
611 url2.RawQuery = query
612 url2.Fragment = fragment
613 return protocol.URI(url2.String())
614 }
615
616 // withPanicHandler wraps an HTTP handler with telemetry-reporting of
617 // panics that would otherwise be silently recovered by the net/http
618 // root handler.
619 func withPanicHandler(h http.Handler) http.HandlerFunc {
620 return func(w http.ResponseWriter, req *http.Request) {
621 panicked := true
622 defer func() {
623 if panicked {
624 bug.Report("panic in HTTP handler")
625 }
626 }()
627 h.ServeHTTP(w, req)
628 panicked = false
629 }
630 }