-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
237 lines (213 loc) · 5.22 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"flag"
"fmt"
"io"
"log"
"math/big"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
// BuildDate: Binary file compilation time
var (
BuildDate string
)
var (
tlsc *tls.Config
transport *http.Transport
revers *httputil.ReverseProxy
)
type Options struct {
UnixSocket string
ProxyURL string
CertFile string
KeyFile string
}
var options *Options
func init() {
options = &Options{}
flag.StringVar(&options.UnixSocket, "unix", "/tmp/fastcar.sock", "unix socket addr")
flag.StringVar(&options.ProxyURL, "proxy", "", "proxy url: scheme://user:password@host:port")
flag.StringVar(&options.CertFile, "cert", "", "tls cert file, empty auto create")
flag.StringVar(&options.KeyFile, "key", "", "tls key file, empty auto create")
flag.Parse()
// ========== transport ============
transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 1024,
IdleConnTimeout: 120 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: 100,
}
if options.ProxyURL != "" {
pu, err := url.Parse(options.ProxyURL)
if err != nil {
panic(fmt.Errorf("invalid proxy url: %w", err))
}
transport.Proxy = http.ProxyURL(pu)
transport.ForceAttemptHTTP2 = false
}
// ========== revers proxy ============
revers = &httputil.ReverseProxy{
FlushInterval: -1,
Director: func(req *http.Request) {
req.URL.Host = req.Host
localAddr := req.Context().Value(http.LocalAddrContextKey).(net.Addr).String()
index := strings.Index(localAddr, ":")
if index < 4 {
log.Println("BUG: Local address format error:", localAddr)
return
}
req.URL.Scheme = localAddr[:index]
},
Transport: transport,
}
// ========== tls config ============
var cf tls.Certificate
var err error
if options.CertFile != "" && options.KeyFile != "" {
cf, err = tls.LoadX509KeyPair(options.CertFile, options.KeyFile)
if err != nil {
panic(fmt.Errorf("load cert file error: %w", err))
}
} else {
key, cert, err := createCert()
if err != nil {
panic(fmt.Errorf("create cert error: %w", err))
}
cf = tls.Certificate{PrivateKey: key, Certificate: [][]byte{cert.Raw}}
}
tlsc = &tls.Config{
Certificates: []tls.Certificate{cf},
}
}
func main() {
_ = os.RemoveAll(options.UnixSocket)
ln, err := net.Listen("unix", options.UnixSocket)
if err != nil {
panic(err)
}
fl := &FastCarListener{ln}
showBanner()
err = http.Serve(fl, revers)
if err != nil {
panic(err)
}
}
func showBanner() {
fmt.Println("running fastcar, listen on unix socket:", options.UnixSocket)
fmt.Println("Build Date: ", BuildDate)
fmt.Println(` ________ ______
| \ / \
| $$$$$$$$ | $$$$$$\
| $$__ | $$ \$$
| $$ \ | $$
| $$$$$ | $$ __
| $$ | $$__/ \
| $$ \$$ $$
\$$ \$$$$$$
`)
}
type bufConn struct {
net.Conn
buf *bytes.Reader
scheme string
}
func (c *bufConn) Read(p []byte) (int, error) {
if c.buf == nil {
return c.Conn.Read(p)
}
n, err := c.buf.Read(p)
if err != nil {
return n, err
}
if n < len(p) {
c.buf = nil
cn, err := c.Conn.Read(p[n:])
cn += n
return cn, err
}
return n, nil
}
func (c *bufConn) LocalAddr() net.Addr {
name := c.scheme + ":" + options.UnixSocket
return &net.UnixAddr{Name: name, Net: "unix"}
}
type FastCarListener struct {
net.Listener
}
func (fl *FastCarListener) Accept() (net.Conn, error) {
conn, err := fl.Listener.Accept()
if err != nil {
return nil, err
}
buf := make([]byte, 1)
_, err = io.ReadFull(conn, buf)
if err != nil {
log.Println("first read err: ", err)
return nil, err
}
bconn := &bufConn{Conn: conn, buf: bytes.NewReader(buf)}
switch buf[0] {
case 0x16:
tlsConn := tls.Server(bconn, tlsc)
if err := tlsConn.Handshake(); err != nil {
return nil, err
}
conn = tlsConn
bconn.scheme = "https"
default:
conn = bconn
bconn.scheme = "http"
}
return conn, nil
}
func createCert() (*ecdsa.PrivateKey, *x509.Certificate, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
template := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano() / 100000),
Subject: pkix.Name{
CommonName: "fastcar",
Organization: []string{"fastcar"},
},
NotBefore: time.Now().Add(-time.Hour * 48),
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 100),
BasicConstraintsValid: true,
IsCA: false,
SignatureAlgorithm: x509.ECDSAWithSHA256,
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageServerAuth,
x509.ExtKeyUsageClientAuth,
},
}
certBytes, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
return nil, nil, err
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, nil, err
}
return key, cert, nil
}