Allow accepting remote connections
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Close #3498 # FZF_API_KEY is required for a non-localhost listen address FZF_API_KEY=xxx fzf --listen 0.0.0.0:6266
authored by Junegunn Choi · committed by Junegunn Choi · parent 70c19cc · Browse files · 5 files·+72 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+72 added−40 removed
- other:+72 added−40 removed
Provenance
- Commit
3f78d76- Tree
51e4492- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
70c19cc
5 files changed+72 added−40 removed
modified:man/man1/fzf.1+13 added-9 removed
791 unmodified lines792 .RS793 e.g. \fBfzf --multi | fzf --sync\fR794 .RE795 .TP796-.B "--listen[=HTTP_PORT]"797-Start HTTP server on the given port. It allows external processes to send798-actions to perform via POST method. If the port number is omitted or given as799-0, fzf will choose the port automatically and export it as \fBFZF_PORT\fR800-environment variable to the child processes started via \fBexecute\fR and801-\fBexecute-silent\fR actions. If \fBFZF_API_KEY\fR environment variable is802-set, the server would require sending an API key with the same value in the803-\fBx-api-key\fR HTTP header.796+.B "--listen[=[ADDR:]PORT]"797+Start HTTP server and listen on the given address. It allows external processes798+to send actions to perform via POST method. If the port number is omitted or799+given as 0, fzf will automatically choose a port and export it as800+\fBFZF_PORT\fR environment variable to the child processes. If801+\fBFZF_API_KEY\fR environment variable is set, the server would require sending802+an API key with the same value in the \fBx-api-key\fR HTTP header.803+\fBFZF_API_KEY\fR is required for a non-localhost listen address.804 805 e.g.806 \fB# Start HTTP server on port 6266807 fzf --listen 62663 unmodified lines811 812 # Send action to the server813 curl -XPOST localhost:6266 -d 'reload(seq 100)+change-prompt(hundred> )'814 815- # Start HTTP server on port 6266 and send an authenticated action815+ # Start HTTP server on port 6266 with remote connections allowed816+ # * Listening on non-localhost address requires using an API key817 export FZF_API_KEY="$(head -c 32 /dev/urandom | base64)"818+ fzf --listen 0.0.0.0:6266819+820+ # Send an authenticated action821 curl -XPOST localhost:6266 -H "x-api-key: $FZF_API_KEY" -d 'change-query(yo)'822 823 # Choose port automatically and export it as $FZF_PORT to the child process824 fzf --listen --bind 'start:execute-silent:echo $FZF_PORT > /tmp/fzf-port'539 unmodified linesmodified:src/options.go+9 added-11 removed
116 unmodified lines117 --expect=KEYS Comma-separated list of keys to complete fzf118 --read0 Read input delimited by ASCII NUL characters119 --print0 Print output delimited by ASCII NUL characters120 --sync Synchronous search for multi-staged filtering121- --listen[=HTTP_PORT] Start HTTP server to receive actions (POST /)121+ --listen[=[ADDR:]PORT] Start HTTP server to receive actions (POST /)122 --version Display version information and exit123 124 Environment variables125 FZF_DEFAULT_COMMAND Default command to use when input is tty207 unmodified lines333 BorderLabel labelOpts334 PreviewLabel labelOpts335 Unicode bool336 Tabstop int337- ListenPort *int337+ ListenAddr *string338 ClearOnExit bool339 Version bool340 }341 1490 unmodified lines1832 nextString(allArgs, &i, "padding required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))1833 case "--tabstop":1834 opts.Tabstop = nextInt(allArgs, &i, "tab stop required")1835 case "--listen":1836- port := optionalNumeric(allArgs, &i, 0)1837- opts.ListenPort = &port1836+ given, addr := optionalNextString(allArgs, &i)1837+ if !given {1838+ addr = defaultListenAddr1839+ }1840+ opts.ListenAddr = &addr1841 case "--no-listen":1839- opts.ListenPort = nil1842+ opts.ListenAddr = nil1843 case "--clear":1844 opts.ClearOnExit = true1845 case "--no-clear":1846 opts.ClearOnExit = false82 unmodified lines1929 opts.Padding = parseMargin("padding", value)1930 } else if match, value := optString(arg, "--tabstop="); match {1931 opts.Tabstop = atoi(value)1932 } else if match, value := optString(arg, "--listen="); match {1930- port := atoi(value)1931- opts.ListenPort = &port1933+ opts.ListenAddr = &value1934 } else if match, value := optString(arg, "--hscroll-off="); match {1935 opts.HscrollOff = atoi(value)1936 } else if match, value := optString(arg, "--scroll-off="); match {1937 opts.ScrollOff = atoi(value)21 unmodified lines1959 if opts.Tabstop < 1 {1960 errorExit("tab stop must be a positive integer")1961 }1962 1961- if opts.ListenPort != nil && (*opts.ListenPort < 0 || *opts.ListenPort > 65535) {1962- errorExit("invalid listen port")1963- }1964-1963 if len(opts.JumpLabels) == 0 {1964 errorExit("empty jump labels")1965 }1966 171 unmodified linesmodified:src/server.go+39 added-16 removed
24 unmodified lines25 offset int26 }27 28 const (29- crlf = "\r\n"30- httpOk = "HTTP/1.1 200 OK" + crlf31- httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf32- httpUnauthorized = "HTTP/1.1 401 Unauthorized" + crlf33- httpReadTimeout = 10 * time.Second34- maxContentLength = 1024 * 102429+ crlf = "\r\n"30+ httpOk = "HTTP/1.1 200 OK" + crlf31+ httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf32+ httpUnauthorized = "HTTP/1.1 401 Unauthorized" + crlf33+ httpReadTimeout = 10 * time.Second34+ maxContentLength = 1024 * 102435+ defaultListenAddr = "localhost:0"36 )37 38 type httpServer struct {39 apiKey []byte40 actionChannel chan []*action41 responseChannel chan string42 }43 43-func startHttpServer(port int, actionChannel chan []*action, responseChannel chan string) (error, int) {44- if port < 0 {45- return nil, port44+func parseListenAddress(address string) (error, string, int) {45+ parts := strings.SplitN(address, ":", 3)46+ if len(parts) == 1 {47+ parts = []string{"localhost", parts[0]}48 }49+ if len(parts) != 2 {50+ return fmt.Errorf("invalid listen address: %s", address), "", 051+ }52+ portStr := parts[len(parts)-1]53+ port, err := strconv.Atoi(portStr)54+ if err != nil || port < 0 || port > 65535 {55+ return fmt.Errorf("invalid listen port: %s", portStr), "", 056+ }57+ if len(parts[0]) == 0 {58+ parts[0] = "localhost"59+ }60+ return nil, parts[0], port61+}62 48- listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))63+func startHttpServer(address string, actionChannel chan []*action, responseChannel chan string) (error, int) {64+ err, host, port := parseListenAddress(address)65 if err != nil {50- return fmt.Errorf("port not available: %d", port), port66+ return err, port67 }68+69+ apiKey := os.Getenv("FZF_API_KEY")70+ if host != "localhost" && host != "127.0.0.1" && len(apiKey) == 0 {71+ return fmt.Errorf("FZF_API_KEY is required for remote access"), port72+ }73+ listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))74+ if err != nil {75+ return fmt.Errorf("failed to listen on %s", address), port76+ }77 if port == 0 {78 addr := listener.Addr().String()54- parts := strings.SplitN(addr, ":", 2)79+ parts := strings.Split(addr, ":")80 if len(parts) < 2 {81 return fmt.Errorf("cannot extract port: %s", addr), port82 }58- var err error59- port, err = strconv.Atoi(parts[1])60- if err != nil {83+ if port, err := strconv.Atoi(parts[len(parts)-1]); err != nil {84 return err, port85 }86 }87 88 server := httpServer{66- apiKey: []byte(os.Getenv("FZF_API_KEY")),89+ apiKey: []byte(apiKey),90 actionChannel: actionChannel,91 responseChannel: responseChannel,92 }93 141 unmodified linesmodified:src/terminal.go+5 added-4 removed
233 unmodified lines234 tabstop int235 margin [4]sizeSpec236 padding [4]sizeSpec237 unicode bool238+ listenAddr *string239 listenPort *int240 borderShape tui.BorderShape241 cleanExit bool242 paused bool343 unmodified lines586 delay = initialDelay587 }588 var previewBox *util.EventBox589 // We need to start previewer if HTTP server is enabled even when --preview option is not specified589- if len(opts.Preview.command) > 0 || hasPreviewAction(opts) || opts.ListenPort != nil {590+ if len(opts.Preview.command) > 0 || hasPreviewAction(opts) || opts.ListenAddr != nil {591 previewBox = util.NewEventBox()592 }593 var renderer tui.Renderer594 fullscreen := !opts.Height.auto && (opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100)64 unmodified lines659 history: opts.History,660 margin: opts.Margin,661 padding: opts.Padding,662 unicode: opts.Unicode,662- listenPort: opts.ListenPort,663+ listenAddr: opts.ListenAddr,664 borderShape: opts.BorderShape,665 borderWidth: 1,666 borderLabel: nil,667 borderLabelOpts: opts.BorderLabel,80 unmodified lines748 }749 750 _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]751 751- if t.listenPort != nil {752- err, port := startHttpServer(*t.listenPort, t.serverInputChan, t.serverOutputChan)752+ if t.listenAddr != nil {753+ err, port := startHttpServer(*t.listenAddr, t.serverInputChan, t.serverOutputChan)754 if err != nil {755 errorExit(err.Error())756 }757 t.listenPort = &port3260 unmodified linesmodified:CHANGELOG.md+6 added
9 unmodified lines10 ```sh11 fzf --preview='fzf-preview.sh {}'12 ```13 - (Experimental) Sixel and Kitty image support now also available on Windows14+- HTTP server can be configured to accept remote connections15+ ```sh16+ # FZF_API_KEY is required for a non-localhost listen address17+ export FZF_API_KEY="$(head -c 32 /dev/urandom | base64)"18+ fzf --listen 0.0.0.0:626619+ ```20 - Bug fixes21 22 0.43.023 ------1733 unmodified lines