forked from onepeerlabs/bee-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dirs.go
320 lines (281 loc) · 7.63 KB
/
dirs.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package beelite
import (
"archive/tar"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/ethersphere/bee/v2/pkg/file/loadsave"
"github.com/ethersphere/bee/v2/pkg/file/redundancy"
"github.com/ethersphere/bee/v2/pkg/log"
"github.com/ethersphere/bee/v2/pkg/manifest"
storage "github.com/ethersphere/bee/v2/pkg/storage"
"github.com/ethersphere/bee/v2/pkg/swarm"
)
var (
errEmptyDir = errors.New("no files in root directory")
errInvalidContentType = errors.New("invalid content-type")
)
const (
multiPartFormData = "multipart/form-data"
contentTypeTar = "application/x-tar"
ContentTypeHeader = "Content-Type"
ContentLengthHeader = "Content-Length"
)
func (bl *Beelite) AddDirBzz(
parentContext context.Context,
batchHex,
filename,
contentType,
indexFilename,
errorFilename string,
act bool,
historyAddress swarm.Address,
encrypt bool,
rLevel redundancy.Level,
reader io.Reader,
) (reference swarm.Address, newHistoryAddress swarm.Address, err error) {
reference = swarm.ZeroAddress
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
err = fmt.Errorf("content type parse failed: %w", err)
return
}
var dReader dirReader
switch mediaType {
case contentTypeTar:
dReader = &tarReader{r: tar.NewReader(reader), logger: bl.logger}
case multiPartFormData:
dReader = &multipartReader{r: multipart.NewReader(reader, params["boundary"])}
default:
err = errInvalidContentType
bl.logger.Error(err, "invalid content-type for directory upload")
return
}
if batchHex == "" {
err = fmt.Errorf("batch is not set")
return
}
batchID, err := hex.DecodeString(batchHex)
if err != nil {
err = errInvalidPostageBatch
return
}
var (
tag uint64
deferred = false
pin = false
)
if deferred || pin {
tag, err = bl.getOrCreateSessionID(uint64(0))
if err != nil {
bl.logger.Error(err, "get or create tag failed")
return
}
}
putter, err := bl.newStamperPutter(parentContext, putterOptions{
BatchID: batchID,
TagID: tag,
Pin: pin,
Deferred: deferred,
})
if err != nil {
err = fmt.Errorf("get putter failed: %w", err)
return
}
reference, err = bl.storeDir(
parentContext,
encrypt,
dReader,
putter,
bl.storer.ChunkStore(),
indexFilename,
errorFilename,
rLevel,
)
if err != nil {
err = fmt.Errorf("store dir failed 1: %w", err)
return
}
encryptedReference := reference
if act {
reference, newHistoryAddress, err = bl.actEncryptionHandler(parentContext, putter, reference, historyAddress)
if err != nil {
bl.logger.Error(err, "access control upload failed")
return
}
}
err = putter.Done(reference)
if err != nil {
bl.logger.Error(err, "store dir failed")
err = errors.Join(fmt.Errorf("store dir failed 2: %w", err), putter.Cleanup())
return
}
reference = encryptedReference
return
}
// storeDir stores all files recursively contained in the directory given as a tar/multipart
// it returns the hash for the uploaded manifest corresponding to the uploaded dir
func (bl *Beelite) storeDir(
ctx context.Context,
encrypt bool,
reader dirReader,
putter storage.Putter,
getter storage.Getter,
indexFilename,
errorFilename string,
rLevel redundancy.Level,
) (swarm.Address, error) {
p := requestPipelineFn(putter, encrypt, rLevel)
factory := requestPipelineFactory(ctx, putter, encrypt, rLevel)
ls := loadsave.New(getter, putter, factory)
dirManifest, err := manifest.NewDefaultManifest(ls, encrypt)
if err != nil {
return swarm.ZeroAddress, err
}
if indexFilename != "" && strings.ContainsRune(indexFilename, '/') {
return swarm.ZeroAddress, errors.New("index document suffix must not include slash character")
}
filesAdded := 0
// iterate through the files in the supplied tar
for {
fileInfo, err := reader.Next()
if errors.Is(err, io.EOF) {
break
} else if err != nil {
return swarm.ZeroAddress, fmt.Errorf("read dir stream: %w", err)
}
fileReference, err := p(ctx, fileInfo.Reader)
if err != nil {
return swarm.ZeroAddress, fmt.Errorf("store dir file: %w", err)
}
bl.logger.Debug("bzz upload dir: file dir uploaded", "file_path", fileInfo.Path, "address", fileReference)
fileMtdt := map[string]string{
manifest.EntryMetadataContentTypeKey: fileInfo.ContentType,
manifest.EntryMetadataFilenameKey: fileInfo.Name,
}
// add file entry to dir manifest
err = dirManifest.Add(ctx, fileInfo.Path, manifest.NewEntry(fileReference, fileMtdt))
if err != nil {
return swarm.ZeroAddress, fmt.Errorf("add to manifest: %w", err)
}
filesAdded++
}
// check if files were uploaded through the manifest
if filesAdded == 0 {
return swarm.ZeroAddress, errEmptyDir
}
// store website information
if indexFilename != "" || errorFilename != "" {
metadata := map[string]string{}
if indexFilename != "" {
metadata[manifest.WebsiteIndexDocumentSuffixKey] = indexFilename
}
if errorFilename != "" {
metadata[manifest.WebsiteErrorDocumentPathKey] = errorFilename
}
rootManifestEntry := manifest.NewEntry(swarm.ZeroAddress, metadata)
err = dirManifest.Add(ctx, manifest.RootPath, rootManifestEntry)
if err != nil {
return swarm.ZeroAddress, fmt.Errorf("add to manifest: %w", err)
}
}
// save manifest
manifestReference, err := dirManifest.Store(ctx)
if err != nil {
return swarm.ZeroAddress, fmt.Errorf("store manifest: %w", err)
}
bl.logger.Debug("bzz upload dir: uploaded dir finished", "address", manifestReference)
return manifestReference, nil
}
type FileInfo struct {
Path string
Name string
ContentType string
Size int64
Reader io.Reader
}
type dirReader interface {
Next() (*FileInfo, error)
}
type tarReader struct {
r *tar.Reader
logger log.Logger
}
func (t *tarReader) Next() (*FileInfo, error) {
for {
fileHeader, err := t.r.Next()
if err != nil {
return nil, err
}
fileName := fileHeader.FileInfo().Name()
contentType := mime.TypeByExtension(filepath.Ext(fileHeader.Name))
fileSize := fileHeader.FileInfo().Size()
filePath := filepath.Clean(fileHeader.Name)
if filePath == "." {
t.logger.Warning("skipping file upload empty path")
continue
}
if runtime.GOOS == "windows" {
// always use Unix path separator
filePath = filepath.ToSlash(filePath)
}
// only store regular files
if !fileHeader.FileInfo().Mode().IsRegular() {
t.logger.Warning("bzz upload dir: skipping file upload as it is not a regular file", "file_path", filePath)
continue
}
return &FileInfo{
Path: filePath,
Name: fileName,
ContentType: contentType,
Size: fileSize,
Reader: t.r,
}, nil
}
}
// multipart reader returns files added as a multipart form. We will ensure all the
// part headers are passed correctly
type multipartReader struct {
r *multipart.Reader
}
func (m *multipartReader) Next() (*FileInfo, error) {
part, err := m.r.NextPart()
if err != nil {
return nil, err
}
filePath := part.FileName()
if filePath == "" {
filePath = part.FormName()
}
if filePath == "" {
return nil, errors.New("filepath missing")
}
fileName := filepath.Base(filePath)
contentType := part.Header.Get(ContentTypeHeader)
if contentType == "" {
return nil, errors.New("content-type missing")
}
contentLength := part.Header.Get(ContentLengthHeader)
if contentLength == "" {
return nil, errors.New("content-length missing")
}
fileSize, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
return nil, errors.New("invalid file size")
}
return &FileInfo{
Path: filePath,
Name: fileName,
ContentType: contentType,
Size: fileSize,
Reader: part,
}, nil
}