Skip to content
Myr

server.go

This file

Path

src/server.go

270 lines · 6.6 KiB · Go

Last changed by

Improve Unix domain socket handlingJunegunn Choibefore adoptionbf77206

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	sock string50}5152func (addr listenAddress) IsLocal() bool {53	return addr.host == "localhost" || addr.host == "127.0.0.1" || len(addr.sock) > 054}5556var defaultListenAddr = listenAddress{"localhost", 0, ""}5758func parseListenAddress(address string) (listenAddress, error) {59	if strings.HasSuffix(address, ".sock") {60		return listenAddress{"", 0, address}, nil61	}6263	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, ""}, nil79}8081func startHttpServer(address listenAddress, actionChannel chan []*action, getHandler func(getParams) string) (net.Listener, int, error) {82	host := address.host83	port := address.port84	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	}8889	var listener net.Listener90	var err error91	if len(address.sock) > 0 {92		if _, err := os.Stat(address.sock); err == nil {93			// Check if the socket is already in use94			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 error118			port, err = strconv.Atoi(parts[len(parts)-1])119			if err != nil {120				return nil, port, err121			}122		}123	}124125	server := httpServer{126		apiKey:        []byte(apiKey),127		actionChannel: actionChannel,128		getHandler:    getHandler,129	}130131	go func() {132		for {133			conn, err := listener.Accept()134			if err != nil {135				if errors.Is(err, net.ErrClosed) {136					return137				}138				continue139			}140			conn.Write([]byte(server.handleHttpRequest(conn)))141			conn.Close()142		}143	}()144145	return listener, port, nil146}147148// Here we are writing a simplistic HTTP server without using net/http149// package to reduce the size of the binary.150//151// * No --listen:            2.8MB152// * --listen with net/http: 5.7MB153// * --listen w/o net/http:  3.3MB154func (server *httpServer) handleHttpRequest(conn net.Conn) string {155	contentLength := 0156	apiKey := ""157	body := ""158	answer := func(code string, message string) string {159		message += "\n"160		return code + fmt.Sprintf("Content-Length: %d%s", len(message), crlf+crlf+message)161	}162	unauthorized := func(message string) string {163		return answer(httpUnauthorized, message)164	}165	bad := func(message string) string {166		return answer(httpBadRequest, message)167	}168	good := func(message string) string {169		return answer(httpOk+jsonContentType, message)170	}171	conn.SetReadDeadline(time.Now().Add(httpReadTimeout))172	scanner := bufio.NewScanner(conn)173	scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) {174		found := bytes.Index(data, []byte(crlf))175		if found >= 0 {176			token := data[:found+len(crlf)]177			return len(token), token, nil178		}179		if atEOF || len(body)+len(data) >= contentLength {180			return 0, data, bufio.ErrFinalToken181		}182		return 0, nil, nil183	})184185	section := 0186	for scanner.Scan() {187		text := scanner.Text()188		switch section {189		case 0:190			getMatch := getRegex.FindStringSubmatch(text)191			if len(getMatch) > 0 {192				response := server.getHandler(parseGetParams(getMatch[1]))193				if len(response) > 0 {194					return good(response)195				}196				return answer(httpUnavailable+jsonContentType, `{"error":"timeout"}`)197			} else if !strings.HasPrefix(text, "POST / HTTP") {198				return bad("invalid request method")199			}200			section++201		case 1:202			if text == crlf {203				if contentLength == 0 {204					return bad("content-length header missing")205				}206				section++207				continue208			}209			pair := strings.SplitN(text, ":", 2)210			if len(pair) == 2 {211				switch strings.ToLower(pair[0]) {212				case "content-length":213					length, err := strconv.Atoi(strings.TrimSpace(pair[1]))214					if err != nil || length <= 0 || length > maxContentLength {215						return bad("invalid content length")216					}217					contentLength = length218				case "x-api-key":219					apiKey = strings.TrimSpace(pair[1])220				}221			}222		case 2:223			body += text224		}225	}226227	if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {228		return unauthorized("invalid api key")229	}230231	if len(body) < contentLength {232		return bad("incomplete request")233	}234	body = body[:contentLength]235236	actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"))237	if err != nil {238		return bad(err.Error())239	}240	if len(actions) == 0 {241		return bad("no action specified")242	}243244	select {245	case server.actionChannel <- actions:246	case <-time.After(channelTimeout):247		return httpUnavailable + crlf248	}249	return httpOk + crlf250}251252func parseGetParams(query string) getParams {253	params := getParams{limit: 100, offset: 0}254	for _, pair := range strings.Split(query, "&") {255		parts := strings.SplitN(pair, "=", 2)256		if len(parts) == 2 {257			switch parts[0] {258			case "limit", "offset":259				if val, err := strconv.Atoi(parts[1]); err == nil {260					if parts[0] == "limit" {261						params.limit = val262					} else {263						params.offset = val264					}265				}266			}267		}268	}269	return params270}