@marcel91200 / caddy Mirror · read-only
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 11, 01:00 UTC

master
go 82 lines 2.18 KB
Raw
1 package proxyprotocol
2
3 import (
4 "errors"
5 "fmt"
6 "strings"
7
8 goproxy "github.com/pires/go-proxyproto"
9 )
10
11 type Policy int
12
13 // as defined in: https://pkg.go.dev/github.com/pires/go-proxyproto@v0.7.0#Policy
14 const (
15 // IGNORE address from PROXY header, but accept connection
16 PolicyIGNORE Policy = iota
17 // USE address from PROXY header
18 PolicyUSE
19 // REJECT connection when PROXY header is sent
20 // Note: even though the first read on the connection returns an error if
21 // a PROXY header is present, subsequent reads do not. It is the task of
22 // the code using the connection to handle that case properly.
23 PolicyREJECT
24 // REQUIRE connection to send PROXY header, reject if not present
25 // Note: even though the first read on the connection returns an error if
26 // a PROXY header is not present, subsequent reads do not. It is the task
27 // of the code using the connection to handle that case properly.
28 PolicyREQUIRE
29 // SKIP accepts a connection without requiring the PROXY header
30 // Note: an example usage can be found in the SkipProxyHeaderForCIDR
31 // function.
32 PolicySKIP
33 )
34
35 var policyToGoProxyPolicy = map[Policy]goproxy.Policy{
36 PolicyUSE: goproxy.USE,
37 PolicyIGNORE: goproxy.IGNORE,
38 PolicyREJECT: goproxy.REJECT,
39 PolicyREQUIRE: goproxy.REQUIRE,
40 PolicySKIP: goproxy.SKIP,
41 }
42
43 var policyMap = map[Policy]string{
44 PolicyUSE: "USE",
45 PolicyIGNORE: "IGNORE",
46 PolicyREJECT: "REJECT",
47 PolicyREQUIRE: "REQUIRE",
48 PolicySKIP: "SKIP",
49 }
50
51 var policyMapRev = map[string]Policy{
52 "USE": PolicyUSE,
53 "IGNORE": PolicyIGNORE,
54 "REJECT": PolicyREJECT,
55 "REQUIRE": PolicyREQUIRE,
56 "SKIP": PolicySKIP,
57 }
58
59 // MarshalText implements the text marshaller method.
60 func (x Policy) MarshalText() ([]byte, error) {
61 return []byte(policyMap[x]), nil
62 }
63
64 // UnmarshalText implements the text unmarshaller method.
65 func (x *Policy) UnmarshalText(text []byte) error {
66 name := string(text)
67 tmp, err := parsePolicy(name)
68 if err != nil {
69 return err
70 }
71 *x = tmp
72 return nil
73 }
74
75 func parsePolicy(name string) (Policy, error) {
76 if x, ok := policyMapRev[strings.ToUpper(name)]; ok {
77 return x, nil
78 }
79 return Policy(0), fmt.Errorf("%s is %w", name, errInvalidPolicy)
80 }
81
82 var errInvalidPolicy = errors.New("invalid policy")