api.go 30.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// 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

19 20 21
//go:generate mimegen --types=./../../cmd/swarm/mimegen/mime.types --package=api --out=gen_mime.go
//go:generate gofmt -s -w gen_mime.go

22
import (
23
	"archive/tar"
24
	"context"
25 26 27
	"crypto/ecdsa"
	"encoding/hex"
	"errors"
28 29
	"fmt"
	"io"
30
	"math/big"
31
	"net/http"
32
	"path"
33 34
	"strings"

35 36 37 38
	"bytes"
	"mime"
	"path/filepath"
	"time"
39 40

	"github.com/ethereum/go-ethereum/common"
41 42
	"github.com/ethereum/go-ethereum/contracts/ens"
	"github.com/ethereum/go-ethereum/core/types"
43
	"github.com/ethereum/go-ethereum/metrics"
44
	"github.com/ethereum/go-ethereum/swarm/log"
45
	"github.com/ethereum/go-ethereum/swarm/spancontext"
46
	"github.com/ethereum/go-ethereum/swarm/storage"
47 48
	"github.com/ethereum/go-ethereum/swarm/storage/feed"
	"github.com/ethereum/go-ethereum/swarm/storage/feed/lookup"
49 50

	opentracing "github.com/opentracing/opentracing-go"
51 52
)

53
var (
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
	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)
80 81
)

82
// Resolver interface resolve a domain name to a hash using ENS
83 84 85 86
type Resolver interface {
	Resolve(string) (common.Hash, error)
}

87 88 89 90 91 92 93
// 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)
}

94
// NoResolverError is returned by MultiResolver.Resolve if no resolver
95
// can be found for the address.
96 97 98 99
type NoResolverError struct {
	TLD string
}

100
// NewNoResolverError creates a NoResolverError for the given top level domain
101 102 103 104
func NewNoResolverError(tld string) *NoResolverError {
	return &NoResolverError{TLD: tld}
}

105
// Error NoResolverError implements error
106 107 108 109 110 111
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)
}
112 113

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

// 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.
129
func MultiResolverOptionWithResolver(r ResolveValidator, tld string) MultiResolverOption {
130 131 132 133 134 135 136 137
	return func(m *MultiResolver) {
		m.resolvers[tld] = append(m.resolvers[tld], r)
	}
}

// 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
	}
	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,
149
// the Hash from the first one which does not return error
150
// 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
// 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
}

182
/*
183 184 185
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
186
*/
187
type API struct {
188
	feed      *feed.Handler
189 190
	fileStore *storage.FileStore
	dns       Resolver
191
	Decryptor func(context.Context, string) DecryptFunc
192 193
}

194
// NewAPI the api constructor initialises a new API instance.
195
func NewAPI(fileStore *storage.FileStore, dns Resolver, feedHandler *feed.Handler, pk *ecdsa.PrivateKey) (self *API) {
196 197 198
	self = &API{
		fileStore: fileStore,
		dns:       dns,
199
		feed:      feedHandler,
200 201 202
		Decryptor: func(ctx context.Context, credentials string) DecryptFunc {
			return self.doDecrypt(ctx, credentials, pk)
		},
203 204 205 206
	}
	return
}

207
// Retrieve FileStore reader API
208 209
func (a *API) Retrieve(ctx context.Context, addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
	return a.fileStore.Retrieve(ctx, addr)
210 211
}

212
// Store wraps the Store API call of the embedded FileStore
213
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) {
214
	log.Debug("api.store", "size", size)
215
	return a.fileStore.Store(ctx, data, size, toEncrypt)
216 217
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
// Resolve a name into a content-addressed hash
// where address could be an ENS name, or a content addressed hash
func (a *API) Resolve(ctx context.Context, address string) (storage.Address, error) {
	// if DNS is not configured, return an error
	if a.dns == nil {
		if hashMatcher.MatchString(address) {
			return common.Hex2Bytes(address), nil
		}
		apiResolveFail.Inc(1)
		return nil, fmt.Errorf("no DNS to resolve name: %q", address)
	}
	// try and resolve the address
	resolved, err := a.dns.Resolve(address)
	if err != nil {
		if hashMatcher.MatchString(address) {
			return common.Hex2Bytes(address), nil
		}
		return nil, err
	}
	return resolved[:], nil
}

240
// Resolve resolves a URI to an Address using the MultiResolver.
241
func (a *API) ResolveURI(ctx context.Context, uri *URI, credentials string) (storage.Address, error) {
242
	apiResolveCount.Inc(1)
243
	log.Trace("resolving", "uri", uri.Addr)
244

245 246 247 248 249 250
	var sp opentracing.Span
	ctx, sp = spancontext.StartSpan(
		ctx,
		"api.resolve")
	defer sp.Finish()

251 252 253 254
	// if the URI is immutable, check if the address looks like a hash
	if uri.Immutable() {
		key := uri.Address()
		if key == nil {
255
			return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
256
		}
257
		return key, nil
258
	}
259

260 261 262
	addr, err := a.Resolve(ctx, uri.Addr)
	if err != nil {
		return nil, err
263
	}
264

265 266
	if uri.Path == "" {
		return addr, nil
267
	}
268 269
	walker, err := a.NewManifestWalker(ctx, addr, a.Decryptor(ctx, credentials), nil)
	if err != nil {
270
		return nil, err
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
	var entry *ManifestEntry
	walker.Walk(func(e *ManifestEntry) error {
		// if the entry matches the path, set entry and stop
		// the walk
		if e.Path == uri.Path {
			entry = e
			// return an error to cancel the walk
			return errors.New("found")
		}
		// ignore non-manifest files
		if e.ContentType != ManifestType {
			return nil
		}
		// if the manifest's path is a prefix of the
		// requested path, recurse into it by returning
		// nil and continuing the walk
		if strings.HasPrefix(uri.Path, e.Path) {
			return nil
		}
		return ErrSkipManifest
	})
	if entry == nil {
		return nil, errors.New("not found")
	}
	addr = storage.Address(common.Hex2Bytes(entry.Hash))
	return addr, nil
298 299
}

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

// Get uses iterative manifest retrieval and prefix matching
326 327
// to resolve basePath to content using FileStore retrieve
// it returns a section reader, mimeType, status, the key of the actual content and an error
328
func (a *API) Get(ctx context.Context, decrypt DecryptFunc, manifestAddr storage.Address, path string) (reader storage.LazySectionReader, mimeType string, status int, contentAddr storage.Address, err error) {
329
	log.Debug("api.get", "key", manifestAddr, "path", path)
330
	apiGetCount.Inc(1)
331
	trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, decrypt)
332
	if err != nil {
333
		apiGetNotFound.Inc(1)
334
		status = http.StatusNotFound
335
		return nil, "", http.StatusNotFound, nil, err
336 337
	}

338
	log.Debug("trie getting entry", "key", manifestAddr, "path", path)
339
	entry, _ := trie.getEntry(path)
340

341
	if entry != nil {
342
		log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
343 344 345 346 347 348 349 350 351 352

		if entry.ContentType == ManifestType {
			log.Debug("entry is manifest", "key", manifestAddr, "new key", entry.Hash)
			adr, err := hex.DecodeString(entry.Hash)
			if err != nil {
				return nil, "", 0, nil, err
			}
			return a.Get(ctx, decrypt, adr, entry.Path)
		}

353
		// we need to do some extra work if this is a Swarm feed manifest
354 355 356
		if entry.ContentType == FeedContentType {
			if entry.Feed == nil {
				return reader, mimeType, status, nil, fmt.Errorf("Cannot decode Feed in manifest")
357
			}
358
			_, err := a.feed.Lookup(ctx, feed.NewQueryLatest(entry.Feed, lookup.NoClue))
359 360 361
			if err != nil {
				apiGetNotFound.Inc(1)
				status = http.StatusNotFound
362
				log.Debug(fmt.Sprintf("get feed update content error: %v", err))
363 364
				return reader, mimeType, status, nil, err
			}
365
			// get the data of the update
366
			_, contentAddr, err := a.feed.GetContent(entry.Feed)
367 368 369
			if err != nil {
				apiGetNotFound.Inc(1)
				status = http.StatusNotFound
370
				log.Warn(fmt.Sprintf("get feed update content error: %v", err))
371 372 373
				return reader, mimeType, status, nil, err
			}

374 375
			// extract content hash
			if len(contentAddr) != storage.AddressLength {
376 377
				apiGetInvalid.Inc(1)
				status = http.StatusUnprocessableEntity
378 379 380
				errorMessage := fmt.Sprintf("invalid swarm hash in feed update. Expected %d bytes. Got %d", storage.AddressLength, len(contentAddr))
				log.Warn(errorMessage)
				return reader, mimeType, status, nil, errors.New(errorMessage)
381
			}
382 383
			manifestAddr = storage.Address(contentAddr)
			log.Trace("feed update contains swarm hash", "key", manifestAddr)
384

385
			// get the manifest the swarm hash points to
386
			trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, NOOPDecrypt)
387 388 389
			if err != nil {
				apiGetNotFound.Inc(1)
				status = http.StatusNotFound
390
				log.Warn(fmt.Sprintf("loadManifestTrie (feed update) error: %v", err))
391 392 393
				return reader, mimeType, status, nil, err
			}

394 395 396 397 398 399
			// 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)
400 401
				err = fmt.Errorf("manifest (feed update) entry for '%s' not found", path)
				log.Trace("manifest (feed update) entry not found", "key", manifestAddr, "path", path)
402
				return reader, mimeType, status, nil, err
403 404 405
			}
		}

406
		// regardless of feed update manifests or normal manifests we will converge at this point
407 408
		// get the key the manifest entry points to and serve it if it's unambiguous
		contentAddr = common.Hex2Bytes(entry.Hash)
409
		status = entry.Status
410
		if status == http.StatusMultipleChoices {
411 412
			apiGetHTTP300.Inc(1)
			return nil, entry.ContentType, status, contentAddr, err
413
		}
414 415
		mimeType = entry.ContentType
		log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
416
		reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
417
	} else {
418
		// no entry found
419
		status = http.StatusNotFound
420
		apiGetNotFound.Inc(1)
421
		err = fmt.Errorf("Not found: could not find resource '%s'", path)
422
		log.Trace("manifest entry not found", "key", contentAddr, "path", path)
423 424 425 426
	}
	return
}

427 428 429 430 431 432 433
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
	}
434
	key, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

	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
453
func (a *API) GetDirectoryTar(ctx context.Context, decrypt DecryptFunc, uri *URI) (io.ReadCloser, error) {
454
	apiGetTarCount.Inc(1)
455
	addr, err := a.Resolve(ctx, uri.Addr)
456 457 458
	if err != nil {
		return nil, err
	}
459
	walker, err := a.NewManifestWalker(ctx, addr, decrypt, nil)
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	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)))
478
			size, err := reader.Size(ctx, nil)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
			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
		})
508 509 510 511
		// close tar writer before closing pipew
		// to flush remaining data to pipew
		// regardless of error value
		tw.Close()
512 513 514 515 516 517 518 519 520 521 522 523 524
		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
525
func (a *API) GetManifestList(ctx context.Context, decryptor DecryptFunc, addr storage.Address, prefix string) (list ManifestList, err error) {
526
	apiManifestListCount.Inc(1)
527
	walker, err := a.NewManifestWalker(ctx, addr, decryptor, nil)
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
	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
}

610
// Modify loads manifest and checks the content hash before recalculating and storing the manifest.
611
func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
612
	apiModifyCount.Inc(1)
613
	quitC := make(chan bool)
614
	trie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
615
	if err != nil {
616
		apiModifyFail.Inc(1)
617
		return nil, err
618 619
	}
	if contentHash != "" {
620
		entry := newManifestTrieEntry(&ManifestEntry{
621 622
			Path:        path,
			ContentType: contentType,
623 624
		}, nil)
		entry.Hash = contentHash
625 626 627 628 629
		trie.addEntry(entry, quitC)
	} else {
		trie.deleteEntry(path, quitC)
	}

630
	if err := trie.recalcAndStore(); err != nil {
631
		apiModifyFail.Inc(1)
632
		return nil, err
633
	}
634
	return trie.ref, nil
635
}
636

637
// AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
638
func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
639
	apiAddFileCount.Inc(1)
640 641 642

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
643
		apiAddFileFail.Inc(1)
644 645
		return nil, "", err
	}
646
	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
647
	if err != nil {
648
		apiAddFileFail.Inc(1)
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
		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(),
	}

665
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
666
	if err != nil {
667
		apiAddFileFail.Inc(1)
668 669 670
		return nil, "", err
	}

671
	fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
672
	if err != nil {
673
		apiAddFileFail.Inc(1)
674 675 676 677 678
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
679
		apiAddFileFail.Inc(1)
680 681 682 683 684 685 686
		return nil, "", err

	}

	return fkey, newMkey.String(), nil
}

687
func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath, defaultPath string, mw *ManifestWriter) (storage.Address, error) {
688 689 690 691
	apiUploadTarCount.Inc(1)
	var contentKey storage.Address
	tr := tar.NewReader(bodyReader)
	defer bodyReader.Close()
692
	var defaultPathFound bool
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
	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)
709 710 711 712 713
		contentType := hdr.Xattrs["user.swarm.content-type"]
		if contentType == "" {
			contentType = mime.TypeByExtension(filepath.Ext(hdr.Name))
		}
		//DetectContentType("")
714 715
		entry := &ManifestEntry{
			Path:        manifestPath,
716
			ContentType: contentType,
717 718 719 720 721 722 723 724 725
			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)
		}
726
		if hdr.Name == defaultPath {
727 728 729 730 731
			contentType := hdr.Xattrs["user.swarm.content-type"]
			if contentType == "" {
				contentType = mime.TypeByExtension(filepath.Ext(hdr.Name))
			}

732 733 734
			entry := &ManifestEntry{
				Hash:        contentKey.Hex(),
				Path:        "", // default entry
735
				ContentType: contentType,
736 737 738 739 740 741 742 743 744 745 746 747 748 749
				Mode:        hdr.Mode,
				Size:        hdr.Size,
				ModTime:     hdr.ModTime,
			}
			contentKey, err = mw.AddEntry(ctx, nil, entry)
			if err != nil {
				apiUploadTarFail.Inc(1)
				return nil, fmt.Errorf("error adding default manifest entry from tar stream: %s", err)
			}
			defaultPathFound = true
		}
	}
	if defaultPath != "" && !defaultPathFound {
		return contentKey, fmt.Errorf("default path %q not found", defaultPath)
750 751 752 753
	}
	return contentKey, nil
}

754
// RemoveFile removes a file entry in a manifest.
755
func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
756
	apiRmFileCount.Inc(1)
757 758 759

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
760
		apiRmFileFail.Inc(1)
761 762
		return "", err
	}
763
	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
764
	if err != nil {
765
		apiRmFileFail.Inc(1)
766 767 768 769 770 771 772 773
		return "", err
	}

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

774
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
775
	if err != nil {
776
		apiRmFileFail.Inc(1)
777 778 779 780 781
		return "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
782
		apiRmFileFail.Inc(1)
783 784 785 786 787
		return "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
788
		apiRmFileFail.Inc(1)
789 790 791 792 793 794 795
		return "", err

	}

	return newMkey.String(), nil
}

796
// AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
797
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) {
798
	apiAppendFileCount.Inc(1)
799 800 801 802 803 804 805 806

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

	buf := make([]byte, buffSize)

807
	oldReader, _ := a.Retrieve(ctx, oldAddr)
808 809 810 811 812 813 814 815 816 817 818 819 820
	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
821
	//oldReader := a.Retrieve(oldKey)
822 823 824 825 826
	//newReader := bytes.NewReader(content)
	//combinedReader := io.MultiReader(oldReader, newReader)

	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
827
		apiAppendFileFail.Inc(1)
828 829
		return nil, "", err
	}
830
	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
831
	if err != nil {
832
		apiAppendFileFail.Inc(1)
833 834 835 836 837 838 839 840
		return nil, "", err
	}

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

841
	mw, err := a.NewManifestWriter(ctx, mkey, nil)
842
	if err != nil {
843
		apiAppendFileFail.Inc(1)
844 845 846 847 848
		return nil, "", err
	}

	err = mw.RemoveEntry(filepath.Join(path, fname))
	if err != nil {
849
		apiAppendFileFail.Inc(1)
850 851 852 853 854 855 856 857 858 859 860
		return nil, "", err
	}

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

861
	fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
862
	if err != nil {
863
		apiAppendFileFail.Inc(1)
864 865 866 867 868
		return nil, "", err
	}

	newMkey, err := mw.Store()
	if err != nil {
869
		apiAppendFileFail.Inc(1)
870 871 872 873 874 875 876
		return nil, "", err

	}

	return fkey, newMkey.String(), nil
}

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

880 881 882 883
	uri, err := Parse("bzz:/" + mhash)
	if err != nil {
		return nil, nil, err
	}
884
	addr, err = a.Resolve(ctx, uri.Addr)
885 886 887 888 889
	if err != nil {
		return nil, nil, err
	}

	quitC := make(chan bool)
890
	rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
891
	if err != nil {
892
		return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
893 894 895 896 897 898 899
	}

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

900
	if err != nil {
901 902 903 904 905
		return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
	}
	return addr, manifestEntryMap, nil
}

906
// FeedsLookup finds Swarm feeds updates at specific points in time, or the latest update
907 908
func (a *API) FeedsLookup(ctx context.Context, query *feed.Query) ([]byte, error) {
	_, err := a.feed.Lookup(ctx, query)
909
	if err != nil {
910
		return nil, err
911 912
	}
	var data []byte
913
	_, data, err = a.feed.GetContent(&query.Feed)
914
	if err != nil {
915
		return nil, err
916
	}
917
	return data, nil
918 919
}

920
// FeedsNewRequest creates a Request object to update a specific feed
921 922
func (a *API) FeedsNewRequest(ctx context.Context, feed *feed.Feed) (*feed.Request, error) {
	return a.feed.NewRequest(ctx, feed)
923 924
}

925
// FeedsUpdate publishes a new update on the given feed
926 927
func (a *API) FeedsUpdate(ctx context.Context, request *feed.Request) (storage.Address, error) {
	return a.feed.Update(ctx, request)
928 929
}

930 931
// ErrCannotLoadFeedManifest is returned when looking up a feeds manifest fails
var ErrCannotLoadFeedManifest = errors.New("Cannot load feed manifest")
932

933 934
// ErrNotAFeedManifest is returned when the address provided returned something other than a valid manifest
var ErrNotAFeedManifest = errors.New("Not a feed manifest")
935

936
// ResolveFeedManifest retrieves the Swarm feed manifest for the given address, and returns the referenced Feed.
937
func (a *API) ResolveFeedManifest(ctx context.Context, addr storage.Address) (*feed.Feed, error) {
938
	trie, err := loadManifest(ctx, a.fileStore, addr, nil, NOOPDecrypt)
939
	if err != nil {
940
		return nil, ErrCannotLoadFeedManifest
941 942 943
	}

	entry, _ := trie.getEntry("")
944 945
	if entry.ContentType != FeedContentType {
		return nil, ErrNotAFeedManifest
946 947
	}

948
	return entry.Feed, nil
949 950
}

951
// ErrCannotResolveFeedURI is returned when the ENS resolver is not able to translate a name to a Swarm feed
952
var ErrCannotResolveFeedURI = errors.New("Cannot resolve Feed URI")
953

954
// ErrCannotResolveFeed is returned when values provided are not enough or invalid to recreate a
955
// feed out of them.
956
var ErrCannotResolveFeed = errors.New("Cannot resolve Feed")
957

958 959
// ResolveFeed attempts to extract feed information out of the manifest, if provided
// If not, it attempts to extract the feed out of a set of key-value pairs
960 961
func (a *API) ResolveFeed(ctx context.Context, uri *URI, values feed.Values) (*feed.Feed, error) {
	var fd *feed.Feed
962 963 964 965 966 967 968
	var err error
	if uri.Addr != "" {
		// resolve the content key.
		manifestAddr := uri.Address()
		if manifestAddr == nil {
			manifestAddr, err = a.Resolve(ctx, uri.Addr)
			if err != nil {
969
				return nil, ErrCannotResolveFeedURI
970 971 972
			}
		}

973
		// get the Swarm feed from the manifest
974
		fd, err = a.ResolveFeedManifest(ctx, manifestAddr)
975 976 977
		if err != nil {
			return nil, err
		}
978
		log.Debug("handle.get.feed: resolved", "manifestkey", manifestAddr, "feed", fd.Hex())
979
	} else {
980 981
		var f feed.Feed
		if err := f.FromValues(values); err != nil {
982
			return nil, ErrCannotResolveFeed
983 984

		}
985
		fd = &f
986
	}
987
	return fd, nil
988
}
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

// MimeOctetStream default value of http Content-Type header
const MimeOctetStream = "application/octet-stream"

// DetectContentType by file file extension, or fallback to content sniff
func DetectContentType(fileName string, f io.ReadSeeker) (string, error) {
	ctype := mime.TypeByExtension(filepath.Ext(fileName))
	if ctype != "" {
		return ctype, nil
	}

	// save/rollback to get content probe from begin of file
	currentPosition, err := f.Seek(0, io.SeekCurrent)
	if err != nil {
		return MimeOctetStream, fmt.Errorf("seeker can't seek, %s", err)
	}

	// read a chunk to decide between utf-8 text and binary
	var buf [512]byte
	n, _ := f.Read(buf[:])
	ctype = http.DetectContentType(buf[:n])

	_, err = f.Seek(currentPosition, io.SeekStart) // rewind to output whole file
	if err != nil {
		return MimeOctetStream, fmt.Errorf("seeker can't seek, %s", err)
	}

	return ctype, nil
}