forked from cubefs/cubefs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
300 lines (263 loc) · 7.28 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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// Copyright 2019 The ChubaoFS Authors.
//
// 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 objectnode
import (
"regexp"
"strings"
"net"
"net/http"
"time"
"github.com/chubaofs/chubaofs/util"
"github.com/chubaofs/chubaofs/util/log"
)
const (
pathSep = "/"
tempFileNameSep = "_"
)
var (
emptyPathItem = PathItem{}
// Regular expression used to match one or more path separators.
regexpSepPrefix = regexp.MustCompile("^/+")
// Regular expression to match more than two consecutive path separators.
regexpDupSep = regexp.MustCompile("/{2,}")
)
// PathItem defines path node attribute information,
// including node name and whether it is a directory.
type PathItem struct {
Name string
IsDirectory bool
}
// PathIterator is a path iterator. Used to sequentially iterate each path node from a complete path.
type PathIterator struct {
cursor int
path string
inited bool
}
func (p *PathIterator) init() {
if !p.inited {
p.path = strings.TrimSpace(p.path)
loc := regexpSepPrefix.FindStringIndex(p.path)
if len(loc) == 2 {
p.path = p.path[loc[1]:]
}
p.path = regexpDupSep.ReplaceAllString(p.path, pathSep)
p.inited = true
}
}
func (p *PathIterator) HasNext() bool {
p.init()
return p.cursor < len(p.path)
}
func (p *PathIterator) Reset() {
p.cursor = 0
}
func (p PathIterator) ToSlice() []PathItem {
newIterator := NewPathIterator(p.path)
result := make([]PathItem, 0)
for newIterator.HasNext() {
result = append(result, newIterator.Next())
}
return result
}
func (p *PathIterator) Next() PathItem {
p.init()
if p.cursor >= len(p.path) {
return emptyPathItem
}
var item PathItem
index := strings.Index(p.path[p.cursor:], pathSep)
if index >= 0 {
item = PathItem{
Name: p.path[p.cursor : p.cursor+index],
IsDirectory: true,
}
p.cursor = p.cursor + index + 1
} else {
item = PathItem{
Name: p.path[p.cursor:],
IsDirectory: false,
}
p.cursor = len(p.path)
}
return item
}
func NewPathIterator(path string) PathIterator {
return PathIterator{
path: path,
}
}
func splitPath(path string) (dirs []string, filename string) {
pathParts := strings.Split(path, pathSep)
if len(pathParts) > 1 {
dirs = pathParts[:len(pathParts)-1]
}
filename = pathParts[len(pathParts)-1]
return
}
func tempFileName(origin string) string {
return "." + origin + tempFileNameSep + util.RandomString(16, util.LowerLetter|util.UpperLetter)
}
func formatSimpleTime(time time.Time) string {
return time.UTC().Format("2006-01-02T15:04:05")
}
func formatTimeISO(time time.Time) string {
return time.UTC().Format("2006-01-02T15:04:05.000Z")
}
func formatTimeISOLocal(time time.Time) string {
return time.Local().Format("2006-01-02T15:04:05.000Z")
}
func formatTimeRFC1123(time time.Time) string {
return time.UTC().Format(http.TimeFormat)
}
func parseTimeRFC1123(timeStr string) (time.Time, error) {
t, err := time.Parse("Mon, 2 Jan 2006 15:04:05 GMT", timeStr)
if err != nil {
return t, err
}
return t, err
}
func transferError(key string, err error) Error {
// TODO: complete sys error transfer
ossError := Error{
Key: key,
Message: err.Error(),
}
return ossError
}
// get request remote IP
func getRequestIP(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
if ok := strings.Contains(IPAddress, ":"); ok {
IPAddress = strings.Split(IPAddress, ":")[0]
}
return IPAddress
}
// check ipnet contains ip
// ip: 172.17.0.2
// ipnet: 172.17.0.0/16
func isIPNetContainsIP(ipStr, ipnetStr string) (bool, error) {
if !strings.Contains(ipnetStr, "/") {
if ipStr == ipnetStr {
return true, nil
} else {
return false, nil
}
}
_, ipnet, err := net.ParseCIDR(ipnetStr)
if err != nil {
log.LogInfof("parse ipnet error ipnet %v", ipnetStr)
return false, err
}
ip := net.ParseIP(ipStr)
if ipnet.Contains(ip) {
return true, nil
}
return false, nil
}
func patternMatch(pattern, key string) bool {
if pattern == "" {
return key == pattern
}
if pattern == "*" {
return true
}
matched, err := regexp.MatchString(pattern, key)
if err != nil {
log.LogErrorf("patternMatch error %v", err)
return false
}
return matched
}
func wrapUnescapedQuot(src string) string {
return "\"" + src + "\""
}
func SplitFileRange(size, blockSize int64) (ranges [][2]int64) {
blocks := size / blockSize
if size%blockSize != 0 {
blocks += 1
}
ranges = make([][2]int64, 0, blocks)
remain := size
aboveRage := [2]int64{0, 0}
for remain > 0 {
curRange := [2]int64{aboveRage[1], 0}
if remain < blockSize {
curRange[1] = size
remain = 0
} else {
curRange[1] = blockSize
remain -= blockSize
}
ranges = append(ranges, curRange)
aboveRage[0], aboveRage[1] = curRange[0], curRange[1]
}
return ranges
}
// Checking and parsing user-defined metadata from request header.
// The optional user-defined metadata names must begin with "x-amz-meta-" to
// distinguish them from other HTTP headers.
// Notes:
// The PUT request header is limited to 8 KB in size. Within the PUT request header,
// the user-defined metadata is limited to 2 KB in size. The size of user-defined
// metadata is measured by taking the sum of the number of bytes in the UTF-8 encoding
// of each key and value.
// Reference: https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html
func ParseUserDefinedMetadata(header http.Header) map[string]string {
metadata := make(map[string]string)
for name, values := range header {
if strings.HasPrefix(name, http.CanonicalHeaderKey(HeaderNameXAmzMetaPrefix)) &&
name != http.CanonicalHeaderKey(HeaderNameXAmzMetadataDirective) {
metaName := strings.ToLower(name[len(HeaderNameXAmzMetaPrefix):])
metaValue := strings.Join(values, ",")
if !strings.HasPrefix(metaName, "oss:") {
metadata[metaName] = metaValue
}
}
}
return metadata
}
// validate Cache-Control
var cacheControlDir = []string{"public", "private", "no-cache", "no-store", "no-transform", "must-revalidate", "proxy-revalidate"}
var maxAgeRegexp = regexp.MustCompile("^((max-age)|(s-maxage))=[1-9][0-9]*$")
func ValidateCacheControl(cacheControl string) bool {
var cacheDirs = strings.Split(cacheControl, ",")
for _, dir := range cacheDirs {
if !contains(cacheControlDir, dir) && !maxAgeRegexp.MatchString(dir) {
log.LogErrorf("invalid cache-control directive: %v", dir)
return false
}
}
return true
}
func ValidateCacheExpires(expires string) bool {
var err error
var stamp time.Time
if stamp, err = time.Parse(RFC1123Format, expires); err != nil {
log.LogErrorf("invalid expires: %v", expires)
return false
}
expiresInt := stamp.Unix()
now := time.Now().UTC().Unix()
if now < expiresInt {
return true
}
log.LogErrorf("Expires less than now: %v, now: %v", expires, now)
return false
}