server.go
This file
Path
src/server.go
252 lines · 6.1 KiB · Go
Last changed by
Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4
History of this fileTake it
1package fzf23import (4 "bufio"5 "bytes"6 "crypto/subtle"7 "errors"8 "fmt"9 "net"10 "os"11 "regexp"12 "strconv"13 "strings"14 "time"15)1617var getRegex *regexp.Regexp1819func init() {20 getRegex = regexp.MustCompile(`^GET /(?:\?([a-z0-9=&]+))? HTTP`)21}2223type getParams struct {24 limit int25 offset int26}2728const (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 httpUnavailable = "HTTP/1.1 503 Service Unavailable" + crlf34 httpReadTimeout = 10 * time.Second35 channelTimeout = 2 * time.Second36 jsonContentType = "Content-Type: application/json" + crlf37 maxContentLength = 1024 * 102438)3940type httpServer struct {41 apiKey []byte42 actionChannel chan []*action43 responseChannel chan string44}4546type listenAddress struct {47 host string48 port int49}5051func (addr listenAddress) IsLocal() bool {52 return addr.host == "localhost" || addr.host == "127.0.0.1"53}5455var defaultListenAddr = listenAddress{"localhost", 0}5657func parseListenAddress(address string) (listenAddress, error) {58 parts := strings.SplitN(address, ":", 3)59 if len(parts) == 1 {60 parts = []string{"localhost", parts[0]}61 }62 if len(parts) != 2 {63 return defaultListenAddr, fmt.Errorf("invalid listen address: %s", address)64 }65 portStr := parts[len(parts)-1]66 port, err := strconv.Atoi(portStr)67 if err != nil || port < 0 || port > 65535 {68 return defaultListenAddr, fmt.Errorf("invalid listen port: %s", portStr)69 }70 if len(parts[0]) == 0 {71 parts[0] = "localhost"72 }73 return listenAddress{parts[0], port}, nil74}7576func startHttpServer(address listenAddress, actionChannel chan []*action, responseChannel chan string) (net.Listener, int, error) {77 host := address.host78 port := address.port79 apiKey := os.Getenv("FZF_API_KEY")80 if !address.IsLocal() && len(apiKey) == 0 {81 return nil, port, errors.New("FZF_API_KEY is required to allow remote access")82 }83 addrStr := fmt.Sprintf("%s:%d", host, port)84 listener, err := net.Listen("tcp", addrStr)85 if err != nil {86 return nil, port, fmt.Errorf("failed to listen on %s", addrStr)87 }88 if port == 0 {89 addr := listener.Addr().String()90 parts := strings.Split(addr, ":")91 if len(parts) < 2 {92 return nil, port, fmt.Errorf("cannot extract port: %s", addr)93 }94 var err error95 port, err = strconv.Atoi(parts[len(parts)-1])96 if err != nil {97 return nil, port, err98 }99 }100101 server := httpServer{102 apiKey: []byte(apiKey),103 actionChannel: actionChannel,104 responseChannel: responseChannel,105 }106107 go func() {108 for {109 conn, err := listener.Accept()110 if err != nil {111 if errors.Is(err, net.ErrClosed) {112 return113 }114 continue115 }116 conn.Write([]byte(server.handleHttpRequest(conn)))117 conn.Close()118 }119 }()120121 return listener, port, nil122}123124// Here we are writing a simplistic HTTP server without using net/http125// package to reduce the size of the binary.126//127// * No --listen: 2.8MB128// * --listen with net/http: 5.7MB129// * --listen w/o net/http: 3.3MB130func (server *httpServer) handleHttpRequest(conn net.Conn) string {131 contentLength := 0132 apiKey := ""133 body := ""134 answer := func(code string, message string) string {135 message += "\n"136 return code + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)137 }138 unauthorized := func(message string) string {139 return answer(httpUnauthorized, message)140 }141 bad := func(message string) string {142 return answer(httpBadRequest, message)143 }144 good := func(message string) string {145 return answer(httpOk+jsonContentType, message)146 }147 conn.SetReadDeadline(time.Now().Add(httpReadTimeout))148 scanner := bufio.NewScanner(conn)149 scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {150 found := bytes.Index(data, []byte(crlf))151 if found >= 0 {152 token := data[:found+len(crlf)]153 return len(token), token, nil154 }155 if atEOF || len(body)+len(data) >= contentLength {156 return 0, data, bufio.ErrFinalToken157 }158 return 0, nil, nil159 })160161 section := 0162 for scanner.Scan() {163 text := scanner.Text()164 switch section {165 case 0:166 getMatch := getRegex.FindStringSubmatch(text)167 if len(getMatch) > 0 {168 server.actionChannel <- []*action{{t: actResponse, a: getMatch[1]}}169 select {170 case response := <-server.responseChannel:171 return good(response)172 case <-time.After(channelTimeout):173 go func() {174 // Drain the channel175 <-server.responseChannel176 }()177 return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`)178 }179 } else if !strings.HasPrefix(text, "POST / HTTP") {180 return bad("invalid request method")181 }182 section++183 case 1:184 if text == crlf {185 if contentLength == 0 {186 return bad("content-length header missing")187 }188 section++189 continue190 }191 pair := strings.SplitN(text, ":", 2)192 if len(pair) == 2 {193 switch strings.ToLower(pair[0]) {194 case "content-length":195 length, err := strconv.Atoi(strings.TrimSpace(pair[1]))196 if err != nil || length <= 0 || length > maxContentLength {197 return bad("invalid content length")198 }199 contentLength = length200 case "x-api-key":201 apiKey = strings.TrimSpace(pair[1])202 }203 }204 case 2:205 body += text206 }207 }208209 if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {210 return unauthorized("invalid api key")211 }212213 if len(body) < contentLength {214 return bad("incomplete request")215 }216 body = body[:contentLength]217218 actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"))219 if err != nil {220 return bad(err.Error())221 }222 if len(actions) == 0 {223 return bad("no action specified")224 }225226 select {227 case server.actionChannel <- actions:228 case <-time.After(channelTimeout):229 return httpUnavailable + crlf230 }231 return httpOk + crlf232}233234func parseGetParams(query string) getParams {235 params := getParams{limit: 100, offset: 0}236 for _, pair := range strings.Split(query, "&") {237 parts := strings.SplitN(pair, "=", 2)238 if len(parts) == 2 {239 switch parts[0] {240 case "limit", "offset":241 if val, err := strconv.Atoi(parts[1]); err == nil {242 if parts[0] == "limit" {243 params.limit = val244 } else {245 params.offset = val246 }247 }248 }249 }250 }251 return params252}