Debian Codegraph @

src/proxy.go

raw
1 package fzf
2
3 import (
4 "bufio"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "os/exec"
10 "os/signal"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/junegunn/fzf/src/tui"
18 "github.com/junegunn/fzf/src/util"
19 )
20
21 const becomeSuffix = ".become"
22
23 // Withheld from the environment replay below, so an outer value cannot
24 // override what the floating pane set
25 const internalEnvPrefix = "__FZF_INTERNAL_"
26
27 func escapeSingleQuote(str string) string {
28 return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"
29 }
30
31 // Read and remove, so preview and execute commands do not inherit it
32 func takeEnv(name string) string {
33 value := os.Getenv(name)
34 os.Unsetenv(name)
35 return value
36 }
37
38 // Applies label updates off the event loop, which would block on the fork
39 type labelUpdater struct {
40 set func(string)
41 mu sync.Mutex
42 pending *string
43 running bool
44 }
45
46 // A queue of one: a burst collapses to the newest label. A goroutine per
47 // update could apply them out of order
48 func (u *labelUpdater) update(label string) {
49 u.mu.Lock()
50 defer u.mu.Unlock()
51 u.pending = &label
52 if u.running {
53 return
54 }
55 u.running = true
56 go u.run()
57 }
58
59 // Ends once caught up, so nothing needs cancelling when Run returns
60 func (u *labelUpdater) run() {
61 for {
62 u.mu.Lock()
63 label := u.pending
64 if label == nil {
65 u.running = false
66 u.mu.Unlock()
67 return
68 }
69 u.pending = nil
70 u.mu.Unlock()
71 u.set(*label)
72 }
73 }
74
75 // Updates the label on the native border, or nil when it is not fzf's to update
76 func nativeLabelSetter() func(string) {
77 // Read both, so neither is left behind
78 tmuxPane, zellijPane := takeEnv(tmuxBorderLabelEnv), takeEnv(zellijBorderLabelEnv)
79 var set func(string)
80 switch {
81 case tmuxPane != "":
82 set = func(label string) { setTmuxBorderLabel(tmuxPane, label) }
83 case zellijPane != "":
84 set = func(label string) { setZellijBorderLabel(zellijPane, label) }
85 default:
86 return nil
87 }
88 updater := &labelUpdater{set: set}
89 return updater.update
90 }
91
92 func popupArgStr(args []string, opts *Options) (string, string) {
93 fzf, rest := args[0], args[1:]
94 args = []string{"--bind=ctrl-z:ignore"}
95 if !opts.Tmux.border && (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine) {
96 if tui.DefaultBorderShape == tui.BorderRounded {
97 rest = append(rest, "--border=rounded")
98 } else {
99 rest = append(rest, "--border=sharp")
100 }
101 }
102 if opts.Tmux.border && opts.Margin == defaultMargin() {
103 args = append(args, "--margin=0,1")
104 }
105 argStr := escapeSingleQuote(fzf)
106 for _, arg := range append(args, rest...) {
107 argStr += " " + escapeSingleQuote(arg)
108 }
109 argStr += ` --no-popup --no-height`
110
111 dir, err := os.Getwd()
112 if err != nil {
113 dir = "."
114 }
115 return argStr, dir
116 }
117
118 func fifo(name string) (string, error) {
119 ns := time.Now().UnixNano()
120 output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-%s-%d", name, ns))
121 output, err := mkfifo(output, 0600)
122 if err != nil {
123 return output, err
124 }
125 return output, nil
126 }
127
128 func runProxy(commandPrefix string, cmdBuilder func(temp string, needBash bool) (*exec.Cmd, error), opts *Options, withExports bool) (int, error) {
129 output, err := fifo("proxy-output")
130 if err != nil {
131 return ExitError, err
132 }
133 defer os.Remove(output)
134
135 // Take the output
136 go func() {
137 withOutputPipe(output, func(outputFile io.ReadCloser) {
138 if opts.Output == nil {
139 io.Copy(os.Stdout, outputFile)
140 } else {
141 reader := bufio.NewReader(outputFile)
142 sep := opts.PrintSep[0]
143 for {
144 item, err := reader.ReadString(sep)
145 if err != nil {
146 break
147 }
148 opts.Output <- item
149 }
150 }
151 })
152 }()
153
154 var command, input string
155 commandPrefix += ` --no-force-tty-in --proxy-script "$0"`
156 if opts.Input == nil && (opts.ForceTtyIn || util.IsTty(os.Stdin)) {
157 command = fmt.Sprintf(`%s > %q`, commandPrefix, output)
158 } else {
159 input, err = fifo("proxy-input")
160 if err != nil {
161 return ExitError, err
162 }
163 defer os.Remove(input)
164
165 go func() {
166 withInputPipe(input, func(inputFile io.WriteCloser) {
167 if opts.Input == nil {
168 io.Copy(inputFile, os.Stdin)
169 } else {
170 for item := range opts.Input {
171 fmt.Fprint(inputFile, item+opts.PrintSep)
172 }
173 }
174 })
175 }()
176
177 if withExports {
178 command = fmt.Sprintf(`%s < %q > %q`, commandPrefix, input, output)
179 } else {
180 // For mintty: cannot directly read named pipe from Go code
181 command = fmt.Sprintf(`command cat %q | %s > %q`, input, commandPrefix, output)
182 }
183 }
184
185 // Write the command to a temporary file and run it with sh to ensure POSIX compliance.
186 var exports []string
187 needBash := false
188 if withExports {
189 // Nullify FZF_DEFAULT_* variables as tmux popup may inject them even when undefined.
190 exports = []string{"FZF_DEFAULT_COMMAND=", "FZF_DEFAULT_OPTS=", "FZF_DEFAULT_OPTS_FILE="}
191 validIdentifier := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
192 for _, pairStr := range os.Environ() {
193 pair := strings.SplitN(pairStr, "=", 2)
194 if strings.HasPrefix(pair[0], internalEnvPrefix) {
195 continue
196 }
197 if validIdentifier.MatchString(pair[0]) {
198 exports = append(exports, fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1])))
199 } else if strings.HasPrefix(pair[0], "BASH_FUNC_") && strings.HasSuffix(pair[0], "%%") {
200 name := pair[0][10 : len(pair[0])-2]
201 exports = append(exports, name+pair[1])
202 exports = append(exports, "export -f "+name)
203 needBash = true
204 }
205 }
206 }
207 temp := WriteTemporaryFile(append(exports, command), "\n")
208 defer os.Remove(temp)
209
210 // Pre-create the become file so that another user on a shared TMPDIR
211 // cannot plant a file or a symbolic link at the predictable path while
212 // fzf is running
213 becomeFile := temp + becomeSuffix
214 becomeF, err := os.OpenFile(becomeFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
215 if err != nil {
216 return ExitError, err
217 }
218 becomeF.Close()
219 defer os.Remove(becomeFile)
220
221 cmd, err := cmdBuilder(temp, needBash)
222 if err != nil {
223 return ExitError, err
224 }
225 cmd.Stderr = os.Stderr
226 intChan := make(chan os.Signal, 1)
227 defer close(intChan)
228 go func() {
229 if sig, valid := <-intChan; valid {
230 cmd.Process.Signal(sig)
231 }
232 }()
233 signal.Notify(intChan, os.Interrupt)
234 if err := cmd.Run(); err != nil {
235 if exitError, ok := err.(*exec.ExitError); ok {
236 code := exitError.ExitCode()
237 if code == ExitBecome {
238 data, err := os.ReadFile(becomeFile)
239 os.Remove(becomeFile)
240 if err != nil {
241 return ExitError, err
242 }
243 if len(data) == 0 {
244 return ExitError, errors.New("invalid become command")
245 }
246 elems := strings.Split(string(data), "\x00")
247 command := elems[0]
248 env := []string{}
249 if len(elems) > 1 {
250 env = elems[1:]
251 }
252 executor := util.NewExecutor(opts.WithShell)
253 ttyin, err := tui.TtyIn(opts.TtyDefault)
254 if err != nil {
255 return ExitError, err
256 }
257 os.Remove(temp)
258 os.Remove(input)
259 os.Remove(output)
260 executor.Become(ttyin, env, command)
261 }
262 return code, err
263 }
264 }
265
266 return ExitOk, nil
267 }