| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 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 |
|
| 35 |
|
| 36 |
func autoNetworkAddressPosix(goplsPath, id string) (network string, address string) { |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 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 |
} |