vendor/github.com/ysmood/leakless/leakless.go

155 lines · 3166 bytes

  1//go:generate go run ./cmd/pack
  2
  3package leakless
  4
  5import (
  6	"bytes"
  7	"compress/gzip"
  8	"encoding/base64"
  9	"encoding/json"
 10	"fmt"
 11	"io/ioutil"
 12	"math/rand"
 13	"net"
 14	"os"
 15	"os/exec"
 16	"path/filepath"
 17	"runtime"
 18	"time"
 19
 20	"github.com/ysmood/leakless/pkg/shared"
 21	"github.com/ysmood/leakless/pkg/utils"
 22)
 23
 24var leaklessBinaries = map[string]string{}
 25
 26// Launcher struct
 27type Launcher struct {
 28	// Lock for leakless.LockPort, default is 2978
 29	Lock int
 30
 31	pid chan int
 32	err string
 33}
 34
 35// New leakless instance
 36func New() *Launcher {
 37	return &Launcher{
 38		Lock: 2978,
 39		pid:  make(chan int),
 40	}
 41}
 42
 43// Command will try to download the leakless bin and prefix the exec.Cmd with the leakless options.
 44func (l *Launcher) Command(name string, arg ...string) *exec.Cmd {
 45	bin := ""
 46	func() {
 47		defer LockPort(l.Lock)()
 48		bin = GetLeaklessBin()
 49	}()
 50
 51	uid := fmt.Sprintf("%x", utils.RandBytes(16))
 52	addr := l.serve(uid)
 53
 54	arg = append([]string{uid, addr, name}, arg...)
 55	return exec.Command(bin, arg...)
 56}
 57
 58// Pid signals the pid of the guarded sub-process. The channel may never receive the pid.
 59func (l *Launcher) Pid() chan int {
 60	return l.pid
 61}
 62
 63// Err message from the guard process
 64func (l *Launcher) Err() string {
 65	return l.err
 66}
 67
 68func (l *Launcher) serve(uid string) string {
 69	srv, err := net.Listen("tcp", "127.0.0.1:0")
 70	if err != nil {
 71		panic("[leakless] serve error: " + err.Error())
 72	}
 73
 74	go func() {
 75		defer func() { _ = srv.Close() }()
 76
 77		conn, err := srv.Accept()
 78		if err != nil {
 79			l.err = err.Error()
 80			l.pid <- 0
 81			return
 82		}
 83
 84		enc := json.NewEncoder(conn)
 85		err = enc.Encode(shared.Message{UID: uid})
 86		if err != nil {
 87			l.err = err.Error()
 88			l.pid <- 0
 89			return
 90		}
 91
 92		dec := json.NewDecoder(conn)
 93		var msg shared.Message
 94		err = dec.Decode(&msg)
 95		if err == nil {
 96			l.err = msg.Error
 97			l.pid <- msg.PID
 98		}
 99		_ = dec.Decode(&msg)
100	}()
101
102	return srv.Addr().String()
103}
104
105var leaklessDir = filepath.Join(os.TempDir(), fmt.Sprintf("leakless-%s-%s", runtime.GOARCH, shared.Version))
106
107// GetLeaklessBin returns the executable path of the guard, if it doesn't exists create one.
108func GetLeaklessBin() string {
109	bin := filepath.Join(leaklessDir, "leakless")
110
111	if runtime.GOOS == "windows" {
112		bin += ".exe"
113	}
114
115	if !utils.FileExists(bin) {
116		name := utils.GetTarget().BinName()
117		raw, err := base64.StdEncoding.DecodeString(leaklessBinaries[name])
118		utils.E(err)
119		gr, err := gzip.NewReader(bytes.NewBuffer(raw))
120		utils.E(err)
121		data, err := ioutil.ReadAll(gr)
122		utils.E(err)
123		utils.E(gr.Close())
124
125		err = utils.OutputFile(bin, data, nil)
126		utils.E(err)
127		utils.E(os.Chmod(bin, 0755))
128	}
129
130	return bin
131}
132
133// Support returns true if the OS is supported by leakless.
134func Support() bool {
135	_, has := leaklessBinaries[utils.GetTarget().BinName()]
136	return has
137}
138
139// LockPort uses a tcp port to create a mutex lock for cross-process locking.
140// It will poll the port to check if it's free.
141func LockPort(port int) func() {
142	var l net.Listener
143	for {
144		var err error
145		l, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
146		if err == nil {
147			break
148		}
149		time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
150	}
151
152	return func() {
153		_ = l.Close()
154	}
155}