| 1 |
package fzf |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"bytes" |
| 6 |
"crypto/subtle" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"net" |
| 10 |
"os" |
| 11 |
"regexp" |
| 12 |
"strconv" |
| 13 |
"strings" |
| 14 |
"time" |
| 15 |
) |
| 16 |
|
| 17 |
var getRegex *regexp.Regexp |
| 18 |
|
| 19 |
func init() { |
| 20 |
getRegex = regexp.MustCompile(`^GET /(?:\?([a-z0-9=&]+))? HTTP`) |
| 21 |
} |
| 22 |
|
| 23 |
type getParams struct { |
| 24 |
limit int |
| 25 |
offset int |
| 26 |
} |
| 27 |
|
| 28 |
const ( |
| 29 |
crlf = "\r\n" |
| 30 |
httpOk = "HTTP/1.1 200 OK" + crlf |
| 31 |
httpBadRequest = "HTTP/1.1 400 Bad Request" + crlf |
| 32 |
httpUnauthorized = "HTTP/1.1 401 Unauthorized" + crlf |
| 33 |
httpUnavailable = "HTTP/1.1 503 Service Unavailable" + crlf |
| 34 |
httpReadTimeout = 10 * time.Second |
| 35 |
channelTimeout = 2 * time.Second |
| 36 |
jsonContentType = "Content-Type: application/json" + crlf |
| 37 |
maxContentLength = 1024 * 1024 |
| 38 |
) |
| 39 |
|
| 40 |
type httpServer struct { |
| 41 |
apiKey []byte |
| 42 |
actionChannel chan []*action |
| 43 |
getHandler func(getParams) string |
| 44 |
} |
| 45 |
|
| 46 |
type listenAddress struct { |
| 47 |
host string |
| 48 |
port int |
| 49 |
sock string |
| 50 |
} |
| 51 |
|
| 52 |
func (addr listenAddress) IsLocal() bool { |
| 53 |
return addr.host == "localhost" || addr.host == "127.0.0.1" || len(addr.sock) > 0 |
| 54 |
} |
| 55 |
|
| 56 |
var defaultListenAddr = listenAddress{"localhost", 0, ""} |
| 57 |
|
| 58 |
func parseListenAddress(address string) (listenAddress, error) { |
| 59 |
if strings.HasSuffix(address, ".sock") { |
| 60 |
return listenAddress{"", 0, address}, nil |
| 61 |
} |
| 62 |
|
| 63 |
parts := strings.SplitN(address, ":", 3) |
| 64 |
if len(parts) == 1 { |
| 65 |
parts = []string{"localhost", parts[0]} |
| 66 |
} |
| 67 |
if len(parts) != 2 { |
| 68 |
return defaultListenAddr, fmt.Errorf("invalid listen address: %s", address) |
| 69 |
} |
| 70 |
portStr := parts[len(parts)-1] |
| 71 |
port, err := strconv.Atoi(portStr) |
| 72 |
if err != nil || port < 0 || port > 65535 { |
| 73 |
return defaultListenAddr, fmt.Errorf("invalid listen port: %s", portStr) |
| 74 |
} |
| 75 |
if len(parts[0]) == 0 { |
| 76 |
parts[0] = "localhost" |
| 77 |
} |
| 78 |
return listenAddress{parts[0], port, ""}, nil |
| 79 |
} |
| 80 |
|
| 81 |
func startHttpServer(address listenAddress, actionChannel chan []*action, getHandler func(getParams) string) (net.Listener, int, error) { |
| 82 |
host := address.host |
| 83 |
port := address.port |
| 84 |
apiKey := os.Getenv("FZF_API_KEY") |
| 85 |
if !address.IsLocal() && len(apiKey) == 0 { |
| 86 |
return nil, port, errors.New("FZF_API_KEY is required to allow remote access") |
| 87 |
} |
| 88 |
|
| 89 |
var listener net.Listener |
| 90 |
var err error |
| 91 |
if len(address.sock) > 0 { |
| 92 |
if _, err := os.Stat(address.sock); err == nil { |
| 93 |
// Check if the socket is already in use |
| 94 |
if conn, err := net.Dial("unix", address.sock); err == nil { |
| 95 |
conn.Close() |
| 96 |
return nil, 0, fmt.Errorf("socket already in use: %s", address.sock) |
| 97 |
} |
| 98 |
os.Remove(address.sock) |
| 99 |
} |
| 100 |
listener, err = net.Listen("unix", address.sock) |
| 101 |
if err != nil { |
| 102 |
return nil, 0, fmt.Errorf("failed to listen on %s", address.sock) |
| 103 |
} |
| 104 |
os.Chmod(address.sock, 0600) |
| 105 |
} else { |
| 106 |
addrStr := fmt.Sprintf("%s:%d", host, port) |
| 107 |
listener, err = net.Listen("tcp", addrStr) |
| 108 |
if err != nil { |
| 109 |
return nil, port, fmt.Errorf("failed to listen on %s", addrStr) |
| 110 |
} |
| 111 |
if port == 0 { |
| 112 |
addr := listener.Addr().String() |
| 113 |
parts := strings.Split(addr, ":") |
| 114 |
if len(parts) < 2 { |
| 115 |
return nil, port, fmt.Errorf("cannot extract port: %s", addr) |
| 116 |
} |
| 117 |
var err error |
| 118 |
port, err = strconv.Atoi(parts[len(parts)-1]) |
| 119 |
if err != nil { |
| 120 |
return nil, port, err |
| 121 |
} |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
go func() { |
| 126 |
server := httpServer{ |
| 127 |
apiKey: []byte(apiKey), |
| 128 |
actionChannel: actionChannel, |
| 129 |
getHandler: getHandler, |
| 130 |
} |
| 131 |
for { |
| 132 |
conn, err := listener.Accept() |
| 133 |
if err != nil { |
| 134 |
if errors.Is(err, net.ErrClosed) { |
| 135 |
return |
| 136 |
} |
| 137 |
continue |
| 138 |
} |
| 139 |
conn.Write([]byte(server.handleHttpRequest(conn))) |
| 140 |
conn.Close() |
| 141 |
} |
| 142 |
}() |
| 143 |
|
| 144 |
return listener, port, nil |
| 145 |
} |
| 146 |
|
| 147 |
// Here we are writing a simplistic HTTP server without using net/http |
| 148 |
// package to reduce the size of the binary. |
| 149 |
// |
| 150 |
// * No --listen: 2.8MB |
| 151 |
// * --listen with net/http: 5.7MB |
| 152 |
// * --listen w/o net/http: 3.3MB |
| 153 |
func (server *httpServer) handleHttpRequest(conn net.Conn) string { |
| 154 |
contentLength := 0 |
| 155 |
apiKey := "" |
| 156 |
var bodyBuilder strings.Builder |
| 157 |
answer := func(code string, message string) string { |
| 158 |
message += "\n" |
| 159 |
return code + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message) |
| 160 |
} |
| 161 |
unauthorized := func(message string) string { |
| 162 |
return answer(httpUnauthorized, message) |
| 163 |
} |
| 164 |
bad := func(message string) string { |
| 165 |
return answer(httpBadRequest, message) |
| 166 |
} |
| 167 |
good := func(message string) string { |
| 168 |
return answer(httpOk+jsonContentType, message) |
| 169 |
} |
| 170 |
conn.SetReadDeadline(time.Now().Add(httpReadTimeout)) |
| 171 |
scanner := bufio.NewScanner(conn) |
| 172 |
scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) { |
| 173 |
found := bytes.Index(data, []byte(crlf)) |
| 174 |
if found >= 0 { |
| 175 |
token := data[:found+len(crlf)] |
| 176 |
return len(token), token, nil |
| 177 |
} |
| 178 |
if atEOF || bodyBuilder.Len()+len(data) >= contentLength { |
| 179 |
return 0, data, bufio.ErrFinalToken |
| 180 |
} |
| 181 |
return 0, nil, nil |
| 182 |
}) |
| 183 |
|
| 184 |
section := 0 |
| 185 |
var getMatch []string |
| 186 |
Loop: |
| 187 |
for scanner.Scan() { |
| 188 |
text := scanner.Text() |
| 189 |
switch section { |
| 190 |
case 0: // Request line |
| 191 |
getMatch = getRegex.FindStringSubmatch(text) |
| 192 |
if len(getMatch) == 0 && !strings.HasPrefix(text, "POST / HTTP") { |
| 193 |
return bad("invalid request method") |
| 194 |
} |
| 195 |
section++ |
| 196 |
case 1: // Request headers |
| 197 |
if text == crlf { // End of headers |
| 198 |
if len(getMatch) > 0 { |
| 199 |
break Loop |
| 200 |
} |
| 201 |
if contentLength == 0 { |
| 202 |
return bad("content-length header missing") |
| 203 |
} |
| 204 |
section++ |
| 205 |
continue |
| 206 |
} |
| 207 |
pair := strings.SplitN(text, ":", 2) |
| 208 |
if len(pair) == 2 { |
| 209 |
switch strings.ToLower(pair[0]) { |
| 210 |
case "content-length": |
| 211 |
length, err := strconv.Atoi(strings.TrimSpace(pair[1])) |
| 212 |
if err != nil || length <= 0 || length > maxContentLength { |
| 213 |
return bad("invalid content length") |
| 214 |
} |
| 215 |
contentLength = length |
| 216 |
case "x-api-key": |
| 217 |
apiKey = strings.TrimSpace(pair[1]) |
| 218 |
} |
| 219 |
} |
| 220 |
case 2: // Request body |
| 221 |
bodyBuilder.WriteString(text) |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 { |
| 226 |
return unauthorized("invalid api key") |
| 227 |
} |
| 228 |
|
| 229 |
if len(getMatch) > 0 { |
| 230 |
response := server.getHandler(parseGetParams(getMatch[1])) |
| 231 |
if len(response) > 0 { |
| 232 |
return good(response) |
| 233 |
} |
| 234 |
return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`) |
| 235 |
} |
| 236 |
|
| 237 |
body := bodyBuilder.String() |
| 238 |
if len(body) < contentLength { |
| 239 |
return bad("incomplete request") |
| 240 |
} |
| 241 |
body = body[:contentLength] |
| 242 |
|
| 243 |
actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"), false) |
| 244 |
if err != nil { |
| 245 |
return bad(err.Error()) |
| 246 |
} |
| 247 |
if len(actions) == 0 { |
| 248 |
return bad("no action specified") |
| 249 |
} |
| 250 |
|
| 251 |
select { |
| 252 |
case server.actionChannel <- actions: |
| 253 |
case <-time.After(channelTimeout): |
| 254 |
return httpUnavailable + crlf |
| 255 |
} |
| 256 |
return httpOk + crlf |
| 257 |
} |
| 258 |
|
| 259 |
func parseGetParams(query string) getParams { |
| 260 |
params := getParams{limit: 100, offset: 0} |
| 261 |
for _, pair := range strings.Split(query, "&") { |
| 262 |
parts := strings.SplitN(pair, "=", 2) |
| 263 |
if len(parts) == 2 { |
| 264 |
switch parts[0] { |
| 265 |
case "limit", "offset": |
| 266 |
if val, err := strconv.Atoi(parts[1]); err == nil { |
| 267 |
if parts[0] == "limit" { |
| 268 |
params.limit = val |
| 269 |
} else { |
| 270 |
params.offset = val |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
} |
| 275 |
} |
| 276 |
return params |
| 277 |
} |