api.go 28.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package api

import (
20
	"archive/tar"
21
	"context"
22 23
	"fmt"
	"io"
24
	"math/big"
25
	"net/http"
26
	"path"
27 28
	"strings"

29 30 31 32
	"bytes"
	"mime"
	"path/filepath"
	"time"
33 34

	"github.com/ethereum/go-ethereum/common"
35 36
	"github.com/ethereum/go-ethereum/contracts/ens"
	"github.com/ethereum/go-ethereum/core/types"
37
	"github.com/ethereum/go-ethereum/metrics"
38 39
	"github.com/ethereum/go-ethereum/swarm/log"
	"github.com/ethereum/go-ethereum/swarm/multihash"
40
	"github.com/ethereum/go-ethereum/swarm/spancontext"
41
	"github.com/ethereum/go-ethereum/swarm/storage"
42
	"github.com/ethereum/go-ethereum/swarm/storage/mru"
43
	opentracing "github.com/opentracing/opentracing-go"
44 45
)

46
var (
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
	apiResolveCount        = metrics.NewRegisteredCounter("api.resolve.count", nil)
	apiResolveFail         = metrics.NewRegisteredCounter("api.resolve.fail", nil)
	apiPutCount            = metrics.NewRegisteredCounter("api.put.count", nil)
	apiPutFail             = metrics.NewRegisteredCounter("api.put.fail", nil)
	apiGetCount            = metrics.NewRegisteredCounter("api.get.count", nil)
	apiGetNotFound         = metrics.NewRegisteredCounter("api.get.notfound", nil)
	apiGetHTTP300          = metrics.NewRegisteredCounter("api.get.http.300", nil)
	apiManifestUpdateCount = metrics.NewRegisteredCounter("api.manifestupdate.count", nil)
	apiManifestUpdateFail  = metrics.NewRegisteredCounter("api.manifestupdate.fail", nil)
	apiManifestListCount   = metrics.NewRegisteredCounter("api.manifestlist.count", nil)
	apiManifestListFail    = metrics.NewRegisteredCounter("api.manifestlist.fail", nil)
	apiDeleteCount         = metrics.NewRegisteredCounter("api.delete.count", nil)
	apiDeleteFail          = metrics.NewRegisteredCounter("api.delete.fail", nil)
	apiGetTarCount         = metrics.NewRegisteredCounter("api.gettar.count", nil)
	apiGetTarFail          = metrics.NewRegisteredCounter("api.gettar.fail", nil)
	apiUploadTarCount      = metrics.NewRegisteredCounter("api.uploadtar.count", nil)
	apiUploadTarFail       = metrics.NewRegisteredCounter("api.uploadtar.fail", nil)
	apiModifyCount         = metrics.NewRegisteredCounter("api.modify.count", nil)
	apiModifyFail          = metrics.NewRegisteredCounter("api.modify.fail", nil)
	apiAddFileCount        = metrics.NewRegisteredCounter("api.addfile.count", nil)
	apiAddFileFail         = metrics.NewRegisteredCounter("api.addfile.fail", nil)
	apiRmFileCount         = metrics.NewRegisteredCounter("api.removefile.count", nil)
	apiRmFileFail          = metrics.NewRegisteredCounter("api.removefile.fail", nil)
	apiAppendFileCount     = metrics.NewRegisteredCounter("api.appendfile.count", nil)
	apiAppendFileFail      = metrics.NewRegisteredCounter("api.appendfile.fail", nil)
	apiGetInvalid          = metrics.NewRegisteredCounter("api.get.invalid", nil)
73 74
)

75
// Resolver interface resolve a domain name to a hash using ENS
76 77 78 79
type Resolver interface {
	Resolve(string) (common.Hash, error)
}

80 81 82 83 84 85 86
// ResolveValidator is used to validate the contained Resolver
type ResolveValidator interface {
	Resolver
	Owner(node [32]byte) (common.Address, error)
	HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
}

87
// NoResolverError is returned by MultiResolver.Resolve if no resolver
88
// can be found for the address.
89 90 91 92
type NoResolverError struct {
	TLD string
}

93
// NewNoResolverError creates a NoResolverError for the given top level domain
94 95 96 97
func NewNoResolverError(tld string) *NoResolverError {
	return &NoResolverError{TLD: tld}
}

98
// Error NoResolverError implements error
99 100 101 102 103 104
func (e *NoResolverError) Error() string {
	if e.TLD == "" {
		return "no ENS resolver"
	}
	return fmt.Sprintf("no ENS endpoint configured to resolve .%s TLD names", e.TLD)
}
105 106 107 108 109

// MultiResolver is used to resolve URL addresses based on their TLDs.
// Each TLD can have multiple resolvers, and the resoluton from the
// first one in the sequence will be returned.
type MultiResolver struct {
110 111
	resolvers map[string][]ResolveValidator
	nameHash  func(string) common.Hash
112 113 114 115 116 117 118 119 120 121
}

// MultiResolverOption sets options for MultiResolver and is used as
// arguments for its constructor.
type MultiResolverOption func(*MultiResolver)

// MultiResolverOptionWithResolver adds a Resolver to a list of resolvers
// for a specific TLD. If TLD is an empty string, the resolver will be added
// to the list of default resolver, the ones that will be used for resolution
// of addresses which do not have their TLD resolver specified.
122
func MultiResolverOptionWithResolver(r ResolveValidator, tld string) MultiResolverOption {
123 124 125 126 127
	return func(m *MultiResolver) {
		m.resolvers[tld] = append(m.resolvers[tld], r)
	}
}

128 129 130 131 132 133 134
// MultiResolverOptionWithNameHash is unused at the time of this writing
func MultiResolverOptionWithNameHash(nameHash func(string) common.Hash) MultiResolverOption {
	return func(m *MultiResolver) {
		m.nameHash = nameHash
	}
}

135 136 137
// NewMultiResolver creates a new instance of MultiResolver.
func NewMultiResolver(opts ...MultiResolverOption) (m *MultiResolver) {
	m = &MultiResolver{
138 139
		resolvers: make(map[string][]ResolveValidator),
		nameHash:  ens.EnsNode,
140 141 142 143 144 145 146 147 148 149 150
	}
	for _, o := range opts {
		o(m)
	}
	return m
}

// Resolve resolves address by choosing a Resolver by TLD.
// If there are more default Resolvers, or for a specific TLD,
// the Hash from the the first one which does not return error
// will be returned.
151 152 153 154
func (m *MultiResolver) Resolve(addr string) (h common.Hash, err error) {
	rs, err := m.getResolveValidator(addr)
	if err != nil {
		return h, err
155 156 157 158 159 160 161 162 163 164
	}
	for _, r := range rs {
		h, err = r.Resolve(addr)
		if err == nil {
			return
		}
	}
	return
}

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
// ValidateOwner checks the ENS to validate that the owner of the given domain is the given eth address
func (m *MultiResolver) ValidateOwner(name string, address common.Address) (bool, error) {
	rs, err := m.getResolveValidator(name)
	if err != nil {
		return false, err
	}
	var addr common.Address
	for _, r := range rs {
		addr, err = r.Owner(m.nameHash(name))
		// we hide the error if it is not for the last resolver we check
		if err == nil {
			return addr == address, nil
		}
	}
	return false, err
}

// HeaderByNumber uses the validator of the given domainname and retrieves the header for the given block number
func (m *MultiResolver) HeaderByNumber(ctx context.Context, name string, blockNr *big.Int) (*types.Header, error) {
	rs, err := m.getResolveValidator(name)
	if err != nil {
		return nil, err
	}
	for _, r := range rs {
		var header *types.Header
		header, err = r.HeaderByNumber(ctx, blockNr)
		// we hide the error if it is not for the last resolver we check
		if err == nil {
			return header, nil
		}
	}
	return nil, err
}

// getResolveValidator uses the hostname to retrieve the resolver associated with the top level domain
func (m *MultiResolver) getResolveValidator(name string) ([]ResolveValidator, error) {
	rs := m.resolvers[""]
	tld := path.Ext(name)
	if tld != "" {
		tld = tld[1:]
		rstld, ok := m.resolvers[tld]
		if ok {
			return rstld, nil
		}
	}
	if len(rs) == 0 {
		return rs, NewNoResolverError(tld)
	}
	return rs, nil
}

// SetNameHash sets the hasher function that hashes the domain into a name hash that ENS uses
func (m *MultiResolver) SetNameHash(nameHash func(string) common.Hash) {
	m.nameHash = nameHash
}

221
/*
222 223 224
API implements webserver/file system related content storage and retrieval
on top of the FileStore
it is the public interface of the FileStore which is included in the ethereum stack
225
*/
226 227 228 229
type API struct {
	resource  *mru.Handler
	fileStore *storage.FileStore
	dns       Resolver
230 231
}

232 233 234 235 236 237
// NewAPI the api constructor initialises a new API instance.
func NewAPI(fileStore *storage.FileStore, dns Resolver, resourceHandler *mru.Handler) (self *API) {
	self = &API{
		fileStore: fileStore,
		dns:       dns,
		resource:  resourceHandler,
238 239 240 241
	}
	return
}

242
// Upload to be used only in TEST
243
func (a *API) Upload(ctx context.Context, uploadDir, index string, toEncrypt bool) (hash string, err error) {
244 245
	fs := NewFileSystem(a)
	hash, err = fs.Upload(uploadDir, index, toEncrypt)
246 247 248
	return hash, err
}

249
// Retrieve FileStore reader API
250 251
func (a *API) Retrieve(ctx context.Context, addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
	return a.fileStore.Retrieve(ctx, addr)
252 253
}

254
// Store wraps the Store API call of the embedded FileStore
255
func (a *API) Store(ctx context.Context, data io.Reader, size int64, toEncrypt bool) (addr storage.Address, wait func(ctx context.Context) error, err error) {
256
	log.Debug("api.store", "size", size)
257
	return a.fileStore.Store(ctx, data, size, toEncrypt)
258 259
}

260
// ErrResolve is returned when an URI cannot be resolved from ENS.
261 262
type ErrResolve error

263
// Resolve resolves a URI to an Address using the MultiResolver.
264
func (a *API) Resolve(ctx context.Context, uri *URI) (storage.Address, error) {
265
	apiResolveCount.Inc(1)
266
	log.Trace("resolving", "uri", uri.Addr)
267

268 269 270 271 272 273
	var sp opentracing.Span
	ctx, sp = spancontext.StartSpan(
		ctx,
		"api.resolve")
	defer sp.Finish()

274 275 276 277
	// if the URI is immutable, check if the address looks like a hash
	if uri.Immutable() {
		key := uri.Address()
		if key == nil {
278
			return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
279
		}
280
		return key, nil
281
	}
282 283

	// if DNS is not configured, check if the address is a hash
284 285 286
	if a.dns == nil {
		key := uri.Address()
		if key == nil {
287
			apiResolveFail.Inc(1)
288 289
			return nil, fmt.Errorf("no DNS to resolve name: %q", uri.Addr)
		}
290
		return key, nil
291
	}
292 293

	// try and resolve the address
294
	resolved, err := a.dns.Resolve(uri.Addr)
295 296
	if err == nil {
		return resolved[:], nil
297 298 299 300
	}

	key := uri.Address()
	if key == nil {
301
		apiResolveFail.Inc(1)
302
		return nil, err
303
	}
304
	return key, nil
305 306
}

307
// Put provides singleton manifest creation on top of FileStore store
308
func (a *API) Put(ctx context.Context, content string, contentType string, toEncrypt bool) (k storage.Address, wait func(context.Context) error, err error) {
309
	apiPutCount.Inc(1)
310
	r := strings.NewReader(content)
311
	key, waitContent, err := a.fileStore.Store(ctx, r, int64(len(content)), toEncrypt)
312
	if err != nil {
313
		apiPutFail.Inc(1)
314
		return nil, nil, err
315 316 317
	}
	manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
	r = strings.NewReader(manifest)
318
	key, waitManifest, err := a.fileStore.Store(ctx, r, int64(len(manifest)), toEncrypt)
319
	if err != nil {
320
		apiPutFail.Inc(1)
321
		return nil, nil, err
322
	}
323 324 325 326 327 328
	return key, func(ctx context.Context) error {
		err := waitContent(ctx)
		if err != nil {
			return err
		}
		return waitManifest(ctx)
329
	}, nil
330 331 332
}

// Get uses iterative manifest retrieval and prefix matching
333 334
// to resolve basePath to content using FileStore retrieve
// it returns a section reader, mimeType, status, the key of the actual content and an error
335
func (a *API) Get(ctx context.Context, manifestAddr storage.Address, path string) (reader storage.LazySectionReader, mimeType string, status int, contentAddr storage.Address, err error) {
336
	log.Debug("api.get", "key", manifestAddr, "path", path)
337
	apiGetCount.Inc(1)
338
	trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil)
339
	if err != nil {
340
		apiGetNotFound.Inc(1)
341
		status = http.StatusNotFound
342
		log.Warn(fmt.Sprintf("loadManifestTrie error: %v", err))
343 344 345
		return
	}

346
	log.Debug("trie getting entry", "key", manifestAddr, "path", path)
347
	entry, _ := trie.getEntry(path)
348

349
	if entry != nil {
350 351 352 353
		log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
		// we need to do some extra work if this is a mutable resource manifest
		if entry.ContentType == ResourceContentType {

354 355
			// get the resource rootAddr
			log.Trace("resource type", "menifestAddr", manifestAddr, "hash", entry.Hash)
356 357
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
358 359
			rootAddr := storage.Address(common.FromHex(entry.Hash))
			rsrc, err := a.resource.Load(ctx, rootAddr)
360 361 362 363 364 365 366 367
			if err != nil {
				apiGetNotFound.Inc(1)
				status = http.StatusNotFound
				log.Debug(fmt.Sprintf("get resource content error: %v", err))
				return reader, mimeType, status, nil, err
			}

			// use this key to retrieve the latest update
368 369
			params := mru.LookupLatest(rootAddr)
			rsrc, err = a.resource.Lookup(ctx, params)
370 371 372 373 374 375 376 377 378
			if err != nil {
				apiGetNotFound.Inc(1)
				status = http.StatusNotFound
				log.Debug(fmt.Sprintf("get resource content error: %v", err))
				return reader, mimeType, status, nil, err
			}

			// if it's multihash, we will transparently serve the content this multihash points to
			// \TODO this resolve is rather expensive all in all, review to see if it can be achieved cheaper
379
			if rsrc.Multihash() {
380 381

				// get the data of the update
382
				_, rsrcData, err := a.resource.GetContent(rootAddr)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
				if err != nil {
					apiGetNotFound.Inc(1)
					status = http.StatusNotFound
					log.Warn(fmt.Sprintf("get resource content error: %v", err))
					return reader, mimeType, status, nil, err
				}

				// validate that data as multihash
				decodedMultihash, err := multihash.FromMultihash(rsrcData)
				if err != nil {
					apiGetInvalid.Inc(1)
					status = http.StatusUnprocessableEntity
					log.Warn("invalid resource multihash", "err", err)
					return reader, mimeType, status, nil, err
				}
				manifestAddr = storage.Address(decodedMultihash)
				log.Trace("resource is multihash", "key", manifestAddr)

				// get the manifest the multihash digest points to
402
				trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil)
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
				if err != nil {
					apiGetNotFound.Inc(1)
					status = http.StatusNotFound
					log.Warn(fmt.Sprintf("loadManifestTrie (resource multihash) error: %v", err))
					return reader, mimeType, status, nil, err
				}

				// finally, get the manifest entry
				// it will always be the entry on path ""
				entry, _ = trie.getEntry(path)
				if entry == nil {
					status = http.StatusNotFound
					apiGetNotFound.Inc(1)
					err = fmt.Errorf("manifest (resource multihash) entry for '%s' not found", path)
					log.Trace("manifest (resource multihash) entry not found", "key", manifestAddr, "path", path)
					return reader, mimeType, status, nil, err
				}

			} else {
				// data is returned verbatim since it's not a multihash
				return rsrc, "application/octet-stream", http.StatusOK, nil, nil
			}
		}

		// regardless of resource update manifests or normal manifests we will converge at this point
		// get the key the manifest entry points to and serve it if it's unambiguous
		contentAddr = common.Hex2Bytes(entry.Hash)
430
		status = entry.Status
431
		if status == http.StatusMultipleChoices {
432 433
			apiGetHTTP300.Inc(1)
			return nil, entry.ContentType, status, contentAddr, err
434
		}
435 436
		mimeType = entry.ContentType
		log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
437
		reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
438
	} else {
439
		// no entry found
440
		status = http.StatusNotFound
441
		apiGetNotFound.Inc(1)
442
		err = fmt.Errorf("manifest entry for '%s' not found", path)
443
		log.Trace("manifest entry not found", "key", contentAddr, "path", path)
444 445 446 447
	}
	return
}

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
func (a *API) Delete(ctx context.Context, addr string, path string) (storage.Address, error) {
	apiDeleteCount.Inc(1)
	uri, err := Parse("bzz:/" + addr)
	if err != nil {
		apiDeleteFail.Inc(1)
		return nil, err
	}
	key, err := a.Resolve(ctx, uri)

	if err != nil {
		return nil, err
	}
	newKey, err := a.UpdateManifest(ctx, key, func(mw *ManifestWriter) error {
		log.Debug(fmt.Sprintf("removing %s from manifest %s", path, key.Log()))
		return mw.RemoveEntry(path)
	})
	if err != nil {
		apiDeleteFail.Inc(1)
		return nil, err
	}

	return newKey, nil
}

// GetDirectoryTar fetches a requested directory as a tarstream
// it returns an io.Reader and an error. Do not forget to Close() the returned ReadCloser
func (a *API) GetDirectoryTar(ctx context.Context, uri *URI) (io.ReadCloser, error) {
	apiGetTarCount.Inc(1)
	addr, err := a.Resolve(ctx, uri)
	if err != nil {
		return nil, err
	}
	walker, err := a.NewManifestWalker(ctx, addr, nil)
	if err != nil {
		apiGetTarFail.Inc(1)
		return nil, err
	}

	piper, pipew := io.Pipe()

	tw := tar.NewWriter(pipew)

	go func() {
		err := walker.Walk(func(entry *ManifestEntry) error {
			// ignore manifests (walk will recurse into them)
			if entry.ContentType == ManifestType {
				return nil
			}

			// retrieve the entry's key and size
			reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
499
			size, err := reader.Size(ctx, nil)
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
			if err != nil {
				return err
			}

			// write a tar header for the entry
			hdr := &tar.Header{
				Name:    entry.Path,
				Mode:    entry.Mode,
				Size:    size,
				ModTime: entry.ModTime,
				Xattrs: map[string]string{
					"user.swarm.content-type": entry.ContentType,
				},
			}

			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}

			// copy the file into the tar stream
			n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
			if err != nil {
				return err
			} else if n != size {
				return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
			}

			return nil
		})
		if err != nil {
			apiGetTarFail.Inc(1)
			pipew.CloseWithError(err)
		} else {
			pipew.Close()
		}
	}()

	return piper, nil
}

// GetManifestList lists the manifest entries for the specified address and prefix
// and returns it as a ManifestList
func (a *API) GetManifestList(ctx context.Context, addr storage.Address, prefix string) (list ManifestList, err error) {
	apiManifestListCount.Inc(1)
	walker, err := a.NewManifestWalker(ctx, addr, nil)
	if err != nil {
		apiManifestListFail.Inc(1)
		return ManifestList{}, err
	}

	err = walker.Walk(func(entry *ManifestEntry) error {
		// handle non-manifest files
		if entry.ContentType != ManifestType {
			// ignore the file if it doesn't have the specified prefix
			if !strings.HasPrefix(entry.Path, prefix) {
				return nil
			}

			// if the path after the prefix contains a slash, add a
			// common prefix to the list, otherwise add the entry
			suffix := strings.TrimPrefix(entry.Path, prefix)
			if index := strings.Index(suffix, "/"); index > -1 {
				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
				return nil
			}
			if entry.Path == "" {
				entry.Path = "/"
			}
			list.Entries = append(list.Entries, entry)
			return nil
		}

		// if the manifest's path is a prefix of the specified prefix
		// then just recurse into the manifest by returning nil and
		// continuing the walk
		if strings.HasPrefix(prefix, entry.Path) {
			return nil
		}

		// if the manifest's path has the specified prefix, then if the
		// path after the prefix contains a slash, add a common prefix
		// to the list and skip the manifest, otherwise recurse into
		// the manifest by returning nil and continuing the walk
		if strings.HasPrefix(entry.Path, prefix) {
			suffix := strings.TrimPrefix(entry.Path, prefix)
			if index := strings.Index(suffix, "/"); index > -1 {
				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
				return ErrSkipManifest
			}
			return nil
		}

		// the manifest neither has the prefix or needs recursing in to
		// so just skip it
		return ErrSkipManifest
	})

	if err != nil {
		apiManifestListFail.Inc(1)
		return ManifestList{}, err
	}

	return list, nil
}

func (a *API) UpdateManifest(ctx context.Context, addr storage.Address, update func(mw *ManifestWriter) error) (storage.Address, error) {
	apiManifestUpdateCount.Inc(1)
	mw, err := a.NewManifestWriter(ctx, addr, nil)
	if err != nil {
		apiManifestUpdateFail.Inc(1)
		return nil, err
	}

	if err := update(mw); err != nil {
		apiManifestUpdateFail.Inc(1)
		return nil, err
	}

	addr, err = mw.Store()
	if err != nil {
		apiManifestUpdateFail.Inc(1)
		return nil, err
	}
	log.Debug(fmt.Sprintf("generated manifest %s", addr))
	return addr, nil
}

627
// Modify loads manifest and checks the content hash before recalculating and storing the manifest.
628
func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
629
	apiModifyCount.Inc(1)
630
	quitC := make(chan bool)
631
	trie, err := loadManifest(ctx, a.fileStore, addr, quitC)
632
	if err != nil {
633
		apiModifyFail.Inc(1)
634
		return nil, err
635 636
	}
	if contentHash != "" {
637
		entry := newManifestTrieEntry(&ManifestEntry{
638 639
			Path:        path,
			ContentType: contentType,
640 641
		}, nil)
		entry.Hash = contentHash
642 643 644 645 646
		trie.addEntry(entry, quitC)
	} else {
		trie.deleteEntry(path, quitC)
	}

647
	if err := trie.recalcAndStore(); err != nil {
648
		apiModifyFail.Inc(1)
649
		return nil, err
650
	}
651
	return trie.ref, nil
652
}
653

654
// AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
655
func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
656
	apiAddFileCount.Inc(1)
657 658 659

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
660
		apiAddFileFail.Inc(1)
661 662
		return nil, "", err
	}
663
	mkey, err := a.Resolve(ctx, uri)
664
	if err != nil {
665
		apiAddFileFail.Inc(1)
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
		return nil, "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

	entry := &ManifestEntry{
		Path:        filepath.Join(path, fname),
		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
		Mode:        0700,
		Size:        int64(len(content)),
		ModTime:     time.Now(),
	}

682
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
683
	if err != nil {
684
		apiAddFileFail.Inc(1)
685 686 687
		return nil, "", err
	}

688
	fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
689
	if err != nil {
690
		apiAddFileFail.Inc(1)
691 692 693 694 695
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
696
		apiAddFileFail.Inc(1)
697 698 699 700 701 702 703
		return nil, "", err

	}

	return fkey, newMkey.String(), nil
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath string, mw *ManifestWriter) (storage.Address, error) {
	apiUploadTarCount.Inc(1)
	var contentKey storage.Address
	tr := tar.NewReader(bodyReader)
	defer bodyReader.Close()
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			apiUploadTarFail.Inc(1)
			return nil, fmt.Errorf("error reading tar stream: %s", err)
		}

		// only store regular files
		if !hdr.FileInfo().Mode().IsRegular() {
			continue
		}

		// add the entry under the path from the request
		manifestPath := path.Join(manifestPath, hdr.Name)
		entry := &ManifestEntry{
			Path:        manifestPath,
			ContentType: hdr.Xattrs["user.swarm.content-type"],
			Mode:        hdr.Mode,
			Size:        hdr.Size,
			ModTime:     hdr.ModTime,
		}
		contentKey, err = mw.AddEntry(ctx, tr, entry)
		if err != nil {
			apiUploadTarFail.Inc(1)
			return nil, fmt.Errorf("error adding manifest entry from tar stream: %s", err)
		}
	}
	return contentKey, nil
}

741
// RemoveFile removes a file entry in a manifest.
742
func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
743
	apiRmFileCount.Inc(1)
744 745 746

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
747
		apiRmFileFail.Inc(1)
748 749
		return "", err
	}
750
	mkey, err := a.Resolve(ctx, uri)
751
	if err != nil {
752
		apiRmFileFail.Inc(1)
753 754 755 756 757 758 759 760
		return "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

761
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
762
	if err != nil {
763
		apiRmFileFail.Inc(1)
764 765 766 767 768
		return "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
769
		apiRmFileFail.Inc(1)
770 771 772 773 774
		return "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
775
		apiRmFileFail.Inc(1)
776 777 778 779 780 781 782
		return "", err

	}

	return newMkey.String(), nil
}

783
// AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
784
func (a *API) AppendFile(ctx context.Context, mhash, path, fname string, existingSize int64, content []byte, oldAddr storage.Address, offset int64, addSize int64, nameresolver bool) (storage.Address, string, error) {
785
	apiAppendFileCount.Inc(1)
786 787 788 789 790 791 792 793

	buffSize := offset + addSize
	if buffSize < existingSize {
		buffSize = existingSize
	}

	buf := make([]byte, buffSize)

794
	oldReader, _ := a.Retrieve(ctx, oldAddr)
795 796 797 798 799 800 801 802 803 804 805 806 807
	io.ReadAtLeast(oldReader, buf, int(offset))

	newReader := bytes.NewReader(content)
	io.ReadAtLeast(newReader, buf[offset:], int(addSize))

	if buffSize < existingSize {
		io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
	}

	combinedReader := bytes.NewReader(buf)
	totalSize := int64(len(buf))

	// TODO(jmozah): to append using pyramid chunker when it is ready
808
	//oldReader := a.Retrieve(oldKey)
809 810 811 812 813
	//newReader := bytes.NewReader(content)
	//combinedReader := io.MultiReader(oldReader, newReader)

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
814
		apiAppendFileFail.Inc(1)
815 816
		return nil, "", err
	}
817
	mkey, err := a.Resolve(ctx, uri)
818
	if err != nil {
819
		apiAppendFileFail.Inc(1)
820 821 822 823 824 825 826 827
		return nil, "", err
	}

	// trim the root dir we added
	if path[:1] == "/" {
		path = path[1:]
	}

828
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
829
	if err != nil {
830
		apiAppendFileFail.Inc(1)
831 832 833 834 835
		return nil, "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
836
		apiAppendFileFail.Inc(1)
837 838 839 840 841 842 843 844 845 846 847
		return nil, "", err
	}

	entry := &ManifestEntry{
		Path:        filepath.Join(path, fname),
		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
		Mode:        0700,
		Size:        totalSize,
		ModTime:     time.Now(),
	}

848
	fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
849
	if err != nil {
850
		apiAppendFileFail.Inc(1)
851 852 853 854 855
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
856
		apiAppendFileFail.Inc(1)
857 858 859 860 861 862 863
		return nil, "", err

	}

	return fkey, newMkey.String(), nil
}

864
// BuildDirectoryTree used by swarmfs_unix
865
func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
866

867 868 869 870
	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return nil, nil, err
	}
871
	addr, err = a.Resolve(ctx, uri)
872 873 874 875 876
	if err != nil {
		return nil, nil, err
	}

	quitC := make(chan bool)
877
	rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC)
878
	if err != nil {
879
		return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
880 881 882 883 884 885 886
	}

	manifestEntryMap = map[string]*manifestTrieEntry{}
	err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
		manifestEntryMap[suffix] = entry
	})

887
	if err != nil {
888 889 890 891 892
		return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
	}
	return addr, manifestEntryMap, nil
}

893 894
// ResourceLookup finds mutable resource updates at specific periods and versions
func (a *API) ResourceLookup(ctx context.Context, params *mru.LookupParams) (string, []byte, error) {
895
	var err error
896
	rsrc, err := a.resource.Load(ctx, params.RootAddr())
897 898 899
	if err != nil {
		return "", nil, err
	}
900
	_, err = a.resource.Lookup(ctx, params)
901 902 903 904
	if err != nil {
		return "", nil, err
	}
	var data []byte
905
	_, data, err = a.resource.GetContent(params.RootAddr())
906 907 908 909 910 911
	if err != nil {
		return "", nil, err
	}
	return rsrc.Name(), data, nil
}

912 913 914
// Create Mutable resource
func (a *API) ResourceCreate(ctx context.Context, request *mru.Request) error {
	return a.resource.New(ctx, request)
915 916
}

917 918 919
// ResourceNewRequest creates a Request object to update a specific mutable resource
func (a *API) ResourceNewRequest(ctx context.Context, rootAddr storage.Address) (*mru.Request, error) {
	return a.resource.NewUpdateRequest(ctx, rootAddr)
920 921 922 923
}

// ResourceUpdate updates a Mutable Resource with arbitrary data.
// Upon retrieval the update will be retrieved verbatim as bytes.
924 925
func (a *API) ResourceUpdate(ctx context.Context, request *mru.SignedResourceUpdate) (storage.Address, error) {
	return a.resource.Update(ctx, request)
926 927 928 929 930 931 932 933
}

// ResourceHashSize returned the size of the digest produced by the Mutable Resource hashing function
func (a *API) ResourceHashSize() int {
	return a.resource.HashSize
}

// ResolveResourceManifest retrieves the Mutable Resource manifest for the given address, and returns the address of the metadata chunk.
934 935
func (a *API) ResolveResourceManifest(ctx context.Context, addr storage.Address) (storage.Address, error) {
	trie, err := loadManifest(ctx, a.fileStore, addr, nil)
936 937 938 939 940 941 942 943 944 945
	if err != nil {
		return nil, fmt.Errorf("cannot load resource manifest: %v", err)
	}

	entry, _ := trie.getEntry("")
	if entry.ContentType != ResourceContentType {
		return nil, fmt.Errorf("not a resource manifest: %s", addr)
	}

	return storage.Address(common.FromHex(entry.Hash)), nil
946
}