-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
103 lines (86 loc) · 2.49 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"flag"
"net"
"os"
"strconv"
)
var config *Config
func handleConnection(conn net.Conn) {
connection := NewConnection(conn)
defer connection.Close()
connection.Handle()
}
func acceptedConnsChannel(listener net.Listener) chan net.Conn {
channel := make(chan net.Conn)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
logger.Warn.Println("Could not accept socket:", err)
continue
}
channel <- conn
}
}()
return channel
}
func listenAndServe(port int) {
listenOn := ":" + strconv.Itoa(port)
server, err := net.Listen("tcp", listenOn)
if err != nil {
logger.Fatal.Println("Could not start server:", err)
os.Exit(1)
}
logger.Info.Println("Server started on", listenOn)
acceptedConnsChannel := acceptedConnsChannel(server)
for {
go handleConnection(<-acceptedConnsChannel)
}
}
func main() {
InitLogger()
configPtr := flag.String("config", "", "config file")
portPtr := flag.Int("port", 25000, "listen port")
stripProxyHeadersPtr := flag.Bool("strip-proxy-headers", true, "strip proxy headers from http requests")
useIncomingLocalAddr := flag.Bool("use-incoming-local-addr", true, "attempt to use the local address of the incoming connection when connecting upstream")
dialTimeoutPtr := flag.Int("dial-timeout", 30, " timeout for connecting to an upstream server in seconds")
usernamePtr := flag.String("username", "", "username for proxy authentication")
passwordPtr := flag.String("password", "", "password for proxy authentication")
flag.Parse()
if *configPtr != "" {
configFile, err := os.Open(*configPtr)
if err != nil {
logger.Fatal.Println("Could not open config file", err)
os.Exit(1)
}
config, err = NewConfigFromReader(configFile)
if err != nil {
logger.Fatal.Println("Could not parse config file", err)
os.Exit(1)
}
configFile.Close()
} else {
config = &Config{
Port: *portPtr,
StripProxyHeaders: *stripProxyHeadersPtr,
UseIncomingLocalAddr: *useIncomingLocalAddr,
DialTimeout: *dialTimeoutPtr,
}
if *usernamePtr != "" {
config.Credentials = []Credential{
{Username: *usernamePtr, Password: *passwordPtr},
}
}
}
err := config.Validate()
if err != nil {
logger.Fatal.Println("Config is not valid:", err)
os.Exit(1)
}
if config.AuthenticationRequired() {
logger.Info.Println("Credentials provided. Proxy authentication will be required for all connections.")
}
logger.Info.Println("Prepare for takeoff...")
listenAndServe(config.Port)
}