-
Notifications
You must be signed in to change notification settings - Fork 31
/
http.go
207 lines (170 loc) · 4.84 KB
/
http.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
package binder
import (
"crypto/tls"
"encoding/base64"
"fmt"
"net"
"strings"
"time"
proto "github.com/inconshreveable/go-tunnel/proto"
vhost "github.com/inconshreveable/go-vhost"
)
const (
maxRandomAttempts = 10
)
func normalize(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
type vhostMuxer interface {
Listen(string) (net.Listener, error)
NextError() (net.Conn, error)
}
type HTTPBinder struct {
mux vhostMuxer // muxer
publicBaseAddr string // public host or host:port address used in creating the returned URLs when binding
proto string // http or https
}
func (b *HTTPBinder) Bind(rawOpts interface{}) (net.Listener, string, error) {
var opts proto.HTTPOptions
if err := proto.UnpackInterfaceField(rawOpts, &opts); err != nil {
return nil, "", err
}
return b.BindOpts(&opts)
}
func (b *HTTPBinder) BindOpts(opts *proto.HTTPOptions) (listener net.Listener, url string, err error) {
for i := 0; i < maxRandomAttempts; i++ {
// pick a name
hostname, isRandom := pickName(opts.Hostname, opts.Subdomain, b.publicBaseAddr)
// bind it - this could fail if the requested hostname is already bound
if listener, err = b.mux.Listen(hostname); err != nil {
// only try again if we're picking names at random
if !isRandom {
return
} else {
continue
}
}
// construct the public url
url = fmt.Sprintf("%s://%s", b.proto, hostname)
// handle http auth
if opts.Auth != "" {
listener = newAuthListener(listener, opts.Auth)
}
return
}
err = fmt.Errorf("Failed to assign random hostname")
return
}
const (
httpResponseTemplate = `HTTP/1.0 %s
Content-Length: %d
%s`
)
func (b *HTTPBinder) handleMuxErrors() {
makeResponse := func(status, content string) []byte {
return []byte(fmt.Sprintf(httpResponseTemplate, status, len(content), content))
}
for {
conn, err := b.mux.NextError()
switch err.(type) {
case vhost.NotFound:
msg := err.Error()
if vconn, ok := conn.(vhost.Conn); ok {
msg = fmt.Sprintf("Tunnel %s not found", vconn.Host())
}
conn.Write(makeResponse("404 Not Found", msg))
case vhost.BadRequest:
conn.Write(makeResponse("400 Bad Request", fmt.Sprintf("Bad request: %v", err)))
case vhost.Closed:
return
default:
if conn != nil {
conn.Write(makeResponse("500 Internal Server Error", fmt.Sprintf("Internal Server Error: %v", err)))
}
}
if conn != nil {
conn.Close()
}
}
}
func sharedInit(mux vhostMuxer, protocol, publicBaseAddr string) (*HTTPBinder, error) {
// make the binder
binder := &HTTPBinder{
mux: mux,
publicBaseAddr: normalize(publicBaseAddr),
proto: protocol,
}
// start handle muxing errors
go binder.handleMuxErrors()
return binder, nil
}
func NewHTTPBinder(addr, publicBaseAddr string, muxTimeout time.Duration) (*HTTPBinder, error) {
// bind a port to listen for http connections
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
// create a new muxer that will let us bind virtual hostnames
mux, err := vhost.NewHTTPMuxer(listener, muxTimeout)
if err != nil {
return nil, err
}
return sharedInit(mux, "http", publicBaseAddr)
}
func NewHTTPSBinder(addr, publicBaseAddr string, muxTimeout time.Duration, tlsConfig *tls.Config) (*HTTPBinder, error) {
// bind a port to listen for https connections
listener, err := tls.Listen("tcp", addr, tlsConfig)
if err != nil {
return nil, err
}
// create a new muxer that will let us bind virtual hostnames
mux, err := vhost.NewHTTPMuxer(listener, muxTimeout)
if err != nil {
return nil, err
}
return sharedInit(mux, "https", publicBaseAddr)
}
// XXX: perhaps this shouldn't be part of a binder
type authListener struct {
net.Listener
encodedAuth string
}
func (a *authListener) Accept() (net.Conn, error) {
for {
c, err := a.Listener.Accept()
if err != nil {
return nil, err
}
var httpConn *vhost.HTTPConn
switch typedConn := c.(type) {
case *vhost.HTTPConn:
httpConn = typedConn
case *HTTPReverseProxyConn:
httpConn = typedConn.HTTPConn
default:
c.Close()
return nil, fmt.Errorf("Accepted conn %v is not *vhost.HTTPConn", c)
}
// If the http auth doesn't match this request's auth
// then fail the request with 401 Not Authorized and request the client reissue the
// request with basic auth
auth := httpConn.Request.Header.Get("Authorization")
if auth != a.encodedAuth {
c.Write([]byte(`HTTP/1.0 401 Not Authorized
WWW-Authenticate: Basic realm="go-tunnel"
Content-Length: 22
Authorization required`))
c.Close()
// accept the next connection if the auth fails
continue
}
return c, nil
}
}
func newAuthListener(l net.Listener, auth string) *authListener {
// pre-encode the http basic auth for fast comparisons later
return &authListener{
Listener: l,
encodedAuth: "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)),
}
}