Debian Codegraph @

gopls/internal/lsprpc/autostart_posix.go

raw symbols SCIP
1 // Copyright 2020 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 //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
6
7 package lsprpc
8
9 import (
10 "crypto/sha256"
11 "errors"
12 "fmt"
13 "log"
14 "os"
15 "os/exec"
16 "os/user"
17 "path/filepath"
18 "strconv"
19 "syscall"
20 )
21
22 func init() {
23 daemonize = daemonizePosix
24 autoNetworkAddress = autoNetworkAddressPosix
25 verifyRemoteOwnership = verifyRemoteOwnershipPosix
26 }
27
28 func daemonizePosix(cmd *exec.Cmd) {
29 cmd.SysProcAttr = &syscall.SysProcAttr{
30 Setsid: true,
31 }
32 }
33
34 // autoNetworkAddressPosix resolves an id on the 'auto' pseudo-network to a
35 // real network and address. On unix, this uses unix domain sockets.
36 func autoNetworkAddressPosix(goplsPath, id string) (network string, address string) {
37 // Especially when doing local development or testing, it's important that
38 // the remote gopls instance we connect to is running the same binary as our
39 // forwarder. So we encode a short hash of the binary path into the daemon
40 // socket name. If possible, we also include the buildid in this hash, to
41 // account for long-running processes where the binary has been subsequently
42 // rebuilt.
43 h := sha256.New()
44 cmd := exec.Command("go", "tool", "buildid", goplsPath)
45 cmd.Stdout = h
46 var pathHash []byte
47 if err := cmd.Run(); err == nil {
48 pathHash = h.Sum(nil)
49 } else {
50 log.Printf("error getting current buildid: %v", err)
51 sum := sha256.Sum256([]byte(goplsPath))
52 pathHash = sum[:]
53 }
54 shortHash := fmt.Sprintf("%x", pathHash)[:6]
55 user := os.Getenv("USER")
56 if user == "" {
57 user = "shared"
58 }
59 basename := filepath.Base(goplsPath)
60 idComponent := ""
61 if id != "" {
62 idComponent = "-" + id
63 }
64 runtimeDir := os.TempDir()
65 if xdg := os.Getenv("XDG_RUNTIME_DIR"); xdg != "" {
66 runtimeDir = xdg
67 }
68 return "unix", filepath.Join(runtimeDir, fmt.Sprintf("%s-%s-daemon.%s%s", basename, shortHash, user, idComponent))
69 }
70
71 func verifyRemoteOwnershipPosix(network, address string) (bool, error) {
72 if network != "unix" {
73 return true, nil
74 }
75 fi, err := os.Stat(address)
76 if err != nil {
77 if os.IsNotExist(err) {
78 return true, nil
79 }
80 return false, fmt.Errorf("checking socket owner: %w", err)
81 }
82 stat, ok := fi.Sys().(*syscall.Stat_t)
83 if !ok {
84 return false, errors.New("fi.Sys() is not a Stat_t")
85 }
86 user, err := user.Current()
87 if err != nil {
88 return false, fmt.Errorf("checking current user: %w", err)
89 }
90 uid, err := strconv.ParseUint(user.Uid, 10, 32)
91 if err != nil {
92 return false, fmt.Errorf("parsing current UID: %w", err)
93 }
94 return stat.Uid == uint32(uid), nil
95 }