Skip to content
Myr

server.go

This file

Path

src/server.go

246 lines · 5.9 KiB · Go

Last changed by

Not known.

History of this file

Take 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	getHandler    func(getParams) 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, getHandler func(getParams) 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		getHandler:    getHandler,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				response := server.getHandler(parseGetParams(getMatch[1]))169				if len(response) > 0 {170					return good(response)171				}172				return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`)173			} else if !strings.HasPrefix(text, "POST / HTTP") {174				return bad("invalid request method")175			}176			section++177		case 1:178			if text == crlf {179				if contentLength == 0 {180					return bad("content-length header missing")181				}182				section++183				continue184			}185			pair := strings.SplitN(text, ":", 2)186			if len(pair) == 2 {187				switch strings.ToLower(pair[0]) {188				case "content-length":189					length, err := strconv.Atoi(strings.TrimSpace(pair[1]))190					if err != nil || length <= 0 || length > maxContentLength {191						return bad("invalid content length")192					}193					contentLength = length194				case "x-api-key":195					apiKey = strings.TrimSpace(pair[1])196				}197			}198		case 2:199			body += text200		}201	}202203	if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {204		return unauthorized("invalid api key")205	}206207	if len(body) < contentLength {208		return bad("incomplete request")209	}210	body = body[:contentLength]211212	actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"))213	if err != nil {214		return bad(err.Error())215	}216	if len(actions) == 0 {217		return bad("no action specified")218	}219220	select {221	case server.actionChannel <- actions:222	case <-time.After(channelTimeout):223		return httpUnavailable + crlf224	}225	return httpOk + crlf226}227228func parseGetParams(query string) getParams {229	params := getParams{limit: 100, offset: 0}230	for _, pair := range strings.Split(query, "&") {231		parts := strings.SplitN(pair, "=", 2)232		if len(parts) == 2 {233			switch parts[0] {234			case "limit", "offset":235				if val, err := strconv.Atoi(parts[1]); err == nil {236					if parts[0] == "limit" {237						params.limit = val238					} else {239						params.offset = val240					}241				}242			}243		}244	}245	return params246}