Skip to content
Myr

server.go

This file

Path

src/server.go

277 lines · 6.8 KiB · Go

Last changed by

Allow bare put action in transform outputJunegunn Choibefore adoptionae78a5c

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	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					return136				}137				continue138			}139			conn.Write([]byte(server.handleHttpRequest(conn)))140			conn.Close()141		}142	}()143144	return listener, port, nil145}146147// Here we are writing a simplistic HTTP server without using net/http148// package to reduce the size of the binary.149//150// * No --listen:            2.8MB151// * --listen with net/http: 5.7MB152// * --listen w/o net/http:  3.3MB153func (server *httpServer) handleHttpRequest(conn net.Conn) string {154	contentLength := 0155	apiKey := ""156	var bodyBuilder strings.Builder157	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, nil177		}178		if atEOF || bodyBuilder.Len()+len(data) >= contentLength {179			return 0, data, bufio.ErrFinalToken180		}181		return 0, nil, nil182	})183184	section := 0185	var getMatch []string186Loop:187	for scanner.Scan() {188		text := scanner.Text()189		switch section {190		case 0: // Request line191			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 headers197			if text == crlf { // End of headers198				if len(getMatch) > 0 {199					break Loop200				}201				if contentLength == 0 {202					return bad("content-length header missing")203				}204				section++205				continue206			}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 = length216				case "x-api-key":217					apiKey = strings.TrimSpace(pair[1])218				}219			}220		case 2: // Request body221			bodyBuilder.WriteString(text)222		}223	}224225	if len(server.apiKey) != 0 && subtle.ConstantTimeCompare([]byte(apiKey), server.apiKey) != 1 {226		return unauthorized("invalid api key")227	}228229	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	}236237	body := bodyBuilder.String()238	if len(body) < contentLength {239		return bad("incomplete request")240	}241	body = body[:contentLength]242243	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	}250251	select {252	case server.actionChannel <- actions:253	case <-time.After(channelTimeout):254		return httpUnavailable + crlf255	}256	return httpOk + crlf257}258259func 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 = val269					} else {270						params.offset = val271					}272				}273			}274		}275	}276	return params277}