forked from caddyserver/caddy
/
setup.go
233 lines (201 loc) · 5.35 KB
/
setup.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
// Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package limits
import (
"errors"
"sort"
"strconv"
"strings"
"github.com/mholt/caddy"
"github.com/mholt/caddy/caddyhttp/httpserver"
)
const (
serverType = "http"
pluginName = "limits"
)
func init() {
caddy.RegisterPlugin(pluginName, caddy.Plugin{
ServerType: serverType,
Action: setupLimits,
})
}
// pathLimitUnparsed is a PathLimit before it's parsed
type pathLimitUnparsed struct {
Path string
Limit string
}
func setupLimits(c *caddy.Controller) error {
bls, err := parseLimits(c)
if err != nil {
return err
}
httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler {
return Limit{Next: next, BodyLimits: bls}
})
return nil
}
func parseLimits(c *caddy.Controller) ([]httpserver.PathLimit, error) {
config := httpserver.GetConfig(c)
if !c.Next() {
return nil, c.ArgErr()
}
args := c.RemainingArgs()
argList := []pathLimitUnparsed{}
headerLimit := ""
switch len(args) {
case 0:
// Format: limits {
// header <limit>
// body <path> <limit>
// body <limit>
// ...
// }
for c.NextBlock() {
kind := c.Val()
pathOrLimit := c.RemainingArgs()
switch kind {
case "header":
if len(pathOrLimit) != 1 {
return nil, c.ArgErr()
}
headerLimit = pathOrLimit[0]
case "body":
if len(pathOrLimit) == 1 {
argList = append(argList, pathLimitUnparsed{
Path: "/",
Limit: pathOrLimit[0],
})
break
}
if len(pathOrLimit) == 2 {
argList = append(argList, pathLimitUnparsed{
Path: pathOrLimit[0],
Limit: pathOrLimit[1],
})
break
}
fallthrough
default:
return nil, c.ArgErr()
}
}
case 1:
// Format: limits <limit>
headerLimit = args[0]
argList = []pathLimitUnparsed{{
Path: "/",
Limit: args[0],
}}
default:
return nil, c.ArgErr()
}
if headerLimit != "" {
size := parseSize(headerLimit)
if size < 1 { // also disallow size = 0
return nil, c.ArgErr()
}
config.Limits.MaxRequestHeaderSize = size
}
if len(argList) > 0 {
pathLimit, err := parseArguments(argList)
if err != nil {
return nil, c.ArgErr()
}
SortPathLimits(pathLimit)
config.Limits.MaxRequestBodySizes = pathLimit
}
return config.Limits.MaxRequestBodySizes, nil
}
func parseArguments(args []pathLimitUnparsed) ([]httpserver.PathLimit, error) {
pathLimit := []httpserver.PathLimit{}
for _, pair := range args {
size := parseSize(pair.Limit)
if size < 1 { // also disallow size = 0
return pathLimit, errors.New("Parse failed")
}
pathLimit = addPathLimit(pathLimit, pair.Path, size)
}
return pathLimit, nil
}
var validUnits = []struct {
symbol string
multiplier int64
}{
{"KB", 1024},
{"MB", 1024 * 1024},
{"GB", 1024 * 1024 * 1024},
{"B", 1},
{"", 1}, // defaulting to "B"
}
// parseSize parses the given string as size limit
// Size are positive numbers followed by a unit (case insensitive)
// Allowed units: "B" (bytes), "KB" (kilo), "MB" (mega), "GB" (giga)
// If the unit is omitted, "b" is assumed
// Returns the parsed size in bytes, or -1 if cannot parse
func parseSize(sizeStr string) int64 {
sizeStr = strings.ToUpper(sizeStr)
for _, unit := range validUnits {
if strings.HasSuffix(sizeStr, unit.symbol) {
size, err := strconv.ParseInt(sizeStr[0:len(sizeStr)-len(unit.symbol)], 10, 64)
if err != nil {
return -1
}
return size * unit.multiplier
}
}
// Unreachable code
return -1
}
// addPathLimit appends the path-to-request body limit mapping to pathLimit
// Slashes are checked and added to path if necessary. Duplicates are ignored.
func addPathLimit(pathLimit []httpserver.PathLimit, path string, limit int64) []httpserver.PathLimit {
// Enforces preceding slash
if path[0] != '/' {
path = "/" + path
}
// Use the last value if there are duplicates
for i, p := range pathLimit {
if p.Path == path {
pathLimit[i].Limit = limit
return pathLimit
}
}
return append(pathLimit, httpserver.PathLimit{Path: path, Limit: limit})
}
// SortPathLimits sort pathLimits by their paths length, longest first
func SortPathLimits(pathLimits []httpserver.PathLimit) {
sorter := &pathLimitSorter{
pathLimits: pathLimits,
by: LengthDescending,
}
sort.Sort(sorter)
}
// structs and methods implementing the sorting interfaces for PathLimit
type pathLimitSorter struct {
pathLimits []httpserver.PathLimit
by func(p1, p2 *httpserver.PathLimit) bool
}
func (s *pathLimitSorter) Len() int {
return len(s.pathLimits)
}
func (s *pathLimitSorter) Swap(i, j int) {
s.pathLimits[i], s.pathLimits[j] = s.pathLimits[j], s.pathLimits[i]
}
func (s *pathLimitSorter) Less(i, j int) bool {
return s.by(&s.pathLimits[i], &s.pathLimits[j])
}
// LengthDescending is the comparator for SortPathLimits
func LengthDescending(p1, p2 *httpserver.PathLimit) bool {
return len(p1.Path) > len(p2.Path)
}