Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than d75bb5c point at it.

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 1–32why, one step back
1package fzf
23import (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" + crlf

Avoid deadlocks by adding a 2 second timeout to GET / endpointJunegunn Choibefore adoption7484292

line 33why, one step back
33 httpUnavailable = "HTTP/1.1 503 Service Unavailable" + crlf

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

line 34why, one step back
34 httpReadTimeout = 10 * time.Second

Set a 2-second timeout for POST requestsJunegunn Choibefore adoption0545388

line 35why, one step back
35 channelTimeout = 2 * time.Second

Avoid deadlocks by adding a 2 second timeout to GET / endpointJunegunn Choibefore adoption7484292

line 36why, one step back
36 jsonContentType = "Content-Type: application/json" + crlf

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 37–56why, one step back
37 maxContentLength = 1024 * 1024
38)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}56

Update error return position according to conventiononee-onlybefore adoption52210a5

line 57why, one step back
57func parseListenAddress(address string) (listenAddress, error) {

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 58–62why, one step back
58 parts := strings.SplitN(address, ":", 3)
59 if len(parts) == 1 {60 parts = []string{"localhost", parts[0]}61 }62 if len(parts) != 2 {

Update error return position according to conventiononee-onlybefore adoption52210a5

line 63why, one step back
63 return defaultListenAddr, fmt.Errorf("invalid listen address: %s", address)

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 64–67why, one step back
64 }
65 portStr := parts[len(parts)-1]66 port, err := strconv.Atoi(portStr)67 if err != nil || port < 0 || port > 65535 {

Update error return position according to conventiononee-onlybefore adoption52210a5

line 68why, one step back
68 return defaultListenAddr, fmt.Errorf("invalid listen port: %s", portStr)

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 69–72why, one step back
69 }
70 if len(parts[0]) == 0 {71 parts[0] = "localhost"72 }

Update error return position according to conventiononee-onlybefore adoption52210a5

line 73why, one step back
73 return listenAddress{parts[0], port}, nil

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 74–75why, one step back
74}
75

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 76why, one step back
76func startHttpServer(address listenAddress, actionChannel chan []*action, responseChannel chan string) (net.Listener, int, error) {

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 77–80why, one step back
77 host := address.host
78 port := address.port79 apiKey := os.Getenv("FZF_API_KEY")80 if !address.IsLocal() && len(apiKey) == 0 {

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 81why, one step back
81 return nil, port, errors.New("FZF_API_KEY is required to allow remote access")

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 82–85why, one step back
82 }
83 addrStr := fmt.Sprintf("%s:%d", host, port)84 listener, err := net.Listen("tcp", addrStr)85 if err != nil {

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 86why, one step back
86 return nil, port, fmt.Errorf("failed to listen on %s", addrStr)

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 87–91why, one step back
87 }
88 if port == 0 {89 addr := listener.Addr().String()90 parts := strings.Split(addr, ":")91 if len(parts) < 2 {

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 92why, one step back
92 return nil, port, fmt.Errorf("cannot extract port: %s", addr)

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 93–96why, one step back
93 }
94 var err error95 port, err = strconv.Atoi(parts[len(parts)-1])96 if err != nil {

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 97why, one step back
97 return nil, port, err

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 98–111why, one step back
98 }
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) {

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 112why, one step back
112 return

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

line 113why, one step back
113 }

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 114why, one step back
114 continue

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 115–120why, one step back
115 }
116 conn.Write([]byte(server.handleHttpRequest(conn)))117 conn.Close()118 }119 }()120

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

line 121why, one step back
121 return listener, port, nil

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 122–144why, one step back
122}
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 {

Avoid deadlocks by adding a 2 second timeout to GET / endpointJunegunn Choibefore adoption7484292

line 145why, one step back
145 return answer(httpOk+jsonContentType, message)

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 146–168why, one step back
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]}}

Avoid deadlocks by adding a 2 second timeout to GET / endpointJunegunn Choibefore adoption7484292

lines 169–171why, one step back
169 select {
170 case response := <-server.responseChannel:171 return good(response)

Set a 2-second timeout for POST requestsJunegunn Choibefore adoption0545388

line 172why, one step back
172 case <-time.After(channelTimeout):

Avoid deadlocks by adding a 2 second timeout to GET / endpointJunegunn Choibefore adoption7484292

lines 173–178why, one step back
173 go func() {
174 // Drain the channel175 <-server.responseChannel176 }()177 return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`)178 }

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 179–217why, one step back
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]217

Refactor the code so that fzf can be used as a library (#3769)Junegunn Choibefore adoptione8405f4

lines 218–220why, one step back
218 actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"))
219 if err != nil {220 return bad(err.Error())

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 221–225why, one step back
221 }
222 if len(actions) == 0 {223 return bad("no action specified")224 }225

Set a 2-second timeout for POST requestsJunegunn Choibefore adoption0545388

lines 226–230why, one step back
226 select {
227 case server.actionChannel <- actions:228 case <-time.After(channelTimeout):229 return httpUnavailable + crlf230 }

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 231–239why, one step back
231 return httpOk + crlf
232}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] {

Update parseGetParams to call strconv.Atoi when params are validonee-onlybefore adoption61bc129

lines 240–247why, one step back
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 }

Deploying to master from @ junegunn/fzf@2671259fdb3094a5eac528f291c1fdadbcf9eda9 🚀junegunnbefore adoptiond75bb5c

lines 248–252why, one step back
248 }
249 }250 }251 return params252}