forked from fabiolb/fabio
/
util.go
113 lines (100 loc) · 2.57 KB
/
util.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
package proxy
import (
"errors"
"log"
"net"
"net/http"
"strings"
"github.com/eBay/fabio/config"
"github.com/eBay/fabio/route"
)
// addHeaders adds/updates headers in request
//
// * add/update `Forwarded` header
// * add X-Forwarded-Proto header, if not present
// * add X-Real-Ip, if not present
// * ClientIPHeader != "": Set header with that name to <remote ip>
// * TLS connection: Set header with name from `cfg.TLSHeader` to `cfg.TLSHeaderValue`
//
func addHeaders(r *http.Request, cfg config.Proxy) error {
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return errors.New("cannot parse " + r.RemoteAddr)
}
// set configurable ClientIPHeader
// X-Real-Ip is set later and X-Forwarded-For is set
// by the Go HTTP reverse proxy.
if cfg.ClientIPHeader != "" &&
cfg.ClientIPHeader != "X-Forwarded-For" &&
cfg.ClientIPHeader != "X-Real-Ip" {
r.Header.Set(cfg.ClientIPHeader, remoteIP)
}
if r.Header.Get("X-Real-Ip") == "" {
r.Header.Set("X-Real-Ip", remoteIP)
}
// set the X-Forwarded-For header for websocket
// connections since they aren't handled by the
// http proxy which sets it.
ws := r.Header.Get("Upgrade") == "websocket"
if ws {
r.Header.Set("X-Forwarded-For", remoteIP)
}
if r.Header.Get("X-Forwarded-Proto") == "" {
switch {
case ws && r.TLS != nil:
r.Header.Set("X-Forwarded-Proto", "wss")
case ws && r.TLS == nil:
r.Header.Set("X-Forwarded-Proto", "ws")
case r.TLS != nil:
r.Header.Set("X-Forwarded-Proto", "https")
default:
r.Header.Set("X-Forwarded-Proto", "http")
}
}
if r.Header.Get("X-Forwarded-Port") == "" {
r.Header.Set("X-Forwarded-Port", localPort(r))
}
fwd := r.Header.Get("Forwarded")
if fwd == "" {
fwd = "for=" + remoteIP
switch {
case ws && r.TLS != nil:
fwd += "; proto=wss"
case ws && r.TLS == nil:
fwd += "; proto=ws"
case r.TLS != nil:
fwd += "; proto=https"
default:
fwd += "; proto=http"
}
}
if cfg.LocalIP != "" {
fwd += "; by=" + cfg.LocalIP
}
r.Header.Set("Forwarded", fwd)
if cfg.TLSHeader != "" && r.TLS != nil {
r.Header.Set(cfg.TLSHeader, cfg.TLSHeaderValue)
}
return nil
}
// target looks up a target URL for the request from the current routing table.
func target(r *http.Request) *route.Target {
t := route.GetTable().Lookup(r, r.Header.Get("trace"))
if t == nil {
log.Print("[WARN] No route for ", r.Host, r.URL)
}
return t
}
func localPort(r *http.Request) string {
if r == nil {
return ""
}
n := strings.Index(r.Host, ":")
if n > 0 && n < len(r.Host)-1 {
return r.Host[n+1:]
}
if r.TLS != nil {
return "443"
}
return "80"
}