blocking-http-proxy/main.go

71 lines
1.9 KiB
Go
Raw Permalink Normal View History

2019-09-12 22:06:48 +02:00
package main
import (
"./proxy"
2019-09-12 22:06:48 +02:00
"crypto/tls"
"fmt"
"github.com/akamensky/argparse"
2019-09-12 22:06:48 +02:00
"net/http"
"os"
2019-09-12 22:06:48 +02:00
)
func readArgs() (string, string, string) {
parser := argparse.NewParser("blocking-http-proxy", "HTTP/S proxy that blocks")
host := parser.String("", "host", &argparse.Options{Help: "host", Required: false})
port := parser.String("", "port", &argparse.Options{Help: "port", Required: false})
blockFile := parser.String("", "block", &argparse.Options{Help: "YAML block file", Required: false})
err := parser.Parse(os.Args)
2019-09-12 22:06:48 +02:00
if err != nil {
fmt.Println(parser.Usage(err))
2019-09-12 22:06:48 +02:00
}
if *host == "" {
*host = "0.0.0.0"
2019-09-12 22:06:48 +02:00
}
if *port == "" {
*port = "11666"
2019-09-12 22:06:48 +02:00
}
if *blockFile == "" {
*blockFile = "block.yaml"
2019-09-12 22:06:48 +02:00
}
return *host, *port, *blockFile
2019-09-12 22:06:48 +02:00
}
func main() {
logger := proxy.NewLogger()
blockedLogger := proxy.NewFileLogger("block.log")
allowLogger := proxy.NewFileLogger("allow.log")
host, port, blockFile := readArgs()
address := host+":"+port
c := proxy.NewConfig()
fmt.Println(len(os.Args), os.Args)
logger.Printf("Server will run on: %s\n", address)
regList := c.LoadBlockedList(blockFile)
2019-09-12 22:06:48 +02:00
server := &http.Server{
Addr: address,
2019-09-12 22:06:48 +02:00
Handler: http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if proxy.ShouldBlock(regList, req.Host) {
blockedLogger.WriteLine("Blocked %s\n", false, req.Host)
2019-09-12 22:06:48 +02:00
if wr, ok := res.(http.Hijacker); ok {
conn, _, err := wr.Hijack()
if err != nil {
fmt.Fprint(res, err)
}
conn.Close()
}
} else {
if req.Method == http.MethodConnect {
allowLogger.WriteLine("proxy_url: %s\n", true, req.Host)
proxy.HandleTunneling(res, req)
2019-09-12 22:06:48 +02:00
} else {
allowLogger.WriteLine("proxy_url: %s %s\n", true, req.Host, req.RequestURI)
proxy.HandleRequestCustom(res, req)
2019-09-12 22:06:48 +02:00
}
}
}),
// Disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
server.ListenAndServe()
}