<commit_before>package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/k0kubun/pp"
)

const (
	httpVer     = "HTTP/1.0"
	headerDelim = ": "
	maxBodyLen  = 1024 * 1024
	serverName  = "LittleHTTP"
	serverVer   = "1.0"
	usage       = "Usage: %s [-port=n] [-chroot -user=u -group=g] [-debug] <docroot>\n"
)

// HTTPHeaderField represents an HTTP header field.
type HTTPHeaderField map[string]string

// HTTPRequest represents an HTTP request.
type HTTPRequest struct {
	method string
	path   string
	ver    float64
	header HTTPHeaderField
	body   []byte
	length int64
}

type option struct {
	debug  bool
	chroot bool
	user   string
	group  string
	port   int
}

type logger interface {
	debug(format string, arg ...interface{})
}

type httpLogger struct {
	debugMode bool
}

func newLogger(debugMode bool) *httpLogger {
	return &httpLogger{debugMode: debugMode}
}

func (l *httpLogger) debug(format string, arg ...interface{}) {
	if !l.debugMode {
		return
	}

	fmt.Fprintf(os.Stderr, format, arg...)
}

func main() {
	opt := &option{}
	flag.BoolVar(&opt.debug, "debug", false, "start on debug mode")
	flag.BoolVar(&opt.chroot, "chroot", false, "change root directory")
	flag.StringVar(&opt.user, "user", "user", "user")
	flag.StringVar(&opt.group, "group", "group", "group")
	flag.IntVar(&opt.port, "port", 8080, "port")
	flag.Parse()

	args := flag.Args()

	logger := newLogger(opt.debug)
	logger.debug("%v\n", opt)

	if _, e := pp.Print(opt); e != nil {
		return
	}

	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, usage, os.Args[0])
		return
	}

	// TODO: installSignalHandlers()

	docroot := args[0]
	service(os.Stdin, os.Stdout, docroot)
}

func service(in, out *os.File, docroot string) {
	req, err := readRequest(in)<commit_msg>httpd.go: add `socket -> bind -> listen` flow<commit_after>package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/k0kubun/pp"
)

const (
	httpVer     = "HTTP/1.0"
	headerDelim = ": "
	maxBodyLen  = 1024 * 1024
	serverName  = "LittleHTTP"
	serverVer   = "1.0"
	usage       = "Usage: %s [-port=n] [-chroot -user=u -group=g] [-debug] <docroot>\n"
)

// HTTPHeaderField represents an HTTP header field.
type HTTPHeaderField map[string]string

// HTTPRequest represents an HTTP request.
type HTTPRequest struct {
	method string
	path   string
	ver    float64
	header HTTPHeaderField
	body   []byte
	length int64
}

type option struct {
	debug  bool
	chroot bool
	user   string
	group  string
	port   int
}

type logger interface {
	debug(format string, arg ...interface{})
}

type httpLogger struct {
	debugMode bool
}

func newLogger(debugMode bool) *httpLogger {
	return &httpLogger{debugMode: debugMode}
}

func (l *httpLogger) debug(format string, arg ...interface{}) {
	if !l.debugMode {
		return
	}

	_, _ = pp.Fprintf(os.Stderr, format, arg...)
}

func main() {
	opt := &option{}
	flag.BoolVar(&opt.debug, "debug", false, "start on debug mode")
	flag.BoolVar(&opt.chroot, "chroot", false, "change root directory")
	flag.StringVar(&opt.user, "user", "user", "user")
	flag.StringVar(&opt.group, "group", "group", "group")
	flag.IntVar(&opt.port, "port", 8080, "port")
	flag.Parse()

	args := flag.Args()

	logger := newLogger(opt.debug)
	logger.debug("%v\n", opt)

	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, usage, os.Args[0])
		return
	}

	// TODO: installSignalHandlers()

	docroot := args[0]

	server, err := listenSocket(opt.port)
	if err != nil {
		perror(err)
		return
	}

	logger.debug("server fd: %v\n", server)

	service(os.Stdin, os.Stdout, docroot)
}

const maxBacklog = 5

func listenSocket(port int) (int, error) {
	sock, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)
	if err != nil {
		return 0, fmt.Errorf("socket() failed: %v", err)
	}

	sa, err := syscall.Getsockname(sock)
	if err != nil {
		return 0, fmt.Errorf("syscall.Getsockname(%v) failed: %v", sock, err)
	}

	if e := syscall.Bind(sock, sa); e != nil {
		return 0, fmt.Errorf("bind(%v, %v) failed: %v", sock, sa, err)
	}

	if e := syscall.Listen(sock, maxBacklog); e != nil {
		return 0, fmt.Errorf("listen(%v, %v) failed: %v", sock, maxBacklog, err)
	}

	return sock, nil
}

func service(in, out *os.File, docroot string) {
	req, err := readRequest(in)
{'fraction_non_alphanumeric': 0.1600831600831601, 'fraction_numerical': 0.012243012243012243, 'mean_word_length': 3.7739801543550167, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2180177', 'n_tokens_mistral': 1725, 'n_tokens_neox': 1635, 'n_words': 423}