github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/swarm/api/api.go (about)

     1  // Copyright 2016 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package api
    18  
    19  //go:generate mimegen --types=./../../cmd/swarm/mimegen/mime.types --package=api --out=gen_mime.go
    20  //go:generate gofmt -s -w gen_mime.go
    21  
    22  import (
    23  	"archive/tar"
    24  	"context"
    25  	"crypto/ecdsa"
    26  	"encoding/hex"
    27  	"errors"
    28  	"fmt"
    29  	"io"
    30  	"math/big"
    31  	"net/http"
    32  	"path"
    33  	"strings"
    34  
    35  	"bytes"
    36  	"mime"
    37  	"path/filepath"
    38  	"time"
    39  
    40  	"github.com/ShyftNetwork/go-empyrean/common"
    41  	"github.com/ShyftNetwork/go-empyrean/contracts/ens"
    42  	"github.com/ShyftNetwork/go-empyrean/core/types"
    43  	"github.com/ShyftNetwork/go-empyrean/metrics"
    44  	"github.com/ShyftNetwork/go-empyrean/swarm/log"
    45  	"github.com/ShyftNetwork/go-empyrean/swarm/spancontext"
    46  	"github.com/ShyftNetwork/go-empyrean/swarm/storage"
    47  	"github.com/ShyftNetwork/go-empyrean/swarm/storage/feed"
    48  	"github.com/ShyftNetwork/go-empyrean/swarm/storage/feed/lookup"
    49  	opentracing "github.com/opentracing/opentracing-go"
    50  )
    51  
    52  var (
    53  	apiResolveCount        = metrics.NewRegisteredCounter("api.resolve.count", nil)
    54  	apiResolveFail         = metrics.NewRegisteredCounter("api.resolve.fail", nil)
    55  	apiPutCount            = metrics.NewRegisteredCounter("api.put.count", nil)
    56  	apiPutFail             = metrics.NewRegisteredCounter("api.put.fail", nil)
    57  	apiGetCount            = metrics.NewRegisteredCounter("api.get.count", nil)
    58  	apiGetNotFound         = metrics.NewRegisteredCounter("api.get.notfound", nil)
    59  	apiGetHTTP300          = metrics.NewRegisteredCounter("api.get.http.300", nil)
    60  	apiManifestUpdateCount = metrics.NewRegisteredCounter("api.manifestupdate.count", nil)
    61  	apiManifestUpdateFail  = metrics.NewRegisteredCounter("api.manifestupdate.fail", nil)
    62  	apiManifestListCount   = metrics.NewRegisteredCounter("api.manifestlist.count", nil)
    63  	apiManifestListFail    = metrics.NewRegisteredCounter("api.manifestlist.fail", nil)
    64  	apiDeleteCount         = metrics.NewRegisteredCounter("api.delete.count", nil)
    65  	apiDeleteFail          = metrics.NewRegisteredCounter("api.delete.fail", nil)
    66  	apiGetTarCount         = metrics.NewRegisteredCounter("api.gettar.count", nil)
    67  	apiGetTarFail          = metrics.NewRegisteredCounter("api.gettar.fail", nil)
    68  	apiUploadTarCount      = metrics.NewRegisteredCounter("api.uploadtar.count", nil)
    69  	apiUploadTarFail       = metrics.NewRegisteredCounter("api.uploadtar.fail", nil)
    70  	apiModifyCount         = metrics.NewRegisteredCounter("api.modify.count", nil)
    71  	apiModifyFail          = metrics.NewRegisteredCounter("api.modify.fail", nil)
    72  	apiAddFileCount        = metrics.NewRegisteredCounter("api.addfile.count", nil)
    73  	apiAddFileFail         = metrics.NewRegisteredCounter("api.addfile.fail", nil)
    74  	apiRmFileCount         = metrics.NewRegisteredCounter("api.removefile.count", nil)
    75  	apiRmFileFail          = metrics.NewRegisteredCounter("api.removefile.fail", nil)
    76  	apiAppendFileCount     = metrics.NewRegisteredCounter("api.appendfile.count", nil)
    77  	apiAppendFileFail      = metrics.NewRegisteredCounter("api.appendfile.fail", nil)
    78  	apiGetInvalid          = metrics.NewRegisteredCounter("api.get.invalid", nil)
    79  )
    80  
    81  // Resolver interface resolve a domain name to a hash using ENS
    82  type Resolver interface {
    83  	Resolve(string) (common.Hash, error)
    84  }
    85  
    86  // ResolveValidator is used to validate the contained Resolver
    87  type ResolveValidator interface {
    88  	Resolver
    89  	Owner(node [32]byte) (common.Address, error)
    90  	HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
    91  }
    92  
    93  // NoResolverError is returned by MultiResolver.Resolve if no resolver
    94  // can be found for the address.
    95  type NoResolverError struct {
    96  	TLD string
    97  }
    98  
    99  // NewNoResolverError creates a NoResolverError for the given top level domain
   100  func NewNoResolverError(tld string) *NoResolverError {
   101  	return &NoResolverError{TLD: tld}
   102  }
   103  
   104  // Error NoResolverError implements error
   105  func (e *NoResolverError) Error() string {
   106  	if e.TLD == "" {
   107  		return "no ENS resolver"
   108  	}
   109  	return fmt.Sprintf("no ENS endpoint configured to resolve .%s TLD names", e.TLD)
   110  }
   111  
   112  // MultiResolver is used to resolve URL addresses based on their TLDs.
   113  // Each TLD can have multiple resolvers, and the resolution from the
   114  // first one in the sequence will be returned.
   115  type MultiResolver struct {
   116  	resolvers map[string][]ResolveValidator
   117  	nameHash  func(string) common.Hash
   118  }
   119  
   120  // MultiResolverOption sets options for MultiResolver and is used as
   121  // arguments for its constructor.
   122  type MultiResolverOption func(*MultiResolver)
   123  
   124  // MultiResolverOptionWithResolver adds a Resolver to a list of resolvers
   125  // for a specific TLD. If TLD is an empty string, the resolver will be added
   126  // to the list of default resolver, the ones that will be used for resolution
   127  // of addresses which do not have their TLD resolver specified.
   128  func MultiResolverOptionWithResolver(r ResolveValidator, tld string) MultiResolverOption {
   129  	return func(m *MultiResolver) {
   130  		m.resolvers[tld] = append(m.resolvers[tld], r)
   131  	}
   132  }
   133  
   134  // NewMultiResolver creates a new instance of MultiResolver.
   135  func NewMultiResolver(opts ...MultiResolverOption) (m *MultiResolver) {
   136  	m = &MultiResolver{
   137  		resolvers: make(map[string][]ResolveValidator),
   138  		nameHash:  ens.EnsNode,
   139  	}
   140  	for _, o := range opts {
   141  		o(m)
   142  	}
   143  	return m
   144  }
   145  
   146  // Resolve resolves address by choosing a Resolver by TLD.
   147  // If there are more default Resolvers, or for a specific TLD,
   148  // the Hash from the first one which does not return error
   149  // will be returned.
   150  func (m *MultiResolver) Resolve(addr string) (h common.Hash, err error) {
   151  	rs, err := m.getResolveValidator(addr)
   152  	if err != nil {
   153  		return h, err
   154  	}
   155  	for _, r := range rs {
   156  		h, err = r.Resolve(addr)
   157  		if err == nil {
   158  			return
   159  		}
   160  	}
   161  	return
   162  }
   163  
   164  // getResolveValidator uses the hostname to retrieve the resolver associated with the top level domain
   165  func (m *MultiResolver) getResolveValidator(name string) ([]ResolveValidator, error) {
   166  	rs := m.resolvers[""]
   167  	tld := path.Ext(name)
   168  	if tld != "" {
   169  		tld = tld[1:]
   170  		rstld, ok := m.resolvers[tld]
   171  		if ok {
   172  			return rstld, nil
   173  		}
   174  	}
   175  	if len(rs) == 0 {
   176  		return rs, NewNoResolverError(tld)
   177  	}
   178  	return rs, nil
   179  }
   180  
   181  /*
   182  API implements webserver/file system related content storage and retrieval
   183  on top of the FileStore
   184  it is the public interface of the FileStore which is included in the ethereum stack
   185  */
   186  type API struct {
   187  	feed      *feed.Handler
   188  	fileStore *storage.FileStore
   189  	dns       Resolver
   190  	Decryptor func(context.Context, string) DecryptFunc
   191  }
   192  
   193  // NewAPI the api constructor initialises a new API instance.
   194  func NewAPI(fileStore *storage.FileStore, dns Resolver, feedHandler *feed.Handler, pk *ecdsa.PrivateKey) (self *API) {
   195  	self = &API{
   196  		fileStore: fileStore,
   197  		dns:       dns,
   198  		feed:      feedHandler,
   199  		Decryptor: func(ctx context.Context, credentials string) DecryptFunc {
   200  			return self.doDecrypt(ctx, credentials, pk)
   201  		},
   202  	}
   203  	return
   204  }
   205  
   206  // Retrieve FileStore reader API
   207  func (a *API) Retrieve(ctx context.Context, addr storage.Address) (reader storage.LazySectionReader, isEncrypted bool) {
   208  	return a.fileStore.Retrieve(ctx, addr)
   209  }
   210  
   211  // Store wraps the Store API call of the embedded FileStore
   212  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) {
   213  	log.Debug("api.store", "size", size)
   214  	return a.fileStore.Store(ctx, data, size, toEncrypt)
   215  }
   216  
   217  // Resolve a name into a content-addressed hash
   218  // where address could be an ENS name, or a content addressed hash
   219  func (a *API) Resolve(ctx context.Context, address string) (storage.Address, error) {
   220  	// if DNS is not configured, return an error
   221  	if a.dns == nil {
   222  		if hashMatcher.MatchString(address) {
   223  			return common.Hex2Bytes(address), nil
   224  		}
   225  		apiResolveFail.Inc(1)
   226  		return nil, fmt.Errorf("no DNS to resolve name: %q", address)
   227  	}
   228  	// try and resolve the address
   229  	resolved, err := a.dns.Resolve(address)
   230  	if err != nil {
   231  		if hashMatcher.MatchString(address) {
   232  			return common.Hex2Bytes(address), nil
   233  		}
   234  		return nil, err
   235  	}
   236  	return resolved[:], nil
   237  }
   238  
   239  // Resolve resolves a URI to an Address using the MultiResolver.
   240  func (a *API) ResolveURI(ctx context.Context, uri *URI, credentials string) (storage.Address, error) {
   241  	apiResolveCount.Inc(1)
   242  	log.Trace("resolving", "uri", uri.Addr)
   243  
   244  	var sp opentracing.Span
   245  	ctx, sp = spancontext.StartSpan(
   246  		ctx,
   247  		"api.resolve")
   248  	defer sp.Finish()
   249  
   250  	// if the URI is immutable, check if the address looks like a hash
   251  	if uri.Immutable() {
   252  		key := uri.Address()
   253  		if key == nil {
   254  			return nil, fmt.Errorf("immutable address not a content hash: %q", uri.Addr)
   255  		}
   256  		return key, nil
   257  	}
   258  
   259  	addr, err := a.Resolve(ctx, uri.Addr)
   260  	if err != nil {
   261  		return nil, err
   262  	}
   263  
   264  	if uri.Path == "" {
   265  		return addr, nil
   266  	}
   267  	walker, err := a.NewManifestWalker(ctx, addr, a.Decryptor(ctx, credentials), nil)
   268  	if err != nil {
   269  		return nil, err
   270  	}
   271  	var entry *ManifestEntry
   272  	walker.Walk(func(e *ManifestEntry) error {
   273  		// if the entry matches the path, set entry and stop
   274  		// the walk
   275  		if e.Path == uri.Path {
   276  			entry = e
   277  			// return an error to cancel the walk
   278  			return errors.New("found")
   279  		}
   280  		// ignore non-manifest files
   281  		if e.ContentType != ManifestType {
   282  			return nil
   283  		}
   284  		// if the manifest's path is a prefix of the
   285  		// requested path, recurse into it by returning
   286  		// nil and continuing the walk
   287  		if strings.HasPrefix(uri.Path, e.Path) {
   288  			return nil
   289  		}
   290  		return ErrSkipManifest
   291  	})
   292  	if entry == nil {
   293  		return nil, errors.New("not found")
   294  	}
   295  	addr = storage.Address(common.Hex2Bytes(entry.Hash))
   296  	return addr, nil
   297  }
   298  
   299  // Put provides singleton manifest creation on top of FileStore store
   300  func (a *API) Put(ctx context.Context, content string, contentType string, toEncrypt bool) (k storage.Address, wait func(context.Context) error, err error) {
   301  	apiPutCount.Inc(1)
   302  	r := strings.NewReader(content)
   303  	key, waitContent, err := a.fileStore.Store(ctx, r, int64(len(content)), toEncrypt)
   304  	if err != nil {
   305  		apiPutFail.Inc(1)
   306  		return nil, nil, err
   307  	}
   308  	manifest := fmt.Sprintf(`{"entries":[{"hash":"%v","contentType":"%s"}]}`, key, contentType)
   309  	r = strings.NewReader(manifest)
   310  	key, waitManifest, err := a.fileStore.Store(ctx, r, int64(len(manifest)), toEncrypt)
   311  	if err != nil {
   312  		apiPutFail.Inc(1)
   313  		return nil, nil, err
   314  	}
   315  	return key, func(ctx context.Context) error {
   316  		err := waitContent(ctx)
   317  		if err != nil {
   318  			return err
   319  		}
   320  		return waitManifest(ctx)
   321  	}, nil
   322  }
   323  
   324  // Get uses iterative manifest retrieval and prefix matching
   325  // to resolve basePath to content using FileStore retrieve
   326  // it returns a section reader, mimeType, status, the key of the actual content and an error
   327  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) {
   328  	log.Debug("api.get", "key", manifestAddr, "path", path)
   329  	apiGetCount.Inc(1)
   330  	trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, decrypt)
   331  	if err != nil {
   332  		apiGetNotFound.Inc(1)
   333  		status = http.StatusNotFound
   334  		return nil, "", http.StatusNotFound, nil, err
   335  	}
   336  
   337  	log.Debug("trie getting entry", "key", manifestAddr, "path", path)
   338  	entry, _ := trie.getEntry(path)
   339  
   340  	if entry != nil {
   341  		log.Debug("trie got entry", "key", manifestAddr, "path", path, "entry.Hash", entry.Hash)
   342  
   343  		if entry.ContentType == ManifestType {
   344  			log.Debug("entry is manifest", "key", manifestAddr, "new key", entry.Hash)
   345  			adr, err := hex.DecodeString(entry.Hash)
   346  			if err != nil {
   347  				return nil, "", 0, nil, err
   348  			}
   349  			return a.Get(ctx, decrypt, adr, entry.Path)
   350  		}
   351  
   352  		// we need to do some extra work if this is a Swarm feed manifest
   353  		if entry.ContentType == FeedContentType {
   354  			if entry.Feed == nil {
   355  				return reader, mimeType, status, nil, fmt.Errorf("Cannot decode Feed in manifest")
   356  			}
   357  			_, err := a.feed.Lookup(ctx, feed.NewQueryLatest(entry.Feed, lookup.NoClue))
   358  			if err != nil {
   359  				apiGetNotFound.Inc(1)
   360  				status = http.StatusNotFound
   361  				log.Debug(fmt.Sprintf("get feed update content error: %v", err))
   362  				return reader, mimeType, status, nil, err
   363  			}
   364  			// get the data of the update
   365  			_, contentAddr, err := a.feed.GetContent(entry.Feed)
   366  			if err != nil {
   367  				apiGetNotFound.Inc(1)
   368  				status = http.StatusNotFound
   369  				log.Warn(fmt.Sprintf("get feed update content error: %v", err))
   370  				return reader, mimeType, status, nil, err
   371  			}
   372  
   373  			// extract content hash
   374  			if len(contentAddr) != storage.AddressLength {
   375  				apiGetInvalid.Inc(1)
   376  				status = http.StatusUnprocessableEntity
   377  				errorMessage := fmt.Sprintf("invalid swarm hash in feed update. Expected %d bytes. Got %d", storage.AddressLength, len(contentAddr))
   378  				log.Warn(errorMessage)
   379  				return reader, mimeType, status, nil, errors.New(errorMessage)
   380  			}
   381  			manifestAddr = storage.Address(contentAddr)
   382  			log.Trace("feed update contains swarm hash", "key", manifestAddr)
   383  
   384  			// get the manifest the swarm hash points to
   385  			trie, err := loadManifest(ctx, a.fileStore, manifestAddr, nil, NOOPDecrypt)
   386  			if err != nil {
   387  				apiGetNotFound.Inc(1)
   388  				status = http.StatusNotFound
   389  				log.Warn(fmt.Sprintf("loadManifestTrie (feed update) error: %v", err))
   390  				return reader, mimeType, status, nil, err
   391  			}
   392  
   393  			// finally, get the manifest entry
   394  			// it will always be the entry on path ""
   395  			entry, _ = trie.getEntry(path)
   396  			if entry == nil {
   397  				status = http.StatusNotFound
   398  				apiGetNotFound.Inc(1)
   399  				err = fmt.Errorf("manifest (feed update) entry for '%s' not found", path)
   400  				log.Trace("manifest (feed update) entry not found", "key", manifestAddr, "path", path)
   401  				return reader, mimeType, status, nil, err
   402  			}
   403  		}
   404  
   405  		// regardless of feed update manifests or normal manifests we will converge at this point
   406  		// get the key the manifest entry points to and serve it if it's unambiguous
   407  		contentAddr = common.Hex2Bytes(entry.Hash)
   408  		status = entry.Status
   409  		if status == http.StatusMultipleChoices {
   410  			apiGetHTTP300.Inc(1)
   411  			return nil, entry.ContentType, status, contentAddr, err
   412  		}
   413  		mimeType = entry.ContentType
   414  		log.Debug("content lookup key", "key", contentAddr, "mimetype", mimeType)
   415  		reader, _ = a.fileStore.Retrieve(ctx, contentAddr)
   416  	} else {
   417  		// no entry found
   418  		status = http.StatusNotFound
   419  		apiGetNotFound.Inc(1)
   420  		err = fmt.Errorf("Not found: could not find resource '%s'", path)
   421  		log.Trace("manifest entry not found", "key", contentAddr, "path", path)
   422  	}
   423  	return
   424  }
   425  
   426  func (a *API) Delete(ctx context.Context, addr string, path string) (storage.Address, error) {
   427  	apiDeleteCount.Inc(1)
   428  	uri, err := Parse("bzz:/" + addr)
   429  	if err != nil {
   430  		apiDeleteFail.Inc(1)
   431  		return nil, err
   432  	}
   433  	key, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
   434  
   435  	if err != nil {
   436  		return nil, err
   437  	}
   438  	newKey, err := a.UpdateManifest(ctx, key, func(mw *ManifestWriter) error {
   439  		log.Debug(fmt.Sprintf("removing %s from manifest %s", path, key.Log()))
   440  		return mw.RemoveEntry(path)
   441  	})
   442  	if err != nil {
   443  		apiDeleteFail.Inc(1)
   444  		return nil, err
   445  	}
   446  
   447  	return newKey, nil
   448  }
   449  
   450  // GetDirectoryTar fetches a requested directory as a tarstream
   451  // it returns an io.Reader and an error. Do not forget to Close() the returned ReadCloser
   452  func (a *API) GetDirectoryTar(ctx context.Context, decrypt DecryptFunc, uri *URI) (io.ReadCloser, error) {
   453  	apiGetTarCount.Inc(1)
   454  	addr, err := a.Resolve(ctx, uri.Addr)
   455  	if err != nil {
   456  		return nil, err
   457  	}
   458  	walker, err := a.NewManifestWalker(ctx, addr, decrypt, nil)
   459  	if err != nil {
   460  		apiGetTarFail.Inc(1)
   461  		return nil, err
   462  	}
   463  
   464  	piper, pipew := io.Pipe()
   465  
   466  	tw := tar.NewWriter(pipew)
   467  
   468  	go func() {
   469  		err := walker.Walk(func(entry *ManifestEntry) error {
   470  			// ignore manifests (walk will recurse into them)
   471  			if entry.ContentType == ManifestType {
   472  				return nil
   473  			}
   474  
   475  			// retrieve the entry's key and size
   476  			reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
   477  			size, err := reader.Size(ctx, nil)
   478  			if err != nil {
   479  				return err
   480  			}
   481  
   482  			// write a tar header for the entry
   483  			hdr := &tar.Header{
   484  				Name:    entry.Path,
   485  				Mode:    entry.Mode,
   486  				Size:    size,
   487  				ModTime: entry.ModTime,
   488  				Xattrs: map[string]string{
   489  					"user.swarm.content-type": entry.ContentType,
   490  				},
   491  			}
   492  
   493  			if err := tw.WriteHeader(hdr); err != nil {
   494  				return err
   495  			}
   496  
   497  			// copy the file into the tar stream
   498  			n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
   499  			if err != nil {
   500  				return err
   501  			} else if n != size {
   502  				return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
   503  			}
   504  
   505  			return nil
   506  		})
   507  		// close tar writer before closing pipew
   508  		// to flush remaining data to pipew
   509  		// regardless of error value
   510  		tw.Close()
   511  		if err != nil {
   512  			apiGetTarFail.Inc(1)
   513  			pipew.CloseWithError(err)
   514  		} else {
   515  			pipew.Close()
   516  		}
   517  	}()
   518  
   519  	return piper, nil
   520  }
   521  
   522  // GetManifestList lists the manifest entries for the specified address and prefix
   523  // and returns it as a ManifestList
   524  func (a *API) GetManifestList(ctx context.Context, decryptor DecryptFunc, addr storage.Address, prefix string) (list ManifestList, err error) {
   525  	apiManifestListCount.Inc(1)
   526  	walker, err := a.NewManifestWalker(ctx, addr, decryptor, nil)
   527  	if err != nil {
   528  		apiManifestListFail.Inc(1)
   529  		return ManifestList{}, err
   530  	}
   531  
   532  	err = walker.Walk(func(entry *ManifestEntry) error {
   533  		// handle non-manifest files
   534  		if entry.ContentType != ManifestType {
   535  			// ignore the file if it doesn't have the specified prefix
   536  			if !strings.HasPrefix(entry.Path, prefix) {
   537  				return nil
   538  			}
   539  
   540  			// if the path after the prefix contains a slash, add a
   541  			// common prefix to the list, otherwise add the entry
   542  			suffix := strings.TrimPrefix(entry.Path, prefix)
   543  			if index := strings.Index(suffix, "/"); index > -1 {
   544  				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
   545  				return nil
   546  			}
   547  			if entry.Path == "" {
   548  				entry.Path = "/"
   549  			}
   550  			list.Entries = append(list.Entries, entry)
   551  			return nil
   552  		}
   553  
   554  		// if the manifest's path is a prefix of the specified prefix
   555  		// then just recurse into the manifest by returning nil and
   556  		// continuing the walk
   557  		if strings.HasPrefix(prefix, entry.Path) {
   558  			return nil
   559  		}
   560  
   561  		// if the manifest's path has the specified prefix, then if the
   562  		// path after the prefix contains a slash, add a common prefix
   563  		// to the list and skip the manifest, otherwise recurse into
   564  		// the manifest by returning nil and continuing the walk
   565  		if strings.HasPrefix(entry.Path, prefix) {
   566  			suffix := strings.TrimPrefix(entry.Path, prefix)
   567  			if index := strings.Index(suffix, "/"); index > -1 {
   568  				list.CommonPrefixes = append(list.CommonPrefixes, prefix+suffix[:index+1])
   569  				return ErrSkipManifest
   570  			}
   571  			return nil
   572  		}
   573  
   574  		// the manifest neither has the prefix or needs recursing in to
   575  		// so just skip it
   576  		return ErrSkipManifest
   577  	})
   578  
   579  	if err != nil {
   580  		apiManifestListFail.Inc(1)
   581  		return ManifestList{}, err
   582  	}
   583  
   584  	return list, nil
   585  }
   586  
   587  func (a *API) UpdateManifest(ctx context.Context, addr storage.Address, update func(mw *ManifestWriter) error) (storage.Address, error) {
   588  	apiManifestUpdateCount.Inc(1)
   589  	mw, err := a.NewManifestWriter(ctx, addr, nil)
   590  	if err != nil {
   591  		apiManifestUpdateFail.Inc(1)
   592  		return nil, err
   593  	}
   594  
   595  	if err := update(mw); err != nil {
   596  		apiManifestUpdateFail.Inc(1)
   597  		return nil, err
   598  	}
   599  
   600  	addr, err = mw.Store()
   601  	if err != nil {
   602  		apiManifestUpdateFail.Inc(1)
   603  		return nil, err
   604  	}
   605  	log.Debug(fmt.Sprintf("generated manifest %s", addr))
   606  	return addr, nil
   607  }
   608  
   609  // Modify loads manifest and checks the content hash before recalculating and storing the manifest.
   610  func (a *API) Modify(ctx context.Context, addr storage.Address, path, contentHash, contentType string) (storage.Address, error) {
   611  	apiModifyCount.Inc(1)
   612  	quitC := make(chan bool)
   613  	trie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
   614  	if err != nil {
   615  		apiModifyFail.Inc(1)
   616  		return nil, err
   617  	}
   618  	if contentHash != "" {
   619  		entry := newManifestTrieEntry(&ManifestEntry{
   620  			Path:        path,
   621  			ContentType: contentType,
   622  		}, nil)
   623  		entry.Hash = contentHash
   624  		trie.addEntry(entry, quitC)
   625  	} else {
   626  		trie.deleteEntry(path, quitC)
   627  	}
   628  
   629  	if err := trie.recalcAndStore(); err != nil {
   630  		apiModifyFail.Inc(1)
   631  		return nil, err
   632  	}
   633  	return trie.ref, nil
   634  }
   635  
   636  // AddFile creates a new manifest entry, adds it to swarm, then adds a file to swarm.
   637  func (a *API) AddFile(ctx context.Context, mhash, path, fname string, content []byte, nameresolver bool) (storage.Address, string, error) {
   638  	apiAddFileCount.Inc(1)
   639  
   640  	uri, err := Parse("bzz:/" + mhash)
   641  	if err != nil {
   642  		apiAddFileFail.Inc(1)
   643  		return nil, "", err
   644  	}
   645  	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
   646  	if err != nil {
   647  		apiAddFileFail.Inc(1)
   648  		return nil, "", err
   649  	}
   650  
   651  	// trim the root dir we added
   652  	if path[:1] == "/" {
   653  		path = path[1:]
   654  	}
   655  
   656  	entry := &ManifestEntry{
   657  		Path:        filepath.Join(path, fname),
   658  		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
   659  		Mode:        0700,
   660  		Size:        int64(len(content)),
   661  		ModTime:     time.Now(),
   662  	}
   663  
   664  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   665  	if err != nil {
   666  		apiAddFileFail.Inc(1)
   667  		return nil, "", err
   668  	}
   669  
   670  	fkey, err := mw.AddEntry(ctx, bytes.NewReader(content), entry)
   671  	if err != nil {
   672  		apiAddFileFail.Inc(1)
   673  		return nil, "", err
   674  	}
   675  
   676  	newMkey, err := mw.Store()
   677  	if err != nil {
   678  		apiAddFileFail.Inc(1)
   679  		return nil, "", err
   680  
   681  	}
   682  
   683  	return fkey, newMkey.String(), nil
   684  }
   685  
   686  func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestPath, defaultPath string, mw *ManifestWriter) (storage.Address, error) {
   687  	apiUploadTarCount.Inc(1)
   688  	var contentKey storage.Address
   689  	tr := tar.NewReader(bodyReader)
   690  	defer bodyReader.Close()
   691  	var defaultPathFound bool
   692  	for {
   693  		hdr, err := tr.Next()
   694  		if err == io.EOF {
   695  			break
   696  		} else if err != nil {
   697  			apiUploadTarFail.Inc(1)
   698  			return nil, fmt.Errorf("error reading tar stream: %s", err)
   699  		}
   700  
   701  		// only store regular files
   702  		if !hdr.FileInfo().Mode().IsRegular() {
   703  			continue
   704  		}
   705  
   706  		// add the entry under the path from the request
   707  		manifestPath := path.Join(manifestPath, hdr.Name)
   708  		contentType := hdr.Xattrs["user.swarm.content-type"]
   709  		if contentType == "" {
   710  			contentType = mime.TypeByExtension(filepath.Ext(hdr.Name))
   711  		}
   712  		//DetectContentType("")
   713  		entry := &ManifestEntry{
   714  			Path:        manifestPath,
   715  			ContentType: contentType,
   716  			Mode:        hdr.Mode,
   717  			Size:        hdr.Size,
   718  			ModTime:     hdr.ModTime,
   719  		}
   720  		contentKey, err = mw.AddEntry(ctx, tr, entry)
   721  		if err != nil {
   722  			apiUploadTarFail.Inc(1)
   723  			return nil, fmt.Errorf("error adding manifest entry from tar stream: %s", err)
   724  		}
   725  		if hdr.Name == defaultPath {
   726  			contentType := hdr.Xattrs["user.swarm.content-type"]
   727  			if contentType == "" {
   728  				contentType = mime.TypeByExtension(filepath.Ext(hdr.Name))
   729  			}
   730  
   731  			entry := &ManifestEntry{
   732  				Hash:        contentKey.Hex(),
   733  				Path:        "", // default entry
   734  				ContentType: contentType,
   735  				Mode:        hdr.Mode,
   736  				Size:        hdr.Size,
   737  				ModTime:     hdr.ModTime,
   738  			}
   739  			contentKey, err = mw.AddEntry(ctx, nil, entry)
   740  			if err != nil {
   741  				apiUploadTarFail.Inc(1)
   742  				return nil, fmt.Errorf("error adding default manifest entry from tar stream: %s", err)
   743  			}
   744  			defaultPathFound = true
   745  		}
   746  	}
   747  	if defaultPath != "" && !defaultPathFound {
   748  		return contentKey, fmt.Errorf("default path %q not found", defaultPath)
   749  	}
   750  	return contentKey, nil
   751  }
   752  
   753  // RemoveFile removes a file entry in a manifest.
   754  func (a *API) RemoveFile(ctx context.Context, mhash string, path string, fname string, nameresolver bool) (string, error) {
   755  	apiRmFileCount.Inc(1)
   756  
   757  	uri, err := Parse("bzz:/" + mhash)
   758  	if err != nil {
   759  		apiRmFileFail.Inc(1)
   760  		return "", err
   761  	}
   762  	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
   763  	if err != nil {
   764  		apiRmFileFail.Inc(1)
   765  		return "", err
   766  	}
   767  
   768  	// trim the root dir we added
   769  	if path[:1] == "/" {
   770  		path = path[1:]
   771  	}
   772  
   773  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   774  	if err != nil {
   775  		apiRmFileFail.Inc(1)
   776  		return "", err
   777  	}
   778  
   779  	err = mw.RemoveEntry(filepath.Join(path, fname))
   780  	if err != nil {
   781  		apiRmFileFail.Inc(1)
   782  		return "", err
   783  	}
   784  
   785  	newMkey, err := mw.Store()
   786  	if err != nil {
   787  		apiRmFileFail.Inc(1)
   788  		return "", err
   789  
   790  	}
   791  
   792  	return newMkey.String(), nil
   793  }
   794  
   795  // AppendFile removes old manifest, appends file entry to new manifest and adds it to Swarm.
   796  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) {
   797  	apiAppendFileCount.Inc(1)
   798  
   799  	buffSize := offset + addSize
   800  	if buffSize < existingSize {
   801  		buffSize = existingSize
   802  	}
   803  
   804  	buf := make([]byte, buffSize)
   805  
   806  	oldReader, _ := a.Retrieve(ctx, oldAddr)
   807  	io.ReadAtLeast(oldReader, buf, int(offset))
   808  
   809  	newReader := bytes.NewReader(content)
   810  	io.ReadAtLeast(newReader, buf[offset:], int(addSize))
   811  
   812  	if buffSize < existingSize {
   813  		io.ReadAtLeast(oldReader, buf[addSize:], int(buffSize))
   814  	}
   815  
   816  	combinedReader := bytes.NewReader(buf)
   817  	totalSize := int64(len(buf))
   818  
   819  	// TODO(jmozah): to append using pyramid chunker when it is ready
   820  	//oldReader := a.Retrieve(oldKey)
   821  	//newReader := bytes.NewReader(content)
   822  	//combinedReader := io.MultiReader(oldReader, newReader)
   823  
   824  	uri, err := Parse("bzz:/" + mhash)
   825  	if err != nil {
   826  		apiAppendFileFail.Inc(1)
   827  		return nil, "", err
   828  	}
   829  	mkey, err := a.ResolveURI(ctx, uri, EMPTY_CREDENTIALS)
   830  	if err != nil {
   831  		apiAppendFileFail.Inc(1)
   832  		return nil, "", err
   833  	}
   834  
   835  	// trim the root dir we added
   836  	if path[:1] == "/" {
   837  		path = path[1:]
   838  	}
   839  
   840  	mw, err := a.NewManifestWriter(ctx, mkey, nil)
   841  	if err != nil {
   842  		apiAppendFileFail.Inc(1)
   843  		return nil, "", err
   844  	}
   845  
   846  	err = mw.RemoveEntry(filepath.Join(path, fname))
   847  	if err != nil {
   848  		apiAppendFileFail.Inc(1)
   849  		return nil, "", err
   850  	}
   851  
   852  	entry := &ManifestEntry{
   853  		Path:        filepath.Join(path, fname),
   854  		ContentType: mime.TypeByExtension(filepath.Ext(fname)),
   855  		Mode:        0700,
   856  		Size:        totalSize,
   857  		ModTime:     time.Now(),
   858  	}
   859  
   860  	fkey, err := mw.AddEntry(ctx, io.Reader(combinedReader), entry)
   861  	if err != nil {
   862  		apiAppendFileFail.Inc(1)
   863  		return nil, "", err
   864  	}
   865  
   866  	newMkey, err := mw.Store()
   867  	if err != nil {
   868  		apiAppendFileFail.Inc(1)
   869  		return nil, "", err
   870  
   871  	}
   872  
   873  	return fkey, newMkey.String(), nil
   874  }
   875  
   876  // BuildDirectoryTree used by swarmfs_unix
   877  func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) {
   878  
   879  	uri, err := Parse("bzz:/" + mhash)
   880  	if err != nil {
   881  		return nil, nil, err
   882  	}
   883  	addr, err = a.Resolve(ctx, uri.Addr)
   884  	if err != nil {
   885  		return nil, nil, err
   886  	}
   887  
   888  	quitC := make(chan bool)
   889  	rootTrie, err := loadManifest(ctx, a.fileStore, addr, quitC, NOOPDecrypt)
   890  	if err != nil {
   891  		return nil, nil, fmt.Errorf("can't load manifest %v: %v", addr.String(), err)
   892  	}
   893  
   894  	manifestEntryMap = map[string]*manifestTrieEntry{}
   895  	err = rootTrie.listWithPrefix(uri.Path, quitC, func(entry *manifestTrieEntry, suffix string) {
   896  		manifestEntryMap[suffix] = entry
   897  	})
   898  
   899  	if err != nil {
   900  		return nil, nil, fmt.Errorf("list with prefix failed %v: %v", addr.String(), err)
   901  	}
   902  	return addr, manifestEntryMap, nil
   903  }
   904  
   905  // FeedsLookup finds Swarm feeds updates at specific points in time, or the latest update
   906  func (a *API) FeedsLookup(ctx context.Context, query *feed.Query) ([]byte, error) {
   907  	_, err := a.feed.Lookup(ctx, query)
   908  	if err != nil {
   909  		return nil, err
   910  	}
   911  	var data []byte
   912  	_, data, err = a.feed.GetContent(&query.Feed)
   913  	if err != nil {
   914  		return nil, err
   915  	}
   916  	return data, nil
   917  }
   918  
   919  // FeedsNewRequest creates a Request object to update a specific feed
   920  func (a *API) FeedsNewRequest(ctx context.Context, feed *feed.Feed) (*feed.Request, error) {
   921  	return a.feed.NewRequest(ctx, feed)
   922  }
   923  
   924  // FeedsUpdate publishes a new update on the given feed
   925  func (a *API) FeedsUpdate(ctx context.Context, request *feed.Request) (storage.Address, error) {
   926  	return a.feed.Update(ctx, request)
   927  }
   928  
   929  // ErrCannotLoadFeedManifest is returned when looking up a feeds manifest fails
   930  var ErrCannotLoadFeedManifest = errors.New("Cannot load feed manifest")
   931  
   932  // ErrNotAFeedManifest is returned when the address provided returned something other than a valid manifest
   933  var ErrNotAFeedManifest = errors.New("Not a feed manifest")
   934  
   935  // ResolveFeedManifest retrieves the Swarm feed manifest for the given address, and returns the referenced Feed.
   936  func (a *API) ResolveFeedManifest(ctx context.Context, addr storage.Address) (*feed.Feed, error) {
   937  	trie, err := loadManifest(ctx, a.fileStore, addr, nil, NOOPDecrypt)
   938  	if err != nil {
   939  		return nil, ErrCannotLoadFeedManifest
   940  	}
   941  
   942  	entry, _ := trie.getEntry("")
   943  	if entry.ContentType != FeedContentType {
   944  		return nil, ErrNotAFeedManifest
   945  	}
   946  
   947  	return entry.Feed, nil
   948  }
   949  
   950  // ErrCannotResolveFeedURI is returned when the ENS resolver is not able to translate a name to a Swarm feed
   951  var ErrCannotResolveFeedURI = errors.New("Cannot resolve Feed URI")
   952  
   953  // ErrCannotResolveFeed is returned when values provided are not enough or invalid to recreate a
   954  // feed out of them.
   955  var ErrCannotResolveFeed = errors.New("Cannot resolve Feed")
   956  
   957  // ResolveFeed attempts to extract feed information out of the manifest, if provided
   958  // If not, it attempts to extract the feed out of a set of key-value pairs
   959  func (a *API) ResolveFeed(ctx context.Context, uri *URI, values feed.Values) (*feed.Feed, error) {
   960  	var fd *feed.Feed
   961  	var err error
   962  	if uri.Addr != "" {
   963  		// resolve the content key.
   964  		manifestAddr := uri.Address()
   965  		if manifestAddr == nil {
   966  			manifestAddr, err = a.Resolve(ctx, uri.Addr)
   967  			if err != nil {
   968  				return nil, ErrCannotResolveFeedURI
   969  			}
   970  		}
   971  
   972  		// get the Swarm feed from the manifest
   973  		fd, err = a.ResolveFeedManifest(ctx, manifestAddr)
   974  		if err != nil {
   975  			return nil, err
   976  		}
   977  		log.Debug("handle.get.feed: resolved", "manifestkey", manifestAddr, "feed", fd.Hex())
   978  	} else {
   979  		var f feed.Feed
   980  		if err := f.FromValues(values); err != nil {
   981  			return nil, ErrCannotResolveFeed
   982  
   983  		}
   984  		fd = &f
   985  	}
   986  	return fd, nil
   987  }
   988  
   989  // MimeOctetStream default value of http Content-Type header
   990  const MimeOctetStream = "application/octet-stream"
   991  
   992  // DetectContentType by file file extension, or fallback to content sniff
   993  func DetectContentType(fileName string, f io.ReadSeeker) (string, error) {
   994  	ctype := mime.TypeByExtension(filepath.Ext(fileName))
   995  	if ctype != "" {
   996  		return ctype, nil
   997  	}
   998  
   999  	// save/rollback to get content probe from begin of file
  1000  	currentPosition, err := f.Seek(0, io.SeekCurrent)
  1001  	if err != nil {
  1002  		return MimeOctetStream, fmt.Errorf("seeker can't seek, %s", err)
  1003  	}
  1004  
  1005  	// read a chunk to decide between utf-8 text and binary
  1006  	var buf [512]byte
  1007  	n, _ := f.Read(buf[:])
  1008  	ctype = http.DetectContentType(buf[:n])
  1009  
  1010  	_, err = f.Seek(currentPosition, io.SeekStart) // rewind to output whole file
  1011  	if err != nil {
  1012  		return MimeOctetStream, fmt.Errorf("seeker can't seek, %s", err)
  1013  	}
  1014  
  1015  	return ctype, nil
  1016  }