-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.go
284 lines (237 loc) · 6.79 KB
/
object.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
package ls3
import (
"errors"
"github.com/gotd/contrib/http_range"
"github.com/h2non/filetype"
"github.com/relvacode/ls3/exception"
"io"
"io/fs"
"net/http"
"net/textproto"
"os"
"path"
"strconv"
"strings"
"time"
)
type Object struct {
io.ReadCloser
Size int64
Range *http_range.Range
LastModified time.Time
// ContentType contains the MIME type of the object data.
// It is the best guess based on the filetype library.
// This is always set, if unknown the MIME type becomes application/octet-stream
ContentType string
// ETag represents the ETag field of the Object.
// It is always empty.
ETag string
}
// Get implements PolicyContextVars for this Object
func (obj *Object) Get(k string) (string, bool) {
switch k {
case "ls3:ObjectSize":
return strconv.FormatInt(obj.Size, 10), true
case "ls3:ObjectContentType":
return obj.ContentType, true
case "ls3:ObjectLastModified":
return obj.LastModified.Format(time.RFC3339), true
default:
return "", false
}
}
func urlPathObjectKey(urlPath string) (string, error) {
if len(urlPath) < 1 {
return "", &exception.Error{
ErrorCode: exception.InvalidArgument,
Message: "Object key must be at least 1 character",
}
}
// Clean the path
urlPath = path.Clean(urlPath)
urlPath = strings.TrimLeft(urlPath, "/")
return urlPath, nil
}
func unwrapFsError(err error) *exception.Error {
if errors.Is(err, os.ErrNotExist) {
return &exception.Error{
ErrorCode: exception.NoSuchKey,
Message: "The specified object key does not exist.",
}
}
if errors.Is(err, os.ErrPermission) {
return &exception.Error{
ErrorCode: exception.AccessDenied,
Message: "You do not have permission to access this object.",
}
}
return &exception.Error{
ErrorCode: exception.InvalidObjectState,
Message: "An undefined permanent error occurred accessing this object.",
}
}
// checkConditionalRequest checks conditional parameters present in HTTP headers
// And returns a status code for that condition.
// Returns [0, nil] if there are no limiting conditions.
func checkConditionalRequest(header http.Header, obj *Object) (int, error) {
var (
ifMatch *bool
ifNoneMatch *bool
)
if _, reqIfMatch := header[textproto.CanonicalMIMEHeaderKey("If-Match")]; reqIfMatch {
var eval = header.Get("If-Match") == obj.ETag
ifMatch = &eval
}
if _, reqIfNoneMatch := header[textproto.CanonicalMIMEHeaderKey("If-None-Match")]; reqIfNoneMatch {
var eval = header.Get("If-None-Match") != obj.ETag
ifNoneMatch = &eval
}
// Check if the object has not been modified expires the requested date.
if reqModifiedSince := header.Get("If-Modified-Since"); reqModifiedSince != "" {
ifModifiedSinceTime, err := time.Parse(http.TimeFormat, reqModifiedSince)
if err != nil {
return 0, &exception.Error{
ErrorCode: exception.InvalidArgument,
Message: "Invalid value for If-Modified-Since.",
}
}
ifModifiedSince := ifModifiedSinceTime.After(obj.LastModified)
if ifMatch != nil {
if *ifMatch && !ifModifiedSince {
return 0, nil
}
}
if !ifModifiedSince {
return http.StatusNotModified, nil
}
}
// Check if the object has not been modified expires the requested date.
if reqUnmodifiedSince := header.Get("If-Unmodified-Since"); reqUnmodifiedSince != "" {
ifUnmodifiedSinceTime, err := time.Parse(http.TimeFormat, reqUnmodifiedSince)
if err != nil {
return 0, &exception.Error{
ErrorCode: exception.InvalidArgument,
Message: "Invalid value for If-Unmodified-Since.",
}
}
ifUnmodifiedSince := obj.LastModified.Before(ifUnmodifiedSinceTime)
if ifNoneMatch != nil {
if !*ifNoneMatch && ifUnmodifiedSince {
return http.StatusNotModified, nil
}
}
if !ifUnmodifiedSince {
return http.StatusPreconditionFailed, nil
}
}
if ifMatch != nil && !*ifMatch {
return http.StatusPreconditionFailed, nil
}
if ifNoneMatch != nil && !*ifNoneMatch {
return http.StatusNotModified, nil
}
return 0, nil
}
type closeProxy struct {
io.Reader
closer func() error
}
func (cp *closeProxy) Close() error {
return cp.closer()
}
func limitRange(r *http.Request, obj *Object) error {
rangeHeader := r.Header.Get("Range")
if rangeHeader == "" {
return nil
}
ranges, err := http_range.ParseRange(rangeHeader, obj.Size)
// Only one range request is supported
if err != nil || len(ranges) != 1 {
return &exception.Error{
ErrorCode: exception.InvalidRange,
Message: "The requested range is not valid for the request. Try another range.",
}
}
obj.Range = &ranges[0]
// Seek object to target start range
seek, ok := obj.ReadCloser.(io.Seeker)
if !ok {
return &exception.Error{
ErrorCode: exception.InvalidRequest,
Message: "Ranged requests are not supported for this object.",
}
}
_, err = seek.Seek(obj.Range.Start, 0)
if err != nil {
return &exception.Error{
ErrorCode: exception.InvalidRange,
Message: "Unable to access object at start range.",
}
}
// Limit reader to end of range
rc := obj.ReadCloser
obj.ReadCloser = &closeProxy{
Reader: io.LimitReader(rc, obj.Range.Length),
closer: rc.Close,
}
return nil
}
// seekOrRefresh moves the current read pointer to the start of the file.
// If f does not implement io.Seeker then the file is closed, and re-opened from the given filesystem.
func seekOrRefresh(f fs.File, from fs.FS, name string) (fs.File, error) {
// If file can be seeked then seek it
if seeker, ok := f.(io.Seeker); ok {
_, err := seeker.Seek(0, 0)
return f, err
}
// Otherwise, close and reopen the file
_ = f.Close()
return from.Open(name)
}
// guessContentType attempts to guess the content type from the input reader.
// It always returns a valid MIME type.
// It returns true if at least some data was read from the reader.
func guessContentType(r io.Reader) (string, bool) {
head := make([]byte, 261)
n, _ := io.ReadFull(r, head) // error can be safely ignored
t, _ := filetype.Match(head)
mt := t.MIME.Value
if mt == "" {
mt = "binary/octet-stream"
}
return mt, n > 0
}
func stat(ctx *RequestContext, key string) (*Object, error) {
f, err := ctx.Filesystem.Open(key)
if err != nil {
return nil, unwrapFsError(err)
}
fi, err := f.Stat()
if err != nil {
_ = f.Close()
return nil, unwrapFsError(err)
}
if !fi.Mode().IsRegular() {
// If file is not a regular file, then pretend the file does not exist.
return nil, unwrapFsError(os.ErrNotExist)
}
contentType, mustRefresh := guessContentType(f)
if mustRefresh {
// If file needs refreshing after guessing the content type then do so
f, err = seekOrRefresh(f, ctx.Filesystem, key)
if err != nil {
return nil, unwrapFsError(err)
}
}
obj := &Object{
Size: fi.Size(),
ReadCloser: f,
LastModified: fi.ModTime().UTC(),
ContentType: contentType,
}
err = limitRange(ctx.Request, obj)
if err != nil {
return nil, err
}
return obj, nil
}